text:
package org.apache.airavata.service.profile.handlers;

import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.AiravataUtils;
import org.apache.airavata.common.utils.Constants;
import org.apache.airavata.common.utils.DBEventService;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.messaging.core.util.DBEventPublisherUtils;
import org.apache.airavata.model.dbevent.CrudType;
import org.apache.airavata.model.dbevent.EntityType;
import org.apache.airavata.model.error.AuthorizationException;
import org.apache.airavata.model.security.AuthzToken;
import org.apache.airavata.model.user.Status;
import org.apache.airavata.model.user.UserProfile;
import org.apache.airavata.model.user.user_profile_modelConstants;
import org.apache.airavata.security.AiravataSecurityException;
import org.apache.airavata.service.profile.client.ProfileServiceClientFactory;
import org.apache.airavata.service.profile.iam.admin.services.cpi.IamAdminServices;
import org.apache.airavata.service.profile.iam.admin.services.cpi.exception.IamAdminServicesException;
import org.apache.airavata.service.profile.user.core.repositories.UserProfileRepository;
import org.apache.airavata.service.profile.user.cpi.UserProfileService;
import org.apache.airavata.service.profile.user.cpi.exception.UserProfileServiceException;
import org.apache.airavata.service.security.AiravataSecurityManager;
import org.apache.airavata.service.security.SecurityManagerFactory;
import org.apache.airavata.service.security.UserInfo;
import org.apache.airavata.service.profile.user.cpi.profile_user_cpiConstants;
import org.apache.airavata.service.security.interceptor.SecurityCheck;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class UserProfileServiceHandler implements UserProfileService.Iface {

    private final static Logger logger = LoggerFactory.getLogger(UserProfileServiceHandler.class);

    private UserProfileRepository userProfileRepository;
    private DBEventPublisherUtils dbEventPublisherUtils = new DBEventPublisherUtils(DBEventService.USER_PROFILE);

    public UserProfileServiceHandler() {

        userProfileRepository = new UserProfileRepository();
    }

    @Override
    public String getAPIVersion() throws TException {
        return profile_user_cpiConstants.USER_PROFILE_CPI_VERSION;
    }

    @Override
    @SecurityCheck
    public String initializeUserProfile(AuthzToken authzToken) throws UserProfileServiceException, AuthorizationException, TException {
        String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
        try {
            // Load UserInfo for the access token and create an initial UserProfile from it
            UserInfo userInfo = SecurityManagerFactory.getSecurityManager().getUserInfoFromAuthzToken(authzToken);
            final UserProfile existingProfile = userProfileRepository.getUserProfileByIdAndGateWay(userInfo.getUsername(), gatewayId);
            // If a user profile already exists, just return the userId
            if (existingProfile != null) {
                return existingProfile.getUserId();
            }
            UserProfile userProfile = new UserProfile();
            userProfile.setUserId(userInfo.getUsername().toLowerCase());
            userProfile.setGatewayId(gatewayId);
            userProfile.setAiravataInternalUserId(userProfile.getUserId() + "@" + gatewayId);
            userProfile.addToEmails(userInfo.getEmailAddress());
            userProfile.setFirstName(userInfo.getFirstName());
            userProfile.setLastName(userInfo.getLastName());
            userProfile.setCreationTime(AiravataUtils.getCurrentTimestamp().getTime());
            userProfile.setLastAccessTime(AiravataUtils.getCurrentTimestamp().getTime());
            userProfile.setValidUntil(-1);
            userProfile.setState(Status.ACTIVE);
            userProfile = userProfileRepository.createUserProfile(userProfile);
            if (null != userProfile) {
                logger.info("Added UserProfile with userId: " + userProfile.getUserId());
                // replicate userProfile at end-places
                dbEventPublisherUtils.publish(EntityType.USER_PROFILE, CrudType.CREATE, userProfile);
                // return userId
                return userProfile.getUserId();
            } else {
                throw new Exception("User creation failed. Please try again.");
            }
        } catch (Exception e) {
            logger.error("Error while initializing user profile", e);
            UserProfileServiceException exception = new UserProfileServiceException();
            exception.setMessage("Error while initializing user profile. More info : " + e.getMessage());
            throw exception;
        }
    }

    @Override
    @SecurityCheck
    public String addUserProfile(AuthzToken authzToken, UserProfile userProfile) throws UserProfileServiceException, AuthorizationException, TException {
        try{
            // Lowercase user id and internal id
            userProfile.setUserId(userProfile.getUserId().toLowerCase());
            userProfile.setAiravataInternalUserId(userProfile.getUserId() + "@" + userProfile.getGatewayId());
            userProfile = userProfileRepository.updateUserProfile(userProfile, getIAMUserProfileUpdater(authzToken, userProfile));
            if (null != userProfile) {
                logger.info("Added UserProfile with userId: " + userProfile.getUserId());
                // replicate userProfile at end-places
                dbEventPublisherUtils.publish(EntityType.USER_PROFILE, CrudType.CREATE, userProfile);
                // return userId
                return userProfile.getUserId();
            } else {
                throw new Exception("User creation failed. Please try again.");
            }
        } catch (Exception e) {
            logger.error("Error while creating user profile", e);
            UserProfileServiceException exception = new UserProfileServiceException();
            exception.setMessage("Error while creating user profile. More info : " + e.getMessage());
            throw exception;
        }
    }

    @Override
    @SecurityCheck
    public boolean updateUserProfile(AuthzToken authzToken, UserProfile userProfile) throws UserProfileServiceException, AuthorizationException, TException {
        try {
            // After updating the user profile in the database but before committing the transaction, the
            // following will update the user profile in the IAM service also. If the update in the IAM service
            // fails then the transaction will be rolled back.
            Runnable iamUserProfileUpdater = getIAMUserProfileUpdater(authzToken, userProfile);
            if(userProfileRepository.updateUserProfile(userProfile, iamUserProfileUpdater) != null) {
                logger.info("Updated UserProfile with userId: " + userProfile.getUserId());
                // replicate userProfile at end-places
                dbEventPublisherUtils.publish(EntityType.USER_PROFILE, CrudType.UPDATE, userProfile);
                return true;
            }
            return false;
        } catch (Exception e) {
            logger.error("Error while Updating user profile", e);
            UserProfileServiceException exception = new UserProfileServiceException();
            exception.setMessage("Error while Updating user profile. More info : " + e.getMessage());
            throw exception;
        }
    }

    private Runnable getIAMUserProfileUpdater(AuthzToken authzToken, UserProfile userProfile) throws UserProfileServiceException {
        String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
        return () -> {
            try {
                AiravataSecurityManager securityManager = SecurityManagerFactory.getSecurityManager();
                AuthzToken serviceAccountAuthzToken = securityManager.getUserManagementServiceAccountAuthzToken(gatewayId);
                IamAdminServices.Client iamAdminServicesClient = getIamAdminServicesClient();
                iamAdminServicesClient.updateUserProfile(serviceAccountAuthzToken, userProfile);
            } catch (AiravataSecurityException|TException e) {
                throw new RuntimeException("Failed to update user profile in IAM service", e);
            }
        };
    }

    @Override
    @SecurityCheck
    public UserProfile getUserProfileById(AuthzToken authzToken, String userId, String gatewayId) throws UserProfileServiceException, AuthorizationException, TException {
        try{
            UserProfile userProfile = userProfileRepository.getUserProfileByIdAndGateWay(userId, gatewayId);
            if(userProfile != null)
                return userProfile;
            else
                throw new Exception("User with userId: " + userId + ", in Gateway: " + gatewayId + ", does not exist.");
        } catch (Exception e) {
            logger.error("Error retrieving user profile by ID", e);
            UserProfileServiceException exception = new UserProfileServiceException();
            exception.setMessage("Error retrieving user profile by ID. More info : " + e.getMessage());
            throw exception;
        }
    }

    @Override
    @SecurityCheck
    public boolean deleteUserProfile(AuthzToken authzToken, String userId, String gatewayId) throws UserProfileServiceException, AuthorizationException, TException {
        try{
            // find user-profile
            UserProfile userProfile = userProfileRepository.getUserProfileByIdAndGateWay(userId, gatewayId);

            // delete user
            boolean deleteSuccess = userProfileRepository.delete(userId);
            logger.info("Delete UserProfile with userId: " + userId + ", " + (deleteSuccess? "Success!" : "Failed!"));

            if (deleteSuccess) {
                // delete userProfile at end-places
                dbEventPublisherUtils.publish(EntityType.USER_PROFILE, CrudType.DELETE, userProfile);
            }
            return deleteSuccess;
        } catch (Exception e) {
            logger.error("Error while deleting user profile", e);
            UserProfileServiceException exception = new UserProfileServiceException();
            exception.setMessage("Error while deleting user profile. More info : " + e.getMessage());
            throw exception;
        }
    }

    @Override
    @SecurityCheck
    public List<UserProfile> getAllUserProfilesInGateway(AuthzToken authzToken, String gatewayId, int offset, int limit) throws UserProfileServiceException, AuthorizationException, TException {
        try{
            List<UserProfile> usersInGateway = userProfileRepository.getAllUserProfilesInGateway(gatewayId, offset, limit);
            if(usersInGateway != null)
                return usersInGateway;
            else
                throw new Exception("There are no users for the requested gatewayId: " + gatewayId);
        } catch (Exception e) {
            logger.error("Error while retrieving user profile List", e);
            UserProfileServiceException exception = new UserProfileServiceException();
            exception.setMessage("Error while retrieving user profile List. More info : " + e.getMessage());
            throw exception;
        }
    }

    @Override
    public boolean doesUserExist(AuthzToken authzToken, String userId, String gatewayId) throws UserProfileServiceException, AuthorizationException, TException {
        try{
            UserProfile userProfile = userProfileRepository.getUserProfileByIdAndGateWay(userId, gatewayId);
            return null != userProfile;
        } catch (Exception e) {
            logger.error("Error while finding user profile", e);
            UserProfileServiceException exception = new UserProfileServiceException();
            exception.setMessage("Error while finding user profile. More info : " + e.getMessage());
            throw exception;
        }
    }

    private IamAdminServices.Client getIamAdminServicesClient() throws UserProfileServiceException {
        try {
            final int serverPort = Integer.parseInt(ServerSettings.getProfileServiceServerPort());
            final String serverHost = ServerSettings.getProfileServiceServerHost();
            return ProfileServiceClientFactory.createIamAdminServiceClient(serverHost, serverPort);
        } catch (IamAdminServicesException|ApplicationSettingsException e) {
            logger.error("Failed to create IAM Admin Services client", e);
            UserProfileServiceException ex = new UserProfileServiceException("Failed to create IAM Admin Services client");
            throw ex;
        }
    }
}


