text:
package it.restart.com.atlassian.jira.plugins.dvcs.test;

import com.atlassian.jira.pageobjects.JiraTestedProduct;
import com.atlassian.jira.plugins.dvcs.pageobjects.JiraLoginPageController;
import com.atlassian.jira.plugins.dvcs.pageobjects.common.MagicVisitor;
import com.atlassian.jira.plugins.dvcs.pageobjects.common.OAuth;
import com.atlassian.jira.plugins.dvcs.pageobjects.component.BitBucketCommitEntry;
import com.atlassian.jira.plugins.dvcs.pageobjects.component.OrganizationDiv;
import com.atlassian.jira.plugins.dvcs.pageobjects.component.RepositoryDiv;
import com.atlassian.jira.plugins.dvcs.pageobjects.page.JiraViewIssuePageController;
import com.atlassian.jira.plugins.dvcs.pageobjects.page.OAuthCredentials;
import com.atlassian.jira.plugins.dvcs.pageobjects.page.RepositoriesPageController;
import com.atlassian.jira.plugins.dvcs.pageobjects.page.RepositoriesPageController.AccountType;
import com.atlassian.jira.plugins.dvcs.pageobjects.page.account.Account;
import com.atlassian.jira.plugins.dvcs.pageobjects.page.account.AccountRepository;
import com.atlassian.jira.plugins.dvcs.pageobjects.page.account.DvcsAccountsPage;
import com.atlassian.jira.plugins.dvcs.pageobjects.remoterestpoint.ChangesetLocalRestpoint;
import com.atlassian.pageobjects.TestedProductFactory;
import com.atlassian.pageobjects.elements.PageElement;
import it.com.atlassian.jira.plugins.dvcs.DvcsWebDriverTestCase;
import it.restart.com.atlassian.jira.plugins.dvcs.github.GithubLoginPage;
import it.restart.com.atlassian.jira.plugins.dvcs.github.GithubOAuthApplicationPage;
import it.restart.com.atlassian.jira.plugins.dvcs.github.GithubOAuthPage;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.util.List;

import static com.atlassian.pageobjects.elements.query.Poller.waitUntilFalse;
import static com.atlassian.pageobjects.elements.query.Poller.waitUntilTrue;
import static it.restart.com.atlassian.jira.plugins.dvcs.test.GithubTestHelper.GITHUB_API_URL;
import static it.restart.com.atlassian.jira.plugins.dvcs.test.GithubTestHelper.REPOSITORY_NAME;
import static it.util.TestAccounts.DVCS_CONNECTOR_TEST_ACCOUNT;
import static it.util.TestAccounts.JIRA_BB_CONNECTOR_ACCOUNT;
import static java.util.Arrays.asList;
import static org.fest.assertions.api.Assertions.assertThat;

public class GithubTests extends DvcsWebDriverTestCase implements BasicTests
{
    private static final JiraTestedProduct JIRA = TestedProductFactory.create(JiraTestedProduct.class);
    private static final List<String> BASE_REPOSITORY_NAMES = asList(
            "missingcommits",
            "repo1",
            "noauthor",
            "test-project");

    private OAuth oAuth;

    @BeforeClass
    public void beforeClass()
    {
        new JiraLoginPageController(JIRA).login();
        // log in to github
        new MagicVisitor(JIRA).visit(GithubLoginPage.class).doLogin();
        // setup up OAuth from github
        oAuth = new MagicVisitor(JIRA).visit(GithubOAuthPage.class).addConsumer(JIRA.getProductInstance().getBaseUrl());
        JIRA.backdoor().plugins().disablePlugin("com.atlassian.jira.plugins.jira-development-integration-plugin");
    }

    @AfterClass
    public void afterClass()
    {
        // delete all organizations
        RepositoriesPageController rpc = new RepositoriesPageController(JIRA);
        rpc.getPage().deleteAllOrganizations();
        // remove OAuth in github
        new MagicVisitor(JIRA).visit(GithubOAuthApplicationPage.class).removeConsumer(oAuth);

        // log out from github
        new MagicVisitor(JIRA).visit(GithubLoginPage.class).doLogout();
    }

    @BeforeMethod
    public void beforeMethod()
    {
        RepositoriesPageController rpc = new RepositoriesPageController(JIRA);
        rpc.getPage().deleteAllOrganizations();
    }

    @Override
    @Test
    public void addOrganization()
    {
        RepositoriesPageController rpc = new RepositoriesPageController(JIRA);
        OrganizationDiv organization = rpc.addOrganization(AccountType.GITHUB, JIRA_BB_CONNECTOR_ACCOUNT,
                getOAuthCredentials(), false);

        assertThat(organization).isNotNull();
        assertThat(organization.getRepositoryNames()).containsAll(BASE_REPOSITORY_NAMES);
    }

    @Override
    @Test
    public void addOrganizationWaitForSync()
    {
        RepositoriesPageController rpc = new RepositoriesPageController(JIRA);
        OrganizationDiv organization = rpc.addOrganization(AccountType.GITHUB, JIRA_BB_CONNECTOR_ACCOUNT,
                getOAuthCredentials(), false);

        assertThat(organization).isNotNull();
        assertThat(organization.getRepositoryNames()).containsAll(BASE_REPOSITORY_NAMES);

        final String expectedMessage = "Mon Feb 06 2012";
        final RepositoryDiv repositoryDiv = organization.findRepository(REPOSITORY_NAME);
        assertThat(repositoryDiv).isNotNull();
        repositoryDiv.enableSync();
        repositoryDiv.sync();
        assertThat(repositoryDiv.getMessage()).isEqualTo(expectedMessage);

        ChangesetLocalRestpoint changesetLocalRestpoint = new ChangesetLocalRestpoint();
        List<String> commitsForQA2 = changesetLocalRestpoint.getCommitMessages("QA-2", 6);
        assertThat(commitsForQA2).contains("BB modified 1 file to QA-2 and QA-3 from TestRepo-QA");
        List<String> commitsForQA3 = changesetLocalRestpoint.getCommitMessages("QA-3", 1);
        assertThat(commitsForQA3).contains("BB modified 1 file to QA-2 and QA-3 from TestRepo-QA");
    }

    @Override
    @Test (expectedExceptions = AssertionError.class, expectedExceptionsMessageRegExp = ".*Error!\\nThe url \\[https://nonexisting.org\\] is incorrect or the server is not responding.*")
    public void addOrganizationInvalidUrl()
    {
        RepositoriesPageController rpc = new RepositoriesPageController(JIRA);
        rpc.addOrganization(AccountType.GITHUB, "https://nonexisting.org/someaccount", getOAuthCredentials(), false, true);
    }

    @Override
    @Test (expectedExceptions = AssertionError.class, expectedExceptionsMessageRegExp = "Invalid OAuth")
    public void addOrganizationInvalidOAuth()
    {
        RepositoriesPageController rpc = new RepositoriesPageController(JIRA);
        rpc.addOrganization(AccountType.GITHUB, JIRA_BB_CONNECTOR_ACCOUNT, new OAuthCredentials("xxx", "yyy"), true, true);
    }

    @Test
    @Override
    public void testPostCommitHookAddedAndRemoved()
    {
        testPostCommitHookAddedAndRemoved(JIRA_BB_CONNECTOR_ACCOUNT, AccountType.GITHUB, REPOSITORY_NAME, JIRA, getOAuthCredentials());
    }

    @Override
    protected boolean postCommitHookExists(final String accountName, final String jiraCallbackUrl)
    {
        List<String> actualHookUrls = GithubTestHelper.getHookUrls(accountName, GITHUB_API_URL, REPOSITORY_NAME);
        return actualHookUrls.contains(jiraCallbackUrl);
    }

    @Test
    @Override
    public void testCommitStatistics()
    {
        RepositoriesPageController rpc = new RepositoriesPageController(JIRA);
        final OrganizationDiv organization = rpc.addOrganization(AccountType.GITHUB, JIRA_BB_CONNECTOR_ACCOUNT,
                getOAuthCredentials(), false);
        final RepositoryDiv repositoryDiv = organization.findRepository("test-project");
        repositoryDiv.enableSync();
        repositoryDiv.sync();

        // QA-2
        List<BitBucketCommitEntry> commitMessages = new JiraViewIssuePageController(JIRA, "QA-3").getCommits(1); // throws AssertionError with other than 1 message
        assertThat(commitMessages).hasSize(1);

        BitBucketCommitEntry commitMessage = commitMessages.get(0);
        List<PageElement> statistics = commitMessage.getStatistics();
        assertThat(statistics).hasSize(1);
        assertThat(commitMessage.getAdditions(statistics.get(0))).isEqualTo("+1");
        assertThat(commitMessage.getDeletions(statistics.get(0))).isEqualTo("-");

        // QA-4
        commitMessages = new JiraViewIssuePageController(JIRA, "QA-4").getCommits(1); // throws AssertionError with other than 1 message
        assertThat(commitMessages).hasSize(1);

        commitMessage = commitMessages.get(0);
        statistics = commitMessage.getStatistics();
        assertThat(statistics).hasSize(1);
        assertThat(commitMessage.isAdded(statistics.get(0))).isTrue();
    }

    @Override
    @Test
    public void shouldBeAbleToSeePrivateRepositoriesFromTeamAccount()
    {
        // we should see 'private-dvcs-connector-test' repo
        RepositoriesPageController rpc = new RepositoriesPageController(JIRA);
        OrganizationDiv organization = rpc.addOrganization(AccountType.GITHUB, "atlassian",
                getOAuthCredentials(), false);

        assertThat(organization.containsRepository("private-dvcs-connector-test"));
    }

