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

using AWS.Compat
using AWS.UUIDs
"""
    AssociateDomain()

Specifies a domain to be associated to Amazon WorkLink.

# Required Parameters
- `AcmCertificateArn`: The ARN of an issued ACM certificate that is valid for the domain being associated.
- `DomainName`: The fully qualified domain name (FQDN).
- `FleetArn`: The Amazon Resource Name (ARN) of the fleet.

# Optional Parameters
- `DisplayName`: The name to display.
"""

associate_domain(AcmCertificateArn, DomainName, FleetArn; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/associateDomain", Dict{String, Any}("AcmCertificateArn"=>AcmCertificateArn, "DomainName"=>DomainName, "FleetArn"=>FleetArn); aws_config=aws_config)
associate_domain(AcmCertificateArn, DomainName, FleetArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/associateDomain", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AcmCertificateArn"=>AcmCertificateArn, "DomainName"=>DomainName, "FleetArn"=>FleetArn), args)); aws_config=aws_config)

"""
    AssociateWebsiteAuthorizationProvider()

Associates a website authorization provider with a specified fleet. This is used to authorize users against associated websites in the company network.

# Required Parameters
- `AuthorizationProviderType`: The authorization provider type.
- `FleetArn`: The ARN of the fleet.

# Optional Parameters
- `DomainName`: The domain name of the authorization provider. This applies only to SAML-based authorization providers.
"""

associate_website_authorization_provider(AuthorizationProviderType, FleetArn; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/associateWebsiteAuthorizationProvider", Dict{String, Any}("AuthorizationProviderType"=>AuthorizationProviderType, "FleetArn"=>FleetArn); aws_config=aws_config)
associate_website_authorization_provider(AuthorizationProviderType, FleetArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/associateWebsiteAuthorizationProvider", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AuthorizationProviderType"=>AuthorizationProviderType, "FleetArn"=>FleetArn), args)); aws_config=aws_config)

"""
    AssociateWebsiteCertificateAuthority()

Imports the root certificate of a certificate authority (CA) used to obtain TLS certificates used by associated websites within the company network.

# Required Parameters
- `Certificate`: The root certificate of the CA.
- `FleetArn`: The ARN of the fleet.

# Optional Parameters
- `DisplayName`: The certificate name to display.
"""

associate_website_certificate_authority(Certificate, FleetArn; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/associateWebsiteCertificateAuthority", Dict{String, Any}("Certificate"=>Certificate, "FleetArn"=>FleetArn); aws_config=aws_config)
associate_website_certificate_authority(Certificate, FleetArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/associateWebsiteCertificateAuthority", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Certificate"=>Certificate, "FleetArn"=>FleetArn), args)); aws_config=aws_config)

"""
    CreateFleet()

Creates a fleet. A fleet consists of resources and the configuration that delivers associated websites to authorized users who download and set up the Amazon WorkLink app.

# Required Parameters
- `FleetName`: A unique name for the fleet.

# Optional Parameters
- `DisplayName`: The fleet name to display.
- `OptimizeForEndUserLocation`: The option to optimize for better performance by routing traffic through the closest AWS Region to users, which may be outside of your home Region.
- `Tags`:  The tags to add to the resource. A tag is a key-value pair.
"""