text:
@echo off
cls
build\tools\nant\nant.exe -buildfile:build\project.build %* -nologo
@echo %time%

redpajama_set_name: RedPajamaGithub


text:
Download templates, scripts, sample app

Introduction

    This is part 4 of a
    series of articles
     about deploying your site to
    Amazon Web Services (AWS),
    Amazon's counterpart to Windows Azure.

    In parts 1, 2 and 3, you saw how to use
    the AWS service
                Elastic Beanstalk to
    deploy a load balanced IIS based web application with a SQL Server database and its own domain name.
    This involved defining your EC2 servers, database server, etc. by completing a series of menus.

	This part introduces the AWS service
	CloudFormation.
	This allows you to express your entire environment in a text file called a template.

    The solution presented in this article
    uses a template to define all the web servers, database server, load balancer, name servers, etc. needed to host a web application.
    It also takes care of deploying the
	web application itself.
    Running a single Publish.ps1 PowerShell script will create/update all the bits of infrastructure and deploy the web application,
 so when it's done, you have a running web site.

Why CloudFormation

About this article

Goals for this solution

Solution Components

Costs

Detailed installation steps

Implementation notes

Next Parts

Why CloudFormation

Specifying your environment by fillout out a few forms is very convenient.
   However, once your environment becomes a bit more complicated,
    you'll quickly run into some drawbacks with this method:

        Repeatabality -
        You or a co-worker needs a carbon copy of your infrastructure in some other region.
        Or you need a test environment that is the same as your live environment.
        With menus, you're reduced to writing down every step and manually creating the copy.

    Source control -
    There is no system to track changes by you or your co-workers.
    No rolling back if you make a mistake.

    Documentation -
    To find out what's in an environment you have to hunt around the AWS dashboards.

    The solution is to express your environment in a text file.
    This is easy to store, give to others and source control.

The AWS service
        CloudFormation
    lets you do exactly that. You define everything as a single large JSON object in a template file.
    CloudFormation takes that file and creates all the servers, load balancers, etc. you specified.
This environment is called a stack.

  When it comes time to modify your stack - remove/add servers, upgrade/downgrade servers, etc. -
    you change your template and invoke CloudFormation again. It will figure out how to modify your existing stack
    to your desired new stack making the fewest changes and causing the least disruption.

Stacks have their own name, such as "Test" or "Live". You can have multiple stacks
    and manage them independently. If you want 2 identical stacks, you'd use the same template to create them both.

    In addition to infrastructure, CloudFormation
    will also deploy software for you, such as a web application.

About this article

    CloudFormation is a low level tool.
    Whereas Elastic Beanstalk takes care of lots of details such as creating the right security groups,
    you have to define all this in your template. There are many details to get right - and many ways
    to get it wrong. I found that the learning curve can be quite steep.

    When I set out to create an MVC web application with SQL Server using CloudFormation, I found that:

        To even get something simple working required getting many bits in place;

    The AWS documentation is extensive, but it only gets you 90% there.
You still have to figure many things out on your own.

        Although AWS and others provide sample code,
        this was too simple or sketchy for my purposes.

    So I'm publishing the fully fledged working solution here that I arrived at.
    You should be able to use this as is for your own web application, or as a basis for your own solution.

    Note that this is not an introduction to CloudFormation or AWS.
    The focus of this article is on describing the solution I came up with.
    However, it has many links to relevant parts of the AWS documentation
    to get all the details. This is not too hard and you'll learn a lot.

Goals for this solution

    The solution described in this article
     sets out to achieve 2 goals: to deploy certain
    infrastructure
    and to
    deploy a web application and its updates.

Infrastructure Goal

    The infrastructure goal was to deploy a web application that uses a database and that has its own domain:

    Lets start from the center of the picture:

        Web servers on EC2 instances -
        The web application will run on one or more EC2 instances - virtual machines in the AWS cloud
        acting as web servers.

        SQL Server database server -
        The web application accesses a SQL Server database hosted on an
        RDS (Relational Database Service) instance.
        RDS is a fully managed database server as a service with automatic
        backups, etc.

        SQL Server standby -
        For enhanced  availability, you can
        use a
        Multi-AZ deployment
        where a standby database server automatically takes over when the main database server fails
        (only available
         in the US East (N. Virginia), US West (Oregon), and EU (Ireland) regions).

        Although reasonably priced for a company, this feature is probably too expensive for a personal site.
        So I created both a CloudFormation
                template without a standy
         and
        a
        template with a standby.

        Auto Scaling Group -
        The auto scaling group starts more EC2 instances when the existing
        instances get overloaded, and terminates instances when there is little to do.

        Code package stored in S3 bucket -
        Seeing that the auto scaling group starts and terminates EC2 instances at will, there is no point in deploying software to
        individual servers. Instead, a package file with the code making up the web application is stored in an
        S3 bucket (the S3 service lets you store files in the cloud).
        When the auto scaling group starts a new EC2 instance, it retrieves the package from the S3 bucket and installs it on the new instance.

        Load Balancer -
        The ELB (Elastic Load Balancer)
        receives web requests from the Internet and parcels them out to the available web servers.

        DNS Name Servers -
        Used to translate your domain name to the IP address of the load balancer.
       Provided by the Route 53 service.

Software deployment goal

    The solution also achieves some software deployment related goals:

Packaging
-        Packages up an ASP.NET web application
        and stores the packet in an S3 bucket.

Deployment -
        Installs IIS, etc. on new EC2 instances with a Deploy.ps1 script.

Version tags -
        Adds tags with the current software version to the EC2 instances,
        to make it easy to see what version a particular instance is running.

Terminate and Replace -
        EC2 instances are never updated with new software versions.
        Instead, instances running old software are terminated and new EC2 instances created with the new software.
        This ensures that all EC2 instances are in the same known state, and that they all have the latest Windows patches.

Rolling updates -
        EC2 instances are replaced one by one, so there are always instances running to serve requests.
        If there is only one EC2 instance, a temporary second instance is created.

        Web.config updated
        -
        During deployment, the web.config file is updated with the software version, and the server name, user name and user password of the database server.

    I didn't look into database schema updates.
    If you use
    Entity Framework Code First,
    the web application itself will update the schema for you.
    However, I appreciate more work would be needed if you can't use Entity Framework or Code First.

Solution Components

    The solution consists of a number of templates, scripts, etc.,
    which are in the
    downloads.
The
    next section
shows how to use those components.

        CloudFormation template without database server standby
        that specifies the infrastructure without the database server standby.

        CloudFormation template with database server standby that
         specifies the infrastructure with the database server standby.

        Very simple sample web application
        that uses a database. You may want to use this to experiment before moving to something more complicated.

            If you have a look at its web.config file, you'll find that it has a
            web.release.config
             transform
            to generate the Release version. That Release version has the placeholders
            {{DbUsername}},
            {{DbPassword}},
            {{DbServer}} and
            {{Version}}.
During deployment these will be replaced by the actual database server details and the software version.

        Deploy.ps1 PowerShell script.

                After a new web server is created by the auto scaling group, any Deploy.ps1 script inside the source tree of your web application is executed
                on the new webserver by the CloudFormation template.

                However, this particular Deploy.ps1 file is a bit more restrictive as to where it sits.
                It has to sit in the root directory of the web application, where the main web.config is located.

                Receives software version, database server details, etc. via parameters.

                Responsible for starting IIS, replacing placeholders in the web.config, etc.

       Publish.ps1
       PowerShell script that packages up your web application, stores it in an S3 bucket and calls the CloudFormation service
      with a template
        to deploy the infrastructure and web application. Also updates an existing stack.

       Stack policy
       that determines what servers can be replaced during an update.
       Use this to prevent CloudFormation from for example replacing a database server
       (more about stack policies).

       User policy
       that provides the Publish.ps1 script all the permissions it needs to spin up the infrastructure.

Costs

    Using AWS services is not free. This section is here to spell this out.
    Personally, I found the amounts involved to be tiny,
    except for Multi-AZ deployments - do not leave these running overnight.

            Pricing Page

            Service is used for

            CloudFormation

            Deployment configuration

            EC2 instances

            Virtual machines running web servers

            Elastic Load Balancing

            Load balancer

            Auto Scaling

            Spinning up/down web servers in response to load

            Route53

            DNS name servers

            S3

            Storing software packages

            RDS,
            SQL Server licence

            Database server (see below)

    Some useful tools

        Simple Monthly Calculator

        Estimate Template Cost

        Estimating the Cost of Your AWS CloudFormation Stack (once your stack is running)