    @Test
    public void linkingRepositoryWithoutAdminPermission()
    {
        RepositoriesPageController rpc = new RepositoriesPageController(JIRA);
        rpc.addOrganization(AccountType.GITHUB, DVCS_CONNECTOR_TEST_ACCOUNT, getOAuthCredentials(), false);

        DvcsAccountsPage accountsPage = JIRA.visit(DvcsAccountsPage.class);
        Account account = accountsPage.getAccount(Account.AccountType.GIT_HUB, DVCS_CONNECTOR_TEST_ACCOUNT);
        AccountRepository repository = account.enableRepository("testemptyrepo", true);

        // check that repository is enabled
        waitUntilTrue(repository.isEnabled());
        waitUntilTrue(repository.hasWarning());
    }

    @Test
    public void linkingRepositoryWithAdminPermission()
    {
        RepositoriesPageController rpc = new RepositoriesPageController(JIRA);
        rpc.addOrganization(AccountType.GITHUB, JIRA_BB_CONNECTOR_ACCOUNT, getOAuthCredentials(), false);

        DvcsAccountsPage accountsPage = JIRA.visit(DvcsAccountsPage.class);
        Account account = accountsPage.getAccount(Account.AccountType.GIT_HUB, JIRA_BB_CONNECTOR_ACCOUNT);
        AccountRepository repository = account.enableRepository(REPOSITORY_NAME, false);

        // check that repository is enabled
        waitUntilTrue(repository.isEnabled());
        waitUntilFalse(repository.hasWarning());
    }

    @Test
    public void autoLinkingRepositoryWithoutAdminPermission()
    {
        RepositoriesPageController rpc = new RepositoriesPageController(JIRA);
        final OrganizationDiv organization = rpc.addOrganization(AccountType.GITHUB, DVCS_CONNECTOR_TEST_ACCOUNT,
                getOAuthCredentials(), false);
        organization.enableAllRepos();

        DvcsAccountsPage accountsPage = JIRA.visit(DvcsAccountsPage.class);
        Account account = accountsPage.getAccount(Account.AccountType.GIT_HUB, DVCS_CONNECTOR_TEST_ACCOUNT);

        for (AccountRepository repository : account.getRepositories())
        {
            waitUntilTrue(repository.isEnabled());
        }
    }

    @Test
    public void autoLinkingRepositoryWithAdminPermission()
    {
        RepositoriesPageController rpc = new RepositoriesPageController(JIRA);
        final OrganizationDiv organization = rpc.addOrganization(AccountType.GITHUB, JIRA_BB_CONNECTOR_ACCOUNT,
                getOAuthCredentials(), false);
        organization.enableAllRepos();

        DvcsAccountsPage accountsPage = JIRA.visit(DvcsAccountsPage.class);
        Account account = accountsPage.getAccount(Account.AccountType.GIT_HUB, JIRA_BB_CONNECTOR_ACCOUNT);

        for (AccountRepository repository : account.getRepositories())
        {
            waitUntilTrue(repository.isEnabled());
            waitUntilFalse(repository.hasWarning());
        }
    }

    //-------------------------------------------------------------------
    //--------- these methods should go to some common utility/class ----
    //-------------------------------------------------------------------

    private OAuthCredentials getOAuthCredentials()
    {
        return new OAuthCredentials(oAuth.key, oAuth.secret);
    }
}


text:
class CreateProjectGalleryImages < ActiveRecord::Migration
  def change
    create_table :project_gallery_images do |t|
      t.integer :project_id
      t.string :title
      t.string :image

      t.timestamps null: false
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
require 'helper'

describe OmniAuth::Builder do
  describe "#provider" do
    it "translates a symbol to a constant" do
      OmniAuth::Strategies.should_receive(:const_get).with('MyStrategy').and_return(Class.new)
      OmniAuth::Builder.new(nil) do
        provider :my_strategy
      end
    end

    it "accepts a class" do
      class ::ExampleClass; end

      expect{
        OmniAuth::Builder.new(nil) do
          provider ::ExampleClass
        end
      }.not_to raise_error
    end

    it "raises a helpful LoadError message if it can't find the class" do
      expect {
        OmniAuth::Builder.new(nil) do
          provider :lorax
        end
      }.to raise_error(LoadError, "Could not find matching strategy for :lorax. You may need to install an additional gem (such as omniauth-lorax).")
    end
  end

  describe "#options" do
    it "merges provided options in" do
      k = Class.new
      b = OmniAuth::Builder.new(nil)
      b.should_receive(:use).with(k, :foo => 'bar', :baz => 'tik')

      b.options :foo => 'bar'
      b.provider k, :baz => 'tik'
    end

    it "adds an argument if no options are provided" do
      k = Class.new
      b = OmniAuth::Builder.new(nil)
      b.should_receive(:use).with(k, :foo => 'bar')

      b.options :foo => 'bar'
      b.provider k
    end
  end
end


text:
package org.innovateuk.ifs.user.builder;

import org.innovateuk.ifs.BaseBuilder;
import org.innovateuk.ifs.user.resource.BusinessType;
import org.innovateuk.ifs.user.resource.ProfileSkillsBaseResource;

import java.util.List;
import java.util.function.BiConsumer;

public abstract class ProfileSkillsBaseResourceBuilder<T extends ProfileSkillsBaseResource, S extends ProfileSkillsBaseResourceBuilder> extends BaseBuilder<T, S> {

    protected ProfileSkillsBaseResourceBuilder(List<BiConsumer<Integer, T>> newActions) {
        super(newActions);
    }

    public S withUser(Long... users) {
        return withArraySetFieldByReflection("user", users);
    }

    public S withSkillsAreas(String... skillsAreas) {
        return withArraySetFieldByReflection("skillsAreas", skillsAreas);
    }

    public S withBusinessType(BusinessType... businessTypes) {
        return withArraySetFieldByReflection("businessType", businessTypes);
    }

}


text:
//
//  CMPPaymentMethod.h
//  Computop
//
//  Created by Thomas Segkoulis on 12/09/16.
//  Copyright © 2016 Computop GmbH. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "CMPPaymentMethodProtocol.h"

/**
 'CMPPaymentMethod'

 The 'CMPPaymentMethod' class constitutes the model that contains all the data for a Payment method.

 */
@interface CMPPaymentMethod : NSObject <CMPPaymentMethodProtocol>

/**
 Payment method id.
 */
@property (nonatomic, strong) NSString *pmID;

/**
 Payment method url.
 */
@property (nonatomic, strong) NSString *url;

/**
 Payment method image string.
 */
@property (nonatomic, strong) NSString *imageStr;

/**
 Payment method template string.
 */
@property (nonatomic, strong) NSString *templateStr;

- (instancetype)initWithDictionary:(NSDictionary*)dictionary;

@end


text:
package influent.kiva.server.spi;

import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import influent.idl.FL_DataAccess;
import influent.idl.FL_EntitySearch;
import influent.kiva.server.dataaccess.KivaDataAccess;
import influent.server.dataaccess.DataNamespaceHandler;
import influent.server.dataaccess.MSSQLDataNamespaceHandler;
import influent.server.sql.SQLBuilder;
import influent.server.utilities.SQLConnectionPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import oculus.aperture.spi.common.Properties;

/**
 * This class is used by the Kiva *server* implementation.
 * It binds the new FL_ implementation for that server.
 *
 */
public class KivaFLDataAccessModule extends AbstractModule {

	private static Logger s_logger = LoggerFactory.getLogger(KivaFLDataAccessModule.class);

	@Override
	protected void configure() {
		bind(FL_DataAccess.class).to(KivaDataAccess.class);
	}

	@Provides @Singleton
	public DataNamespaceHandler namespaceHandler() {
		return new MSSQLDataNamespaceHandler();
	}

	/*
	 * Provide the database service
	 */
	@Provides @Singleton
	public KivaDataAccess connect (
		@Named("aperture.server.config") Properties config,
		SQLConnectionPool connectionPool,
		FL_EntitySearch search,
		DataNamespaceHandler namespaceHandler,
		SQLBuilder sqlBuilder
	) {

		try {
			return new KivaDataAccess(
				config,
				connectionPool,
				search,
				namespaceHandler,
				sqlBuilder
			);
		} catch (Exception e) {
			addError("Failed to load Data Access", e);
			return null;
		}
	}

}


text:
package api

import (
	"github.com/Sirupsen/logrus"
	"github.com/micro/go-micro/selector"
	"net/http"
	"os"
	"strings"

	"github.com/labstack/echo"
	"github.com/micro/go-micro/broker"
	"github.com/micro/go-micro/client"
	"github.com/micro/go-micro/registry"
	"github.com/micro/go-micro/transport"
)

const (
	DefaultRequestTopic  = "gogap.micro:topic:post-api:request"
	DefaultResponseTopic = "gogap.micro:topic:post-api:response"
)

var internalAllowHeaders = []string{
	"Origin",
	"Content-Type",
	"Authorization",
	"Accept",
	"Accept-Encoding",
	"X-Requested-With",
	"X-Forwarded-Payload",
	"X-CSRF-Token",
	"X-Request-Id",
	APIHeader,
	MultiCallHeader,
	APICallTimeoutHeader,
}

type EchoEngine int

const (
	Standard EchoEngine = 0
	Fasthttp EchoEngine = 1
)

type XDomainOptions struct {
	Path    string            `json:"path"`
	LibPath string            `json:"lib_path"`
	LibUrl  string            `json:"lib_url"`
	Masters map[string]string `json:"masters"`
}

type CORSOptions struct {
	AllowOrigins     []string
	AllowMethods     []string
	AllowHeaders     []string
	ExposeHeaders    []string
	AllowCredentials bool
	MaxAge           int
}

type Option func(*Options)