create_fleet(FleetName; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/createFleet", Dict{String, Any}("FleetName"=>FleetName); aws_config=aws_config)
create_fleet(FleetName, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/createFleet", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("FleetName"=>FleetName), args)); aws_config=aws_config)

"""
    DeleteFleet()

Deletes a fleet. Prevents users from accessing previously associated websites.

# Required Parameters
- `FleetArn`: The ARN of the fleet.

"""

delete_fleet(FleetArn; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/deleteFleet", Dict{String, Any}("FleetArn"=>FleetArn); aws_config=aws_config)
delete_fleet(FleetArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/deleteFleet", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("FleetArn"=>FleetArn), args)); aws_config=aws_config)

"""
    DescribeAuditStreamConfiguration()

Describes the configuration for delivering audit streams to the customer account.

# Required Parameters
- `FleetArn`: The ARN of the fleet.

"""

describe_audit_stream_configuration(FleetArn; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/describeAuditStreamConfiguration", Dict{String, Any}("FleetArn"=>FleetArn); aws_config=aws_config)
describe_audit_stream_configuration(FleetArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/describeAuditStreamConfiguration", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("FleetArn"=>FleetArn), args)); aws_config=aws_config)

"""
    DescribeCompanyNetworkConfiguration()

Describes the networking configuration to access the internal websites associated with the specified fleet.

# Required Parameters
- `FleetArn`: The ARN of the fleet.

"""

describe_company_network_configuration(FleetArn; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/describeCompanyNetworkConfiguration", Dict{String, Any}("FleetArn"=>FleetArn); aws_config=aws_config)
describe_company_network_configuration(FleetArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/describeCompanyNetworkConfiguration", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("FleetArn"=>FleetArn), args)); aws_config=aws_config)

"""
    DescribeDevice()

Provides information about a user's device.

# Required Parameters
- `DeviceId`: A unique identifier for a registered user's device.
- `FleetArn`: The ARN of the fleet.

"""

describe_device(DeviceId, FleetArn; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/describeDevice", Dict{String, Any}("DeviceId"=>DeviceId, "FleetArn"=>FleetArn); aws_config=aws_config)
describe_device(DeviceId, FleetArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/describeDevice", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DeviceId"=>DeviceId, "FleetArn"=>FleetArn), args)); aws_config=aws_config)

"""
    DescribeDevicePolicyConfiguration()

Describes the device policy configuration for the specified fleet.

# Required Parameters
- `FleetArn`: The ARN of the fleet.

"""

describe_device_policy_configuration(FleetArn; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/describeDevicePolicyConfiguration", Dict{String, Any}("FleetArn"=>FleetArn); aws_config=aws_config)
describe_device_policy_configuration(FleetArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/describeDevicePolicyConfiguration", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("FleetArn"=>FleetArn), args)); aws_config=aws_config)

"""
    DescribeDomain()

Provides information about the domain.

# Required Parameters
- `DomainName`: The name of the domain.
- `FleetArn`: The ARN of the fleet.

"""

describe_domain(DomainName, FleetArn; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/describeDomain", Dict{String, Any}("DomainName"=>DomainName, "FleetArn"=>FleetArn); aws_config=aws_config)
describe_domain(DomainName, FleetArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/describeDomain", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DomainName"=>DomainName, "FleetArn"=>FleetArn), args)); aws_config=aws_config)

"""
    DescribeFleetMetadata()

Provides basic information for the specified fleet, excluding identity provider, networking, and device configuration details.

# Required Parameters
- `FleetArn`: The Amazon Resource Name (ARN) of the fleet.

"""

describe_fleet_metadata(FleetArn; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/describeFleetMetadata", Dict{String, Any}("FleetArn"=>FleetArn); aws_config=aws_config)
describe_fleet_metadata(FleetArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/describeFleetMetadata", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("FleetArn"=>FleetArn), args)); aws_config=aws_config)

"""
    DescribeIdentityProviderConfiguration()

Describes the identity provider configuration of the specified fleet.

# Required Parameters
- `FleetArn`: The ARN of the fleet.

"""

describe_identity_provider_configuration(FleetArn; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/describeIdentityProviderConfiguration", Dict{String, Any}("FleetArn"=>FleetArn); aws_config=aws_config)
describe_identity_provider_configuration(FleetArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/describeIdentityProviderConfiguration", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("FleetArn"=>FleetArn), args)); aws_config=aws_config)

"""
    DescribeWebsiteCertificateAuthority()

Provides information about the certificate authority.

# Required Parameters
- `FleetArn`: The ARN of the fleet.
- `WebsiteCaId`: A unique identifier for the certificate authority.

"""

describe_website_certificate_authority(FleetArn, WebsiteCaId; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/describeWebsiteCertificateAuthority", Dict{String, Any}("FleetArn"=>FleetArn, "WebsiteCaId"=>WebsiteCaId); aws_config=aws_config)
describe_website_certificate_authority(FleetArn, WebsiteCaId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/describeWebsiteCertificateAuthority", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("FleetArn"=>FleetArn, "WebsiteCaId"=>WebsiteCaId), args)); aws_config=aws_config)

"""
    DisassociateDomain()

Disassociates a domain from Amazon WorkLink. End users lose the ability to access the domain with Amazon WorkLink.

# Required Parameters
- `DomainName`: The name of the domain.
- `FleetArn`: The ARN of the fleet.

"""

disassociate_domain(DomainName, FleetArn; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/disassociateDomain", Dict{String, Any}("DomainName"=>DomainName, "FleetArn"=>FleetArn); aws_config=aws_config)
disassociate_domain(DomainName, FleetArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/disassociateDomain", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DomainName"=>DomainName, "FleetArn"=>FleetArn), args)); aws_config=aws_config)

"""
    DisassociateWebsiteAuthorizationProvider()

Disassociates a website authorization provider from a specified fleet. After the disassociation, users can't load any associated websites that require this authorization provider.

# Required Parameters
- `AuthorizationProviderId`: A unique identifier for the authorization provider.
- `FleetArn`: The ARN of the fleet.

"""

disassociate_website_authorization_provider(AuthorizationProviderId, FleetArn; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/disassociateWebsiteAuthorizationProvider", Dict{String, Any}("AuthorizationProviderId"=>AuthorizationProviderId, "FleetArn"=>FleetArn); aws_config=aws_config)
disassociate_website_authorization_provider(AuthorizationProviderId, FleetArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/disassociateWebsiteAuthorizationProvider", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("AuthorizationProviderId"=>AuthorizationProviderId, "FleetArn"=>FleetArn), args)); aws_config=aws_config)

"""
    DisassociateWebsiteCertificateAuthority()

Removes a certificate authority (CA).

# Required Parameters
- `FleetArn`: The ARN of the fleet.
- `WebsiteCaId`: A unique identifier for the CA.

"""

disassociate_website_certificate_authority(FleetArn, WebsiteCaId; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/disassociateWebsiteCertificateAuthority", Dict{String, Any}("FleetArn"=>FleetArn, "WebsiteCaId"=>WebsiteCaId); aws_config=aws_config)
disassociate_website_certificate_authority(FleetArn, WebsiteCaId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/disassociateWebsiteCertificateAuthority", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("FleetArn"=>FleetArn, "WebsiteCaId"=>WebsiteCaId), args)); aws_config=aws_config)

"""
    ListDevices()

Retrieves a list of devices registered with the specified fleet.

# Required Parameters
- `FleetArn`: The ARN of the fleet.

# Optional Parameters
- `MaxResults`: The maximum number of results to be included in the next page.
- `NextToken`: The pagination token used to retrieve the next page of results for this operation. If this value is null, it retrieves the first page.
"""

list_devices(FleetArn; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/listDevices", Dict{String, Any}("FleetArn"=>FleetArn); aws_config=aws_config)
list_devices(FleetArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/listDevices", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("FleetArn"=>FleetArn), args)); aws_config=aws_config)

"""
    ListDomains()

Retrieves a list of domains associated to a specified fleet.

# Required Parameters
- `FleetArn`: The ARN of the fleet.

# Optional Parameters
- `MaxResults`: The maximum number of results to be included in the next page.
- `NextToken`: The pagination token used to retrieve the next page of results for this operation. If this value is null, it retrieves the first page.
"""

list_domains(FleetArn; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/listDomains", Dict{String, Any}("FleetArn"=>FleetArn); aws_config=aws_config)
list_domains(FleetArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/listDomains", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("FleetArn"=>FleetArn), args)); aws_config=aws_config)

"""
    ListFleets()

Retrieves a list of fleets for the current account and Region.

# Optional Parameters
- `MaxResults`: The maximum number of results to be included in the next page.
- `NextToken`: The pagination token used to retrieve the next page of results for this operation. If this value is null, it retrieves the first page.
"""

list_fleets(; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/listFleets"; aws_config=aws_config)
list_fleets(args::AbstractDict{String, Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/listFleets", args; aws_config=aws_config)

"""
    ListTagsForResource()

Retrieves a list of tags for the specified resource.

# Required Parameters
- `ResourceArn`: The Amazon Resource Name (ARN) of the fleet.

"""

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

"""
    ListWebsiteAuthorizationProviders()

Retrieves a list of website authorization providers associated with a specified fleet.

# Required Parameters
- `FleetArn`: The ARN of the fleet.

# Optional Parameters
- `MaxResults`: The maximum number of results to be included in the next page.
- `NextToken`: The pagination token to use to retrieve the next page of results for this operation. If this value is null, it retrieves the first page.
"""

list_website_authorization_providers(FleetArn; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/listWebsiteAuthorizationProviders", Dict{String, Any}("FleetArn"=>FleetArn); aws_config=aws_config)
list_website_authorization_providers(FleetArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/listWebsiteAuthorizationProviders", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("FleetArn"=>FleetArn), args)); aws_config=aws_config)

"""
    ListWebsiteCertificateAuthorities()

Retrieves a list of certificate authorities added for the current account and Region.

# Required Parameters
- `FleetArn`: The ARN of the fleet.

# Optional Parameters
- `MaxResults`: The maximum number of results to be included in the next page.
- `NextToken`: The pagination token used to retrieve the next page of results for this operation. If this value is null, it retrieves the first page.
"""

list_website_certificate_authorities(FleetArn; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/listWebsiteCertificateAuthorities", Dict{String, Any}("FleetArn"=>FleetArn); aws_config=aws_config)
list_website_certificate_authorities(FleetArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/listWebsiteCertificateAuthorities", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("FleetArn"=>FleetArn), args)); aws_config=aws_config)

"""
    RestoreDomainAccess()

Moves a domain to ACTIVE status if it was in the INACTIVE status.

# Required Parameters
- `DomainName`: The name of the domain.
- `FleetArn`: The ARN of the fleet.

"""

restore_domain_access(DomainName, FleetArn; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/restoreDomainAccess", Dict{String, Any}("DomainName"=>DomainName, "FleetArn"=>FleetArn); aws_config=aws_config)
restore_domain_access(DomainName, FleetArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/restoreDomainAccess", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DomainName"=>DomainName, "FleetArn"=>FleetArn), args)); aws_config=aws_config)

"""
    RevokeDomainAccess()

Moves a domain to INACTIVE status if it was in the ACTIVE status.

# Required Parameters
- `DomainName`: The name of the domain.
- `FleetArn`: The ARN of the fleet.

"""

revoke_domain_access(DomainName, FleetArn; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/revokeDomainAccess", Dict{String, Any}("DomainName"=>DomainName, "FleetArn"=>FleetArn); aws_config=aws_config)
revoke_domain_access(DomainName, FleetArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/revokeDomainAccess", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DomainName"=>DomainName, "FleetArn"=>FleetArn), args)); aws_config=aws_config)

"""
    SignOutUser()

Signs the user out from all of their devices. The user can sign in again if they have valid credentials.

# Required Parameters
- `FleetArn`: The ARN of the fleet.
- `Username`: The name of the user.

"""

sign_out_user(FleetArn, Username; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/signOutUser", Dict{String, Any}("FleetArn"=>FleetArn, "Username"=>Username); aws_config=aws_config)
sign_out_user(FleetArn, Username, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/signOutUser", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("FleetArn"=>FleetArn, "Username"=>Username), args)); aws_config=aws_config)

"""
    TagResource()

Adds or overwrites one or more tags for the specified resource, such as a fleet. Each tag consists of a key and an optional value. If a resource already has a tag with the same key, this operation updates its value.

# Required Parameters
- `ResourceArn`: The Amazon Resource Name (ARN) of the fleet.
- `Tags`: The tags to add to the resource. A tag is a key-value pair.

"""

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

"""
    UntagResource()

Removes one or more tags from the specified resource.

# Required Parameters
- `ResourceArn`: The Amazon Resource Name (ARN) of the fleet.
- `tagKeys`: The list of tag keys to remove from the resource.

"""

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

"""
    UpdateAuditStreamConfiguration()

Updates the audit stream configuration for the fleet.

# Required Parameters
- `FleetArn`: The ARN of the fleet.

# Optional Parameters
- `AuditStreamArn`: The ARN of the Amazon Kinesis data stream that receives the audit events.
"""

update_audit_stream_configuration(FleetArn; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/updateAuditStreamConfiguration", Dict{String, Any}("FleetArn"=>FleetArn); aws_config=aws_config)
update_audit_stream_configuration(FleetArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/updateAuditStreamConfiguration", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("FleetArn"=>FleetArn), args)); aws_config=aws_config)

"""
    UpdateCompanyNetworkConfiguration()

Updates the company network configuration for the fleet.

# Required Parameters
- `FleetArn`: The ARN of the fleet.
- `SecurityGroupIds`: The security groups associated with access to the provided subnets.
- `SubnetIds`: The subnets used for X-ENI connections from Amazon WorkLink rendering containers.
- `VpcId`: The VPC with connectivity to associated websites.

"""

update_company_network_configuration(FleetArn, SecurityGroupIds, SubnetIds, VpcId; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/updateCompanyNetworkConfiguration", Dict{String, Any}("FleetArn"=>FleetArn, "SecurityGroupIds"=>SecurityGroupIds, "SubnetIds"=>SubnetIds, "VpcId"=>VpcId); aws_config=aws_config)
update_company_network_configuration(FleetArn, SecurityGroupIds, SubnetIds, VpcId, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/updateCompanyNetworkConfiguration", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("FleetArn"=>FleetArn, "SecurityGroupIds"=>SecurityGroupIds, "SubnetIds"=>SubnetIds, "VpcId"=>VpcId), args)); aws_config=aws_config)

"""
    UpdateDevicePolicyConfiguration()

Updates the device policy configuration for the fleet.

# Required Parameters
- `FleetArn`: The ARN of the fleet.

# Optional Parameters
- `DeviceCaCertificate`: The certificate chain, including intermediate certificates and the root certificate authority certificate used to issue device certificates.
"""

update_device_policy_configuration(FleetArn; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/updateDevicePolicyConfiguration", Dict{String, Any}("FleetArn"=>FleetArn); aws_config=aws_config)
update_device_policy_configuration(FleetArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/updateDevicePolicyConfiguration", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("FleetArn"=>FleetArn), args)); aws_config=aws_config)

"""
    UpdateDomainMetadata()

Updates domain metadata, such as DisplayName.

# Required Parameters
- `DomainName`: The name of the domain.
- `FleetArn`: The ARN of the fleet.

# Optional Parameters
- `DisplayName`: The name to display.
"""

update_domain_metadata(DomainName, FleetArn; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/updateDomainMetadata", Dict{String, Any}("DomainName"=>DomainName, "FleetArn"=>FleetArn); aws_config=aws_config)
update_domain_metadata(DomainName, FleetArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/updateDomainMetadata", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("DomainName"=>DomainName, "FleetArn"=>FleetArn), args)); aws_config=aws_config)

"""
    UpdateFleetMetadata()

Updates fleet metadata, such as DisplayName.

# Required Parameters
- `FleetArn`: The ARN of the fleet.

# Optional Parameters
- `DisplayName`: The fleet name to display. The existing DisplayName is unset if null is passed.
- `OptimizeForEndUserLocation`: The option to optimize for better performance by routing traffic through the closest AWS Region to users, which may be outside of your home Region.
"""

update_fleet_metadata(FleetArn; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/UpdateFleetMetadata", Dict{String, Any}("FleetArn"=>FleetArn); aws_config=aws_config)
update_fleet_metadata(FleetArn, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/UpdateFleetMetadata", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("FleetArn"=>FleetArn), args)); aws_config=aws_config)

"""
    UpdateIdentityProviderConfiguration()

Updates the identity provider configuration for the fleet.

# Required Parameters
- `FleetArn`: The ARN of the fleet.
- `IdentityProviderType`: The type of identity provider.

# Optional Parameters
- `IdentityProviderSamlMetadata`: The SAML metadata document provided by the customer’s identity provider. The existing IdentityProviderSamlMetadata is unset if null is passed.
"""

update_identity_provider_configuration(FleetArn, IdentityProviderType; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/updateIdentityProviderConfiguration", Dict{String, Any}("FleetArn"=>FleetArn, "IdentityProviderType"=>IdentityProviderType); aws_config=aws_config)
update_identity_provider_configuration(FleetArn, IdentityProviderType, args::AbstractDict{String, <:Any}; aws_config::AWSConfig=global_aws_config()) = worklink("POST", "/updateIdentityProviderConfiguration", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("FleetArn"=>FleetArn, "IdentityProviderType"=>IdentityProviderType), args)); aws_config=aws_config)


text:
# Code to launch and interact with Jupyter, not via messaging protocol
##################################################################

include(joinpath("..","deps","kspec.jl"))

##################################################################

import Conda

isyes(s) = isempty(s) || lowercase(strip(s)) in ("y", "yes")

function find_jupyter_subcommand(subcommand::AbstractString)
    jupyter = JUPYTER
    if jupyter == "jupyter" || jupyter == "jupyter.exe" # look in PATH
        jupyter = Sys.which(exe("jupyter"))
        if jupyter === nothing
            jupyter = joinpath(Conda.SCRIPTDIR, exe("jupyter"))
        end
    end
    isconda = dirname(jupyter) == abspath(Conda.SCRIPTDIR)
    if !Sys.isexecutable(jupyter)
        if isconda && isyes(Base.prompt("install Jupyter via Conda, y/n? [y]"))
           Conda.add(subcommand == "lab" ? "jupyterlab" : "jupyter")
        else
            error("$jupyter is not installed, cannot run $subcommand")
        end
    end

    cmd = `$jupyter $subcommand`

    # fails in Windows if jupyter directory is not in PATH (jupyter/jupyter_core#62)
    pathsep = Sys.iswindows() ? ';' : ':'
    withenv("PATH" => dirname(jupyter) * pathsep * get(ENV, "PATH", "")) do
        if isconda
            # sets PATH and other environment variables for Julia's Conda environment
            cmd = Conda._set_conda_env(cmd)
        else
            setenv(cmd, ENV)
        end
    end

    return cmd
end

##################################################################

function launch(cmd, dir, detached)
    @info("running $cmd")
    if Sys.isapple() # issue #551 workaround, remove after macOS 10.12.6 release?
        withenv("BROWSER"=>"open") do
            p = run(Cmd(cmd, detach=true, dir=dir); wait=false)
        end
    else
        p = run(Cmd(cmd, detach=true, dir=dir); wait=false)
    end
    if !detached
        try
            wait(p)
        catch e
            if isa(e, InterruptException)
                kill(p, 2) # SIGINT
            else
                kill(p) # SIGTERM
                rethrow()
            end
        end
    end
    return p
end

"""
    notebook(; dir=homedir(), detached=false)

The `notebook()` function launches the Jupyter notebook, and is
equivalent to running `jupyter notebook` at the operating-system
command-line.    The advantage of launching the notebook from Julia
is that, depending on how Jupyter was installed, the user may not
know where to find the `jupyter` executable.

By default, the notebook server is launched in the user's home directory,
but this location can be changed by passing the desired path in the
`dir` keyword argument.  e.g. `notebook(dir=pwd())` to use the current
directory.

By default, `notebook()` does not return; you must hit ctrl-c
or quit Julia to interrupt it, which halts Jupyter.  So, you
must leave the Julia terminal open for as long as you want to
run Jupyter.  Alternatively, if you run `notebook(detached=true)`,
the `jupyter notebook` will launch in the background, and will
continue running even after you quit Julia.  (The only way to
stop Jupyter will then be to kill it in your operating system's
process manager.)
"""
function notebook(; dir=homedir(), detached=false)
    inited && error("IJulia is already running")
    notebook = find_jupyter_subcommand("notebook")
    return launch(notebook, dir, detached)
end

"""
    jupyterlab(; dir=homedir(), detached=false)

Similar to `IJulia.notebook()` but launches JupyterLab instead
of the Jupyter notebook.
"""
function jupyterlab(; dir=homedir(), detached=false)
    inited && error("IJulia is already running")
    lab = find_jupyter_subcommand("lab")
    jupyter = first(lab)
    if dirname(jupyter) == abspath(Conda.SCRIPTDIR) &&
       !Sys.isexecutable(exe(jupyter, "-lab")) &&
       isyes(Base.prompt("install JupyterLab via Conda, y/n? [y]"))
        Conda.add("jupyterlab")
    end
    return launch(lab, dir, detached)
end

function qtconsole()
    qtconsole = find_jupyter_subcommand("qtconsole")
    if inited
        run(`$qtconsole --existing $connection_file`; wait=false)
    else
        error("IJulia is not running. qtconsole must be called from an IJulia session.")
    end
end

ext: jl


text:
module Plot

using ..Utils: compute_co_occurrence_matrix, ari_over_markov_chain, generate_all_clusterings
using ..Evaluate: compute_posterior_probability, compute_posterior_probability_confidence_interval
using Plots
using Statistics
using Clustering

function plot_assignments(assignments::Vector{Int64}; title="Cluster assignments for observations")
    plot(
        1:length(assignments),
        assignments,
        seriestype = :scatter,
        xlabel="Observation",
        ylabel="Cluster",
        title=title,
        legend=false
    )
end

function plot_assignments(assignments::Vector{Float64}; title="Cluster assignments for observations")
    assignments = Vector{Int64}(assignments)
    plot_assignments(assignments, title=title)
end

function plot_co_occurrence_matrix(markov_chain::Matrix{Int64}; num_burn_in=0, title="Co-occurrence matrix")
    co_occurrence_matrix = compute_co_occurrence_matrix(markov_chain[:, (num_burn_in+1):end])
    gr()
    heatmap(1:size(co_occurrence_matrix,1),
           1:size(co_occurrence_matrix,2),
           co_occurrence_matrix,
           c=cgrad([:white, :blue]),
           xlabel="Observations",
           ylabel="Observations",
           title=title
        )
end

function plot_co_occurrence_matrix(markov_chains::Array{Int64}; num_burn_in=0, plot_size=500)
    num_chains = size(markov_chains)[3]
    subplots = []
    for chain = 1:num_chains
        markov_chain = markov_chains[:, :, chain]
        co_occurrence_matrix = compute_co_occurrence_matrix(markov_chain, num_burn_in=num_burn_in)
        gr()
        subplot = heatmap(1:size(co_occurrence_matrix,1),
           1:size(co_occurrence_matrix,2), co_occurrence_matrix,
           c=cgrad([:white, :blue]),
           xlabel="Observations", ylabel="Observations",
           title="Chain $chain: Co-occurrence Matrix")
        push!(subplots, subplot)
    end
    plot(subplots..., layout = (num_chains, 1), legend=false, size = (plot_size*(4/3), plot_size * num_chains*(3/4)))
end

function plot_co_occurrence_matrix(markov_chain::Matrix{Int64}, weights::Vector{Float64})
    co_occurrence_matrix = compute_co_occurrence_matrix(markov_chain, weights)
    gr()
    heatmap(1:size(co_occurrence_matrix,1),
        1:size(co_occurrence_matrix,2), co_occurrence_matrix,
        c=cgrad([:white, :blue]),
        xlabel="Observations", ylabel="Observations",
        title="Co-occurrence Matrix")
end

function plot_co_occurrence_matrix(assignment::Vector{Int64})
    markov_chain = reshape(assignment, length(assignment), 1)
    plot_co_occurrence_matrix(markov_chain)
end

function plot_co_occurrence_matrix(assignment::Vector{Float64})
    assignment = Vector{Int64}(assignment)
    plot_co_occurrence_matrix(assignment)
end

function plot_arrival_posterior_probabilities(markov_chain::Matrix{Int64}, true_clustering;
                                              num_burn_in=0, title="Arrival time posterior probabilities")
    num_iterations = size(markov_chain)[2]
    num_observations = size(markov_chain)[1]
    arrival_counts = zeros(Float64, num_observations)
    observations = Array{Int64}(1:num_observations)
    for i = (num_burn_in+1):num_iterations
        arrival_counts += (markov_chain[:, i] .=== observations)
    end
    arrival_posterior_probabilities = arrival_counts / (num_iterations - num_burn_in)

    num_clusters = maximum(true_clustering)
    clusters = Array{Int64}(1:num_clusters)
    true_arrivals = []
    for cluster = clusters
        arrival = findfirst(true_clustering .=== cluster)
        append!(true_arrivals, arrival)
    end

    colours = Vector{String}(undef, num_observations)

    for observation = 1:num_observations
        posterior_probability = arrival_posterior_probabilities[observation]
        if posterior_probability >= 0.5
            if observation in true_arrivals # true positive
                colours[observation] = "green"
            else # false positive
                colours[observation] = "red"
            end
        else
            if observation in true_arrivals # false negative
                colours[observation] = "red"
            else # true negative
                colours[observation] = "green"
            end
        end
    end
    vline(
        true_arrivals,
        linecolor="black",
        linestyle=:dash,
        legend=nothing,
        ylims=[0., 1.]
    )
    plot!(
        1:num_observations,
        arrival_posterior_probabilities,
        color=colours,
        seriestype=:scatter,
        xlabel="Observation",
        ylabel="Probability",
        legend=false,
        title=title
    )
end

function plot_log_likelihoods(log_likelihoods::Vector{Float64}; title="Log likelihoods over iterations")
    plot(
        1:size(log_likelihoods)[1],
        log_likelihoods,
        seriestype=:line,
        xlabel="Iteration",
        ylabel="Log likelihood",
        legend=false,
        title=title
    )
end

function plot_log_likelihoods(log_likelihoods::Matrix{Float64};
                              assignment_types=[],
                              legend_location=:topright,
                              title="Log likelihood over iterations")
    num_chains = size(log_likelihoods)[2]
    num_iterations = size(log_likelihoods)[1]
    if length(assignment_types) > 0
        @assert length(assignment_types) == num_chains
    end
    assignment_types = ["Initial assignment: $assignment_type" for assignment_type in assignment_types]
    plot(
        1:num_iterations,
        log_likelihoods,
        seriestype=:line,
        title=title,
        xlabel="Iteration",
        ylabel="Log likelihood",
        legend=legend_location,
        label=reshape(assignment_types, 1, length(assignment_types))
    )
end

function plot_num_clusters(markov_chain::Matrix{Int64}; true_number=0, title="Number of clusters")
    num_unique_clusters_vector = mapslices(u->length(unique(u)), markov_chain, dims=1)
    plot(
        1:length(num_unique_clusters_vector),
        vec(num_unique_clusters_vector),
        seriestype=:line,
        xlabel="Iteration",
        ylabel="Number of clusters",
        title=title,
        legend=false
    )
    if true_number > 0
        hline!([true_number], label="True number of clusters = $true_number")
    end
end

function plot_num_clusters(markov_chain::Array{Int64};
                           true_number=0,
                           assignment_types=[],
                           legend_location=:topright,
                           title="Number of clusters over iterations")
    num_iterations = size(markov_chain)[2]
    num_chains = size(markov_chain)[3]
    if length(assignment_types) > 0
        @assert length(assignment_types) === num_chains
    end
    num_clusters = Matrix{Int64}(undef, num_iterations, num_chains)
    for chain = 1:num_chains
        num_unique_clusters_vector = vec(mapslices(u->length(unique(u)), markov_chain[:, :, chain], dims=1))
        num_clusters[:, chain] = num_unique_clusters_vector
    end
    assignment_types = ["Initial assignment: $assignment_type" for assignment_type in assignment_types]
    plot(1:num_iterations,
        num_clusters,
        seriestype=:line,
        title=title,
        xlabel="Iteration",
        ylabel="Number of clusters",
        legend=legend_location,
        label=reshape(assignment_types, 1, length(assignment_types))
        )
    if true_number > 0
        hline!([true_number], label="True number of clusters = $true_number")
    end
end

function plot_trace(values;
                    ylabel="Trace",
                    assignment_types=[],
                    title="$ylabel over iterations")
    num_chains = size(values)[end]
    num_iterations = size(values)[1]
    if length(assignment_types) > 0
        @assert length(assignment_types) == num_chains
    end
    assignment_types = ["Initial assignment: $assignment_type" for assignment_type in assignment_types]
    plot(
        1:num_iterations,
        values,
        seriestype=:line,
        title="$ylabel over iterations",
        xlabel="Iteration",
        ylabel=ylabel,
        label=reshape(assignment_types, 1, length(assignment_types))
    )
end

function plot_ari_posterior_distribution(true_clustering::Vector{Int64},
                                         assignment_posterior::Matrix{Int64};
                                         num_burn_in=0,
                                         title="ARI posterior distribution")
    ari_posterior = ari_over_markov_chain(true_clustering, assignment_posterior[:, (num_burn_in+1):end])
    mean_ari = round(mean(ari_posterior), digits=3)
    plot(
        ari_posterior,
        seriestype=:histogram,
        legend=true,
        label=""
    )
    vline!(
        [mean_ari],
        label="Mean ARI = $mean_ari",
        xlabel="ARI",
        ylabel="Frequency",
        title=title
    )
end

function plot_ari_posterior_distribution(true_clustering::Vector{Int64},
                                         assignment_posterior::Array{Int64};
                                         num_burn_in=0,
                                         title="ARI posterior distribution")
    num_chains = size(assignment_posterior)[3]
    subplots = []
    for chain = 1:num_chains
        ari_posterior = ari_over_markov_chain(true_clustering, assignment_posterior[:, (num_burn_in+1):end, chain])
        mean_ari = round(mean(ari_posterior), digits=3)
        subplot = plot(ari_posterior, seriestype=:histogram, legend=true, label="", title="Chain $chain", xlabel="ARI")
        vline!([mean_ari], label="Mean ARI = $mean_ari")
        push!(subplots, subplot)
    end
    plot(subplots..., layout=(num_chains, 1), legend=true)
end

function plot_cluster_sizes_histogram(clustering::Vector{Int64}; title="Histogram of cluster sizes")
    num_clusters = length(unique(clustering))
    cluster_sizes = Vector{Int64}(undef, num_clusters)
    for cluster = 1:num_clusters
        cluster_sizes[cluster] = count(clustering .=== cluster)
    end
    mean_cluster_size = round(mean(cluster_sizes), digits=2)
    plot(
        cluster_sizes,
        seriestype=:histogram,
        legend=true,
        label="",
        bins=10,
        title=title
    )
    xlabel!("Size of cluster")
    vline!([mean_cluster_size], label="Mean cluster size = $mean_cluster_size")
end

function plot_clustering_posterior_probability_validation(markov_chain::Matrix{Int64},
                                                          data,
                                                          model;
                                                          title="95% Confidence Intervals for True Posterior Probabilities")
    gr()
    n = size(markov_chain)[1]
    all_clusterings = generate_all_clusterings(n)
    num_clusterings = size(all_clusterings)[1]
    true_posterior_probabilities = Vector{Float64}(undef, num_clusterings)
    mcmc_means = Vector{Float64}(undef, num_clusterings)
    mcmc_conf_length = Vector{Float64}(undef, num_clusterings)
    for (i, clustering) in enumerate(all_clusterings)
        true_clustering_posterior_probability = compute_posterior_probability(clustering, data, model)
        true_posterior_probabilities[i] = true_clustering_posterior_probability
        (prob_mean, conf_length) = compute_posterior_probability_confidence_interval(clustering, markov_chain)
        mcmc_means[i] = prob_mean
        mcmc_conf_length[i] = conf_length
    end

    colours = Vector{String}(undef, num_clusterings)
    for i = 1:num_clusterings
        true_posterior_prob = true_posterior_probabilities[i]
        mcmc_mean = mcmc_means[i]
        conf_length = mcmc_conf_length[i]
        if (mcmc_mean - conf_length <= true_posterior_prob) && (true_posterior_prob <= mcmc_mean + conf_length)
            colours[i] = "blue"
        else
            colours[i] = "red"
        end
    end

    # Create custom error bars
    # Top caps
    p = plot(
          mcmc_means + mcmc_conf_length,
          seriestype=:scatter,
          markershape=:hline,
          markercolor=:black,
          markersize=10,
          legend=nothing,
          )
    # Bottom caps
    plot!(p,
          mcmc_means - mcmc_conf_length,
          seriestype=:scatter,
          markershape=:hline,
          markercolor=:black,
          markersize=10,
          legend=nothing,
          )
    # Vertical bars
    for i=1:num_clusterings
        mcmc_mean = mcmc_means[i]
        conf_length = mcmc_conf_length[i]
        bar_end_points = [
            mcmc_mean - conf_length,
            mcmc_mean + conf_length
        ]
        plot!(
            p,
            [i, i],
            bar_end_points,
            seriestype=:line,
            legend=nothing,
            linecolor=:black
            )
    end
    plot!(
        p,
        true_posterior_probabilities,
        seriestype=:scatter,
        color=colours,
        legend=nothing,
        xlabel="Clustering",
        ylabel="Posterior Probability",
        title=title,
        )
    p
end

function plot_kmeans_elbow(data; max_num_clusters=10, title="Distortion over k for k-means clustering")
    totalcosts = Vector{Float64}(undef, max_num_clusters)
    for k = 1:max_num_clusters
        kmeans_result = kmeans(data, k)
        totalcosts[k] = kmeans_result.totalcost
    end
    plot(
        1:max_num_clusters,
        totalcosts,
        label="",
        title=title,
        xlabel="Number of clusters (k)",
        ylabel="Distortion"
    )
end

end

max_stars_repo_name: realseanla/ntl-stick-breaking-julia

max_issues_repo_name: realseanla/ntl-stick-breaking-julia

max_forks_repo_name: realseanla/ntl-stick-breaking-julia


text:
using MOCNeutronTransport
@testset "Triangle_3D" begin
    for T in [Float32, Float64]
        @testset "Constructors" begin
            p₁ = Point_3D(T, 0)
            p₂ = Point_3D(T, 1)
            p₃ = Point_3D(T, 1, 1)
            tri = Triangle_3D((p₁, p₂, p₃))
            @test tri.points == (p₁, p₂, p₃)

            # single constructor
            tri = Triangle_3D(p₁, p₂, p₃)
            @test tri.points == (p₁, p₂, p₃)
        end

        @testset "Methods" begin
            p₁ = Point_3D(T, 0)
            p₂ = Point_3D(T, 1)
            p₃ = Point_3D(T, 1, 1)
            tri = Triangle_3D((p₁, p₂, p₃))

            # interpolation
            tri(0, 0) ≈ p₁
            tri(1, 0) ≈ p₂
            tri(0, 1) ≈ p₃
            tri(1//2, 1//2) ≈ Point_3D(T, 1//2, 1//2)

            # area
            a = area(tri)
            @test typeof(a) == typeof(T(1))
            @test a == T(1//2)

            # intersect
            # line is not coplanar with triangle
            p₄ = Point_3D(T, 9//10, 1//10, -5)
            p₅ = Point_3D(T, 9//10, 1//10,  5)
            l = LineSegment_3D(p₄, p₅)
            bool, point = intersect(l, tri)
            @test bool
            @test point ≈ Point_3D(T, 9//10, 1//10,  0)

            # line is coplanar with triangle
            p₄ = Point_3D(T, 1//2, -1)
            p₅ = Point_3D(T, 1//2,  2)
            l = LineSegment_3D(p₄, p₅)
            bool, point = intersect(l, tri)
            @test !bool

            # no intersection non-coplanar
            p₄ = Point_3D(T, 2, 1//10, -5)
            p₅ = Point_3D(T, 2, 1//10,  5)
            l = LineSegment_3D(p₄, p₅)
            bool, point = intersect(l, tri)
            @test !bool

            # no intersection coplanar
            p₄ = Point_3D(T, 2, -1)
            p₅ = Point_3D(T, 2,  2)
            l = LineSegment_3D(p₄, p₅)
            bool, point = intersect(l, tri)
            @test !bool
        end
    end
end

max_stars_repo_name: KyleVaughn/MOCNeutronTransport

max_issues_repo_name: KyleVaughn/MOCNeutronTransport

max_forks_repo_name: KyleVaughn/MOCNeutronTransport


text:
# This is an example of WGAN_GP using ADCME.jl
# Reference: https://github.com/eriklindernoren/Keras-GAN/blob/master/wgan_gp/wgan_gp.py#L147
using ADCME
using PyPlot
# step 0: parameters
img_rows = 28
img_cols = 28
channels = 1
img_shape = (img_rows, img_cols, channels)
latent_dim = 100
variable_scope("rms", reuse=AUTO_REUSE) do
    global optimizer1 = RMSPropOptimizer(0.00005)
    global optimizer2 = RMSPropOptimizer(0.00005)
end
n_critic = 5
batch_size = 32
Xtrain,_,_,_ = mnist(Float32)
Xtrain = (Xtrain.-127.5f0)/127.5f0
Xtrain = reshape(Xtrain, size(Xtrain)...,1)

function generator(x)
    scope = "generator"
    variable_scope(scope, reuse=AUTO_REUSE) do
        x = dense(x, 128*7*7, activation="relu")
        x = Reshape(x, (7,7,128),name="2")
        x = UpSampling2D(x,name="3")
        x = conv2d(x, 128, kernel_size=4, padding="same")
        # x = BatchNormalization(x, momentum=0.8)
        x = relu(x)
        x = UpSampling2D(x,name="5")
        x = conv2d(x, 64, kernel_size=4, padding="same")
        # x = BatchNormalization(x,momentum=0.8)
        x = relu(x)
        x = conv2d(x, channels, kernel_size=4, padding="same")
        x = tanh(x)
    end
    return x
end

function critic(x)
    variable_scope("critic", reuse=AUTO_REUSE) do
        x = conv2d(x, 16, kernel_size=3, strides=2, padding="same")
        x = leaky_relu(x, alpha=0.2)
        x = dropout(x, 0.25)
        x = conv2d(x, 32, kernel_size=3, strides=2, padding="same")
        x = ZeroPadding2D(x, padding=((0,1),(0,1)))
        # x = BatchNormalization(x, momentum=0.8)
        x = leaky_relu(x, alpha=0.2)
        x = dropout(x, 0.25)
        x = conv2d(x, 64, kernel_size=3, strides=2, padding="same")
        # x = BatchNormalization(x, momentum=0.8)
        x = leaky_relu(x, alpha=0.2)
        x = dropout(x, 0.25)
        x = conv2d(x, 128, kernel_size=3, strides=1, padding="same")
        # x = BatchNormalization(x, momentum=0.8)
        x = leaky_relu(x, alpha=0.2)
        x = dropout(x, 0.25)
        x = flatten(x)
        x = dense(x, 1)
        x = sigmoid(x)
    end
    return x
end

function wasserstein_loss(ypred, ytrue)
    return mean(ytrue.*ypred)
end

function gradient_penalty_loss(y_pred, averaged_samples)
    grad = tf.gradients(y_pred, averaged_samples)[1]
    grd_sqr_sum = sum(grad^2, dims=[2;3;4])
    grd_l2_norm = sqrt(grd_sqr_sum)
    gradient_penalty = (1 - grd_l2_norm)^2
    return mean(gradient_penalty)
end

# step 1: create generator neural network
real_img = placeholder(Float32, shape=[batch_size, img_shape...])
z_disc = placeholder(Float32, shape=[batch_size, latent_dim])
fake_img = generator(z_disc)
# error("inspection")
fake = critic(fake_img)
valid = critic(real_img)

α = random_uniform((32,1,1,1), dtype=Float32)
interpolated_img = α * real_img + (1 - α) * fake_img
validity_interpolated = critic(interpolated_img)

l1 = wasserstein_loss(valid, -ones(Float32,batch_size,1))
l2 = wasserstein_loss(fake, ones(Float32,batch_size,1))
l3 = gradient_penalty_loss(validity_interpolated, interpolated_img)
l_critic = l1 + l2 + 10*l3

z_gen = placeholder(Float32, shape=[batch_size, latent_dim])
img = generator(z_gen)
valid = critic(img)
l_generator = wasserstein_loss(valid, -ones(Float32,batch_size,1))

# error("inspection")
critic_var = get_collection("critic")
generator_var = get_collection("generator")
variable_scope("rms", reuse=AUTO_REUSE) do
    global train_critic = minimize(optimizer1, l_critic, var_list=critic_var)
    global train_generator = minimize(optimizer2, l_generator, var_list=generator_var)
end

si_z_gen = placeholder(Float32, shape=[25, 100])
si_img = generator(si_z_gen)
function sample_images(epoch)
    noise = randn(25, latent_dim)
    gen_images = run(sess, si_img, feed_dict=Dict(si_z_gen=>noise))
    gen_images = 0.5*gen_images .+ 1
    close("all")
    figure()
    cnt = 1
    for i = 1:5
        for j = 1:5
            subplot(5,5,i+(j-1)*5)
            imshow(gen_images[cnt,:,:,1], cmap="gray")
            axis("off")
            cnt+=1
        end
    end
    savefig("images/mnist_$epoch.png")
    close("all")
end

# # step 2: training
sess = Session()
init(sess)
epochs = 600000
d_loss = nothing
noise  = nothing
_l1    = nothing
_l2    = nothing
_l3    = nothing
noise  = nothing
for epoch = 1:epochs
    for _ = 1:n_critic
        global d_loss, _l1, _l2, _l3, noise
        idx = rand(1:size(Xtrain,1), batch_size)
        imgs = Xtrain[idx,:,:,:]
        noise = randn(Float32, batch_size, latent_dim)
        _l1,_l2,_l3,d_loss,_ = run(sess, [l1,l2,l3,l_critic, train_critic],
            feed_dict=Dict(real_img=>imgs, z_disc=>noise))
    end
    # noise = randn(batch_size, latent_dim)
    #k1,k2 = run(sess, [l2, l_generator], feed_dict=Dict(z_disc=>noise, z_gen=>noise))
    #@show k1, k2
    g_loss,_ = run(sess, [l_generator, train_generator],
            feed_dict=Dict(z_gen=>noise))
    if mod(epoch, 100)==1
        sample_images(epoch)
    end
    println("$epoch [D loss: $(d_loss)] [G loss: $(g_loss)]")
    println("Diagnose: $_l1, $_l2, $_l3")
end


text:
using Epicrop
using Test
using DataFrames
using Dates
using CSV
using Downloads

@testset "hlipmodel tests" begin
    # sometimes the POWER data download fails, this sets the timeout to 60 seconds instead of 20
    downloader = Downloads.Downloader()
    downloader.easy_hook = (easy, info) -> Downloads.Curl.setopt(easy, Downloads.Curl.CURLOPT_LOW_SPEED_TIME, 120)

    w = CSV.read(
        Downloads.download(
            "https://power.larc.nasa.gov/api/temporal/daily/point?parameters=PRECTOTCORR,T2M,RH2M&community=ag&start=20100701&end=20101028&latitude=14.6774&longitude=121.25562&format=csv&time_standard=utc&user=Epicropjl",
            downloader=downloader),
            DataFrame, header = 12)

    # rename the columns to match the expected column names for hlipmodel
    rename!(w, :RH2M => :RHUM, :T2M => :TEMP, :PRECTOTCORR => :RAIN)

    # add columns for YYYYMMDD and lat/lon
    insertcols!(w, 1, :YYYYMMDD => range(Date(2010, 06, 30); step=Day(1), length=120))
    insertcols!(w, :LAT => 14.6774, :LON => 121.25562)

    RcA = [0 0.35; 20 0.35; 40 0.35; 60 0.47; 80 0.59; 100 0.71; 120 1]

    RcT = [15 0; 20 0.06; 25 1.0; 30 0.85; 35 0.16; 40 0]

    bs = hlipmodel(
		wth = w,
		emergence = "2010-07-01",
		onset = 20,
		duration = 120,
		rhlim = 90,
		rainlim = 5,
		H0 = 600,
		I0 = 1,
		RcA = RcA,
		RcT = RcT,
		RcOpt = 0.61,
		p = 6,
		i = 19,
		Sx = 100000,
		a = 1,
		RRS = 0.01,
		RRG = 0.1
    )

    @test nrow(bs) == 120
    @test ncol(bs) == 16
    @test isapprox(bs[120, 13], 0.0843, atol = 0.0001)

    # test helper functions for individual rice diseases
    bbmodel = bacterialblight(wth = w, emergence = "2010-07-01")
    @test nrow(bbmodel) == 120
    @test ncol(bbmodel) == 16
    @test isapprox(bbmodel[120, 13], 0.45708, atol = 0.0001)

    bsmodel = brownspot(wth = w, emergence = "2010-07-01")
    @test nrow(bsmodel) == 120
    @test ncol(bsmodel) == 16
    @test isapprox(bsmodel[120, 13], 0.0843, atol = 0.0001)

    lbmodel = leafblast(wth = w, emergence = "2010-07-01")
    @test nrow(lbmodel) == 120
    @test ncol(lbmodel) == 16
    @test isapprox(lbmodel[120, 13], 5.81269e-6, atol = 0.0001)

    sbmodel = sheathblight(wth = w, emergence = "2010-07-01")
    @test nrow(sbmodel) == 120
    @test ncol(sbmodel) == 16
    @test isapprox(sbmodel[120, 13], 0.78539, atol = 0.0001)

    tmodel = tungro(wth = w, emergence = "2010-07-01")
    @test nrow(tmodel) == 120
    @test ncol(tmodel) == 16
    @test isapprox(tmodel[120, 13], 0.07564, atol = 0.0001)

end


text:
using NiLang, Test, NiLang.AD

@testset "loaddata" begin
    @test NiLang.loaddata(GVar(0.1), 0.3) == GVar(0.3)
    @test NiLang.loaddata(Complex(GVar(0.1, 0.2), GVar(0.2)), 0.3+0.6im) == Complex(GVar(0.3), GVar(0.6))
    @test NiLang.loaddata(typeof(Complex(GVar(0.1, 0.2), GVar(0.2))), 0.3+0.6im) == Complex(GVar(0.3), GVar(0.6))
    @test NiLang.loaddata(GVar(0.2, AutoBcast{Float64,3}(zeros(3))), 0.3) == GVar(0.3, AutoBcast{Float64,3}(zeros(3)))
    @test NiLang.loaddata((GVar(0.2, AutoBcast{Float64,3}(zeros(3))), 7), (0.3, 4)) == (GVar(0.3, AutoBcast{Float64,3}(zeros(3))), 4)
    @test NiLang.loaddata(typeof((GVar(0.2, AutoBcast{Float64,3}(zeros(3))), 7)), (0.3, 4)) == (GVar(0.3, AutoBcast{Float64,3}(zeros(3))), 4)
    @test NiLang.loaddata(4, 2.0) == 2
end

@testset "push load" begin
    x = (0.3, 3.0, [1,2,3.0])
    @instr PUSH!(x)
    t = (0.0, 0.0, Float64[])
    @test x == t && typeof(x) == typeof(t)
    y = (0.0, GVar(0.0), GVar{Float64,Float64}[])
    @instr POP!(y)
    t = (0.3, GVar(3.0), GVar([1,2, 3.0]))
    @test y == t && typeof(y) == typeof(t)

    x = [0.3, 3.0, [1,2,3.0]]
    @instr PUSH!(x)
    t = []
    @test x == t && typeof(x) == typeof(t)
    y = []
    @instr POP!(y)
    t = [0.3, GVar(3.0), GVar([1,2, 3.0])]
    @test y == t && typeof(y) == typeof(t)

    x = (0.3, 3.0, [1,2,3.0])
    @instr @invcheckoff PUSH!(x)
    t = (0.0, 0.0, Float64[])
    @test x == t && typeof(x) == typeof(t)
    y = (0.0, GVar(0.0), GVar(zeros(0)))
    @instr @invcheckoff POP!(y)
    t = (0.3, GVar(3.0), GVar([1,2, 3.0]))
    @test y == t && typeof(y) == typeof(t)

    x = (0.3, 3.0, [1,2,3.0])
    @instr @invcheckoff COPYPUSH!(x)
    t = (0.3, 3.0, [1,2,3.0])
    @test x == t && typeof(x) == typeof(t)
    y = (0.3, GVar(t[2]), GVar(t[3]))
    @instr @invcheckoff COPYPOP!(y)
    t = (0.3, GVar(3.0), GVar([1,2, 3.0]))
    @test y == t && typeof(y) == typeof(t)

    x = (0.3, 3.0, [1,2,3.0])
    @instr COPYPUSH!(x)
    t = (0.3, 3.0, [1,2,3.0])
    @test x == t && typeof(x) == typeof(t)
    y = (0.3, GVar(t[2]), GVar(t[3]))
    @instr COPYPOP!(y)
    t = (0.3, GVar(3.0), GVar([1,2, 3.0]))
    @test y == t && typeof(y) == typeof(t)

    x = [0.3, 3.0, [1,2,3.0]]
    @instr COPYPUSH!(x)
    t = [0.3, 3.0, [1,2,3.0]]
    @test x == t && typeof(x) == typeof(t)
    y = [0.3, GVar(t[2]), GVar(t[3])]
    @instr COPYPOP!(y)
    t = [0.3, GVar(3.0), GVar([1,2, 3.0])]
    @test y == t && typeof(y) == typeof(t)
end


text:
import Base.==

"""

LDict is an ordered dictionary. It is assumed to be used in the field name => field mapping. In practice, the number of columns is not that long, and it is more efficient to implement LDict as 2 vectors, one for keys and one for values.

### Constructors

```julia
LDict{K,V}(dict::Associative{K, V}) # LDict from a dictionary dict. The result order is undetermined.
LDict{K,V}(dict::Associative{K, V}, ks) # LDict from a dictionary dict. ks is a vector of keys, and the keys in the result are ordered in that way. An error is thrown if one of ks is not found in dict.
LDict{K,V}(ks::Vector{K}, vs::Vector{V})
LDict(ps::Pair...)
LDict(ps::Tuple...)
```

"""
immutable LDict{K,V} <: Associative{K,V}
  keys::Vector{K}
  values::Vector{V}

  LDict() = new(Vector{K}(), Vector{V}())
  LDict(ks::Vector{K}, vs::Vector{V}) =
    if length(ks) == length(vs)
      new(ks, vs)
    else
      throw(ArgumentError("LDict: keys anvd values have different lengths. keys: ", ks, ", values: ", values))
    end
end

LDict(ks::Vector, vs::Vector) = begin
  try
    typed_keys = type_array(ks)
    typed_values = type_array(vs)
    LDict{eltype(typed_keys),eltype(typed_values)}(typed_keys, typed_values)
  catch e
    if isa(e, UndefRefError)
      LDict{eltype(ks), eltype(vs)}(ks, vs)
    else
      rethrow(e)
    end
  end
end

# sometimes checking types is too expensive. this version just creates an LDict without type checking.
create_ldict_nocheck() = LDict{Any,Any}()
create_ldict_nocheck(ks::Vector, vs::Vector) = LDict{eltype(ks), eltype(vs)}(ks, vs)
create_ldict_nocheck(ps::Pair...) = create_ldict_nocheck(type_array([x.first for x in ps]), type_array([x.second for x in ps]))
create_ldict_nocheck(ps::Tuple...) = create_ldict_nocheck(type_array([x[1] for x in ps]), type_array([x[2] for x in ps]))
create_ldict_nocheck(dict::Associative) = create_ldict_nocheck(collect(keys(dict)), collect(values(dict)))
create_ldict_nocheck{K,V}(dict::Associative{K,V}, ks::Vector{K}) = begin
  dict_keys = collect(keys(dict))
  dict_values = collect(values(dict))
  create_ldict_nocheck(ks, map(k->dict_values[findfirst(dict_keys, k)],ks))
end

LDict() = LDict{Any,Any}()
LDict(ps::Pair...) = LDict(type_array([x.first for x in ps]), type_array([x.second for x in ps]))
LDict(ps::Tuple...) = LDict(type_array([x[1] for x in ps]), type_array([x[2] for x in ps]))
LDict(dict::Associative) = LDict(collect(keys(dict)), collect(values(dict)))
LDict{K,V}(dict::Associative{K,V}, ks::Vector{K}) = begin
  dict_keys = collect(keys(dict))
  dict_values = collect(values(dict))
  LDict(ks, map(k->dict_values[findfirst(dict_keys, k)],ks))
end

# for iteration.
Base.start(::LDict) = 1
Base.next(ldict::LDict, state) = (Pair(ldict.keys[state], ldict.values[state]), state+1)
Base.done(ldict::LDict, s) = s > length(ldict)

Base.length(ldict::LDict) = length(ldict.keys)
Base.eltype{K, V}(::Type{LDict{K, V}}) = Pair{K, V}

Base.keys(dict::LDict) = dict.keys
Base.values(dict::LDict) = dict.values

"""

`merge(dict::LDict, ds...)`

Combine an `LDict` `dict` with `Associative` `ds`'s.
The subsequent elements in ds will either update the preceding one, or append the key-value pair.

##### Examples

```julia
julia> merge(LDict(:a=>3, :b=>5), Dict(:b=>"X", :c=>"Y"), LDict(:c=>'x', 'd'=>'y'))
MultidimensionalTables.LDict{Any,Any} with 4 entries:
  :a  => 3
  :b  => "X"
  :c  => 'x'
  'd' => 'y'
```

"""
Base.merge(dict::LDict, ds::Associative...) = begin
  keys = copy(dict.keys)
  values = copy(dict.values)
  keytype = eltype(keys)
  valuetype = eltype(values)
  for d in ds
    for (k,v) in d
      ind = findfirst(keys, k)
      if ind > 0
        if isa(v, valuetype)
          values[ind] = v
        else
          valuetype = promote_type(valuetype, typeof(v))
          newvalues = similar(values, valuetype, length(values))
          copy!(newvalues, values)
          values = newvalues
          values[ind] = v
        end
      else
        if isa(k, keytype)
          push!(keys, k)
        else
          keytype = promote_type(keytype, typeof(k))
          newkeys = similar(keys, keytype, length(keys)+1)
          copy!(newkeys, keys)
          keys = newkeys
          keys[end] = k
        end
        if isa(v, valuetype)
          push!(values, v)
        else
          valuetype = promote_type(valuetype, typeof(v))
          newvalues = similar(values, valuetype, length(values) + 1)
          copy!(newvalues, values)
          values = newvalues
          values[end] = v
        end
      end
    end
  end
  LDict(keys, values)
end

"""

`deletekeys(dict::LDict, keys...)`

Delete `keys` keys from `dict`. A missing key will be silently ignored.

```julia
julia> deletekeys(LDict(:a=>3, :b=>5, :c=>10), :a, :b, :x)
MultidimensionalTables.LDict{Symbol,Int64} with 1 entry:
  :c => 10
```

"""
deletekeys{K,V}(dict::LDict{K,V}, keys...) = begin
  dictkeys = dict.keys
  dictvalues = dict.values
  newkeys = K[]
  newvalues = V[]
  for (k,v) in dict
    ind = findfirst(keys, k)
    if ind==0
      push!(newkeys, k)
      push!(newvalues, v)
    end
  end
  LDict(newkeys, newvalues)
end

"""

`selectkeys(dict::LDict, keys...)`

Select `keys` keys from `dict`. A missing key will raise an error.

##### Examples

```julia
julia> selectkeys(LDict(:a=>3, :b=>5, :c=>10), :a, :b)
MultidimensionalTables.LDict{Symbol,Int64} with 2 entries:
  :a => 3
  :b => 5
```

"""
selectkeys{K,V}(dict::LDict{K,V}, keys...) = begin
  dictkeys = dict.keys
  dictvalues = dict.values
  LDict(collect(keys), [dictvalues[findfirst(dictkeys, k)] for k in keys])
end

# implement some basic functionalities for dictionaries.
Base.get{K,V}(ldict::LDict{K,V}, key::K, _) = begin
  intind = findfirst(ldict.keys, key)
  if intind <=0
    throw(BoundsError(ldict, key))
  else
    ldict.values[intind]::V
  end
end

Base.get!{K,V}(ldict::LDict{K,V}, key::K, value::V) = begin
  intind = findfirst(ldict.keys, key)
  if intind <=0
    push!(ldict.keys, key)
    push!(ldict.values, value)
    value::V
  else
    ldict.values[intind]::V
  end
end

Base.setindex!{K,V}(ldict::LDict{K,V}, value::V, key::K) = begin
  intind = findfirst(ldict.keys, key)
  if intind <=0
    push!(ldict.keys, key)
    push!(ldict.values, value)
    value
  else
    ldict.values[intind] = value
    value
  end
end

function ==(x::LDict, y::LDict)
  length(x) == length(y) &&
    wrap_array(x.keys) == wrap_array(y.keys) &&
    wrap_array(x.values) == wrap_array(y.values)
end
Base.isequal(x::LDict, y::LDict) = x==y
Base.haskey(ldict::LDict, k) = 0 < findfirst(ldict.keys, k)

# igna applies igna to each value. Usually igna maps Nullable(x) to x and Nullable{T}() to any arbitrary value.
# it is meant to be used when you know there is no null value.
# However, the usage is not robust in the sense that you can apply igna to any nullable array.
# it is here now, but probably will be removed later.
igna(ldict::LDict, na_replace) = LDict(ldict.keys, igna(ldict.values, na_replace))
igna(ldict::LDict) = LDict(ldict.keys, map(igna, ldict.values))

isna{K,V<:AbstractArray}(ldict::LDict{K,V}) = reduce(&, map(isna, ldict.values))
isna{K,V}(ldict::LDict{K,V}) = all(map(isna, ldict.values))

Base.copy(ldict::LDict) = LDict(copy(ldict.keys), copy(ldict.values))
copy_arrayvalues(ldict::LDict) = LDict(copy(ldict.keys), map(copy, ldict.values))

# see array_util.jl for documentation.
mapvalues(f::Function, ldict::LDict) = try
  LDict(ldict.keys, map(f, ldict.values)) #[f(v) for v in ldict.values]) # for some reason, comprehension[] was much slower than map...
catch err
  # I found sometimes there is a type error, depending the order of execution.
  # Without knowing the reason precisely, I just put a try catch expression.
  # Hopefully, this will not impact the performance much.
  if isa(err, TypeError)
    buf = cell(length(ldict.values))
    map!(f, buf, ldict.values)
    LDict(ldict.keys, collect(simplify_array(buf)))
  else
    rethrow()
  end
end
Base.keys(ldict::LDict) = ldict.keys
Base.values(ldict::LDict) = ldict.values

"""

`reorder(ldict::LDict, ks...)`

Reorder the keys so that the first few keys are `ks`.

##### Examples

```julia
julia> reorder(LDict(:a=>1, :b=>2, :c=>3), :b, :c)
MultidimensionalTables.LDict{Symbol,Int64} with 3 entries:
  :b => 2
  :c => 3
  :a => 1
```

"""
reorder(ldict::LDict, ks...) = create_ldict_nocheck(ldict, [ks...;setdiff(ldict.keys, ks)])

"""

`rename(ldict::LDict, ks...)`

Renames the first few keys using `ks`.

##### Examples

```julia
julia> rename(LDict(:a=>1, :b=>2, :c=>3), :b, 'x')
MultidimensionalTables.LDict{Any,Int64} with 3 entries:
  :b  => 1
  'x' => 2
  :c  => 3
```

"""
rename(ldict::LDict, ks...) = create_ldict_nocheck([ks...;drop(ldict.keys, length(ks))...], ldict.values)


text:
function f_BS_equation(cur_reactor::AbstractReactor, cur_value::Number)
  cur_G_T = K_BS(cur_reactor)

  cur_G_T *= cur_reactor.T_bar

  cur_G_T /= cur_value

  cur_equation = Equation(0, 0, 1, cur_G_T)

  cur_equation
end


text:
"""
2D traveling wave solution for the Euler equations in a parallelogram domain

     --------
    /      /
   /      /
  /      /
 --------

δx = 1, δy = 0.5, θ = π / 4

Instability is somehow detected for order larger than 2.

"""

using KitBase, FluxReconstruction, LinearAlgebra, OrdinaryDiffEq, Plots
using KitBase.OffsetArrays
using KitBase.ProgressMeter: @showprogress
using Base.Threads: @threads
cd(@__DIR__)
pyplot()

set = Setup(
    case = "dev",
    space = "2d0f",
    flux = "hll",
    collision = "nothing",
    interpOrder = 2,
    limiter = "positivity",
    boundary = "euler",
    cfl = 0.1,
    maxTime = 1.0,
)

begin
    lx, ly = 1.0, 0.5
    x0 = 0.0
    x1 = x0 + lx
    nx = 30
    Δx = lx / nx
    y0 = 0.0
    y1 = y0 + ly
    ny = 15
    Δy = ly / ny

    vertices = OffsetArray{Float64}(undef, 0:nx+1, 0:ny+1, 4, 2)
    for j in axes(vertices, 2), i in axes(vertices, 1)
        vertices[i, j, 1, 1] = x0 + 0.5 * (j - 1) / ny + (i - 1) * Δx
        vertices[i, j, 2, 1] = vertices[i, j, 1, 1] + Δx
        vertices[i, j, 3, 1] = vertices[i, j, 2, 1] + Δy
        vertices[i, j, 4, 1] = vertices[i, j, 3, 1] - Δx

        vertices[i, j, 1, 2] = y0 + 0.5 * (j - 1) * Δy
        vertices[i, j, 2, 2] = vertices[i, j, 1, 2]
        vertices[i, j, 3, 2] = vertices[i, j, 1, 2] + Δy
        vertices[i, j, 4, 2] = vertices[i, j, 3, 2]
    end

    x = OffsetArray{Float64}(undef, 0:nx+1, 0:ny+1)
    y = similar(x)
    dx = similar(x)
    dy = similar(y)
    for i = 0:nx+1, j = 0:ny+1
        x[i, j] = (vertices[i, j, 1, 1] + vertices[i, j, 4, 1]) / 2 + Δx / 2
        y[i, j] = vertices[i, j, 1, 2] + 0.5 * Δy
        dx[i, j] = Δx
        dy[i, j] = Δy
    end

    ps0 = PSpace2D(x0, x1, nx, y0, y1, ny, x, y, dx, dy, vertices)
    deg = set.interpOrder - 1
    ps = FRPSpace2D(ps0, deg)
end

vs = nothing
gas = Gas(Kn = 1e-6, Ma = 0.0, K = 1.0)
ib = nothing
ks = SolverSet(set, ps0, vs, gas, ib)

function dudt!(du, u, p, t)
    iJ, ll, lr, dhl, dhr, lpdm, γ = p

    nx = size(u, 1) - 2
    ny = size(u, 2) - 2
    nsp = size(u, 3)

    f = OffsetArray{Float64}(undef, 0:nx+1, 0:ny+1, nsp, nsp, 4, 2)
    @inbounds @threads for i in axes(f, 1)
        for j in axes(f, 2), k = 1:nsp, l = 1:nsp
            fg, gg = euler_flux(u[i, j, k, l, :], γ)
            for m = 1:4
                f[i, j, k, l, m, :] .= iJ[i, j][k, l] * [fg[m], gg[m]]
            end
        end
    end

    u_face = OffsetArray{Float64}(undef, 0:nx+1, 0:ny+1, 4, nsp, 4)
    f_face = OffsetArray{Float64}(undef, 0:nx+1, 0:ny+1, 4, nsp, 4, 2)
    @inbounds @threads for i in axes(u_face, 1)
        for j in axes(u_face, 2), l = 1:nsp, m = 1:4
            u_face[i, j, 1, l, m] = dot(u[i, j, l, :, m], ll)
            u_face[i, j, 2, l, m] = dot(u[i, j, :, l, m], lr)
            u_face[i, j, 3, l, m] = dot(u[i, j, l, :, m], lr)
            u_face[i, j, 4, l, m] = dot(u[i, j, :, l, m], ll)

            for n = 1:2
                f_face[i, j, 1, l, m, n] = dot(f[i, j, l, :, m, n], ll)
                f_face[i, j, 2, l, m, n] = dot(f[i, j, :, l, m, n], lr)
                f_face[i, j, 3, l, m, n] = dot(f[i, j, l, :, m, n], lr)
                f_face[i, j, 4, l, m, n] = dot(f[i, j, :, l, m, n], ll)
            end
        end
    end

    fx_interaction = zeros(nx + 1, ny, nsp, 4)
    @inbounds @threads for i = 1:nx+1
        for j = 1:ny, k = 1:nsp
            fw = @view fx_interaction[i, j, k, :]
            uL = local_frame(u_face[i-1, j, 2, k, :], n1[i, j][1], n1[i, j][2])
            uR = local_frame(u_face[i, j, 4, k, :], n1[i, j][1], n1[i, j][2])
            flux_hll!(fw, uL, uR, γ, 1.0)
            fw .= global_frame(fw, n1[i, j][1], n1[i, j][2])
        end
    end
    fy_interaction = zeros(nx, ny + 1, nsp, 4)
    @inbounds @threads for i = 1:nx
        for j = 1:ny+1, k = 1:nsp
            fw = @view fy_interaction[i, j, k, :]
            uL = local_frame(u_face[i, j-1, 3, k, :], n2[i, j][1], n2[i, j][2])
            uR = local_frame(u_face[i, j, 1, k, :], n2[i, j][1], n2[i, j][2])
            flux_hll!(fw, uL, uR, γ, 1.0)
            fw .= global_frame(fw, n2[i, j][1], n2[i, j][2])
        end
    end

    rhs1 = zeros(nx, ny, nsp, nsp, 4)
    @inbounds @threads for i = 1:nx
        for j = 1:ny, k = 1:nsp, l = 1:nsp, m = 1:4
            rhs1[i, j, k, l, m] = dot(f[i, j, :, l, m, 1], lpdm[k, :])
        end
    end
    rhs2 = zeros(nx, ny, nsp, nsp, 4)
    @inbounds @threads for i = 1:nx
        for j = 1:ny, k = 1:nsp, l = 1:nsp, m = 1:4
            rhs2[i, j, k, l, m] = dot(f[i, j, k, :, m, 2], lpdm[l, :])
        end
    end

    @inbounds @threads for i = 1:nx
        for j = 1:ny, k = 1:nsp, l = 1:nsp, m = 1:4
            fxL = (iJ[i, j][k, l] * n1[i, j])[1] * fx_interaction[i, j, l, m]
            fxR = (iJ[i, j][k, l] * n1[i+1, j])[1] * fx_interaction[i+1, j, l, m]
            fyL = (iJ[i, j][k, l] * n2[i, j])[2] * fy_interaction[i, j, l, m]
            fyR = (iJ[i, j][k, l] * n2[i, j+1])[2] * fy_interaction[i, j+1, l, m]
            du[i, j, k, l, m] = -(
                rhs1[i, j, k, l, m] +
                rhs2[i, j, k, l, m] +
                (fxL - f_face[i, j, 4, l, m, 1]) * dhl[k] +
                (fxR - f_face[i, j, 2, l, m, 1]) * dhr[k] +
                (fyL - f_face[i, j, 1, k, m, 2]) * dhl[l] +
                (fyR - f_face[i, j, 3, k, m, 2]) * dhr[l]
            )
        end
    end

    return nothing
end

begin
    u0 = OffsetArray{Float64}(undef, 0:ps.nx+1, 0:ps.ny+1, deg + 1, deg + 1, 4)
    for i in axes(u0, 1), j in axes(u0, 2), k in axes(u0, 3), l in axes(u0, 4)
        ρ = 1.0 + 0.1 * sin(2π * i / ps.nx)
        prim = [ρ, 1.0, 0.0, ρ]
        u0[i, j, k, l, :] .= prim_conserve(prim, ks.gas.γ)
    end

    n1 = [[0.0, 0.0] for i = 1:ps.nx+1, j = 1:ps.ny]
    for i = 1:ps.nx+1, j = 1:ps.ny
        angle = -π / 4
        n1[i, j] .= [cos(angle), sin(angle)]
    end

    n2 = [[0.0, 0.0] for i = 1:ps.nx, j = 1:ps.ny+1]
    for i = 1:ps.nx, j = 1:ps.ny+1
        n2[i, j] .= [0.0, 1.0]
    end
end

tspan = (0.0, 1.0)
p = (ps.iJ, ps.ll, ps.lr, ps.dhl, ps.dhr, ps.dl, ks.gas.γ)
prob = ODEProblem(dudt!, u0, tspan, p)

dt = 0.001
nt = tspan[2] ÷ dt |> Int
itg = init(prob, Euler(), save_everystep = false, adaptive = false, dt = dt)
sol0 = zeros(ps.nx, ps.ny, 4)
for i = 1:ps.nx, j = 1:ps.ny
    sol0[i, j, :] .= conserve_prim(itg.u[i, j, 2, 2, :], ks.gas.γ)
    sol0[i, j, 4] = 1 / sol0[i, j, 4]
end

@showprogress for iter = 1:nt÷2
    # bcs
    itg.u[0, :, :, :, :] .= itg.u[ps.nx, :, :, :, :]
    itg.u[ps.nx+1, :, :, :, :] .= itg.u[1, :, :, :, :]
    itg.u[:, 0, :, :, :] .= itg.u[:, ps.ny, :, :, :]
    itg.u[:, ps.ny+1, :, :, :] .= itg.u[:, 1, :, :, :]

    step!(itg)
end

begin
    sol = zeros(ps.nx, ps.ny, 4)
    for i = 1:ps.nx, j = 1:ps.ny
        sol[i, j, :] .= conserve_prim(itg.u[i, j, 2, 2, :], ks.gas.γ)
        sol[i, j, 4] = 1 / sol[i, j, 4]
    end

    idx = 1
    plot(ps.x[1:ps.nx, 1], sol0[1:ps.nx, 10, idx])
    plot!(ps.x[1:ps.nx, 1], sol[1:ps.nx, 10, idx])
end
contourf(ps.x[1:ps.nx, 1:ps.ny], ps.y[1:ps.nx, 1:ps.ny], sol[1:ps.nx, 1:ps.ny, 4])


text:
import Crayons;
import OhMyREPL

function colorscheme_elflord()
	color_scheme = OhMyREPL.Passes.SyntaxHighlighter.ColorScheme()

	# Keyword
	OhMyREPL.Passes.SyntaxHighlighter.keyword!(color_scheme, Crayons.Crayon(foreground = :white, bold=true))

	# Number
	OhMyREPL.Passes.SyntaxHighlighter.number!(color_scheme, Crayons.Crayon(foreground = :white, bold=true))

	# Text
	OhMyREPL.Passes.SyntaxHighlighter.text!(color_scheme, Crayons.Crayon(foreground = :light_gray, bold=false))

	# Symbol
	OhMyREPL.Passes.SyntaxHighlighter.symbol!(color_scheme, Crayons.Crayon(foreground = :magenta, bold=true))

	# String
	OhMyREPL.Passes.SyntaxHighlighter.string!(color_scheme, Crayons.Crayon(foreground = :light_magenta, bold=true))

	# Operators
	OhMyREPL.Passes.SyntaxHighlighter.op!(color_scheme, Crayons.Crayon(foreground = :light_cyan, bold=true))

	# Macros
	OhMyREPL.Passes.SyntaxHighlighter.macro!(color_scheme, Crayons.Crayon(foreground = :light_green, bold=true))

	# Comment
	OhMyREPL.Passes.SyntaxHighlighter.comment!(color_scheme, Crayons.Crayon(foreground = :dark_gray, bold=true))

	# Argument definitions
	OhMyREPL.Passes.SyntaxHighlighter.argdef!(color_scheme, Crayons.Crayon(foreground = :light_blue, bold=true))

	# Function definitions
	OhMyREPL.Passes.SyntaxHighlighter.function_def!(color_scheme, Crayons.Crayon(foreground = :default, bold=true))

	# Function call
	OhMyREPL.Passes.SyntaxHighlighter.call!(color_scheme, Crayons.Crayon(foreground = :default, bold=true))

	# Error
	OhMyREPL.Passes.SyntaxHighlighter.error!(color_scheme, Crayons.Crayon(foreground = :light_red, bold=false))

	return color_scheme
end

function colorscheme_Mustang()
	color_scheme = OhMyREPL.Passes.SyntaxHighlighter.ColorScheme()

	# Keyword
	OhMyREPL.Passes.SyntaxHighlighter.keyword!(color_scheme, Crayons.Crayon(foreground = :050, bold=false))

	# Number
	OhMyREPL.Passes.SyntaxHighlighter.number!(color_scheme, Crayons.Crayon(foreground = :208, bold=true))

	# Text
	OhMyREPL.Passes.SyntaxHighlighter.text!(color_scheme, Crayons.Crayon(foreground = :252, bold=false))

	# Symbol
	OhMyREPL.Passes.SyntaxHighlighter.symbol!(color_scheme, Crayons.Crayon(foreground = :149, bold=true))

	# String
	OhMyREPL.Passes.SyntaxHighlighter.string!(color_scheme, Crayons.Crayon(foreground = :149, bold=true))

	# Operators
	OhMyREPL.Passes.SyntaxHighlighter.op!(color_scheme, Crayons.Crayon(foreground = :254, bold=false))

	# Macros
	OhMyREPL.Passes.SyntaxHighlighter.macro!(color_scheme, Crayons.Crayon(foreground = :191, bold=true))

	# Comment
	OhMyREPL.Passes.SyntaxHighlighter.comment!(color_scheme, Crayons.Crayon(foreground = :244, bold=false))

	# Argument definitions
	OhMyREPL.Passes.SyntaxHighlighter.argdef!(color_scheme, Crayons.Crayon(foreground = :105, bold=true))

	# Function definitions
	OhMyREPL.Passes.SyntaxHighlighter.function_def!(color_scheme, Crayons.Crayon(foreground = :light_gray, bold=true))

	# Function call
	OhMyREPL.Passes.SyntaxHighlighter.call!(color_scheme, Crayons.Crayon(foreground = :254, bold=true))

	# Error
	OhMyREPL.Passes.SyntaxHighlighter.error!(color_scheme, Crayons.Crayon(foreground = :196, bold=true))

	return color_scheme
end

function colorscheme_wuye()
	color_scheme = OhMyREPL.Passes.SyntaxHighlighter.ColorScheme()

	# Keyword
	OhMyREPL.Passes.SyntaxHighlighter.keyword!(color_scheme, Crayons.Crayon(foreground = :086, bold=true))

	# Number
	OhMyREPL.Passes.SyntaxHighlighter.number!(color_scheme, Crayons.Crayon(foreground = :051, bold=true))

	# Text
	OhMyREPL.Passes.SyntaxHighlighter.text!(color_scheme, Crayons.Crayon(foreground = :252, bold=false))

	# Symbol
	OhMyREPL.Passes.SyntaxHighlighter.symbol!(color_scheme, Crayons.Crayon(foreground = :199, bold=true))

	# String
	OhMyREPL.Passes.SyntaxHighlighter.string!(color_scheme, Crayons.Crayon(foreground = :199, bold=true))

	# Operators
	OhMyREPL.Passes.SyntaxHighlighter.op!(color_scheme, Crayons.Crayon(foreground = :51, bold=false))

	# Macros
	OhMyREPL.Passes.SyntaxHighlighter.macro!(color_scheme, Crayons.Crayon(foreground = :163, bold=true))

	# Comment
	OhMyREPL.Passes.SyntaxHighlighter.comment!(color_scheme, Crayons.Crayon(foreground = :244, bold=false))

	# Argument definitions
	OhMyREPL.Passes.SyntaxHighlighter.argdef!(color_scheme, Crayons.Crayon(foreground = :039, bold=false))

	# Function definitions
	OhMyREPL.Passes.SyntaxHighlighter.function_def!(color_scheme, Crayons.Crayon(foreground = :254, bold=true))

	# Function call
	OhMyREPL.Passes.SyntaxHighlighter.call!(color_scheme, Crayons.Crayon(foreground = :051, bold=true))

	# Error
	OhMyREPL.Passes.SyntaxHighlighter.error!(color_scheme, Crayons.Crayon(foreground = :196, bold=true))

	return color_scheme
end

function apply_colorscheme(cs)

	# Apply colorscheme
	OhMyREPL.Passes.SyntaxHighlighter.add!("cs", cs)
	OhMyREPL.colorscheme!("cs")

	# Set bracket highlighting
	c = Crayons.Crayon(background = :black, foreground=:black, bold = true)
	OhMyREPL.Passes.BracketHighlighter.setcrayon!(c)

	# Bracket autocompletion off
	OhMyREPL.enable_autocomplete_brackets(false)

	# Prompt
	OhMyREPL.input_prompt!("julia>", :light_green)
	#OhMyREPL.output_prompt!("", :white)
end

# Apply colorscheme
# One can view the available colors with > Crayons.test_256_colors()
#cs = colorscheme_Mustang()
cs = colorscheme_wuye()
apply_colorscheme(cs)


text:
# Copyright (C) 2020 Argonne National Laboratory
# Written by Alinson Santos Xavier <axavier@anl.gov>

using RELOG

@testset "compress" begin
    basedir = dirname(@__FILE__)
    instance = RELOG.parsefile("$basedir/../../instances/s1.json")
    compressed = RELOG._compress(instance)

    product_name_to_product = Dict(p.name => p for p in compressed.products)
    location_name_to_facility = Dict()
    for p in compressed.plants
        location_name_to_facility[p.location_name] = p
    end
    for c in compressed.collection_centers
        location_name_to_facility[c.name] = c
    end

    p1 = product_name_to_product["P1"]
    p2 = product_name_to_product["P2"]
    p3 = product_name_to_product["P3"]
    c1 = location_name_to_facility["C1"]
    l1 = location_name_to_facility["L1"]

    @test compressed.time == 1
    @test compressed.building_period == [1]

    @test p1.name == "P1"
    @test p1.transportation_cost ≈ [0.015]
    @test p1.transportation_energy ≈ [0.115]
    @test p1.transportation_emissions["CO2"] ≈ [0.051]
    @test p1.transportation_emissions["CH4"] ≈ [0.0025]

    @test c1.name == "C1"
    @test c1.amount ≈ [1869.12]

    @test l1.plant_name == "F1"
    @test l1.location_name == "L1"
    @test l1.energy ≈ [0.115]
    @test l1.emissions["CO2"] ≈ [0.051]
    @test l1.emissions["CH4"] ≈ [0.0025]
    @test l1.sizes[1].opening_cost ≈ [500]
    @test l1.sizes[2].opening_cost ≈ [1250]
    @test l1.sizes[1].fixed_operating_cost ≈ [60]
    @test l1.sizes[2].fixed_operating_cost ≈ [60]
    @test l1.sizes[1].variable_operating_cost ≈ [30]
    @test l1.sizes[2].variable_operating_cost ≈ [30]
    @test l1.disposal_limit[p2] ≈ [2.0]
    @test l1.disposal_limit[p3] ≈ [2.0]
    @test l1.disposal_cost[p2] ≈ [-10.0]
    @test l1.disposal_cost[p3] ≈ [-10.0]
end

max_stars_repo_name: ANL-CEEESA/RELOG

max_issues_repo_name: ANL-CEEESA/RELOG

max_forks_repo_name: ANL-CEEESA/RELOG


text:
using Documenter
using NeXLCore

function addNISTHeaders(htmlfile::String)
    # read HTML
    html = transcode(String,read(htmlfile))
    # Find </head>
    i = findfirst(r"</[Hh][Ee][Aa][Dd]>", html)
    # Already added???
    j = findfirst("nist-header-footer", html)
    if isnothing(j) && (!isnothing(i))
        # Insert nist-pages links right before </head>
        res = html[1:i.start-1]*
            "<link rel=\"stylesheet\" href=\"https://pages.nist.gov/nist-header-footer/css/nist-combined.css\">\n"*
            "<script src=\"https://pages.nist.gov/nist-header-footer/js/jquery-1.9.0.min.js\" type=\"text/javascript\" defer=\"defer\"></script>\n"*
            "<script src=\"https://pages.nist.gov/nist-header-footer/js/nist-header-footer.js\" type=\"text/javascript\" defer=\"defer\"></script>\n"*
            html[i.start:end]
        write(htmlfile, res)
        println("Inserting NIST header/footer into $htmlfile")
    end
    return htmlfile
end

include(joinpath("..","weave","buildweave.jl"))

pages = [
            # "Start Page" => "index.md",
            "Getting Started" => "gettingstarted.md",
            "Bremsstrahlung" => "bremsstrahlung.md",
            "Mass Fraction Uncertainty" => "Au60Ag40unc.md",
            "Backscatter" => "eta.md",
            "Fluorescence Yield" => "fluoryield.md",
            "O by Stoichiometry" => "OByStoic.md",
            "Mean Ionization Potential" => "meanionizationpotential.md",
            "API: Structures and Methods" => "methods.md"
         ]

makedocs(
    doctest=false,
    sitename = "NeXLCore",
    modules = [ NeXLCore ],
    pages = pages
)

addNISTHeaders(joinpath(@__DIR__, "build","index.html"))
addNISTHeaders.(map(name->joinpath(@__DIR__, "build", splitext(name)[1], "index.html"), map(p->p.second, pages)))

rm.(joinpath(@__DIR__,"src",page[2]) for page in pages[2:end])

# deploydocs(repo = "github.com/JuliaLang/NeXLCore.jl.git")


text:
module JuDO

import Base: show
import Dates: DateTime, unix2datetime, now
import HTTP
import JSON: parse, json

export AbstractClient, Client

export Account, getaccount!
export Action, getallactions!, getaction!
export Volume, VolumeSnapshot, getallvolumes!, createvolume!, getvolume!,
       getallvolumesnapshots!, snapshotvolume!, deletevolume!,
       attachvolume!, removevolume!, resizevolume!, getallvolumeactions!,
       getvolumeaction!, deletevolumesnapshot!
export Certificate, getallcertificates!, getcertificate!, createcertificate!,
       deletecertificate!
export Domain, getalldomains!, createdomain!, getdomain!, deletedomain!
export Record, getalldomainrecords!, getdomainrecord!, createdomainrecord!,
       updatedomainrecord!, deletedomainrecord!
export Droplet, getalldroplets!, getdropletsbytag!, getdroplet!, createdroplet!,
       createdroplets!, getalldropletkernels!, getalldropletsnapshots!,
       getalldropletbackups!, deletedroplet!, getdropletneighbors!,
       getalldropletneighbors!

include("client.jl")
include("regions.jl")

include("account.jl")
include("actions.jl")
include("certificates.jl")
include("domains.jl")
include("images.jl")
include("records.jl")
include("sizes.jl")
include("ssh_keys.jl")
include("volumes.jl")

include("droplets.jl")

end # module


text:
using Manifolds, ManifoldsBase, Documenter

makedocs(
    # for development, we disable prettyurls
    format = Documenter.HTML(prettyurls = false),
    modules = [Manifolds, ManifoldsBase],
    authors = "Seth Axen, Mateusz Baran, Ronny Bergmann, and contributors.",
    sitename = "Manifolds.jl",
    pages = [
        "Home" => "index.md",
        "ManifoldsBase.jl" => "interface.md",
        "Manifolds" => [
            "Basic manifolds" => [
                "Cholesky space" => "manifolds/choleskyspace.md",
                "Circle" => "manifolds/circle.md",
                "Euclidean" => "manifolds/euclidean.md",
                "Fixed-rank matrices" => "manifolds/fixedrankmatrices.md",
                "Generalized Stiefel" => "manifolds/generalizedstiefel.md",
                "Generalized Grassmann" => "manifolds/generalizedgrassmann.md",
                "Grassmann" => "manifolds/grassmann.md",
                "Hyperbolic space" => "manifolds/hyperbolic.md",
                "Lorentzian manifold" => "manifolds/lorentz.md",
                "Oblique manifold" => "manifolds/oblique.md",
                "Rotations" => "manifolds/rotations.md",
                "Skew-symmetric matrices" => "manifolds/skewsymmetric.md",
                "Sphere" => "manifolds/sphere.md",
                "Stiefel" => "manifolds/stiefel.md",
                "Symmetric matrices" => "manifolds/symmetric.md",
                "Symmetric positive definite" => "manifolds/symmetricpositivedefinite.md",
                "Torus" => "manifolds/torus.md"
            ],
            "Combined manifolds" => [
                "Graph manifold" => "manifolds/graph.md",
                "Power manifold" => "manifolds/power.md",
                "Product manifold" => "manifolds/product.md",
                "Vector bundle" => "manifolds/vector_bundle.md"
            ],
            "Manifold decorators" => [
                "Metric manifold" => "manifolds/metric.md",
                "Group manifold" => "manifolds/group.md"
            ]
        ],
        "Statistics" => "statistics.md",
        "Distributions" => "distributions.md",
        "Notation" => "notation.md",
        "Library" => [
            "Public" => "lib/public.md",
            "Internals" => "lib/internals.md",
            "Automatic differentiation" => "lib/autodiff.md"
        ]
    ]
)

deploydocs(
    repo = "github.com/JuliaManifolds/Manifolds.jl.git",
    push_preview = true,
)


text:
#-------------------------------------------------------------------------------
# File: data.jl
# Description: This files contains data that is used for experiment.
# Date: November 17, 2019
# Authors: Killian Fretaud, Rémi Garcia,
#-------------------------------------------------------------------------------

function data()
    P2_2 = [1 4; 3 2]
    P2_3 = [1 4 2; 3 2 1]
    P3_3 = [1 4 2; 3 2 1; 6 2 1]
    P4_4 = [6 1 2 3; 2 3 2 1; 4 6 2 1; 5 3 2 3]
    P4_5 = [6 1 2 3 2; 2 3 5 2 1; 4 6 3 2 1; 4 5 3 2 3]
    P4_5_bis = [1 1 1 1 1; 2 4 5 1 2; 2 6 1 2 3; 1 2 2 1 2]

    T2 = [2, 3, 1]
    T3 = [1, 1, 2, 1]
    T4 = [2, 3, 1, 5, 1]
    T5 = [2, 3, 1, 5, 1, 1]
    T5_bis = [3, 1, 2, 1, 1, 3]

    list_instances = [
        Instance(2, 2, T2, P2_2),
        Instance(2, 3, T3, P2_3),
        Instance(3, 3, T3, P3_3),
        Instance(4, 4, T4, P4_4)
        #Instance(4, 5, T5, P4_5),
        #Instance(4, 5, T5_bis, P4_5_bis)
    ]

    list_instances_equi = [
        Instance(2, 2, ones(Int, 3), P2_2),
        Instance(2, 3, ones(Int, 4), P2_3),
        Instance(3, 3, ones(Int, 4), P3_3),
        Instance(4, 4, ones(Int, 5), P4_4)
    #    Instance(4, 5, ones(Int, 5), P4_5),
    #    Instance(4, 5, ones(Int, 5), P4_5_bis)
    ]

    println("\n***** Instances loaded *****\n")

    return list_instances, list_instances_equi
end

max_stars_repo_name: k-fretaud/Flowshop-robotic-cell

max_issues_repo_name: k-fretaud/Flowshop-robotic-cell

max_forks_repo_name: k-fretaud/Flowshop-robotic-cell


text:
using DSPopt
using StructJuMP

NS = 3;                        # number of scenarios
probability = [1/3, 1/3, 1/3]; # probability

CROPS  = 1:3 # set of crops (wheat, corn and sugar beets, resp.)
PURCH  = 1:2 # set of crops to purchase (wheat and corn, resp.)
SELL   = 1:4 # set of crops to sell (wheat, corn, sugar beets under 6K and those over 6K)

Cost     = [150., 230., 260.]    # cost of planting crops
Budget   = 500.                # budget capacity
Purchase = [238., 210.];        # purchase price
Sell     = [170., 150., 36., 10.] # selling price
Yield    = [3.0 3.6 24.0;
            2.5 3.0 20.0;
            2.0 2.4 16.0]
Minreq   = [200., 240., 0.]      # minimum crop requirement

# JuMP model
m = StructuredModel(num_scenarios = NS)

@variable(m, x[i=CROPS] >= 0, Int)
@objective(m, Min, sum(Cost[i] * x[i] for i=CROPS))
@constraint(m, sum(x[i] for i=CROPS) <= Budget)

for s in 1:NS
    blk = StructuredModel(parent = m, id = s, prob = probability[s])
    @variable(blk, y[j=PURCH] >= 0)
    @variable(blk, w[k=SELL] >= 0)
    @objective(blk, Min,
          sum(Purchase[j] * y[j] for j=PURCH)
        - sum(Sell[k] * w[k] for k=SELL))
    @constraint(blk, const_minreq[j=PURCH], Yield[s,j] * x[j] + y[j] - w[j] >= Minreq[j])
    @constraint(blk, const_minreq_beets, Yield[s,3] * x[3] - w[3] - w[4] >= Minreq[3])
    @constraint(blk, const_aux, w[3] <= 6000)

    # farmer.txt: quadratic constraints
    @constraint(blk, const_quad, w[1]^2 <= 1600)
end

@testset "optimize!: $j" for j in [DSPopt.Dual, DSPopt.ExtensiveForm] #instances(DSPopt.Methods)

    dsp.is_stochastic = true

    status = DSPopt.optimize!(m, is_stochastic = true, solve_type = j)
    @test DSPopt.termination_status(m) == MOI.OPTIMAL
    @test isapprox(dual_objective_value(m), -105093.3333333334, rtol=0.1)

    primsol = value()
    dualsol = dual()

    print("Optimal objective value: ", objective_value(m), "\n")
    print("Dual objective value: ", dual_objective_value(m), "\n")
    # print("Optimal primal solution: \n")
    # print(primsol, "\n")
    DSPopt.freeSolver(dsp)
    @testset "freeModel" begin
        DSPopt.freeModel(dsp)
        @test dsp.p != C_NULL
        @test length(dsp.numRows) == 0
        @test length(dsp.numCols) == 0
        @test isnan(dsp.primVal)
        @test isnan(dsp.dualVal)
        @test length(dsp.colVal) == 0
        @test length(dsp.rowVal) == 0
        @test dsp.nblocks == -1
        @test dsp.block_ids == []
        @test dsp.is_stochastic == false
        @test dsp.solve_type == DSPopt.Dual
        @test length(dsp.quadConstrs) == 0
        @test length(dsp.linConstrs) == 0
    end
end

# @testset "writeFile" begin
#     DSPopt.writeMps!(m, "farmer", is_stochastic = true)
#     @test isfile("farmer.mps")
# end


text:
# Copyright 2013 Peter Chronz
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

module OpenFlow
# TODO Write a macro that prints infos only in debug mode.
# TODO Controller-initiated messages.
# TODO Use the improved bytesconstructor macro on the types that require
# factory methods.
# TODO Break down the large macros into functions.
# TODO Convenience constructors to expose via API without header creation.
# TODO Promotion for type creation or at least generic external constructors.
# TODO License
# TODO Command line interface.
# TODO TLS
# TODO Dictionary for the constants for pretty printing.
# TODO Use get/setfield() for field access.
# TODO Use rpad when creating strings to be converted to Bytes. Actually combine
# rpad and ascii.
# TODO Document the core code.
# TODO How to disable all of the potentially slowing assertions when running in production?
# TODO Extend @string to provide show method.
# TODO Try out using hex2bytes(hex(Int)) and the other way round for
# (de)serialization.

include("incl/constants.jl")

# We will be using a lot of byte/octect arrays here
typealias Bytes Vector{Uint8}

bytes(byts::Bytes) = byts
function bytes(ui::Uint8)
    [ui]
end
bytes(s::ASCIIString) = Uint8[int(c) for c in s]
function bytes(ui::Uint16)
    byts = zeros(Uint8, 2)
    byts[1] = uint8(ui >> 8)
    byts[2] = uint8(ui)
    byts
end
function bytes(ui::Uint32)
    byts = zeros(Uint8, 4)
    byts[1] = uint8(ui >> 24)
    byts[2] = uint8(ui >> 16)
    byts[3] = uint8(ui >> 8)
    byts[4] = uint8(ui)
    byts
end
function bytes(ui::Uint64)
    byts = zeros(Uint8, 8)
    byts[1] = uint8(ui >> 56)
    byts[2] = uint8(ui >> 48)
    byts[3] = uint8(ui >> 40)
    byts[4] = uint8(ui >> 32)
    byts[5] = uint8(ui >> 24)
    byts[6] = uint8(ui >> 16)
    byts[7] = uint8(ui >> 8)
    byts[8] = uint8(ui)
    byts
end

give_length(arr::Bytes) = length(arr)
include("incl/macros.jl")
include("incl/ofptypes.jl")

function assemblemessage(header::OfpHeader, body::Bytes)
    if header.msgtype == OFPT_HELLO
        if length(body) != 0
            return nothing
        else
            return OfpEmptyMessage(header)
        end
    elseif header.msgtype == OFPT_ERROR
        return OfpError(header, body)
    elseif header.msgtype == OFPT_ECHO_REQUEST
        if length(body) != 0
            return nothing
        else
            return OfpEmptyMessage(header)
        end
    elseif header.msgtype == OFPT_ECHO_REPLY
        if length(body) != 0
            return nothing
        else
            return OfpEmptyMessage(header)
        end
    elseif header.msgtype == OFPT_VENDOR
        if length(body) != 0
            return nothing
        else
            return OfpVendorHeader(header, body)
        end
    elseif header.msgtype == OFPT_FEATURES_REQUEST
        if length(body) != 0
            return nothing
        else
            return OfpEmptyMessage(header)
        end
    elseif header.msgtype == OFPT_FEATURES_REPLY
        return OfpSwitchFeatures(header, body)
    elseif header.msgtype == OFPT_GET_CONFIG_REQUEST
        if length(body) != 0
            return nothing
        else
            return OfpEmptyMessage(header)
        end
    elseif header.msgtype == OFPT_GET_CONFIG_REPLY
        return OfpSwitchConfig(header, body)
    elseif header.msgtype == OFPT_SET_CONFIG
        return OfpSwitchConfig(header, body)
    elseif header.msgtype == OFPT_PACKET_IN
        return OfpPacketIn(header, body)
    elseif header.msgtype == OFPT_FLOW_REMOVED
        return OfpFlowRemoved(header, body)
    elseif header.msgtype == OFPT_PORT_STATUS
        return OfpPortStatus(header, body)
    elseif header.msgtype == OFPT_PACKET_OUT
        return OfpPacketOut(header, body)
    elseif header.msgtype == OFPT_FLOW_MOD
        return OfpFlowMod(header, body)
    elseif header.msgtype == OFPT_PORT_MOD
        return OfpPortMod(header, body)
    elseif header.msgtype == OFPT_STATS_REQUEST
        return OfpStatsRequest(header, body)
    elseif header.msgtype == OFPT_STATS_REPLY
        return OfpStatsReply(header, body)
    elseif header.msgtype == OFPT_BARRIER_REQUEST
        if length(body) != 0
            return nothing
        else
            return OfpEmptyMessage(header)
        end
    elseif header.msgtype == OFPT_BARRIER_REPLY
        if length(body) != 0
            return nothing
        else
            return OfpEmptyMessage(header)
        end
    elseif header.msgtype == OFPT_QUEUE_GET_CONFIG_REQUEST
        return OfpQueueGetConfigRequest(header, body)
    elseif header.msgtype == OFPT_QUEUE_GET_CONFIG_REPLY
        return OfpQueueGetConfigReply(header, body)
    else
        return nothing
    end
end

type UnexpectedIntLength <: Exception
end
# XXX there must be something like this somewhere in Julia's API
# utility functions for assembling bytes to Uints
# TODO how about writing "convert" methods for this?
function btoui(b1::Uint8, b2::Uint8, b3::Uint8, b4::Uint8, b5::Uint8, b6::Uint8,
    b7::Uint8, b8::Uint8)
    ui::Uint64 = uint64(0)
    ui |= b1
    ui = ui << 8
    ui |= b2
    ui = ui << 8
    ui |= b3
    ui = ui << 8
    ui |= b4
    ui = ui << 8
    ui |= b5
    ui = ui << 8
    ui |= b6
    ui = ui << 8
    ui |= b7
    ui = ui << 8
    ui |= b8
    ui
end
function btoui(b1::Uint8, b2::Uint8, b3::Uint8, b4::Uint8)
    ui::Uint32 = uint32(0)
    ui |= b1
    ui = ui << 8
    ui |= b2
    ui = ui << 8
    ui |= b3
    ui = ui << 8
    ui |= b4
    ui
end
function btoui(b1::Uint8, b2::Uint8)
    ui::Uint16 = uint16(0)
    ui |= b1
    ui = ui << 8
    ui |= b2
    ui
end
btoui(b1::Uint8) = b1

function seek_next_header(sock::TcpSocket)
    v::Uint8 = 0xff
    while true
        v = read(sock, Uint8, 1)[1]
        if v == 0x01
            t = read(sock, Uint8, 1)[1]
            if 0x00 <= t <= 0x15
                l = ntoh(read(sock, Uint16, 1)[1])
                if l >= 0x0008
                    i = ntoh(read(sock, Uint32, 1)[1])
                    return OfpHeader(v, t, l, i)
                end
            end
        end
    end
end

function start_server(msghandler::Function, port = 6633)
    info("Julia SDN server is up and running.")
	server = listen(port)
    # XXX Probably it would be a good idead to set this dynamically based on the
    # number of sockets and the amount of available memory.
    max_buf = 1024*1024*8
    @sync begin
        @async begin
            while true
                socket = accept(server)
                socket.line_buffered = false
                info("Created a new socket: $(hash(socket))")
                @async begin
                    begin
                        let socket = socket
                            while true
                                try
                                    waiting = nb_available(socket.buffer)
                                    if waiting > max_buf
                                        read(socket, Uint8, waiting)
                                    end
                                    # read the header
                                    header::OfpHeader = seek_next_header(socket)
                                    # read the body
                                    msgbody = read(socket, Uint8, header.msglen - 8)
                                    # assemble the corresponding message
                                    message::Union(OfpMessage, Nothing) = assemblemessage(header, msgbody)
                                    if message != nothing
                                        # handle the message
                                        responses::Vector{OfpMessage} = msghandler(message, hash(socket))
                                        for r in responses
                                            write(socket, bytes(r))
                                        end
                                    end
                                catch e
                                    if isa(e, EOFError)
                                        break
                                    end
                                end
                                yield()
                            end
                        end
                    end
                end
            end
        end
    end
end

include("incl/exports.jl")
end

max_stars_repo_name: pchronz/juliaflow

max_issues_repo_name: pchronz/juliaflow

max_forks_repo_name: pchronz/juliaflow


text:
# Autogenerated wrapper script for UserNSSandbox_jll for aarch64-linux-gnu
export sandbox

JLLWrappers.@generate_wrapper_header("UserNSSandbox")
JLLWrappers.@declare_executable_product(sandbox)
function __init__()
    JLLWrappers.@generate_init_header()
    JLLWrappers.@init_executable_product(
        sandbox,
        "bin/sandbox",
    )

    JLLWrappers.@generate_init_footer()
end  # __init__()