Multi-AZ deployment

    Multi-AZ deployments are much more expensive than a database server without standby.

    Amazon have implemented fail over for SQL Server servers using
    the
    SQL Server Mirroring feature. This feature is
    not available
     on SQL Server Express or SQL Server Web Edition.

    As of March 2015, Your cheapest option that supports mirroring would be a SQL Server Standard Edition database
    on a db.m1.small instance
    (pricing).

    Keep in mind that AWS will charge you for the SQL Server Standard Edition licence, while a SQL Server Express licence is free.

    Also, you'll be paying for 2 database servers - the main server and the standby.

    If you're just playing around,
    I wouldn't keep a Multi-AZ deployment running overnight.

Detailed installation steps

    This section shows how to spin up the infrastructure
    plus deploy a web application. First we need to get some once-off preliminaries out of the way, and then
    we can run the Publish.ps1 script to create the stack. You can use the same script to update your stack later on.

1. AWS Account

I'm assuming you have an AWS account
        (get one),
        and a key pair
        (get one).

2. Download

Download all the
        components
         to a directory on your computer.
        It may be easiest to simply
        download the entire Github project
         with all the articles in this series and then grab the components.

3. Set user policy

The user (probably yourself) that will run the Publish.ps1 script
        needs to have all the permissions required to spin up all the different infrastructure elements.

    You express these permissions as an
    IAM policy.
You then attach that policy to the user.

    First create the policy:

        Sign into the AWS Console;

        Click Services (top of the screen) | IAM | Policies | Create Policy;

        Click Select for Create your own policy;

        Make up a nice name for your new policy, such as "Publish-CloudFormation-Stack".
        Whatever name you choose, write it down somewhere.

        Open the
        user policy file
        you just downloaded and copy and paste its content to the Policy Document. You'll see that a policy is simply a JSON object.

        Click Create Policy;

    Then attach your new policy to the user:

Click Users;

    Click the user that will be running the Publish.ps1 script;

        Click Attach Policy;

        Enter the policy you just created in the filter. Select your policy. Click Attach Policy;

4. Store credentials in credentials store

    When you run an AWS PowerShell command, it sends a message to AWS to make an update or retrieve information.
Just as you need to log into AWS before you can do this manually, the
    command must carry credentials, so it can be authenticated by AWS.

    You could pass your credentials to each command, but that means your credentials are exposed in your PowerShell scripts.

    A better way is to store your credentials in a
    credentials store,
    which is simply a file somewhere on your machine:

    Get the access key and secret key of the user that will run the Publish.ps1 script
    (how).

        Think of a name for your new credentials store, such as "mycredentials".

    Open a PowerShell command line and run:

Set-AWSCredentials -AccessKey <acess key> -SecretKey <secret key> -StoreAs <store name>

    As an aside, if you have a look at the
    Publish.ps1
    script, you'll see that it uses this command to tell
    the PowerShell commands in the current session to use the credentials in the credentials store:

Set-AWSCredentials -ProfileName <store name>

5. Find your CIDR

          You don't want everybody in the world to be able to try and RDP into your EC2 instances
      or SSMS into your database servers.

    To lock this down, the Publish.ps1 script lets you pass in the
      CIDR
of the machine that can RDP or SSMS into your servers.

    To find the CIDR of your machine:

        Get your external IP address;

        Add /32 at the end. So if your IP address is 130.180.2.320, your CIDR  is
        130.180.2.320/32.

6. Create RDS option group to switch on SQL Server mirroring

    You only need to do this
    if you plan to use a Multi-AZ deployment.

    AWS' implementation of Multi-AZ deployments for SQL Server
    is based on the
    SQL Server Mirroring
    feature.
    To switch on this feature,
    you need to associate your RDS instance with an
    option group
     that has the mirroring option enabled.

    Because this option group is simply a bit of infrastructure, you'd think you can create this
    in a CloudFormation template. Oddly, that cannot be done. You have to create it manually once off.
When you run Publish.ps1, you'll pass in the name of the option group that you create here via a
    parameter.

    To create the option group:

        In the AWS console, click Services | RDS | Option Groups | Create Group;

    Think of a name for your option group, such as "sqlserver-mirroring".
    Fill in the name and a description. Write down the name, you'll need it later on;

        Set Engine to sqlserver-se (Standard Edition) or sqlserver-ee (Enterprise Edition);

        Set Major Engine Version to version 11 (which is the same as the EngineVersion specified in the
        CloudFormation template);

        Click Create. This creates your option group and takes you back to the option groups list;

        Select your new option group;

        Click Add Option (near top of the page);

        Mirroring is the only option. You probably want to set Apply Immediately to Yes. Click Add Option.

7. Run Publish.ps1 script

    With the preliminaries done, you can now run the
    Publish.ps1
    script to spin up the infrastructure
    and deploy the web application.

Time to run

    Running this script takes a while.
    Spinning up a new stack and deploying the site
    takes about 20 minutes in my experience.
    If you go for a stack with a Multi-AZ database deployment, 50 minutes is more like it.

    Luckily, updates (running the script again for the same stack) tend to take far less time because CloudFormation
    does the minimum necessary to do the updates.

Domain

    If you own a spare domain name that you want to use here, you'll pass that to the script
    via the websiteDomain parameter.

    If you don't have a domain to use right now, just use a bogus domain such as "mybogusdomain.com".

Usage of the Publish.ps1 script

.\publish.ps1 -version <code version> -stackName <stack name> -websiteDomain <web site domain>
    -keyName <key name> -credentialsStoreName <credential store name> -adminCidr <admin cidr>
    -dbMasterUsername <database username> -dbMasterUserPassword <database password>
    -bucketName <S3 bucket to store code> -templatePath <template file>
    -csProjPath <.csproj file of your web application> -dbOptionGroupName <option group name>
    -stackPolicyPath <file with stack policy&gt

Example

    This is just an example that spins up infrastructure without a Multi-AZ deployment.
    It assumes you stored the downloaded files in a directory "c:\aws".

    Do not copy this blindly, but use your own
    parameter values, especially the ones that are underlined below.

.\publish.ps1 -version 1.0.0 -stackName teststack -websiteDomain mybogusdomain.com -keyName mykeyname
    -credentialsStoreName mycredentials -adminCidr 130.180.2.320/32
    -dbMasterUsername dbusername -dbMasterUserPassword 'MustBe$uperHardToGu3ss!'
    -bucketName must-be-unique-across-all-S3-buckets-in-AWS
    -templatePath 'c:\aws\Template with SQL Server Express\Ec2RdsRoute54.template'
    -csProjPath 'c:\aws\SimpleSiteWithDb\SimpleSiteWithDb\SimpleSiteWithDb.csproj'
    -stackPolicyPath 'c:\aws\stackpolicy.txt'