type Options struct {
	Address        string
	CORS           CORSOptions
	Path           string
	ResponseHeader http.Header
	BodyLimit      string

	Engine EchoEngine

	TLSCertFile string
	TLSKeyFile  string

	MicroTLSCertFile string
	MicroTLSKeyFile  string

	Client    client.Client
	Transport transport.Transport
	Registry  registry.Registry
	Broker    broker.Broker
	Selector  selector.Selector

	Middlewares []echo.MiddlewareFunc

	EnableRequestTopic  bool
	EnableResponseTopic bool

	MicroHeaders []string

	ResponseTopic string
	RequestTopic  string

	Logger *logrus.Logger
}

func Address(address string) Option {
	return func(o *Options) {
		o.Address = address
	}
}

func TLSOptions(certFile, keyFile string) Option {
	return func(o *Options) {
		o.TLSCertFile = certFile
		o.TLSKeyFile = keyFile
	}
}

func TLSOptionsFromEnv(cert, key string) Option {
	return func(o *Options) {
		o.TLSCertFile = os.Getenv(cert)
		o.TLSKeyFile = os.Getenv(key)
	}
}

func ResponseHeader(key, val string) Option {
	return func(o *Options) {
		if key != "" {
			if o.ResponseHeader == nil {
				o.ResponseHeader = make(http.Header)
			}
			o.ResponseHeader.Set(key, val)
		}
	}
}

func CORS(cors CORSOptions) Option {
	return func(o *Options) {

		allowHeaders := distinctString(append(internalAllowHeaders, cors.AllowHeaders...))
		allowMethods := distinctString(append(cors.AllowMethods, "POST"))
		exposeHeaders := distinctString(cors.ExposeHeaders)

		o.CORS.AllowHeaders = allowHeaders
		o.CORS.AllowMethods = allowMethods
		o.CORS.ExposeHeaders = exposeHeaders
		o.CORS.AllowOrigins = cors.AllowOrigins
		o.CORS.AllowCredentials = cors.AllowCredentials
		o.CORS.MaxAge = cors.MaxAge

	}
}

func Engine(engine EchoEngine) Option {
	return func(o *Options) {
		o.Engine = engine
	}
}

func Path(path string) Option {
	return func(o *Options) {
		o.Path = path
	}
}

func BodyLimit(size string) Option {
	return func(o *Options) {
		if size == "" {
			o.BodyLimit = "2M"
		}
	}
}

func Logger(logger *logrus.Logger) Option {
	return func(o *Options) {
		o.Logger = logger
	}
}

func Middlewares(middlewares ...echo.MiddlewareFunc) Option {
	return func(o *Options) {
		o.Middlewares = append(o.Middlewares, middlewares...)
	}
}

func MicroClient(c client.Client) Option {
	return func(o *Options) {
		if c != nil {
			o.Client = c
		}
	}
}

func MicroHeaders(headers ...string) Option {
	return func(o *Options) {
		o.MicroHeaders = distinctString(headers)
	}
}

func MicroTransport(t transport.Transport) Option {
	return func(o *Options) {
		if t != nil {
			o.Transport = t

			if o.Client != nil {
				o.Client.Init(client.Transport(t))
			}
		}
	}
}

func MicroRegistry(r registry.Registry) Option {
	return func(o *Options) {
		o.Registry = r

		if o.Client != nil {
			o.Client.Init(client.Registry(r))
		}
	}
}

func MicroSelector(s selector.Selector) Option {
	return func(o *Options) {
		o.Selector = s

		if o.Client != nil {
			o.Client.Init(client.Selector(s))
		}
	}
}

func MicroTLSOptions(certFile, keyFile string) Option {
	return func(o *Options) {
		o.MicroTLSCertFile = certFile
		o.MicroTLSKeyFile = keyFile
	}
}

func MicroBroker(b broker.Broker) Option {
	return func(o *Options) {
		o.Broker = b
	}
}

func EnableResponseTopic(enable bool) Option {
	return func(o *Options) {
		o.EnableResponseTopic = enable
	}
}

func EnableRequestTopic(enable bool) Option {
	return func(o *Options) {
		o.EnableRequestTopic = enable
	}
}

func Topic(requestTopic, responseTopic string) Option {
	return func(o *Options) {
		requestTopic = strings.TrimSpace(requestTopic)
		responseTopic = strings.TrimSpace(responseTopic)

		if requestTopic == "" {
			requestTopic = DefaultRequestTopic
		}

		if responseTopic == "" {
			responseTopic = DefaultResponseTopic
		}

		o.RequestTopic = requestTopic
		o.ResponseTopic = responseTopic
	}
}

func distinctString(values []string) []string {
	if values == nil {
		return nil
	}

	distinctCache := map[string]string{}

	for _, v := range values {
		distinctCache[strings.ToLower(v)] = v
	}

	newValues := []string{}

	for _, v := range distinctCache {
		newValues = append(newValues, v)
	}

	return newValues
}


text:
from __future__ import print_function

import requests
import os
import json

METHOD = {
    'https': 'https://',
    'http': 'http://'
}

URLS = {
    'TOKEN':               '/api/token-auth/',
    'PROJECTS':            '/api/repository/projects/',
    'SPECIMENS':           '/api/repository/specimens/',
    'SUBJECT_GROUPS':      '/api/repository/subject_groups/',
    'SITES':               '/api/repository/sites/',
    'SUBJECTS':            '/api/repository/subjects/',
    'PROJECT_PANELS':      '/api/repository/panel_templates/',
    'SITE_PANELS':         '/api/repository/site_panels/',
    'COMPENSATIONS':       '/api/repository/compensations/',
    'CREATE_COMPENSATION': '/api/repository/compensations/add/',
    'STIMULATIONS':        '/api/repository/stimulations/',
    'SAMPLES':             '/api/repository/samples/',
    'CREATE_SAMPLES':      '/api/repository/samples/add/',
    'SAMPLE_METADATA':     '/api/repository/samplemetadata/',
    'VISIT_TYPES':         '/api/repository/visit_types/',
    'SAMPLE_COLLECTION':   '/api/repository/sample_collections/',

    # Process related API URLs
    'PROCESSES':                 '/api/repository/processes/',
    'WORKERS':                   '/api/repository/workers/',
    'VERIFY_WORKER':             '/api/repository/verify_worker/',
    'PROCESS_REQUESTS':          '/api/repository/process_requests/',
    'VIABLE_PROCESS_REQUESTS':   '/api/repository/viable_process_requests/',
    'ASSIGNED_PROCESS_REQUESTS': '/api/repository/assigned_process_requests/',
    'CLUSTERS':                  '/api/repository/clusters/',
    'SAMPLE_CLUSTERS':           '/api/repository/sample_clusters/',
    'SAMPLE_CLUSTER_COMPONENTS': '/api/repository/sample_cluster_components/',
}

def get_request(token, url, params=None):
    """
    Returns a dictionary with the following keys:
        status: HTTP response status code
        reason: HTTP response reason
        data: A dictionary converted from JSON response data
    """

    headers = {
        'User-Agent': 'python',
        'Authorization': "Token %s" % token,
    }

    response = requests.get(url, headers=headers, params=params, verify=False)

    if response.status_code == 200:
        try:
            data = response.json()
        except Exception as e:
            data = response.text()
            print(e)
    else:
        data = response.text

    return {
        'status': response.status_code,
        'reason': response.reason,
        'data': data,
    }

def get_token(host, username, password, method=METHOD['https']):
    """
    Login to host url using user credentials given.

    Returns the authenticating user's token (string) if successful,
    returns None if authentication failed.
    """
    url = '%s%s%s' % (method, host, URLS['TOKEN'])

    token = None

    data = {
        'username': username,
        'password': password,
    }

    try:
        response = requests.post(url, data=data, verify=False)
    except Exception as e:
        print(e)
        return None

    if response.status_code == 200:
        try:
            data = response.json()
            if 'token' in data:
                token = data['token']
                # delete all the user credentials
                del(data, response, username, password)
            else:
                print("Authentication token not in response")

        except Exception as e:
            print(e)
            return None
    else:
        print("Authentication failed (%s: %s)" % (
            response.status_code, response.reason))

    return token

def get_projects(host, token, project_name=None, method=METHOD['https']):
    url = '%s%s%s' % (method, host, URLS['PROJECTS'])
    filter_params = dict()

    if project_name is not None:
        filter_params['project_name'] = project_name

    return get_request(token, url, filter_params)

def get_project(host, token, project_pk, method=METHOD['https']):
    """
    GET a serialized Project instance
        project_pk    (required)

    Returns a dictionary with keys:
        'status': The HTTP response code
        'reason': The HTTP response reason
        'data': Dictionary representation of object
    """
    url = '%s%s%s%s/' % (method, host, URLS['PROJECTS'], project_pk)
    return get_request(token, url)

def get_specimens(host, token, specimen_name=None, method=METHOD['https']):
    url = '%s%s%s' % (method, host, URLS['SPECIMENS'])
    filter_params = dict()

    if specimen_name is not None:
        filter_params['specimen_name'] = specimen_name

    return get_request(token, url, filter_params)

def get_subject_groups(
        host,
        token,
        group_name=None,
        project_pk=None,
        method=METHOD['https']):
    url = '%s%s%s' % (method, host, URLS['SUBJECT_GROUPS'])
    filter_params = dict()

    if group_name is not None:
        filter_params['group_name'] = group_name

    if project_pk is not None:
        filter_params['project'] = project_pk

    return get_request(token, url, filter_params)

def get_visit_types(
        host,
        token,
        visit_type_name=None,
        project_pk=None,
        method=METHOD['https']):
    url = '%s%s%s' % (method, host, URLS['VISIT_TYPES'])
    filter_params = dict()

    if visit_type_name is not None:
        filter_params['visit_type_name'] = visit_type_name

    if project_pk is not None:
        filter_params['project'] = project_pk

    return get_request(token, url, filter_params)

def get_visit_type(host, token, visit_type_pk, method=METHOD['https']):
    """
    GET a serialized ProjectVisitType instance
        visit_type_pk    (required)

    Returns a dictionary with keys:
        'status': The HTTP response code
        'reason': The HTTP response reason
        'data': Dictionary representation of object
    """
    url = '%s%s%s%s/' % (method, host, URLS['VISIT_TYPES'], visit_type_pk)
    return get_request(token, url)

def get_sites(
        host,
        token,
        site_name=None,
        project_pk=None,
        method=METHOD['https']):
    url = '%s%s%s' % (method, host, URLS['SITES'])
    filter_params = dict()

    if site_name is not None:
        filter_params['site_name'] = site_name

    if project_pk is not None:
        filter_params['project'] = project_pk

    return get_request(token, url, filter_params)

def get_site(host, token, site_pk, method=METHOD['https']):
    """
    GET a serialized Site instance
        site_pk    (required)

    Returns a dictionary with keys:
        'status': The HTTP response code
        'reason': The HTTP response reason
        'data': Dictionary representation of object
    """
    url = '%s%s%s%s/' % (method, host, URLS['SITES'], site_pk)
    return get_request(token, url)

def get_subjects(
        host,
        token,
        subject_code=None,
        project_pk=None,
        subject_group_pk=None,
        method=METHOD['https']):
    url = '%s%s%s' % (method, host, URLS['SUBJECTS'])
    filter_params = dict()

    if subject_code is not None:
        filter_params['subject_code'] = subject_code

    if project_pk is not None:
        filter_params['project'] = project_pk

    if subject_group_pk is not None:
        filter_params['subject_group'] = subject_group_pk

    return get_request(token, url, filter_params)

def get_subject(host, token, subject_pk, method=METHOD['https']):
    """
    GET a serialized Subject instance
        subject_pk    (required)

    Returns a dictionary with keys:
        'status': The HTTP response code
        'reason': The HTTP response reason
        'data': Dictionary representation of object
    """
    url = '%s%s%s%s/' % (method, host, URLS['SUBJECTS'], subject_pk)
    return get_request(token, url)

def get_project_panels(
        host,
        token,
        panel_name=None,
        staining=None,
        project_pk=None,
        method=METHOD['https']):
    url = '%s%s%s' % (method, host, URLS['PROJECT_PANELS'])
    filter_params = dict()

    if panel_name is not None:
        filter_params['panel_name'] = panel_name

    if staining is not None:
        filter_params['staining'] = staining

    if project_pk is not None:
        filter_params['project'] = project_pk

    return get_request(token, url, filter_params)

def get_project_panel(host, token, project_panel_pk, method=METHOD['https']):
    """
    GET a serialized ProjectPanel instance
        project_panel_pk    (required)

    Returns a dictionary with keys:
        'status': The HTTP response code
        'reason': The HTTP response reason
        'data': Dictionary representation of object
    """
    url = '%s%s%s%s/' % (method, host, URLS['PROJECT_PANELS'], project_panel_pk)
    return get_request(token, url)

def get_site_panels(
        host,
        token,
        project_panel_pk=None,
        site_pk=None,
        project_pk=None,
        panel_type=None,
        method=METHOD['https']):
    url = '%s%s%s' % (method, host, URLS['SITE_PANELS'])
    filter_params = dict()

    if site_pk is not None:
        filter_params['site'] = site_pk

    if project_panel_pk is not None:
        filter_params['panel_template'] = project_panel_pk

    if project_pk is not None:
        filter_params['project'] = project_pk

    if panel_type is not None:
        filter_params['panel_type'] = panel_type

    return get_request(token, url, filter_params)

def get_site_panel(host, token, site_panel_pk, method=METHOD['https']):
    """
    GET a serialized SitePanel instance
        site_panel_pk    (required)

    Returns a dictionary with keys:
        'status': The HTTP response code
        'reason': The HTTP response reason
        'data': Dictionary representation of object
    """
    url = '%s%s%s%s/' % (method, host, URLS['SITE_PANELS'], site_panel_pk)
    return get_request(token, url)

def is_site_panel_match(
        host,
        token,
        site_panel_pk,
        parameter_dict,
        method=METHOD['https']):
    """
    GET a serialized ProjectPanel instance
        site_panel_pk    (required)

    Returns True/False whether dictionary matches the site panel
    """

    # TODO: verify the parameter_dict

    response = get_site_panel(host, token, site_panel_pk, method=method)

    site_parameters = None

    if 'data' in response:
        if 'parameters' in response['data']:
            site_parameters = response['data']['parameters']

    matches = dict()
    non_matches = dict()
    missing = dict()

    if site_parameters:
        for param in site_parameters:
            if 'fcs_number' in param:
                if param['fcs_number'] in parameter_dict:
                    candidate = parameter_dict[param['fcs_number']]
                    if 'n' not in candidate:
                        non_matches[param['fcs_number']] = candidate
                        continue
                    if candidate['n'] != param['fcs_text']:
                        non_matches[param['fcs_number']] = candidate
                        continue
                    if 's' not in candidate and param['fcs_opt_text'] != '':
                        non_matches[param['fcs_number']] = candidate
                        continue
                    elif 's' in candidate:
                        if candidate['s'] != param['fcs_opt_text']:
                            non_matches[param['fcs_number']] = candidate
                            continue
                    # if we get here, everything matched
                    matches[param['fcs_number']] = candidate
                else:
                    missing[param['fcs_number']] = [
                        param['fcs_text'],
                        param['fcs_opt_text']
                    ]

    if (len(matches) == len(site_parameters)) and \
            len(non_matches) == 0 and \
            len(missing) == 0:
        return True

    return False

def get_compensations(
        host,
        token,
        name=None,
        site_panel_pk=None,
        site_pk=None,
        project_pk=None,
        acquisition_date=None,
        method=METHOD['https']):
    url = '%s%s%s' % (method, host, URLS['COMPENSATIONS'])
    filter_params = dict()

    if name is not None:
        filter_params['name'] = name

    if site_panel_pk is not None:
        filter_params['site_panel'] = site_panel_pk

    if site_pk is not None:
        filter_params['site'] = site_pk

    if project_pk is not None:
        filter_params['project'] = project_pk

    if acquisition_date is not None:
        filter_params['acquisition_date'] = acquisition_date

    return get_request(token, url, filter_params)

def get_compensation(host, token, compensation_pk, method=METHOD['https']):
    """
    GET a serialized Compensation instance
        compensation_pk    (required)

    Returns a dictionary with keys:
        'status': The HTTP response code
        'reason': The HTTP response reason
        'data': Dictionary representation of object
    """
    url = '%s%s%s%s/' % (method, host, URLS['COMPENSATIONS'], compensation_pk)
    return get_request(token, url)

def get_stimulations(
        host,
        token,
        project_pk=None,
        stimulation_name=None,
        method=METHOD['https']):
    url = '%s%s%s' % (method, host, URLS['STIMULATIONS'])
    filter_params = dict()

    if project_pk is not None:
        filter_params['project'] = project_pk

    if stimulation_name is not None:
        filter_params['stimulation_name'] = stimulation_name

    return get_request(token, url, filter_params)

def get_stimulation(host, token, stimulation_pk, method=METHOD['https']):
    """
    GET a serialized Stimulation instance
        stimulation_pk    (required)

    Returns a dictionary with keys:
        'status': The HTTP response code
        'reason': The HTTP response reason
        'data': Dictionary representation of object
    """
    url = '%s%s%s%s/' % (method, host, URLS['STIMULATIONS'], stimulation_pk)
    return get_request(token, url)

def get_samples(
        host,
        token,
        subject_pk=None,
        site_pk=None,
        project_pk=None,
        visit_pk=None,
        stimulation_pk=None,
        specimen_pk=None,
        site_panel_pk=None,
        project_panel_pk=None,
        original_filename=None,
        subject_code=None,
        acquisition_date=None,
        sha1=None,
        method=METHOD['https']):
    url = '%s%s%s' % (method, host, URLS['SAMPLES'])
    filter_params = dict()

    if subject_pk is not None:
        filter_params['subject'] = subject_pk

    if site_pk is not None:
        filter_params['site'] = site_pk

    if project_pk is not None:
        filter_params['project'] = project_pk

    if visit_pk is not None:
        filter_params['visit'] = visit_pk

    if stimulation_pk is not None:
        filter_params['stimulation'] = stimulation_pk

    if specimen_pk is not None:
        filter_params['specimen'] = specimen_pk

    if site_panel_pk is not None:
        filter_params['site_panel'] = site_panel_pk

    if project_panel_pk is not None:
        filter_params['panel'] = project_panel_pk

    if original_filename is not None:
        filter_params['original_filename'] = original_filename

    if subject_code is not None:
        filter_params['subject_code'] = subject_code

    if acquisition_date is not None:
        filter_params['acquisition_date'] = acquisition_date

    if sha1 is not None:
        filter_params['sha1'] = sha1

    return get_request(token, url, filter_params)

def get_sample(host, token, sample_pk, method=METHOD['https']):
    """
    GET a serialized Sample instance
        sample_pk    (required)

    Returns a dictionary with keys:
        'status': The HTTP response code
        'reason': The HTTP response reason
        'data': Dictionary representation of object
    """
    url = '%s%s%s%s/' % (method, host, URLS['SAMPLES'], sample_pk)
    return get_request(token, url)