PowerShell special characters in parameter values

    If any parameter value contain a $, enclose the parameter value with single quotes ('), not with double quotes. That way, PowerShell won't regard the $ as
    the start of a variable and try to expand it.

Parameters

version

      Version of the code you're deploying. For example "2.1.0".
The version doubles as the name of the code package in the S3 bucket.
If you're running Publish.ps1 to update infrastructure whilst keeping the web application the same, use the same version.

stackName

       For example, "Test" or
      "Live".
      The set of servers, etc. you create with a template is called a stack. You can create a different set of servers
      by passing in a different stack name.

websiteDomain

      Domain of the web application that will be associated with the name servers. For example, "mydomain.com" for your Live stack, or "test-domain.com" for your Test stack.

keyName

      Name of the key pair that you
      created earlier.
      You'll use this to log into your EC2 instances. Remember that key pairs are tied to a region.

credentialsStoreName

      Name of the credentials store where you stored your credentials
      earlier.

adminCidr

      Use the CIDR you found
      earlier.

dbMasterUsername

dbMasterUserPassword

      RDS only supports SQL Server Authentication. These are the username and password that will be able
      to access your new database server via SSMS, and that will be inserted into your web.config.

bucketName

      S3 bucket where the code packages will be stored. This name must be unique across all S3 buckets
      hosted by AWS. To make sure a given S3 bucket name is available, it would be easiest to create the S3 bucket yourself
      and then pass your chosen name in via this parameter. To open the S3 dashboard, click Services | S3.

templatePath

      Path to the CloudFormation template to use.
      Use one of the
      templates in the downloads
      or use your own.

          If you use your own template and it has
          parameters,
          be aware that the
           Publish.ps1
          script sets only a limited set of parameters (in the method launch-stack).
          All other parameters must be optional and/or have defaults.

csProjPath

      Path of the .csproj file of the web application you're deploying. The Publish.ps1 script will build the site in release mode,
      package up the code and store the package in the S3 bucket.

dbOptionGroupName (optional)

      Name of the option group you created
      earlier that has mirroring enabled. Only use this if you're
      using a template that creates a SQL Server Standard Edition (or higher) database server
      (such as this template).

            If you try to use such an option group with an engine that does not support mirroring, such as SQL Server Express or SQL Server Web Edition,
            CloudFormation will fail to create your stack.

stackPolicyPath (optional)

      File path of a stack policy to protect for example your database during stack updates
      (example).
      If you do not use a stack policy, do not use this parameter.

8. Set nameservers

        After you've created your stack, you need to change the configuration of your
        domain name so it uses your
        new Route53 name servers.

        Part 3 of this series described how to do that
        here.

9. Copy data and schema from old database

        If you have an existing database, you'll want to copy its schema and data to your new RDS database.
        Part 2 of this series described how to do that
        here.

        Unless you delete your database server,
        this needs to be done only once after the initial creation of your stack.

Implementation notes

		This section isn't a detailed discussion of every file
		in the
		downloads.
		That would be very boring. I also provided a lot of comments and apart from the templates the files are not very complicated.

		Instead, this section
		discusses some of the more interesting
		things I learned when building this solution.

CloudFormation template

        On a high level, a CloudFormation template is simply a long list of infrastructure resources.
        The
        introduction to building CloudFormation templates
        is well worth reading, as is the
        user guide.
        There are also
        the
        Pseudo Parameters Reference
        and the
        Intrinsic Function Reference.

        I gained a lot from looking at
        sample templates and snippets.
        Also, each resource has a type, such as AWS::RDS::DBInstance. Googling those types and understanding what they do taught me a lot
        on how AWS works.

    Having said that, there were a few tricky bits I wanted to discuss here.

Loading a code package onto a new EC2 instance

        The
        auto scaling group
        is responsible for creating new EC2 instances.
        This includes installing the web application,
        installing IIS, etc.

        This installation work is handled by a
        launch configuration - a separate resource.
If you search for
        AWS::AutoScaling::AutoScalingGroup in the
        template,
        you'll find  that it is associated with the auto scaling group via the
        auto scaling group's
        LaunchConfigurationName
        property.

        If you now search for
        LaunchConfig,
        you'll find that it knows everything about configuring a new EC2 instance, including the AMI image id, its instance type
        and everything related to installing the web application. The installation story is spread over two properties:
        the UserData property and the
        AWS::CloudFormation::Init object in the Metadata property.

		The
		UserData property contains
		scripts that will be run on the new EC2 instance after it has been created. Oddly, it is
		Base64
		encoded.
		Luckily, the built in
		intrinsic function
		Fn::Base64  does the Base64 encoding for us:

"LaunchConfig" : {
    "Type" : "AWS::AutoScaling::LaunchConfiguration",
    "Properties" : {
        "UserData" : { "Fn::Base64" : { "Fn::Join" : ["", [
            "<script>\n",
                "... MS-DOS commands ... \n"
            "</script>\n",
            "<powershell>\n",
                "... PowerShell commands ... \n"
            "</powershell>\n"
        ]] } }
    }
}

        Looking at the template,
        you'll see that the one MS-DOS command calls
        the
        cfn-init.exe program.
        This
        CloudFormation Helper Script is always available on an EC2 instance.
        It actions the meta data in the
        AWS::CloudFormation::Init
        object.
        You'll see
        below
         that the AWS::CloudFormation::Init
        object used in this template
        gets cfn-init.exe
        to
        load a package file (a .zip file) from the S3 bucket
        and extract the files into the
        c:\inetpub\deploy directory.

        After cfn-init.exe has executed, the PowerShell script kicks in.
        This finds all files called Deploy.ps1 within the code package and
        invokes
         them as PowerShell scripts.
        Note that it has to
        set the execution policy
         to Bypass temporarily to allow this to happen.
        It then cleans up the
        c:\inetpub\deploy directory.

The
    AWS::CloudFormation::Init
        documentation is well worth reading.
        One of its many tricks is the
        sources section, which allows you to download a .zip file from a URL and extract it into a directory on the EC2 instance.
        Here that URL is the package in the S3 bucket, but you could also load a .zip file from Github.

    In principle you can extract the files in any directory. However, keep in mind that:

        c:\inetpub\temp is used by IIS for its own purposes. Deleting it does break things.

        c:\inetpub\wwwroot is used by the default web site in IIS.

        %temp% gets expanded into the temporary directory by Windows Explorer, but
    not by AWS::CloudFormation::Init.

    This is why in the end I used
    c:\inetpub\deploy
    as a temporary directory to extract the web application.

Starting the software update process

        You can run the Publish.ps1 script to purely install
        a new version of your web application, without changes to the CloudFormation template.
    As part of this, Publish.ps1 uploads a new package to the S3 bucket.
        Question is how to get the launch configuration to pick up this new version and
        replace EC2 instances running the old version with EC2 instances running the new version.
        Luckily, AWS makes this fairly easy.

        Firstly, when you update a property of a
        launch configuration,
        that launch configuration gets replaced by a new configuration.
        Then when its auto scaling group creates new EC2 instances, those instances
        receive the latest version
         of your web application.

        If you have a look at the AWS::CloudFormation::Init object used in the launch configuration,
        you see that the sources property changes
        when you update the
        Version parameter.
        This is because the name of every package is based on the version.
        So that solves how to give new EC2 instances the latest web application version.

        Basing the names of packages on their version means that packages of previous versions are preserved (unless you manually delete them).
        Obviously this takes space.
        In order to save space, you could give all packages the same name, so old packages get overwritten (you would have to modify the
        Publish.ps1 script to make this happen).
        However, in that case the
        sources property no longer changes with the version.

In that case, to still have the launch configuration replaced when the version changes,
        you could set the Version property on the Metadata:

"LaunchConfig" : {
    "Type" : "AWS::AutoScaling::LaunchConfiguration",
    "Metadata" : {
        "Version" : { "Ref" : "Version" },

        Having made sure that new EC2 instances receive the latest code,
        we still have to get rid of the EC2 instances running old code.
You can do this by specifying
        an
        UpdatePolicy Attribute
        for your auto scaling group
        (in the template, search for "UpdatePolicy").
        In addition to causing the auto scaling group to replace EC2 instances in a rolling update,
        this also lets you specify how many EC2 insances get replaced in one go, etc.

Allowing EC2 instances to read a file from an S3 bucket

        For the EC2 instances to load the package from the S3 bucket, they have to have permission to do so.

        This can be done by creating a
        role.
        This is a collection of permissions that can be assigned to for example a user on a temporary basis.
        The permissions themselves are contained in a
        policy,
        which needs to be attached to the role.

        In the template, the permission to execute a GetObject action (that is, file load)
        on the package is encoded in a policy in the
        RolePolicies resource
        of type
        AWS::IAM::Policy.
        Its Roles property
        attaches the policy to the
        InstanceRole
        resource of type
        AWS::IAM::Role.

        An added twist is that it isn't the EC2 instance itself that will be loading the package, but software
        running under Windows on that virtual machine. Because of this,
        InstanceRole needs to be first added to an
        InstanceProfile
        (details).
        In the template this InstanceProfile is imaginatively called
InstanceProfile.

        Finally, we can now
        attach
InstanceProfile
        to the
        launch configuration
        (resource LaunchConfig)
        via its
        IamInstanceProfile
        property.

Setting credentials for retrieving resources listed in AWS::CloudFormation::Init

        In addition to
        allowing EC2 instances to read a file from an S3 bucket,
        you also need to provide credentials for accessing those files (unless they are not protected at all).

        You do this by adding a
        AWS::CloudFormation::Authentication
        object to the Metadata
        of your
        launch configuration (search for "AWS::CloudFormation::Authentication" in
        the template).
You can use this to provide credentials for any resources or files listed in your
    AWS::CloudFormation::Init
object.
If you were to retrieve files or resources from for example Github,
        this would be the place to provide your Github credentials.

        As far as providing credentials for the S3 bucket is concerned, the simplest way here
        is to refer to the InstanceRole object
        that had already been created by the template.

Some pages that I found useful:

        Bootstrapping on AWS

            AWS CloudFormation Office Hours: January 30, 2014

            Authenticated File Downloads with CloudFormation

Adding version tags to EC2 instances

        One goal was to have a version tag on each EC2 instance, to make it easy to find out what software version
        it runs. Of course, EC2 instances get created and terminated by the auto scaling group, so you can't add tags directly to the EC2 instances.

    A simple solution is to add the version tag to the auto scaling group itself
    (details).
    If you look at the
    WebServerGroup (of type
    AWS::AutoScaling::AutoScalingGroup) in the template,
    you'll find that it has a
    Tags
    property
containing the version tag.
    Setting
    PropagateAtLaunch to true ensures that the tag will be copied to newly launced EC2 instances.

Publish.ps1

        You run this PowerShell script to create or update a stack.

This script interacts with AWS using PowerShell Cmdlets provided by
        AWS Tools for Windows PowerShell.
        I found that this works well and is very well documented.

        Some things I learned while writing this script:

            Some sample CloudFormation templates on the Internet hard code
            the ID of the
            Amazon Machine Image (AMI)
           to use with EC2 instances.
            I followed their lead, until one day I found that the AMI I had hardcoded no longer existed.

            In fact, AWS
            regularly provides
             new updated AMIs with new IDs, so hard coding IDs won't work long term. The solution was to get the latest EC2 instance AMI
                each time you create or update a stack:

$imageId = (Get-EC2ImageByName -Names WINDOWS_2012R2_BASE | Select -ExpandProperty ImageId)

            At the end of the method launch-stack, it waits until the stack has been completely created or updated.
            It does this by polling the status of the stack every 5 seconds (in method waitfor-stack-status).
            I had to interpret the AWS stack status (a string) to find out whether the create/update had succeeded/failed or was still in progress.
            This was made easier by having the
            full set of stack status codes.

            The Cmdlets

            New-CFNStack
            and
            Update-CFNStack
are used to create/update a stack using a template.
            When your template creates an
            IAM Instance Profile,
             for example to give EC2 instances access to an S3 bucket,
            you have to allow the Cmdlets to use that template by
            passing in
            "CAPABILITY_IAM"
            via the
            Capability parameter:

New-CFNStack -Capability @( "CAPABILITY_IAM" ) ....

            In method upload-deployment,
            I used
            MSBuild
            and more specifically its
            Package
            target to build and package up the web application into a single .zip file using the line:

msbuild $csProjPath /t:Package /p:Configuration=Release /p:PackageLocation=$releaseZip /p:AutoParameterizationWebConfigConnectionStrings=False

                I looked at alternatives such as
                OctoPack, but this is the simplest way and it works well.

                By default, the Package target
                replaces the web.config's connection by a replacable token, which is not what I want here.
                Setting AutoParameterizationWebConfigConnectionStrings to False suppresses this behaviour.

Deploy.ps1 PowerShell script

        This PowerShell script runs on the EC2 instance after the web application package has been copied there and has been unzipped.
        It isn't complicated and well documented.

A few interesting things:

            You'll see that I used
            appcmd.exe
            to work with IIS, rather than easier to use
            IIS Cmdlets.

            The reason behind this is that the IIS Cmdlets require the
            WebAdministration module to have been loaded, and I found I couldn't count on this always being the case.
            So I used appcmd.exe which always works.

            I was sometimes confronted with the error message
            HTTP Error 500.21 - Internal Server Error Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list.

            The solution was to re-install the .Net framework
            (Stack Overflow discussion), using

cmd /c %systemroot%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i

            Be careful with the PowerShell Cmdlet Out-File. By default it produces a file with encoding Unicode.
            IIS chokes on this when reading for example web.config. I believe that in most cases you're better off with UTF8 anyway:

Out-File ..... -encoding UTF8

Trial site Web.Release.config

        This is the web.config transform that generates the release version of the web.config. You can see the placeholders
        that will be replaced by Deploy.ps1.

    Some connection strings use Integrated Security=SSPI;. Do not use this with an AWS hosted site. It will cause AWS to try to log into your database with the
    NT AUTHORITY\ANONYMOUS LOGON account rather than your own account - which will fail.

Next Parts

    In
    future parts,
I am intending to
    write about deploying a stack from
    TeamCity,
    blue/green deployments and
    breaking large templates into manageable pieces.


text:
"""Camera model tensorflow ops python interface."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf

camera_model_module = tf.load_op_library(
    tf.compat.v1.resource_loader.get_path_to_datafile('camera_model_ops.so'))

world_to_image = camera_model_module.world_to_image
image_to_world = camera_model_module.image_to_world


text:
package com.saintdan.framework.exception;

import com.saintdan.framework.enums.ErrorType;

/**
 * Commons exception.
 *
 * @author Liao Yifan
 * @date 11/5/15
 * @since JDK1.8
 */
public class CommonsException extends SystemException {

  private static final long serialVersionUID = -1041148006846583767L;

  private final static ErrorType ERROR_TYPE = ErrorType.SYS0100;

  public CommonsException(ErrorType type, Throwable t, String errorMsg) {
    super(type, t, errorMsg);
  }

  public CommonsException(ErrorType type, String errorMsg) {
    super(type, errorMsg);
  }

  public CommonsException(ErrorType type) {
    super(type);
  }

  public CommonsException() {
    super(ERROR_TYPE);
  }
}


text:
import { Component } from '@angular/core';
import { Router, ROUTER_DIRECTIVES } from '@angular/router';
import { CORE_DIRECTIVES, FORM_DIRECTIVES } from '@angular/common';

const template = require('./buildCaseLately.html');
/**
 * 구현 필요
 */
@Component({
  selector: 'buildCaseLately',
  directives: [ ROUTER_DIRECTIVES, CORE_DIRECTIVES, FORM_DIRECTIVES ],
  template: template
})
export class BuildCaseLately {
  }


text:
package org.gradle.test.performance.mediummonolithicjavaproject.p487;

import org.junit.Test;
import static org.junit.Assert.*;

public class Test9745 {
    Production9745 objectUnderTest = new Production9745();

    @Test
    public void testProperty0() {
        Production9742 value = new Production9742();
        objectUnderTest.setProperty0(value);
        assertEquals(value, objectUnderTest.getProperty0());
    }

    @Test
    public void testProperty1() {
        Production9743 value = new Production9743();
        objectUnderTest.setProperty1(value);
        assertEquals(value, objectUnderTest.getProperty1());
    }

    @Test
    public void testProperty2() {
        Production9744 value = new Production9744();
        objectUnderTest.setProperty2(value);
        assertEquals(value, objectUnderTest.getProperty2());
    }

    @Test
    public void testProperty3() {
        String value = "value";
        objectUnderTest.setProperty3(value);
        assertEquals(value, objectUnderTest.getProperty3());
    }

    @Test
    public void testProperty4() {
        String value = "value";
        objectUnderTest.setProperty4(value);
        assertEquals(value, objectUnderTest.getProperty4());
    }

    @Test
    public void testProperty5() {
        String value = "value";
        objectUnderTest.setProperty5(value);
        assertEquals(value, objectUnderTest.getProperty5());
    }

    @Test
    public void testProperty6() {
        String value = "value";
        objectUnderTest.setProperty6(value);
        assertEquals(value, objectUnderTest.getProperty6());
    }

    @Test
    public void testProperty7() {
        String value = "value";
        objectUnderTest.setProperty7(value);
        assertEquals(value, objectUnderTest.getProperty7());
    }

    @Test
    public void testProperty8() {
        String value = "value";
        objectUnderTest.setProperty8(value);
        assertEquals(value, objectUnderTest.getProperty8());
    }

    @Test
    public void testProperty9() {
        String value = "value";
        objectUnderTest.setProperty9(value);
        assertEquals(value, objectUnderTest.getProperty9());
    }

}


text:
package echosign.api.clientv20;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import echosign.api.clientv20.dto.DocumentCreationInfo;
import echosign.api.clientv20.dto.SenderInfo;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="apiKey" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="senderInfo" type="{http://dto.api.echosign}SenderInfo"/>
 *         <element name="documentCreationInfo" type="{http://dto.api.echosign}DocumentCreationInfo"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "apiKey",
    "senderInfo",
    "documentCreationInfo"
})
@XmlRootElement(name = "sendDocument")
public class SendDocument {

    @XmlElement(required = true, nillable = true)
    protected String apiKey;
    @XmlElement(required = true, nillable = true)
    protected SenderInfo senderInfo;
    @XmlElement(required = true, nillable = true)
    protected DocumentCreationInfo documentCreationInfo;

    /**
     * Gets the value of the apiKey property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getApiKey() {
        return apiKey;
    }

    /**
     * Sets the value of the apiKey property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setApiKey(String value) {
        this.apiKey = value;
    }

    /**
     * Gets the value of the senderInfo property.
     *
     * @return
     *     possible object is
     *     {@link SenderInfo }
     *
     */
    public SenderInfo getSenderInfo() {
        return senderInfo;
    }

    /**
     * Sets the value of the senderInfo property.
     *
     * @param value
     *     allowed object is
     *     {@link SenderInfo }
     *
     */
    public void setSenderInfo(SenderInfo value) {
        this.senderInfo = value;
    }

    /**
     * Gets the value of the documentCreationInfo property.
     *
     * @return
     *     possible object is
     *     {@link DocumentCreationInfo }
     *
     */
    public DocumentCreationInfo getDocumentCreationInfo() {
        return documentCreationInfo;
    }

    /**
     * Sets the value of the documentCreationInfo property.
     *
     * @param value
     *     allowed object is
     *     {@link DocumentCreationInfo }
     *
     */
    public void setDocumentCreationInfo(DocumentCreationInfo value) {
        this.documentCreationInfo = value;
    }

}


text:
package tree;

import java.util.*;

public class q_637 {
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> result = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            long sum = 0, count = 0;
            Queue<TreeNode> temp = new LinkedList<>();
            while(!queue.isEmpty()){
                TreeNode n = queue.poll();
                sum += n.val;
                count++;
                if(n.left != null)
                    temp.offer(n.left);
                if(n.right != null)
                    temp.offer(n.right);
            }
            queue = temp;
            result.add(sum*1.0/count);
        }
        return result;
    }
}


text:
// Contributors:  Christian Trutz <christian.trutz@belaso.de>
package org.apache.log4j;

import java.io.IOException;

/**
 * This class is a minimal implementation of the original Log4J class.
 *
 * @author Christian Trutz <christian.trutz@belaso.de>
 * */
public class RollingFileAppender {

    public RollingFileAppender() {
        super();
    }

    public RollingFileAppender(Layout layout, String filename) throws IOException {
        super();
    }

    public RollingFileAppender(Layout layout, String filename, boolean append) throws IOException {
        super();
    }

    public void setMaxBackupIndex(int maxBackups) {
        // nothing to do
    }

    public void setMaximumFileSize(long maxFileSize) {
        // nothing to do
    }

}


text:
/**
 *
 */
package org.rcsb.mmtf.intracoders;

import static org.junit.Assert.assertArrayEquals;

import org.junit.Test;
import org.rcsb.mmtf.intracoders.RecursiveIndexingCoder;

/**
 * Tests the encoding and decoding methods of RecursiveIndexingCoder.
 *
 * @author Yana Valasatava
 *
 */
public class TestRecursiveIndexingCoder {

	/**
	 * Recursive Indexing encoder test.
	 */
	@Test
	public void recursiveIndexingEncodeTest() {

		int[] in = {10, 2, 3, 7, 0, 15, -8, -17};
		int[] outTest =  {7, 3, 2, 3, 7, 0, 0, 7, 7, 1, -8, 0, -8, -8, -1};
		RecursiveIndexingCoder coder = new RecursiveIndexingCoder(7);
		int[] out = coder.encode(in);
		assertArrayEquals(outTest, out);
	}

	/**
	 * Recursive Indexing encoder test on empty arrays.
	 */
	@Test
	public void emptyRecursiveIndexingEncodeTest() {
		// Allocate the byte array
		int[] in = {};
		int[] outTest =  {};
		RecursiveIndexingCoder coder = new RecursiveIndexingCoder(7);
		int[] out = coder.encode(in);
		assertArrayEquals(outTest, out);
	}

	/**
	 * Recursive Indexing decoder test.
	 */
	@Test
	public void recursiveIndexingDecodeTest() {

		int[] in =  {7, 3, 2, 3, 7, 0, 0, 7, 7, 1, -8, 0, -8, -8, -1};
		int[] outTest = {10, 2, 3, 7, 0, 15, -8, -17};
		RecursiveIndexingCoder coder = new RecursiveIndexingCoder(7);
		int[] out = coder.decode(in);
		assertArrayEquals(outTest, out);
	}

	/**
	 * Recursive Indexing decoder test.
	 */
	@Test
	public void emptyRecursiveIndexingDecodeTest() {

		int[] in =  {};
		int[] outTest = {};
		RecursiveIndexingCoder coder = new RecursiveIndexingCoder(7);
		int[] out = coder.decode(in);
		assertArrayEquals(outTest, out);
	}
}


text:
define(["jointjs", "lodash", "jquery",
 "./parser_element", "./helpers"],
 function(joint, _, $, ParserElement, Helpers){
  var renderObject = Helpers.renderObject;
  var renderedLinks = [];
  var renderLink = function(graph, source, target, pKey){
    var elements = graph.getElements();
    var sources = _.where(elements, {id: source.get("graphId") });
    var targets = _.where(elements, {id: target.get("graphId") });
    if(sources.length == 0 || targets.length == 0){
      return false;
    }

    var key = pKey+"#"+source.get("friendlyName")+"#"+target.get("friendlyName");
    var linkAttrs = window.tildaCache[key];
    if(linkAttrs == null){
      linkAttrs = {
        source: { id: source.get("graphId") },
        target: { id: target.get("graphId") }
      }
      var attrs = {
        '.marker-target': { d: 'M 10 0 L 0 5 L 10 10 z' },
        'key': pKey+"#"+source.get("friendlyName")+"#"+target.get("friendlyName")
      }
      if(source.get('_type') == "Object"){
        if(target.get("schemaName") != source.get("schemaName")){
          attrs = _.merge(attrs, {
            '.connection': { stroke: 'rgb(65,113,156)', 'stroke-width': 1 }
          })
        } else {
          attrs = _.merge(attrs, {
            '.connection': { stroke: 'rgb(5,113,156)', 'stroke-width': 1, 'stroke-dasharray': '5 2' }
          })
        }
      } else if(source.get('_type') == "View"){
        if(target.get("schemaName") != source.get("schemaName")){
          attrs = _.merge(attrs, {
            '.connection': { stroke: 'rgb(0,176,80)', 'stroke-width': 1 }
          })
        } else {
          attrs = _.merge(attrs, {
            '.connection': { stroke: 'rgb(0,176,80)', 'stroke-width': 1, 'stroke-dasharray': '5 2' }
          })
        }
      } else if(source.get('_type') == "Mapper"){
        if(target.get("schemaName") != source.get("schemaName")){
          attrs = _.merge(attrs, {
            '.connection': { stroke: 'rgb(248,203,173)', 'stroke-width': 1 }
          })
        } else {
          attrs = _.merge(attrs, {
            '.connection': { stroke: 'rgb(248,203,173)', 'stroke-width': 1, 'stroke-dasharray': '5 2' }
          })
        }
      }
      linkAttrs["attrs"] = attrs
    } else {
      linkAttrs = _.merge(linkAttrs, {
        source: { id: source.get("graphId") },
        target: { id: target.get("graphId") }
      })
    }
    var vertices = linkAttrs.vertices;
    var link = new joint.dia.Link(linkAttrs);
    var eventHandler = function(event){
      var key = event.get("attrs").key.toLowerCase();
      var syncSet = {}
      var attributes = event.attributes;
      window.tildaCache[key] = _.merge(attributes, { vertices: this.get('vertices') })
    }
    if(vertices){
      link.set('vertices', vertices);
    }
    link.on("change:vertices", _.debounce(eventHandler, 500, { 'maxWait' : 1000 }));
    graph.addCell(link);
    renderedLinks.push(linkAttrs);
  }

  var X = {};
  var objRel = function(graph, object, pKey){
    var rels = object.get('references') || [];
    _.each(rels, function(target){
      renderLink(graph, object, target, pKey)
      objRel.apply(this, [graph, target, pKey]);
    })
  }
  var renderObjectRelations = {
    // This method will add outSchema object
    "Object": objRel,
    "View": objRel,
    "onlyView": objRel,
    "Mapper": objRel
  }
  return renderObjectRelations;
});


text:
- https://portswigger.net/web-security
  + Free, online web security training from the creators of Burp Suite


text:
<?php namespace HipsterJazzbo\FireAndForget;

use HipsterJazzbo\FireAndForget\Exceptions\InvalidUrlException;
use HipsterJazzbo\FireAndForget\Exceptions\SocketException;
use League\Uri\Schemes\Http as HttpUri;
use RuntimeException;

/**
 * Class FireAndForget
 *
 * @package HipsterJazzbo\FireAndForget
 */
class FireAndForget
{

    /**
     * @var int
     */
    private $connectionTimeout;

    /**
     * @param int $connectionTimeout
     */
    function __construct($connectionTimeout = 5)
    {
        $this->connectionTimeout = $connectionTimeout;
    }

    /**
     * @param string $url
     * @param array  $params
     */
    public function get($url, $params)
    {
        $this->fire('GET', $url, $params);
    }

    /**
     * @param string $url
     * @param array  $params
     */
    public function post($url, $params)
    {
        $this->fire('POST', $url, $params);
    }

    /**
     * @param string $url
     * @param array  $params
     */
    public function put($url, $params)
    {
        $this->fire('PUT', $url, $params);
    }

    /**
     * @param string $url
     * @param array  $params
     */
    public function delete($url, $params)
    {
        $this->fire('DELETE', $url, $params);
    }

    /**
     * @param string $method
     * @param string $url
     * @param array  $params
     *
     * @throws SocketException
     */
    private function fire($method, $url, $params)
    {
        try {
            $url = HttpUri::createFromString($url);
        } catch (RuntimeException $e) {
            throw new InvalidUrlException($e->getMessage(), $url);
        }

        $scheme = $url->getScheme() === 'https' ? 'ssl://' : '';
        $host   = $scheme . $url->getHost();
        $port   = $url->getPort() ?: $this->getDefaultPort($url->getScheme());

        $request = $this->getRequest($method, $url, $params);
        $socket  = @fsockopen($host, $port, $errno, $errstr, $this->connectionTimeout);

        if (! $socket) {
            throw new SocketException($errstr, $errno);
        }

        fwrite($socket, $request);
        fclose($socket);
    }

    /**
     * @param array $params
     *
     * @return string
     */
    private function buildQueryString($params)
    {
        return http_build_query($params);
    }

    /**
     * @param string  $method
     * @param HttpUri $url
     * @param array   $params
     *
     * @return string
     */
    private function getRequest($method, $url, $params)
    {
        $queryString = $this->buildQueryString($params);
        $headers     = $this->getHeaders($method, $url, $queryString);
        $body        = $this->getBody($method, $queryString);

        return $headers . "\r\n" . $body;
    }

    /**
     * @param string  $method
     * @param HttpUri $url
     * @param string  $queryString
     *
     * @return string
     */
    private function getHeaders($method, $url, $queryString)
    {
        $path = $method === 'GET' ? $url->getPath() . "?" . $queryString : $url->getPath();

        $headers = $method . " /" . $path . " HTTP/1.1\r\n";
        $headers .= "Host: " . $url->getHost() . "\r\n";
        $headers .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $headers .= "Content-Length: " . strlen($queryString) . "\r\n";
        $headers .= "Connection: Close\r\n";

        return $headers;
    }

    /**
     * @param string $method
     * @param string $queryString
     *
     * @return string
     */
    private function getBody($method, $queryString)
    {
        return $method === 'GET' ? '' : $queryString;
    }

    /**
     * @param $scheme
     *
     * @return int
     */
    private function getDefaultPort($scheme)
    {
        switch ($scheme) {
            case 'https':
                $defaultPort = 443;
                break;

            case 'http':
                $defaultPort = 80;
                break;

            default:
                $defaultPort = 80;
        }

        return $defaultPort;
    }
}


text:
require_relative 'generators'

module Topographer
  class Tasks < Thor;
    namespace :topographer

    register(Generators::Install, 'install', 'install --models=model1 model2 model3', 'Installs the topographer importer scaffold')
  end
end


text:
using System;
using Windows.ApplicationModel.DataTransfer;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using AppStudio.DataProviders.Rss;
using Windows10News.Sections;
using Windows10News.Services;
using Windows10News.ViewModels;
using AppStudio.Uwp;

namespace Windows10News.Pages
{
    public sealed partial class BusinessDetailPage : Page
    {
        private DataTransferManager _dataTransferManager;

        public BusinessDetailPage()
        {
            this.ViewModel = DetailViewModel.CreateNew(Singleton<BusinessConfig>.Instance);

            this.InitializeComponent();
            new Microsoft.ApplicationInsights.TelemetryClient().TrackPageView(this.GetType().FullName);
        }

        public DetailViewModel ViewModel { get; set; }

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            await this.ViewModel.LoadDataAsync(e.Parameter as ItemViewModel);

            _dataTransferManager = DataTransferManager.GetForCurrentView();
            _dataTransferManager.DataRequested += OnDataRequested;

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            _dataTransferManager.DataRequested -= OnDataRequested;

            base.OnNavigatedFrom(e);
        }

        private void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs args)
        {
            ViewModel.ShareContent(args.Request);
        }

        private void ChangeFontSize(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            AppBarButton button = sender as AppBarButton;
            int newFontSize = Int32.Parse(button.Tag.ToString());
            mainPanel.BodyFontSize = newFontSize;
        }
    }
}


text:
import pandas as pd

# TODO: Load up the dataset
# Ensuring you set the appropriate header column names
#
df = pd.read_csv('Datasets/servo.csv',
                  names = ['motor', 'screw', 'pgain', 'vgain', 'class'])
print(df)

# TODO: Create a slice that contains all entries
# having a vgain equal to 5. Then print the
# length of (# of samples in) that slice:
#
df_vgain = df[df.vgain == 5]
print(len(df_vgain))

# TODO: Create a slice that contains all entries
# having a motor equal to E and screw equal
# to E. Then print the length of (# of
# samples in) that slice:
#
df_slice = df[(df.motor == 'E') & (df.screw == 'E')]
print(len(df_slice))

# TODO: Create a slice that contains all entries
# having a pgain equal to 4. Use one of the
# various methods of finding the mean vgain
# value for the samples in that slice. Once
# you've found it, print it:
#
df_slice_again = df[df.pgain == 4]
print(df_slice_again)
df_slice_again['vgain'].mean()

# TODO: (Bonus) See what happens when you run
# the .dtypes method on your dataframe!


text:
package org.arakhne.afc.math.geometry.d1;

import org.arakhne.afc.math.geometry.AbstractGeomFactoryBase;

/** Abstract implementation of a factory of geometric primitives.
 *
 * @param <V> the types of the vectors.
 * @param <P> is the type of the points.
 * @author $Author: sgalland$
 * @version $FullVersion$
 * @mavengroupid $GroupId$
 * @mavenartifactid $ArtifactId$
 * @since 14.0
 */
public abstract class AbstractGeomFactory1D<V extends Vector1D<? super V, ? super P, ?>,
		P extends Point1D<? super P, ? super V, ?>>
		extends AbstractGeomFactoryBase
		implements GeomFactory1D<V, P> {
	//
}


text:
Frequently Asked Questions
==========================

My project isn't building correctly
-----------------------------------

First, you should check out the Builds tab of your project.
That records all of the build attempts that RTD has made to build your project.
If you see ``ImportError`` messages for custom Python modules,
see our section on :ref:`faq:My documentation requires additional dependencies`.

If you are still seeing errors because of C library dependencies,
please see :ref:`faq:I get import errors on libraries that depend on C modules`.

Help, my build passed but my documentation page is 404 Not Found!
-----------------------------------------------------------------

This often happens because you don't have an `index.html` file being generated.
Make sure you have one of the following files:

    * `index.rst`
    * `index.md`

At the top level of your built documentation,
otherwise we aren't able to serve a "default" index page.

To test if your docs actually built correctly,
you can navigate to a specific page (`/en/latest/README.html` for example).

My documentation requires additional dependencies
-------------------------------------------------

For most Python dependencies, you can can specify a requirements file
which details your dependencies. See our guide on :ref:`guides/reproducible-builds:using a configuration file`.
You can also set your project documentation to install your project itself
as a dependency.

If your project or its dependencies rely on C libraries,
see :ref:`faq:I get import errors on libraries that depend on C modules`.

My project requires some additional settings
--------------------------------------------

If this is just a dependency issue,
see :ref:`faq:My documentation requires additional dependencies`.

Read the Docs offers some settings which can be used for a variety of purposes.
To enable these settings,
please send an email to support@readthedocs.org and we will change the settings for the project.
Read more about these settings :doc:`here <guides/feature-flags>`.

I get import errors on libraries that depend on C modules
---------------------------------------------------------

.. note::

   Another use case for this is when you have a module with a C extension.

This happens because our build system doesn't have the dependencies for building your project.
This happens with things like ``libevent``, ``mysql``, and other python packages that depend on C libraries.
We can't support installing random C binaries on our system, so there is another way to fix these imports.

With Sphinx you can use the built-in `autodoc_mock_imports`_ for mocking.
If such libraries are installed via ``setup.py``, you also will need to remove all the C-dependent libraries from your ``install_requires`` in the RTD environment.

.. _autodoc_mock_imports: http://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#confval-autodoc_mock_imports

How do I change behavior when building with Read the Docs?
----------------------------------------------------------

When RTD builds your project, it sets the :envvar:`READTHEDOCS` environment
variable to the string ``'True'``. So within your Sphinx :file:`conf.py` file, you
can vary the behavior based on this. For example::

    import os
    on_rtd = os.environ.get('READTHEDOCS') == 'True'
    if on_rtd:
        html_theme = 'default'
    else:
        html_theme = 'nature'

The :envvar:`READTHEDOCS` variable is also available in the Sphinx build
environment, and will be set to ``True`` when building on RTD::

    {% if READTHEDOCS %}
    Woo
    {% endif %}

`Client Error 401` when building documentation
----------------------------------------------

If you did not install the `test_data` fixture during the installation
instructions, you will get the following error::

    slumber.exceptions.HttpClientError: Client Error 401: http://localhost:8000/api/v1/version/

This is because the API admin user does not exist, and so cannot authenticate.
You can fix this by loading the test_data::

    ./manage.py loaddata test_data

If you'd prefer not to install the test data, you'll need to provide a database
account for the builder to use. You can provide these credentials by editing the
following settings::

    SLUMBER_USERNAME = 'test'
    SLUMBER_PASSWORD = 'test'

Deleting a stale or broken build environment
--------------------------------------------

See :doc:`guides/wipe-environment`.

How do I host multiple projects on one custom domain?
-----------------------------------------------------

We support the concept of subprojects, which allows multiple projects to share a
single domain. If you add a subproject to a project, that documentation will
be served under the parent project's subdomain or custom domain.

For example,
Kombu is a subproject of Celery,
so you can access it on the `celery.readthedocs.io` domain:

https://celery.readthedocs.io/projects/kombu/en/latest/

This also works the same for custom domains:

http://docs.celeryproject.org/projects/kombu/en/latest/

You can add subprojects in the project admin dashboard.

For details on custom domains, see our documentation on :doc:`/custom_domains`.

Where do I need to put my docs for RTD to find it?
--------------------------------------------------

Read the Docs will crawl your project looking for a ``conf.py``. Where it finds the ``conf.py``,
it will run ``sphinx-build`` in that directory.
So as long as you only have one set of sphinx documentation in your project, it should Just Work.

You can specify an exact path to your documentation using a Read the Docs :doc:`config-file/index`.

I want to use the Blue/Default Sphinx theme
-------------------------------------------

We think that our theme is badass,
and better than the default for many reasons.
Some people don't like change though |:smile:|,
so there is a hack that will let you keep using the default theme.
If you set the ``html_style`` variable in your ``conf.py``,
it should default to using the default theme.
The value of this doesn't matter, and can be set to ``/default.css`` for default behavior.

I want to use the Read the Docs theme locally
---------------------------------------------

There is a repository for that: https://github.com/readthedocs/sphinx_rtd_theme.
Simply follow the instructions in the README.

Image scaling doesn't work in my documentation
-----------------------------------------------

Image scaling in docutils depends on PIL. PIL is installed in the system that RTD runs on. However, if you are using the virtualenv building option, you will likely need to include PIL in your requirements for your project.

I want comments in my docs
--------------------------

RTD doesn't have explicit support for this.
That said, a tool like `Disqus`_ (and the `sphinxcontrib-disqus`_ plugin) can be used for this purpose on RTD.

.. _Disqus: https://disqus.com/
.. _sphinxcontrib-disqus: https://pypi.python.org/pypi/sphinxcontrib-disqus

How do I support multiple languages of documentation?
-----------------------------------------------------

See the section on :doc:`localization`.

Does Read The Docs work well with "legible" docstrings?
-------------------------------------------------------

Yes. One criticism of Sphinx is that its annotated docstrings are too
dense and difficult for humans to read. In response, many projects
have adopted customized docstring styles that are simultaneously
informative and legible. The
`NumPy <https://numpydoc.readthedocs.io/en/latest/format.html#docstring-standard>`__
and
`Google <https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings>`__
styles are two popular docstring formats.  Fortunately, the default
Read The Docs theme handles both formats just fine, provided
your ``conf.py`` specifies an appropriate Sphinx extension that
knows how to convert your customized docstrings.  Two such extensions
are `numpydoc <https://github.com/numpy/numpydoc>`_ and
`napoleon <http://sphinxcontrib-napoleon.readthedocs.io>`_. Only
``napoleon`` is able to handle both docstring formats. Its default
output more closely matches the format of standard Sphinx annotations,
and as a result, it tends to look a bit better with the default theme.

.. note::

   To use these extensions you need to specify the dependencies on your project
   by following this :ref:`guide <guides/reproducible-builds:using a configuration file>`.

Can I document a python package that is not at the root of my repository?
-------------------------------------------------------------------------

Yes. The most convenient way to access a python package for example via
`Sphinx's autoapi`_ in your documentation is to use the *Install your project
inside a virtualenv using setup.py install* option in the admin panel of
your project. However this assumes that your ``setup.py`` is in the root of
your repository.

If you want to place your package in a different directory or have multiple
python packages in the same project, then create a pip requirements file. You
can specify the relative path to your package inside the file.
For example you want to keep your python package in the ``src/python``
directory, then create a ``requirements.txt`` file with the
following contents::

    src/python/

Please note that the path must be relative to the working directory where ``pip`` is launched,
rather than the directory where the requirements file is located.
Therefore, even if you want to move the requirements file to a ``requirements/`` directory,
the example path above would work.

You can customize the path to your requirements file and any other installed dependency
using a Read the Docs :doc:`config-file/index`.

.. _Sphinx's autoapi: http://sphinx-doc.org/ext/autodoc.html
.. _pip requirements file: https://pip.pypa.io/en/stable/user_guide.html#requirements-files

I need to install a package in a environment with pinned versions
-----------------------------------------------------------------

To ensure proper installation of a python package, the ``pip`` :ref:`install method <config-file/v2:python.install>` will automatically upgrade every dependency to its most recent version in case they aren't pinned by the package definition.
If instead you'd like to pin your dependencies outside the package, you can add this line to your requirements or environment file (if you are using Conda).

In your ``requirements.txt`` file::

    # path to the directory containing setup.py relative to the project root
    -e .

In your Conda environment file (``environment.yml``)::

    # path to the directory containing setup.py relative to the environment file
    -e ..

How can I avoid search results having a deprecated version of my docs?
----------------------------------------------------------------------

If readers search something related to your docs in Google, it will probably return the most relevant version of your documentation.
It may happen that this version is already deprecated and you want to stop Google indexing it as a result,
and start suggesting the latest (or newer) one.

To accomplish this, you can add a ``robots.txt`` file to your documentation's root so it ends up served at the root URL of your project
(for example, https://yourproject.readthedocs.io/robots.txt).
We have documented how to set this up in our :ref:`hosting:Custom robots.txt Pages` docs.

Can I remove advertising from my documentation?
-----------------------------------------------

See :ref:`Opting out of advertising <advertising/ethical-advertising:Opting Out>`.

How do I change my project slug (the URL your docs are served at)?
------------------------------------------------------------------

We don't support allowing folks to change the slug for their project.
You can update the name which is shown on the site,
but not the actual URL that documentation is served.

The main reason for this is that all existing URLs to the content will break.
You can delete and re-create the project with the proper name to get a new slug,
but you really shouldn't do this if you have existing inbound links,
as it `breaks the internet <http://www.w3.org/Provider/Style/URI.html>`_.

If that isn't enough,
you can request the change sending an email to support@readthedocs.org.

How do I change the version slug of my project?
-----------------------------------------------

We don't support allowing folks to change the slug for their versions.
But you can rename the branch/tag to achieve this.
If that isn't enough,
you can request the change sending an email to support@readthedocs.org.

What commit of Read the Docs is in production?
----------------------------------------------

We deploy readthedocs.org from the ``rel`` branch in our GitHub repository.
You can see the latest commits that have been deployed by looking on GitHub: https://github.com/readthedocs/readthedocs.org/commits/rel

We also keep an up-to-date :doc:`changelog </changelog>`.


text:
package org.saiku.datasources.connection;

import java.util.Collection;
import org.apache.commons.vfs.FileName;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSystemConfigBuilder;
import org.apache.commons.vfs.FileSystemException;
import org.apache.commons.vfs.FileSystemOptions;
import org.apache.commons.vfs.VFS;
import org.apache.commons.vfs.impl.DefaultFileSystemManager;
import org.apache.commons.vfs.provider.FileProvider;
import org.saiku.service.datasource.IDatasourceManager;

public class MondrianVFS
        implements FileProvider
{
    IDatasourceManager datasourceManager;

    public void setDatasourceManager(IDatasourceManager dms)
    {
        this.datasourceManager = dms;
    }

    public void init()
    {
        try
        {
            DefaultFileSystemManager dfsm = (DefaultFileSystemManager)VFS.getManager();
            if (!dfsm.hasProvider("mondrian")) {
                dfsm.addProvider("mondrian", this);
            }
        }
        catch (FileSystemException e) {}
    }

    public FileObject findFile(FileObject fileObject, String catalog, FileSystemOptions fileSystemOptions)
            throws FileSystemException
    {
        return new RepositoryVfsFileObject(catalog, this.datasourceManager);
    }

    public FileObject createFileSystem(String s, FileObject fileObject, FileSystemOptions fileSystemOptions)
            throws FileSystemException
    {
        return null;
    }

    public FileSystemConfigBuilder getConfigBuilder()
    {
        return null;
    }

    public Collection getCapabilities()
    {
        return null;
    }

    public FileName parseUri(FileName fileName, String s)
            throws FileSystemException
    {
        return null;
    }
}


text:
package com.netflix.metacat.connector.jdbc.services;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.netflix.metacat.common.QualifiedName;
import com.netflix.metacat.common.dto.Pageable;
import com.netflix.metacat.common.dto.Sort;
import com.netflix.metacat.common.server.connectors.ConnectorRequestContext;
import com.netflix.metacat.common.server.connectors.ConnectorDatabaseService;
import com.netflix.metacat.common.server.connectors.model.DatabaseInfo;
import com.netflix.metacat.connector.jdbc.JdbcExceptionMapper;
import lombok.Getter;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

/**
 * Generic JDBC implementation of the ConnectorDatabaseService.
 *
 * @author tgianos
 * @since 1.0.0
 */
@Slf4j
@Getter
public class JdbcConnectorDatabaseService implements ConnectorDatabaseService {

    private final DataSource dataSource;
    private final JdbcExceptionMapper exceptionMapper;

    /**
     * Constructor.
     *
     * @param dataSource      The jdbc datasource instance to use to make connections
     * @param exceptionMapper The exception mapper to use
     */
    @Inject
    public JdbcConnectorDatabaseService(
        @Nonnull @NonNull final DataSource dataSource,
        @Nonnull @NonNull final JdbcExceptionMapper exceptionMapper
    ) {
        this.dataSource = dataSource;
        this.exceptionMapper = exceptionMapper;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void create(@Nonnull final ConnectorRequestContext context, @Nonnull final DatabaseInfo resource) {
        final String databaseName = resource.getName().getDatabaseName();
        log.debug("Beginning to create database {} for request {}", databaseName, context);
        try (final Connection connection = this.dataSource.getConnection()) {
            JdbcConnectorUtils.executeUpdate(connection, "CREATE DATABASE " + databaseName);
            log.debug("Finished creating database {} for request {}", databaseName, context);
        } catch (final SQLException se) {
            throw this.exceptionMapper.toConnectorException(se, resource.getName());
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void delete(@Nonnull final ConnectorRequestContext context, @Nonnull final QualifiedName name) {
        final String databaseName = name.getDatabaseName();
        log.debug("Beginning to drop database {} for request {}", databaseName, context);
        try (final Connection connection = this.dataSource.getConnection()) {
            JdbcConnectorUtils.executeUpdate(connection, "DROP DATABASE " + databaseName);
            log.debug("Finished dropping database {} for request {}", databaseName, context);
        } catch (final SQLException se) {
            throw this.exceptionMapper.toConnectorException(se, name);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public DatabaseInfo get(@Nonnull final ConnectorRequestContext context, @Nonnull final QualifiedName name) {
        final String databaseName = name.getDatabaseName();
        log.debug("Beginning to get database metadata for {} for request {}", databaseName, context);
        return DatabaseInfo.builder().name(name).build();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<DatabaseInfo> list(
        @Nonnull final ConnectorRequestContext context,
        @Nonnull final QualifiedName name,
        @Nullable final QualifiedName prefix,
        @Nullable final Sort sort,
        @Nullable final Pageable pageable
    ) {
        final String catalogName = name.getCatalogName();
        log.debug("Beginning to list database metadata for catalog {} for request {}", catalogName, context);

        final ImmutableList.Builder<DatabaseInfo> builder = ImmutableList.builder();
        for (final QualifiedName dbName : this.listNames(context, name, prefix, sort, pageable)) {
            builder.add(this.get(context, dbName));
        }
        log.debug("Finished listing database metadata for catalog {} for request {}", catalogName, context);
        return builder.build();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<QualifiedName> listNames(
        @Nonnull final ConnectorRequestContext context,
        @Nonnull final QualifiedName name,
        @Nullable final QualifiedName prefix,
        @Nullable final Sort sort,
        @Nullable final Pageable pageable
    ) {
        final String catalogName = name.getCatalogName();
        log.debug("Beginning to list database names for catalog {} for request {}", catalogName, context);

        try (final Connection connection = this.dataSource.getConnection()) {
            final DatabaseMetaData metaData = connection.getMetaData();
            final List<QualifiedName> names = Lists.newArrayList();

            try (final ResultSet schemas = prefix == null || StringUtils.isEmpty(prefix.getDatabaseName())
                ? metaData.getSchemas(connection.getCatalog(), null)
                : metaData
                .getSchemas(
                    connection.getCatalog(),
                    prefix.getDatabaseName() + JdbcConnectorUtils.MULTI_CHARACTER_SEARCH
                )
            ) {
                while (schemas.next()) {
                    final String schemaName = schemas.getString("TABLE_SCHEM").toLowerCase(Locale.ENGLISH);
                    // skip internal schemas
                    if (!schemaName.equals("information_schema")) {
                        names.add(QualifiedName.ofDatabase(name.getCatalogName(), schemaName));
                    }
                }
            }

            // Does user want sorting?
            if (sort != null) {
                // We can only really sort by the database name at this level so ignore SortBy field
                final Comparator<QualifiedName> comparator = Comparator.comparing(QualifiedName::getDatabaseName);
                JdbcConnectorUtils.sort(names, sort, comparator);
            }

            // Does user want pagination?
            final List<QualifiedName> results = JdbcConnectorUtils.paginate(names, pageable);

            log.debug("Finished listing database names for catalog {} for request {}", catalogName, context);
            return results;
        } catch (final SQLException se) {
            throw this.exceptionMapper.toConnectorException(se, name);
        }
    }
}


text:
'use strict';

//Setting up route
angular.module('control-panel').config(['$stateProvider',
	function($stateProvider) {
		// Control panel state routing
		$stateProvider.
		state('control-panel', {
			url: '/control-panel',
			templateUrl: 'modules/control-panel/views/control-panel.client.view.html'
		}).
		state('widget', {
			url: '/widget',
			templateUrl: 'modules/control-panel/views/widget.client.view.html'
		});
	}
]);


text:
apetools.devices.macdevice.MacDevice.channel
============================================

.. currentmodule:: apetools.devices.macdevice

.. autoattribute:: MacDevice.channel


text:
std::vector<int> parseInts(std::string str) {
	std::vector<int> integers;
	std::stringstream ss(str);
	while (ss) {
		int currentInteger;
		char currentComma;
		ss >> currentInteger >> currentComma;
		integers.push_back(currentInteger);
	}
	return integers;
}

int main() {
	std::string str;

	std::cin >> str; // std::getline is not needed, because of input format.

	std::vector<int> integers = parseInts(str);

	for (int i = 0; i < integers.size(); ++i) {
		std::cout << integers[i] << std::endl;
	}

	return 0;
}