def download_sample(
        host,
        token,
        sample_pk,
        filename=None,
        directory=None,
        method=METHOD['https']):
    """
    Download sample as FCS
    """
    url = "%s%s/api/repository/samples/%d/fcs_original/" % (method, host, sample_pk)

    if filename is None:
        filename = str(sample_pk) + '.fcs'
    if directory is None:
        directory = os.getcwd()

    headers = {'Authorization': "Token %s" % token}
    data = ''
    try:
        r = requests.get(url, headers=headers, verify=False)
    except Exception as e:
        print(e)
        return {'status': None, 'reason': 'No response', 'data': data}

    if r.status_code == 200:
        try:
            with open("%s/%s" % (directory, filename), "wb") as data_file:
                data_file.write(r.content)
        except Exception as e:
            print(e)
    else:
        data = r.text

    return {
        'status': r.status_code,
        'reason': r.reason,
        'data': data,
    }

def download_clean_sample(
        host,
        token,
        sample_pk,
        filename=None,
        directory=None,
        method=METHOD['https']):
    """
    Download clean sample as FCS
    """
    url = "%s%s/api/repository/samples/%d/fcs_clean/" % (
        method,
        host,
        sample_pk
    )

    if filename is None:
        filename = str(sample_pk) + '_clean.fcs'
    if directory is None:
        directory = os.getcwd()

    headers = {'Authorization': "Token %s" % token}
    data = ''
    try:
        r = requests.get(url, headers=headers, verify=False)
    except Exception as e:
        print(e)
        return {'status': None, 'reason': 'No response', 'data': data}

    if r.status_code == 200:
        try:
            with open("%s/%s" % (directory, filename), "wb") as data_file:
                data_file.write(r.content)
        except Exception as e:
            print(e)
    else:
        data = r.text

    return {
        'status': r.status_code,
        'reason': r.reason,
        'data': data,
    }

def post_sample(
        host,
        token,
        file_path,
        subject_pk,
        visit_type_pk,
        specimen_pk,
        pretreatment,
        storage,
        stimulation_pk,
        site_panel_pk,
        acquisition_date,
        compensation_pk=None,
        method=METHOD['https']):
    """
    POST a FCS sample, associating the file with the following:
        subject_pk       (required)
        visit_type_pk    (required)
        specimen_pk      (required)
        pretreatment     (required)
        storage          (required)
        stimulation_pk   (required)
        site_panel_pk    (required)
        acquisition_date (required)
        compensation_pk  (optional)

    Returns a dictionary with keys:
        'status': The HTTP response code
        'reason': The HTTP response reason
        'data': Dictionary string representation of object successfully posted,
                empty string if unsuccessful
    """

    url = '%s%s%s' % (method, host, URLS['CREATE_SAMPLES'])
    headers = {'Authorization': "Token %s" % token}

    # Subject, visit, specimen, stimulation, and site_panel are required
    data = {
        'subject': subject_pk,
        'visit': visit_type_pk,
        'specimen': specimen_pk,
        'pretreatment': pretreatment,
        'storage': storage,
        'stimulation': stimulation_pk,
        'site_panel': site_panel_pk,
        'acquisition_date': acquisition_date
    }

    # add the compensation field if present
    if compensation_pk:
        data['compensation'] = compensation_pk

    file_obj = open(file_path, "rb")

    # get FCS file
    files = {
        'sample_file': (os.path.basename(file_obj.name), file_obj)
    }

    try:
        response = requests.post(
            url,
            headers=headers,
            data=data,
            files=files,
            verify=False)
    except Exception as e:
        file_obj.close()
        print(e)
        return {'status': None, 'reason': 'No response', 'data': ''}

    file_obj.close()

    if response.status_code == 201:
        try:
            data = response.json()
        except Exception as e:
            data = response.text()
            print(e)
    else:
        data = response.text

    return {
        'status': response.status_code,
        'reason': response.reason,
        'data': data,
    }

def get_sample_metadata(
        host,
        token,
        sample_pk=None,
        key=None,
        method=METHOD['https']):
    url = '%s%s%s' % (method, host, URLS['SAMPLE_METADATA'])
    filter_params = dict()

    if sample_pk is not None:
        filter_params['sample'] = sample_pk

    if key is not None:
        filter_params['key'] = key

    return get_request(token, url, filter_params)

def get_sample_collection(
        host,
        token,
        sample_collection_pk,
        method=METHOD['https']):
    """
    GET a serialized Sample Collection instance
        sample_collection_pk    (required)

    Returns a dictionary with keys:
        'status': The HTTP response code
        'reason': The HTTP response reason
        'data': Dictionary representation of object
    """
    url = '%s%s%s%s/' % (
        method,
        host,
        URLS['SAMPLE_COLLECTION'],
        sample_collection_pk
    )
    return get_request(token, url)

def download_compensation(
        host,
        token,
        compensation_pk,
        data_format='npy',
        filename=None,
        directory=None,
        method=METHOD['https']):
    """
    Download sample data as CSV or Numpy (npy)

    Options:
        'data_format': 'npy' (default) or 'csv'
        'filename': filename to use for downloaded file
                    (default is the comp_<PK>.<format>, eg comp_42.npy)
    """
    if data_format == 'npy':
        url = "%s%s/api/repository/compensations/%d/npy/" % (
            method, host, compensation_pk)
    elif data_format == 'csv':
        url = "%s%s/api/repository/compensations/%d/csv/" % (
            method, host, compensation_pk)
    else:
        print("Data format %s not supported, use 'npy' or 'csv'" % data_format)
        return

    if filename is None:
        filename = 'comp_' + str(compensation_pk) + '.' + data_format
    if directory is None:
        directory = os.getcwd()

    headers = {'Authorization': "Token %s" % token}
    data = ''
    try:
        r = requests.get(url, headers=headers, verify=False)
    except Exception as e:
        print(e)
        return {'status': None, 'reason': 'No response', 'data': data}

    if r.status_code == 200:
        try:
            with open("%s/%s" % (directory, filename), "wb") as data_file:
                data_file.write(r.content)
        except Exception as e:
            print(e)
    else:
        data = r.text

    return {
        'status': r.status_code,
        'reason': r.reason,
        'data': data,
    }

def post_compensation(
        host,
        token,
        name,
        panel_template_pk,
        acquisition_date,
        matrix_text,
        method=METHOD['https']):
    """
    POST a compensation matrix. The matrix text can be comma or tab delimited.
        name              (required)
        panel_template_pk (required)
        acquisition_date  (required)
        matrix_text       (required)

    Returns a dictionary with keys:
        'status': The HTTP response code
        'reason': The HTTP response reason
        'data': Dictionary string representation of object successfully posted,
                empty string if unsuccessful
    """

    url = '%s%s%s' % (method, host, URLS['CREATE_COMPENSATION'])
    headers = {'Authorization': "Token %s" % token}

    # Subject, visit, specimen, stimulation, and site_panel are required
    data = {
        'name': name,
        'panel_template': panel_template_pk,
        'acquisition_date': acquisition_date,
        'matrix_text': matrix_text
    }

    try:
        response = requests.post(
            url,
            headers=headers,
            data=data,
            verify=False)
    except Exception as e:
        print(e)
        return {'status': None, 'reason': 'No response', 'data': ''}

    if response.status_code == 201:
        try:
            data = response.json()
        except Exception as e:
            data = response.text()
            print(e)
    else:
        data = response.text

    return {
        'status': response.status_code,
        'reason': response.reason,
        'data': data,
    }

###################################
# START PROCESS MANAGER FUNCTIONS #
#    Note: Most of these require  #
#    the user to be a superuser   #
#    or a Worker                  #
###################################
def get_processes(host, token, process_name=None, method=METHOD['https']):
    url = '%s%s%s' % (method, host, URLS['PROCESSES'])
    filter_params = dict()

    if process_name is not None:
        filter_params['process_name'] = process_name

    return get_request(token, url, filter_params)

def get_workers(host, token, worker_name=None, method=METHOD['https']):
    url = '%s%s%s' % (method, host, URLS['WORKERS'])
    filter_params = dict()

    if worker_name is not None:
        filter_params['worker_name'] = worker_name

    return get_request(token, url, filter_params)

def get_process_requests(
        host,
        token,
        process_pk=None,
        worker_pk=None,
        request_user_pk=None,
        method=METHOD['https']):
    url = '%s%s%s' % (method, host, URLS['PROCESS_REQUESTS'])
    filter_params = dict()

    if process_pk is not None:
        filter_params['process'] = process_pk

    if worker_pk is not None:
        filter_params['worker'] = worker_pk

    if request_user_pk is not None:
        filter_params['request_user'] = request_user_pk

    return get_request(token, url, filter_params)

def get_assigned_process_requests(
        host,
        token,
        method=METHOD['https']):
    """
    Returns process requests that are assigned to the requesting worker
    i.e. the requesting user must be a Worker in the ReFlow server
    Also, only non-Completed requests will be returned
    """
    url = '%s%s%s' % (method, host, URLS['ASSIGNED_PROCESS_REQUESTS'])
    filter_params = dict()

    return get_request(token, url, filter_params)

def get_viable_process_requests(
        host,
        token,
        process_pk=None,
        worker_pk=None,
        request_user_pk=None,
        method=METHOD['https']):
    """
    Returns process requests that are compatible with the requesting user
    i.e. the requesting user must be a Worker registered with the Process
    Also, only unassigned 'Pending' requests will be returned
    """
    url = '%s%s%s' % (method, host, URLS['VIABLE_PROCESS_REQUESTS'])
    filter_params = dict()

    if process_pk is not None:
        filter_params['process'] = process_pk

    if worker_pk is not None:
        filter_params['worker'] = worker_pk

    if request_user_pk is not None:
        filter_params['request_user'] = request_user_pk

    return get_request(token, url, filter_params)

def get_process_request(
        host,
        token,
        process_request_pk,
        method=METHOD['https']):
    """
    GET a serialized ProcessRequest instance
        process_request_pk    (required)

    Returns a dictionary with keys:
        'status': The HTTP response code
        'reason': The HTTP response reason
        'data': Dictionary representation of object
    """
    url = '%s%s%s%s/' % (
        method,
        host,
        URLS['PROCESS_REQUESTS'],
        process_request_pk)
    return get_request(token, url)

def request_pr_assignment(
        host,
        token,
        process_request_pk,
        method=METHOD['https']):
    """
    Requesting user must be a Worker registered with the Process and
    and the ProcessRequest must have 'Pending' status
    """
    url = '%s%s%s%s/%s/' % (
        method,
        host,
        URLS['PROCESS_REQUESTS'],
        process_request_pk,
        'request_assignment')
    headers = {'Authorization': "Token %s" % token}

    try:
        r = requests.patch(
            url,
            data={
                'process_request':
                process_request_pk
            },
            headers=headers,
            verify=False)
    except Exception as e:
        print(e)
        return {'status': None, 'reason': 'No response', 'data': ''}

    if r.status_code == 201:
        try:
            data = r.json()
        except Exception as e:
            data = r.text()
            print(e)
    else:
        data = r.text

    return {
        'status': r.status_code,
        'reason': r.reason,
        'data': data,
    }

def report_pr_error(
        host,
        token,
        process_request_pk,
        error_msg_string,
        method=METHOD['https']):
    """
    Requesting user must be a Worker assigned to the ProcessRequest and
    and the ProcessRequest must have 'Worker' status
    """
    url = '%s%s%s%s/%s/' % (
        method,
        host,
        URLS['PROCESS_REQUESTS'],
        process_request_pk,
        'report_error')
    headers = {'Authorization': "Token %s" % token}

    r = requests.patch(
        url,
        data={
            'status_message': error_msg_string
        },
        headers=headers,
        verify=False
    )

    if r.status_code == 201:
        data = r.json()
    else:
        data = r.text

    return {
        'status': r.status_code,
        'reason': r.reason,
        'data': data,
    }

def verify_pr_assignment(
        host,
        token,
        process_request_pk,
        method=METHOD['https']):
    """
    Result will include 'assignment': True of request.user (Worker) is assigned
    to the specified ProcessRequest
    """
    url = '%s%s%s%s/%s/' % (
        method,
        host,
        URLS['PROCESS_REQUESTS'],
        process_request_pk,
        'verify_assignment')
    filter_params = dict()

    if process_request_pk is not None:
        filter_params['process_request'] = process_request_pk

    return get_request(token, url, filter_params)

def revoke_pr_assignment(
        host,
        token,
        process_request_pk,
        method=METHOD['https']):
    """
    Requests un-assignment from a ProcessRequest on the ReFlow server
    """
    url = '%s%s%s%s/%s/' % (
        method,
        host,
        URLS['PROCESS_REQUESTS'],
        process_request_pk,
        'revoke_assignment')
    filter_params = dict()

    if process_request_pk is not None:
        filter_params['process_request'] = process_request_pk

    return get_request(token, url, filter_params)

def purge_pr_results(
        host,
        token,
        process_request_pk,
        method=METHOD['https']):
    """
    Requests that previous ProcessRequest results be deleted. Only works
    for uncompleted PRs, and only for the assigned Worker.
    """
    url = '%s%s%s%s/%s/' % (
        method,
        host,
        URLS['PROCESS_REQUESTS'],
        process_request_pk,
        'purge_results')
    filter_params = dict()

    if process_request_pk is not None:
        filter_params['process_request'] = process_request_pk

    return get_request(token, url, filter_params)

def report_pr_progress(
        host,
        token,
        process_request_pk,
        percent_complete,
        method=METHOD['https']):
    """
    Requesting user must be a Worker assigned to the ProcessRequest and
    and the ProcessRequest must have 'Worker' status. Percent complete should
    be an integer, and will be reported back as such to the ReFlow server.
    """
    url = '%s%s%s%s' % (
        method,
        host,
        URLS['PROCESS_REQUESTS'],
        process_request_pk)
    headers = {'Authorization': "Token %s" % token}

    r = requests.patch(
        url,
        data={
            'percent_complete': percent_complete
        },
        headers=headers,
        verify=False
    )

    if r.status_code == 201:
        data = r.json()
    else:
        data = r.text

    return {
        'status': r.status_code,
        'reason': r.reason,
        'data': data,
    }

def complete_pr_assignment(
        host,
        token,
        process_request_pk,
        method=METHOD['https']):
    """
    Report that the ProcessRequest has been completed
    """
    url = '%s%s%s%s/%s/' % (
        method,
        host,
        URLS['PROCESS_REQUESTS'],
        process_request_pk,
        'complete_assignment')
    filter_params = dict()

    if process_request_pk is not None:
        filter_params['process_request'] = process_request_pk

    return get_request(token, url, filter_params)

def verify_worker(host, token, method=METHOD['https']):
    """
    Result will include 'worker': True if request.user is a Worker on host
    """
    url = '%s%s%s' % (method, host, URLS['VERIFY_WORKER'])
    filter_params = dict()

    return get_request(token, url, filter_params)

def post_cluster(
        host,
        token,
        process_request_id,
        cluster_index,
        method=METHOD['https']):
    """
    POST a Cluster instance.
        process_request_id (required)
        cluster_index      (required)

    Returns a dictionary with keys:
        'status': The HTTP response code
        'reason': The HTTP response reason
        'data': Dictionary string representation of object successfully posted,
                empty string if unsuccessful
    """

    url = '%s%s%s' % (method, host, URLS['CLUSTERS'])
    headers = {'Authorization': "Token %s" % token}

    # process_request and index are required
    data = {
        'process_request': process_request_id,
        'index': cluster_index
    }

    try:
        response = requests.post(
            url,
            headers=headers,
            data=data,
            verify=False)
    except Exception as e:
        print(e)
        return {'status': None, 'reason': 'No response', 'data': ''}

    if response.status_code == 201:
        try:
            data = response.json()
        except Exception as e:
            data = response.text()
            print(e)
    else:
        data = response.text

    return {
        'status': response.status_code,
        'reason': response.reason,
        'data': data,
    }

def post_sample_cluster(
        host,
        token,
        cluster_id,
        sample_id,
        param_dict,
        events,
        event_percentage,
        components,
        method=METHOD['https']):
    """
    POST a SampleCluster instance.
        cluster_id     (required)
        param_dict     (required)
        event_indices  (required)

    Returns a dictionary with keys:
        'status': The HTTP response code
        'reason': The HTTP response reason
        'data': Dictionary string representation of object successfully posted,
                empty string if unsuccessful
    """

    url = '%s%s%s' % (method, host, URLS['SAMPLE_CLUSTERS'])
    headers = {
        'Authorization': "Token %s" % token,
        'Content-type': 'application/json'  # b/c of the nested param_dict
    }

    # process_request and index are required
    data = {
        'cluster_id': cluster_id,
        'sample_id': sample_id,
        'parameters': param_dict,
        'events': events,
        'event_percentage': event_percentage,
        'components': components
    }

    # convert to JSON b/c of nested objects (param_dict)
    data = json.dumps(data)

    response = requests.post(
        url,
        headers=headers,
        data=data,
        verify=False)

    if response.status_code == 201:
        try:
            data = response.json()
        except Exception as e:
            # Since we got a 201 response but couldn't JSON-ify the response,
            # we still need to return something sensible
            data = response.text()
            print(e)
    else:
        data = response.text

    return {
        'status': response.status_code,
        'reason': response.reason,
        'data': data,
    }

def get_sample_clusters(
        host,
        token,
        process_request_pk=None,
        method=METHOD['https']):
    url = '%s%s%s' % (method, host, URLS['SAMPLE_CLUSTERS'])
    filter_params = dict()

    if process_request_pk is not None:
        filter_params['process_request'] = process_request_pk

    return get_request(token, url, filter_params)

def get_sample_cluster_components(
        host,
        token,
        process_request_pk=None,
        sample_pk=None,
        method=METHOD['https']):
    url = '%s%s%s' % (method, host, URLS['SAMPLE_CLUSTER_COMPONENTS'])
    filter_params = dict()

    if process_request_pk is not None:
        filter_params['process_request'] = process_request_pk
    if sample_pk is not None:
        filter_params['sample'] = sample_pk

    return get_request(token, url, filter_params)

def download_sample_cluster_events(
        host,
        token,
        sample_cluster_pk,
        filename=None,
        directory=None,
        method=METHOD['https']):
    """
    Download sample data as CSV or Numpy (npy)

    Options:
        'data_format': 'npy' (default) or 'csv'
        'filename': filename to use for downloaded file
                    (default is the comp_<PK>.<format>, eg comp_42.npy)
    """
    url = "%s%s/api/repository/sample_clusters/%d/csv/" % (
        method,
        host,
        sample_cluster_pk
    )

    if filename is None:
        filename = 'sample_cluster_' + str(sample_cluster_pk) + '.csv'
    if directory is None:
        directory = os.getcwd()

    headers = {'Authorization': "Token %s" % token}
    data = ''
    try:
        r = requests.get(url, headers=headers, verify=False)
    except Exception as e:
        print(e)
        return {'status': None, 'reason': 'No response', 'data': data}

    if r.status_code == 200:
        try:
            with open("%s/%s" % (directory, filename), "wb") as data_file:
                data_file.write(r.content)
        except Exception as e:
            print(e)
    else:
        data = r.text

    return {
        'status': r.status_code,
        'reason': r.reason,
        'data': data,
    }


text:
require 'calabash-android/abase'

class OrderType < Calabash::ABase

	def select_option
		performAction('click_on_text', sandwich)
	end

end


text:
/*
 //#include <CoreAudio/CoreAudio.h>
	//AudioDeviceID outputDevID;

 OSStatus
 waveIOProc(AudioDeviceID inDevice,
			const AudioTimeStamp* inNow,
			const AudioBufferList* inInputData,
			const AudioTimeStamp* inInputTime,
			AudioBufferList* outOutputData,
			const AudioTimeStamp* inOutputTime,
			void* inContext)
 {
	 float* buffer = outOutputData->mBuffers[0].mData;
	 UInt32 bufferSize = outOutputData->mBuffers[0].mDataByteSize;
	 UInt32 numChannels = outOutputData->mBuffers[0].mNumberChannels;

	 ddSoundMixer* mixer = (ddSoundMixer*)inContext;

	 if ( !dd_mixerCallback(buffer, bufferSize) )
	 {
		 dd_warn("audioCallback underrun!");
		 ddSoundMixer_stop(mixer);
		 return kAudioHardwareUnspecifiedError;
	 }

	 return kAudioHardwareNoError;
 }

 {
	 AudioDeviceID outputDevID;
	 ddSoundMixer* mixer = dd_malloc(sizeof(ddSoundMixer));

	 OSStatus status;
	 UInt32 size;

	 size = sizeof(outputDevID);
	 status = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &size, &outputDevID);

	 if ( status )
	 {
		 dd_warn("AudioHardwareGetProperty status %d", status);
		 return NULL;
	 }

	 size = sizeof(bufferByteCount);
	 bufferByteCount = MIXER_BUFFER_SIZE * sizeof(float);

	 status = AudioDeviceSetProperty(outputDevID, NULL, 0, DD_FALSE, kAudioDevicePropertyBufferSize, size, &bufferByteCount);

	 if ( status )
	 {
		 dd_warn("AudioDeviceSetProperty setting buffer size status %d", status);
		 return NULL;
	 }

	 status = AudioDeviceAddIOProc(outputDevID, waveIOProc, mixer);

	 if ( status )
	 {
		 dd_warn("AudioDeviceAddIOProc status %d", status);
		 return NULL;
	 }

	 mixer->outputDevID = outputDevID;
	 mixer->playing = DD_FALSE;

	 return mixer;
 }

 void
 ddSoundMixer_start(ddSoundMixer* mixer)
 {
#ifdef DD_PLATFORM_MAC_OS_X
	 OSStatus status;

	 status = AudioDeviceStart(mixer->outputDevID, waveIOProc);

	 if ( status )
		 dd_warn("AudioDeviceStop status %d", status);

	 mixer->playing = DD_TRUE;
#endif DD_PLATFORM_MAC_OS_X
 }

 void
 ddSoundMixer_stop(ddSoundMixer* mixer)
 {
#ifdef DD_PLATFORM_MAC_OS_X
	 OSStatus status;

	 status = AudioDeviceStop(mixer->outputDevID, waveIOProc);

	 if ( status )
		 dd_warn("AudioDeviceStop status %d", status);

	 mixer->playing = DD_FALSE;
#endif DD_PLATFORM_MAC_OS_X
 }

 */

#import "FlashView.h"
#import "SWFAction.h"
#import "SWFActionObject.h"
#import "SWFDrawable.h"
#import "SWFMovieClip.h"
#import "SWFPlayer.h"

void
setupImageClass(ddPlayer* player);

@implementation SWFPlayer

+ (id)player
{
	return [[[self alloc] init] autorelease];
}

- (id)init
{
	if ( (self = [super init]) == nil )
		return nil;

	player = nil;

	return self;
}

- (void)dealloc
{
	[root release];
	[globals release];

	dd_destroyPlayer(player);

	[super dealloc];
}

- (ddPlayer*)ddPlayer
{
	return player;
}

- (SWFMovieClip*)movieClip
{
	return [SWFMovieClip clipWithDDMovieClip:ddPlayer_getMovieClip(player)];
}

- (SWFDrawable*)drawClip
{
	return [SWFDrawable drawableWithDDDrawable:(ddDrawable*)ddPlayer_getPlayClip(player)];
}

- (float)frameRate
{
	return ddPlayer_getFrameRate(player);
}

- (void)keyDown:(unichar)c
{
	ddPlayer_doKeyDown(player, c);
}

- (void)keyUp:(unichar)c
{
	ddPlayer_doKeyUp(player, c);
}

- (BOOL)loadMovieAtPath:(NSString*)path forFlashView:(FlashView*)view
{
	ddImage* image = [view image];
	FILE* f = fopen([path cString], "r");
	player = dd_newPlayer_file(f, image);

	if ( ddPlayer_readMovie(player) < 0 )
		return NO;

	setupImageClass(player);

	ddImage_clear(image, ddPlayer_getBackgroundColor(player));

	return YES;
}

- (void)mouseDown:(NSPoint)point
{
	ddPlayer_doMouseDown(player, point.x, point.y);
}

- (void)mouseUp:(NSPoint)point
{
	ddPlayer_doMouseUp(player, point.x, point.y);
}

- (ddCursorType)mouseMoved:(NSPoint)point
{
	return ddPlayer_doMouseMove(player, point.x, point.y);
}

- (void)replaceImage:(ddImage*)image
{
	ddPlayer_setImage(player, image);
}

- (void)setTraceFunction:(void*)func userData:(void*)data
{
	dd_setActionTraceFunction(player, func, data);
}

- (SWFActionObject*)globals
{
	if ( globals == nil )
		globals = [[SWFActionObject objectWithDDActionObject:ddPlayer_getGlobals(player)] retain];

	return globals;
}

- (SWFActionObject*)root
{
	if ( root == nil )
		root = [[SWFActionObject objectWithDDActionObject:(ddActionObject*)ddPlayer_getRootClip(player)] retain];

	return root;
}

- (SWFAction*)currentAction
{
	return [self actionAtFrameDepth:0];
}

- (int)actionOffsetAtFrameDepth:(int)depth
{
	ddActionContext* context = ddPlayer_actionContextAtDepth(player, depth);
	return ddActionContext_getActionOffset(context);
}

- (int)actionStackDepth
{
	return ddPlayer_actionStackDepth(player);
}

- (NSString*)actionNameAtFrameDepth:(int)depth
{
	ddActionContext* context = ddPlayer_actionContextAtDepth(player, depth);
	char* name = ddActionContext_getLabel(context);

	if ( name != NULL )
		return [NSString stringWithCString:name];
	else
		return @"no name";
}

- (SWFAction*)actionAtFrameDepth:(int)depth
{
	ddActionContext* context = ddPlayer_actionContextAtDepth(player, depth);

	if ( context != NULL )
		return [SWFAction actionWithDDAction:ddActionContext_getAction(context)];
	else
		return nil;
}

- (BOOL)stepFrame:(ddRect**)rectsPtr nRects:(int*)countPtr mode:(ddStepMode)mode
{
	if ( !hitBreakpoint )
		ddPlayer_step(player);

	if ( ddPlayer_executeFrameActions(player, mode) )
	{
		// hit a breakpoint
		hitBreakpoint = YES;

		return NO;
	}
	else
	{
		ddPlayer_updateDisplay(player, rectsPtr, countPtr);

		[globals release];
		globals = nil;

		[root release];
		root = nil;

		hitBreakpoint = NO;

		SInt16 soundbuffer[2 * 44000];
		int size = 2 * 44000;

		ddPlayer_renderFrameSoundIntoBuffer(player, soundbuffer, &size);

		return YES;
	}
}

@end


text:
require 'letsencrypt_standalone'

module LetsencryptStandalone
  class Config < Base
    @@config = nil
    attr_accessor :config, :location, :port
    def initialize(config_file: nil)
      @location ||= config_file
      @@config ||= JSON.parse(File.read(@location), :symbolize_names => true)
    end

    def output_dir
      config.output_dir || super
    end

    %i(account domains email path).each do |meth|
      define_method meth do
        config.fetch(meth, nil)
      end
    end

    def config
      @@config
    end

    def ssl_subdir
      config[:ssl_subdir] || 'ssl_certs'
    end

    def www_root
      config[:www_root] || 'public'
    end

    def tries
      config.fetch(:tries, 5)
    end

    def add(domains:)
      domains.each do |domain|
        @@config[:domains] << {host: domain} unless @@config[:domains].any? {|h| h[:host] == domain}
      end
    end

    def push_certs_locations(files:, domain:)
      config[:domains].map! do |d|
        d[:host] == domain.host ? d.merge(certificates: files) : d
      end
    end

    def push_private_key_name(domain:)
      config[:domains].map! do |d|
        d[:host] == domain.host ? d.merge(private_key: domain.private_key_name) : d
      end
    end

    def write
      File.new(location, 'w').write(JSON.pretty_generate(config))
    end

    class << self
      def config
        @@config
      end

      def ssl_subdir
        @@config[:ssl_subdir] || 'ssl_certs'
      end
    end
  end
end


text:
RSpec.describe RoleMaking do
  it "has a version number" do
    expect(RoleMaking::VERSION).not_to be nil
  end

end


text:
/* global _, angular */

class GroveTableCtrl {
  constructor($scope, $http, Problem, GroveService, MapService, Grove, Upload, _) {
    'ngInject';
    this.$http = $http;
    this.Upload = Upload;
    this.Problem = Problem;
    this.Grove = Grove;
    this.groveService = GroveService;
    this.groveTable = GroveService.groveTable;
    this.mapService = MapService;
    this.$scope = $scope;
    this.groveService = GroveService;
    this.setUpGroves();
  }

  addGrovesToMap() {
    const groves = this.groveService.groveTable.selected;
    this.mapService.addGrovesToMap(groves)
      .then(map => {
          this.map = map;
      });
  }

  removeGrovesfromMap() {
      const groves = this.map.selectedGroves;
      this.mapService.removeGrovesfromMap(groves)
          .then(map => {
            this.map = map;
        });
  }

   selectGrove(grove) {
    if (_.includes(this.groveTable.selected, grove.id)) {
        _.remove(this.groveTable.selected, grove.id);
    } else {
      console.log('pushing', grove.id, this.groveTable.selected);
      this.groveTable.selected.push(grove.id);
    }
  }

  selectMapGrove(grove) {
      if (_.isNil(this.map.selectedGroves)) {
          this.map.selectedGroves = [];
      }
      if (_.includes(this.map.selectedGroves, grove.id)) {
          _.remove(this.map.selectedGroves, grove.id);
      } else {
        this.map.selectedGroves.push(grove.id);
      }
  }

  setUpGroves() {
    this.groveService.getGroves()
        .then(() => {
            if (this.groveTable.groves.length) {
                this.selectedGrove = this.groveTable.groves[0];
            }
        });
  }

}

let GroveTable = {
  bindings: {
    map: '=?'
  },
  controller: GroveTableCtrl,
  templateUrl: 'components/groveTable/groveTable.html'
};

export default GroveTable;


text:
/*
 * Hibernate Validator, declare and validate application constraints
 *
 * License: Apache License, Version 2.0
 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
 */
package org.hibernate.validator.internal.constraintvalidators.bv.time.past;

import java.time.Clock;
import java.time.OffsetTime;

/**
 * Check that the {@code java.time.OffsetTime} passed is in the past.
 *
 * @author Guillaume Smet
 */
public class PastValidatorForOffsetTime extends AbstractPastJavaTimeValidator<OffsetTime> {

	@Override
	protected OffsetTime getReferenceValue(Clock reference) {
		return OffsetTime.now( reference );
	}

}


text:
package org.jdfs.commons.codec;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.demux.MessageDecoderResult;
import org.jdfs.commons.request.JdfsRequestConstants;
import org.jdfs.commons.request.JdfsServerInfoRequest;

/**
 *  server状态通告请求解码器的缺省实现
 *
 * @author James Quan
 * @version 2015年2月4日 下午1:39:19
 */
public class JdfsServerInfoRequestMessageDecoder extends
		JdfsRequestMessageDecoder<JdfsServerInfoRequest> {

	private boolean ipv6 = false;

	/**
	 * 返回是否使用ipv6,缺省为{@code false}
	 * @return
	 */
	public boolean isIpv6() {
		return ipv6;
	}

	/**
	 * 设置是否使用ipv6,缺省为{@code false}
	 * @param ipv6
	 */
	public void setIpv6(boolean ipv6) {
		this.ipv6 = ipv6;
	}

	@Override
	protected int getRequestCode() {
		return JdfsRequestConstants.REQUEST_SERVER_INFO;
	}

	@Override
	protected JdfsServerInfoRequest createRequest(int batchId, int code) {
		JdfsServerInfoRequest r =  new JdfsServerInfoRequest();
		r.setBatchId(batchId);
		return r;
	}

	@Override
	protected MessageDecoderResult decodeRequest(
			DecoderState<JdfsServerInfoRequest> state, IoSession session,
			IoBuffer in) throws Exception {
		int l = 8 + (ipv6 ? 16  : 4);
		if(in.remaining() < l) {
			return MessageDecoderResult.NEED_DATA;
		}
		byte[] addr = ipv6 ? new byte[16] : new byte[4];
		in.get(addr);
		int port = in.getInt();
		int status = in.getInt();
		JdfsServerInfoRequest request = state.getRequest();
		request.setHostAddress(addr);
		request.setHostPort(port);
		request.setStatus(status);
		return MessageDecoderResult.OK;
	}

}


text:
from msrest.serialization import Model

class QueryTroubleshootingParameters(Model):
    """Parameters that define the resource to query the troubleshooting result.

    :param target_resource_id: The target resource ID to query the
     troubleshooting result.
    :type target_resource_id: str
    """

    _validation = {
        'target_resource_id': {'required': True},
    }

    _attribute_map = {
        'target_resource_id': {'key': 'targetResourceId', 'type': 'str'},
    }

    def __init__(self, target_resource_id):
        super(QueryTroubleshootingParameters, self).__init__()
        self.target_resource_id = target_resource_id


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CurrentRoomExpectedUsersProperty.cs" company="Exit Games GmbH">
//   Part of: Pun Cockpit
// </copyright>
// <author>developer@exitgames.com</author>
// --------------------------------------------------------------------------------------------------------------------

using System.Linq;
using UnityEngine.UI;

namespace Photon.Pun.Demo.Cockpit
{
    /// <summary>
    /// PhotonNetwork.CurrentRoom.ExpectedUsers UI property.
    /// </summary>
    public class CurrentRoomExpectedUsersProperty : PropertyListenerBase
    {
        public Text Text;

        string[] _cache = null;

        void Update()
        {

            if (PhotonNetwork.CurrentRoom == null || PhotonNetwork.CurrentRoom.ExpectedUsers == null)
            {
                if (_cache != null)
                {
                    _cache = null;
                    Text.text = "n/a";
                }

                return;

            }

            if (_cache == null || (PhotonNetwork.CurrentRoom.ExpectedUsers != null && !PhotonNetwork.CurrentRoom.ExpectedUsers.SequenceEqual(_cache)))
            {

                Text.text = string.Join("\n", PhotonNetwork.CurrentRoom.ExpectedUsers);

                this.OnValueChanged();

                return;
            }

            if (PhotonNetwork.CurrentRoom.ExpectedUsers == null && _cache != null)
            {

                Text.text = string.Join("\n", PhotonNetwork.CurrentRoom.ExpectedUsers);

                this.OnValueChanged();

                return;
            }
        }
    }
}


text:
import { IPromise } from 'angular';

import { IVpc, NetworkReader } from '@spinnaker/core';

export class VpcReader {
  private static cache: IPromise<IVpc[]>;

  public static listVpcs(): IPromise<IVpc[]> {
    if (this.cache) {
      return this.cache;
    }
    this.cache = NetworkReader.listNetworksByProvider('aws').then((vpcs: IVpc[]) => {
      return vpcs.map(vpc => {
        vpc.label = vpc.name;
        vpc.deprecated = !!vpc.deprecated;
        if (vpc.deprecated) {
          vpc.label += ' (deprecated)';
        }
        return vpc;
      });
    });
    return this.cache;
  }

  public static resetCache() {
    this.cache = null;
  }

  public static getVpcName(id: string) {
    return this.listVpcs().then(vpcs => {
      const match = vpcs.find(test => {
        return test.id === id;
      });
      return match ? match.name : null;
    });
  }
}


text:
//
//  GTLSQLAdminDatabaseInstance.h
//

// ----------------------------------------------------------------------------
// NOTE: This file is generated from Google APIs Discovery Service.
// Service:
//   Cloud SQL Administration API (sqladmin/v1beta3)
// Description:
//   API for Cloud SQL database instance management.
// Documentation:
//   https://developers.google.com/cloud-sql/docs/admin-api/
// Classes:
//   GTLSQLAdminDatabaseInstance (0 custom class methods, 15 custom properties)

#if GTL_BUILT_AS_FRAMEWORK
  #import "GTL/GTLObject.h"
#else
  #import "GTLObject.h"
#endif

@class GTLSQLAdminIpMapping;
@class GTLSQLAdminSettings;
@class GTLSQLAdminSslCert;

// ----------------------------------------------------------------------------
//
//   GTLSQLAdminDatabaseInstance
//

// A Cloud SQL instance resource.

@interface GTLSQLAdminDatabaseInstance : GTLObject

// The current disk usage of the instance in bytes.
@property (retain) NSNumber *currentDiskSize;  // longLongValue

// The database engine type and version. Can be MYSQL_5_5 or MYSQL_5_6. Defaults
// to MYSQL_5_5. The databaseVersion cannot be changed after instance creation.
@property (copy) NSString *databaseVersion;

// HTTP 1.1 Entity tag for the resource.
@property (copy) NSString *ETag;

// Name of the Cloud SQL instance. This does not include the project ID.
@property (copy) NSString *instance;

// The instance type. This can be one of the following.
// CLOUD_SQL_INSTANCE: Regular Cloud SQL instance.
// READ_REPLICA_INSTANCE: Cloud SQL instance acting as a read-replica.
@property (copy) NSString *instanceType;

// The assigned IP addresses for the instance.
@property (retain) NSArray *ipAddresses;  // of GTLSQLAdminIpMapping

// This is always sql#instance.
@property (copy) NSString *kind;

// The name of the instance which will act as master in the replication setup.
@property (copy) NSString *masterInstanceName;

// The maximum disk size of the instance in bytes.
@property (retain) NSNumber *maxDiskSize;  // longLongValue

// The project ID of the project containing the Cloud SQL instance. The Google
// apps domain is prefixed if applicable.
@property (copy) NSString *project;

// The geographical region. Can be us-east1, us-central, asia-east1 or
// europe-west1. Defaults to us-central. The region can not be changed after
// instance creation.
@property (copy) NSString *region;

// The replicas of the instance.
@property (retain) NSArray *replicaNames;  // of NSString

// SSL configuration.
@property (retain) GTLSQLAdminSslCert *serverCaCert;

// The user settings.
@property (retain) GTLSQLAdminSettings *settings;

// The current serving state of the Cloud SQL instance. This can be one of the
// following.
// RUNNABLE: The instance is running, or is ready to run when accessed.
// SUSPENDED: The instance is not available, for example due to problems with
// billing.
// PENDING_CREATE: The instance is being created.
// MAINTENANCE: The instance is down for maintenance.
// UNKNOWN_STATE: The state of the instance is unknown.
@property (copy) NSString *state;

@end