text:
'use strict';

import type {RootTag} from 'react-native/Libraries/Types/RootTagTypes';

import * as React from 'react';
import {StyleSheet, Text, View} from 'react-native';
import BatchedBridge from 'react-native/Libraries/BatchedBridge/BatchedBridge';
import renderApplication from 'react-native/Libraries/ReactNative/renderApplication';

type FlexTestAppProps = $ReadOnly<{||}>;
class FlexTestApp extends React.Component<FlexTestAppProps> {
  render(): React.Node {
    return (
      <View
        style={FlexTestAppStyles.container}
        testID="container"
        collapsable={false}>
        <View
          style={[FlexTestAppStyles.child, FlexTestAppStyles.bgRed]}
          collapsable={false}
        />
        <View
          style={[FlexTestAppStyles.child, FlexTestAppStyles.bgBlue]}
          collapsable={false}
        />
      </View>
    );
  }
}

const FlexTestAppStyles = StyleSheet.create({
  container: {
    width: 200,
    height: 200,
    flexDirection: 'row',
  },
  child: {
    flex: 1,
  },
  bgRed: {
    backgroundColor: '#ff0000',
  },
  bgBlue: {
    backgroundColor: '#0000ff',
  },
});

type FlexWithTextProps = $ReadOnly<{||}>;
class FlexWithText extends React.Component<FlexWithTextProps> {
  render(): React.Node {
    return (
      <View
        style={FlexWithTextStyles.container}
        testID="container"
        collapsable={false}>
        <View style={FlexWithTextStyles.row} collapsable={false}>
          <Text style={FlexWithTextStyles.inner}>Hello</Text>
          <Text style={FlexWithTextStyles.inner}>World</Text>
        </View>
      </View>
    );
  }
}

const FlexWithTextStyles = StyleSheet.create({
  container: {
    flexDirection: 'column',
    margin: 20,
  },
  row: {
    flexDirection: 'row',
    alignItems: 'flex-end',
    height: 300,
  },
  inner: {
    flex: 1,
    margin: 10,
  },
});

type AbsolutePositionTestAppProps = $ReadOnly<{||}>;
class AbsolutePositionTestApp extends React.Component<AbsolutePositionTestAppProps> {
  render(): React.Node {
    return (
      <View
        style={AbsolutePositionTestAppStyles.absolute}
        testID="absolute"
        collapsable={false}
      />
    );
  }
}

const AbsolutePositionTestAppStyles = StyleSheet.create({
  absolute: {
    position: 'absolute',
    top: 15,
    left: 10,
    width: 50,
    height: 60,
  },
});

type AbsolutePositionBottomRightTestAppProps = $ReadOnly<{||}>;
class AbsolutePositionBottomRightTestApp extends React.Component<AbsolutePositionBottomRightTestAppProps> {
  render(): React.Node {
    return (
      <View
        style={AbsolutePositionBottomRightTestAppStyles.container}
        testID="container"
        collapsable={false}>
        <View
          style={AbsolutePositionBottomRightTestAppStyles.absolute}
          collapsable={false}
        />
      </View>
    );
  }
}

const AbsolutePositionBottomRightTestAppStyles = StyleSheet.create({
  container: {
    width: 100,
    height: 100,
  },
  absolute: {
    position: 'absolute',
    bottom: 15,
    right: 10,
    width: 50,
    height: 60,
  },
});

type CenteredTextViewProps = $ReadOnly<{|
  text?: ?string,
|}>;
class CenteredTextView extends React.Component<CenteredTextViewProps> {
  render(): React.Node {
    return (
      <View collapsable={false}>
        <View style={CenteredTextViewStyles.parent} collapsable={false}>
          <Text style={CenteredTextViewStyles.text} testID="text">
            {this.props.text}
          </Text>
        </View>
      </View>
    );
  }
}

const CenteredTextViewStyles = StyleSheet.create({
  parent: {
    width: 200,
    height: 100,
    backgroundColor: '#aa3311',
    justifyContent: 'center',
    alignItems: 'center',
  },
  text: {
    fontSize: 15,
    color: '#672831',
  },
});

let flushUpdatePositionInList: null | (() => void) = null;

type UpdatePositionInListTestAppProps = $ReadOnly<{||}>;
type UpdatePositionInListTestAppState = {|
  active: boolean,
|};
class UpdatePositionInListTestApp extends React.Component<
  UpdatePositionInListTestAppProps,
  UpdatePositionInListTestAppState,
> {
  state: UpdatePositionInListTestAppState = {
    active: false,
  };

  /* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's
   * LTI update could not be added via codemod */
  constructor(...args) {
    super(...args);
    flushUpdatePositionInList = () => this.setState({active: true});
  }

  render(): React.Node {
    return (
      <View collapsable={false} testID="container">
        <View
          style={UpdatePositionInListTestAppStyles.element}
          collapsable={false}
        />
        <View
          style={[
            UpdatePositionInListTestAppStyles.element,
            this.state.active && UpdatePositionInListTestAppStyles.active,
          ]}
          collapsable={false}
        />
        <View
          style={UpdatePositionInListTestAppStyles.element}
          collapsable={false}
        />
      </View>
    );
  }
}

const UpdatePositionInListTestAppStyles = StyleSheet.create({
  element: {
    height: 10,
  },
  active: {
    height: 50,
  },
});

/**
 * This is a workaround for the following flow problem:
 *
 *   const emptyObject: {||} = {}; // Raises error
 *
 * @see https://github.com/facebook/flow/issues/2977
 */
const emptyExactProps = Object.freeze({});

const UIManagerTestModule = {
  renderFlexTestApplication(rootTag: RootTag) {
    renderApplication(FlexTestApp, emptyExactProps, rootTag);
  },
  renderFlexWithTextApplication(rootTag: RootTag) {
    renderApplication(FlexWithText, emptyExactProps, rootTag);
  },
  renderAbsolutePositionBottomRightTestApplication(rootTag: RootTag) {
    renderApplication(
      AbsolutePositionBottomRightTestApp,
      emptyExactProps,
      rootTag,
    );
  },
  renderAbsolutePositionTestApplication(rootTag: RootTag) {
    renderApplication(AbsolutePositionTestApp, emptyExactProps, rootTag);
  },
  renderCenteredTextViewTestApplication(rootTag: RootTag, text: string) {
    renderApplication(CenteredTextView, {text: text}, rootTag);
  },
  renderUpdatePositionInListTestApplication(rootTag: RootTag) {
    renderApplication(UpdatePositionInListTestApp, emptyExactProps, rootTag);
  },
  flushUpdatePositionInList,
};

BatchedBridge.registerCallableModule(
  'UIManagerTestModule',
  UIManagerTestModule,
);

export default UIManagerTestModule;


text:
using Autofac;
using Autofac.Integration.WebApi;
using SA.DataAccess.Sql;
using SA.Repositories;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Web;

namespace SA.Api
{
    internal sealed class Bootstrapper
    {
        internal static IContainer Run()
        {
            var builder = new ContainerBuilder();
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterType<SurveyRepository>().AsImplementedInterfaces();
            builder.RegisterType<SurveyResponseRepository>().AsImplementedInterfaces();
            builder.RegisterType<ReportRepository>().AsImplementedInterfaces();
            builder.RegisterType<SqlConnection>().AsImplementedInterfaces().InstancePerDependency();
            builder.RegisterType<Accessor>().AsImplementedInterfaces();
            return builder.Build();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
var app = require('../../examples/error-pages')
  , request = require('supertest');

describe('error-pages', function(){
  describe('GET /', function(){
    it('should respond with page list', function(done){
      request(app)
      .get('/')
      .expect(/Pages Example/, done)
    })
  })

  describe('Accept: text/html',function(){
    describe('GET /403', function(){
      it('should respond with 403', function(done){
        request(app)
        .get('/403')
        .expect(403, done)
      })
    })

    describe('GET /404', function(){
      it('should respond with 404', function(done){
        request(app)
        .get('/404')
        .expect(404, done)
      })
    })

    describe('GET /500', function(){
      it('should respond with 500', function(done){
        request(app)
        .get('/500')
        .expect(500, done)
      })
    })
  })

  describe('Accept: application/json',function(){
    describe('GET /403', function(){
      it('should respond with 403', function(done){
        request(app)
        .get('/403')
        .set('Accept','application/json')
        .expect(403, done)
      })
    })

    describe('GET /404', function(){
      it('should respond with 404', function(done){
        request(app)
        .get('/404')
        .set('Accept','application/json')
        .expect(404, { error: 'Not found' }, done)
      })
    })

    describe('GET /500', function(){
      it('should respond with 500', function(done){
        request(app)
        .get('/500')
        .set('Accept', 'application/json')
        .expect(500, done)
      })
    })
  })

  describe('Accept: text/plain',function(){
    describe('GET /403', function(){
      it('should respond with 403', function(done){
        request(app)
        .get('/403')
        .set('Accept','text/plain')
        .expect(403, done)
      })
    })

    describe('GET /404', function(){
      it('should respond with 404', function(done){
        request(app)
        .get('/404')
        .set('Accept', 'text/plain')
        .expect(404)
        .expect('Not found', done);
      })
    })

    describe('GET /500', function(){
      it('should respond with 500', function(done){
        request(app)
        .get('/500')
        .set('Accept','text/plain')
        .expect(500, done)
      })
    })
  })
})


text:
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>SplitApp - sap.m</title>
		<link href="SplitApp.css" rel="stylesheet">
		<script src="shared-config.js"></script>
		<script id="sap-ui-bootstrap"
				src="../../../resources/sap-ui-core.js"
				data-sap-ui-async="true"
				data-sap-ui-compatVersion="edge"
				data-sap-ui-libs="sap.m"
				data-sap-ui-onInit="module:local/SplitApp"
				data-sap-ui-resourceRoots='{
					"local": "./",
					"qunit.internal.acc": "../../../test-resources/sap/ui/core/qunit/internal/acc"
				}'>
		</script>
	</head>
	<body id="body" class="sapUiBody">
	</body>
</html>


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<base target="contentwin" /><title>Tools and Utilities Guide</title>

Copyright

License

About this guide

Purpose of this document

Audience

How this guide is organized

What are the Derby tools and utilities?

Overview

Environment setup and the Derby tools

Java Platform, Standard Edition 6

Classpath

About Derby databases

JDBC connection basics

JDBC drivers overview

Database connection URLs

Tools and localization

About locales

Database locale

Specifying an alternate codeset

Formatting display of locale-sensitive data

Using ij

Starting ij

Creating a database using ij

Starting ij using properties

Getting started with ij

Connecting to a Derby database

The ij Driver name and connection URL

Using ij commands

Other uses for ij

Running ij scripts

ij properties reference

ij.connection.connectionName property

ij.database property

ij.dataSource property

ij.exceptionTrace property

ij.maximumDisplayWidth property

ij.outfile property

ij.password property

ij.protocol property

ij.protocol.protocolName property

ij.showErrorCode property

ij.showNoConnectionsAtStart property

ij.showNoCountForSelect property

ij.URLCheck property

ij.user property

derby.ui.codeset property

derby.ui.locale property

ij commands and errors reference

ij commands

Conventions for ij examples

ij SQL command behavior

ij command example

Absolute command

After Last command

Async command

Autocommit command

Before First command

Close command

Commit command

Connect command

Describe command

Disconnect command

Driver command

Elapsedtime command

Execute command

Exit command

First command

Get Cursor command

Get Scroll Insensitive Cursor command

Help command

HoldForConnection command

Last command

LocalizedDisplay command

MaximumDisplayWidth command

Next command

NoHoldForConnection command

Prepare command

Previous command

Protocol command

Readonly command

Relative command

Remove command

Rollback command

Run command

Set Connection command

Show command

Wait For command

Syntax for comments in ij commands

Syntax for identifiers in ij commands

Syntax for strings in ij commands

ij errors

ERROR SQLState

WARNING SQLState

IJ ERROR

IJ WARNING

JAVA ERROR

sysinfo

sysinfo example

Using sysinfo to check the classpath

dblook

Using dblook

dblook options

Generating the DDL for a database

dblook examples

SignatureChecker

Using SignatureChecker

PlanExporter

Using PlanExporter

PlanExporter XML format

PlanExporter example

Optional tools

Using the databaseMetaData optional tool

Using the foreignViews optional tool

Using the luceneSupport optional tool

Creating an index

Updating an index

Querying an index

Dropping an index

Listing indexes

Running the luceneSupport tool with a security manager

Using the simpleJson optional tool

Using the rawDBReader optional tool

Trademarks


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>DIRECT-LINK-SAME-GROUP-COST-SLIDER</title>

I create a slider controlling the cost of having a direct link
	between members of the same group.

	Begin micro-behaviour

DIRECT-LINK-SAME-GROUP-COST-SLIDER

	Begin NetLogo code:

create-slider
  "the-same-group-direct-link-cost"
  "625" "10" ; lower left corner
  "875" "50" ; upper right corner
  "0" "1" ; minimum and maximum value
  ".01" ; increment
  ".4" ; initial value

	End NetLogo code

Variants

You can change the location, minimum and maximum values, increment, and
	initial value.

Related Micro-behaviours

	TOTAL-COST uses the value of
	the-same-group-direct-link-cost.

	DIRECT-LINK-BENEFIT-SLIDER adds a slider for the benefit of a direct
	link if in different groups or groups aren't defined.

History

This was implemented by Ken Kahn.


text:
require "csv"

class Masticate::MaxRows < Masticate::Base
  def configure(opts)
    standard_options(opts)

    @groupby = opts[:by] or raise "missing field to group by"
    @maxon = opts[:max] or raise "missing field to max on"
  end

  def maxrows(opts)
    execute(opts)
  end

  def crunch(row)
    if !@headers
      @headers = row
      @index_by = row.index(@groupby) or raise "Unable to find column '#{@groupby}'"
      @index_max = row.index(@maxon) or raise "Unable to find column '#{@maxon}'"
      @accum = {}
      row
    elsif row.nil?
      # output the accumulated results
      @accum.each do |k,row|
        yield row
      end
    else
      key = row[@index_by]
      if !@accum[key]
        @accum[key] = row
      else
        oldscore = @accum[key][@index_max]
        newscore = row[@index_max]
        if newscore > oldscore
          @accum[key] = row
        end
      end
      nil
    end
  end
end


text:
package com.ubergeek42.weechat.relay.messagehandler;

import java.util.Date;
import java.util.HashSet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ubergeek42.weechat.Buffer;
import com.ubergeek42.weechat.BufferLine;
import com.ubergeek42.weechat.relay.RelayMessageHandler;
import com.ubergeek42.weechat.relay.protocol.Array;
import com.ubergeek42.weechat.relay.protocol.Hdata;
import com.ubergeek42.weechat.relay.protocol.HdataEntry;
import com.ubergeek42.weechat.relay.protocol.RelayObject;
import com.ubergeek42.weechat.relay.protocol.RelayObject.WType;

public class LineHandler implements RelayMessageHandler {
    final private static boolean DEBUG = false;
    private static Logger logger = LoggerFactory.getLogger("LineHandler");

    private final BufferManager cb;

    public LineHandler(BufferManager cb) {
        this.cb = cb;
    }

    @Override
    public void handleMessage(RelayObject obj, String id) {
        if (DEBUG) logger.debug("handleMessage(..., {}): whdata.getCount() = {}", id, ((Hdata) obj).getCount());

        Buffer buffer = null;
        Hdata whdata = (Hdata) obj;
        HashSet<Buffer> toUpdate = new HashSet<Buffer>();

        for (int i = 0; i < whdata.getCount(); i++) {
            HdataEntry hde = whdata.getItem(i);
            // TODO: check last item of path is line_data

            // Get the information about the "line"
            String message = hde.getItem("message").asString();
            String prefix = hde.getItem("prefix").asString();
            boolean displayed = (hde.getItem("displayed").asChar() == 0x01);
            Date time = hde.getItem("date").asTime();
            String bPointer;
            if (id.equals("_buffer_line_added")) {
                bPointer = hde.getItem("buffer").asPointer();
            } else {
                bPointer = hde.getPointer(0);
            }

            // Try to get highlight status(added in 0.3.8-dev: 2012-03-06)
            RelayObject t = hde.getItem("highlight");
            boolean highlight = false;
            if (t != null) {
                highlight = (t.asChar() == 0x01);
            }

            String[] tags = null;
            // Try to get the array tags (added in 0.3.9-dev: 2012-07-23)
            // Make sure it is the right type as well, prior to this commit it is just a pointer
            RelayObject tagsobj = hde.getItem("tags_array");
            if (tagsobj != null && tagsobj.getType() == WType.ARR) {
                Array tagsArray = tagsobj.asArray();
                tags = tagsArray.asStringArray();
            }
            // Find the buffer to put the line in
            buffer = cb.findByPointer(bPointer);
            if (buffer == null) {
                logger.debug("Unable to find buffer to update");
                return;
            }
            // Do we already have this line?
            if (!buffer.hasLine(hde.getPointer())) {
                // Create a new message object, and add it to the correct buffer
                // #################### DEBUG
                //logger.warn("handleMessage(): new [{}] [{}]", prefix, message);
                // #################### DEBUG
                BufferLine cm = new BufferLine(hde.getPointer(), time, prefix, message, displayed, highlight, tags);
                if (id.equals("_buffer_line_added")) {
                    // Check if this line should be added as an unread line
                    // TODO make this into a preference as users might have
                    // different tastes
                    // TODO more elaborate checking of notify level
                    if (cm.isUnread() && buffer.getNotifyLevel() >= 1) {
                        buffer.addLine(cm);
                    } else {
                        buffer.addLineNoUnread(cm);
                    }
                    cb.buffersChanged();
                } else if (id.equals("listlines_reverse")) { // lines come in most recent to least recent
                    // TODO: check buffer isn't null...
                    buffer.addLineFirstNoNotify(cm);
                    //toUpdate.add(buffer);
                }
            }
        }
        // this loop probably should be written more neatly, but—
        // listlines_reverse usually comes in a bulk
        // after these were listed we can assume the buffer holds the maximum amount of lines
        // for the time being
        if (id.equals("listlines_reverse") && buffer != null) {
            buffer.holdsAllLinesItIsSupposedToHold = true;
            buffer.notifyManyLinesAdded();
        }
        for (Buffer wb : toUpdate) {
            wb.notifyLineAdded();
        }
    }
}


text:
package org.opendaylight.opflex.genie.content.model.mownership;

/**
 * Created by midvorki on 9/27/14.
 */
public enum DefinitionScope
{
    GLOBAL,
    OWNER,
    CLASS,
    MODULE,
    MEMBER,
    GROUP
    ;

    public static DefinitionScope get(String aIn)
    {
        for (DefinitionScope lScope : DefinitionScope.values())
        {
            if (aIn.equalsIgnoreCase(lScope.toString()))
            {
                return lScope;
            }
        }
        return GLOBAL;
    }
}


text:
<?php

// # Add Addresses to Wallet
//
// This sample code demonstrate how you can add addresses to a wallet, as documented here at:
// http://dev.blockcypher.com/#wallets
//
// API used: GET /v1/btc/main/wallets/Wallet-Name/addresses

// In samples we are using CreateWallet.php sample to get the created instance of wallet.
// You have to run that sample before running this one or there will be no wallets

require __DIR__ . '/../bootstrap.php';

if (isset($_GET['wallet_name'])) {
    $walletName = filter_input(INPUT_GET, 'wallet_name', FILTER_SANITIZE_SPECIAL_CHARS);
} else {
    $walletName = 'alice'; // Default wallet name for samples
}

$walletClient = new \BlockCypher\Client\WalletClient($apiContexts['BTC.main']);

$addressList = \BlockCypher\Api\AddressList::fromAddressesArray(array(
    "13cj1QtfW61kQHoqXm3khVRYPJrgQiRM6j"
));

try {
    /// Add addresses to Wallet
    $output = $walletClient->addAddresses($walletName, $addressList);
} catch (Exception $ex) {
    ResultPrinter::printError("Add Addresses to a Wallet", "Wallet", $walletName, $addressList, $ex);
    exit(1);
}

ResultPrinter::printResult("Add Addresses to a Wallet", "Wallet", $walletName, $addressList, $output);

return $output;


text:
namespace ExampleApp
{
    namespace MyPinCreation
    {
        namespace View
        {
            class MyPinCreationConfirmationViewModule: public IMyPinCreationConfirmationViewModule, private Eegeo::NonCopyable
            {
            private:
                MyPinCreationConfirmationController* m_pController;
                MyPinCreationConfirmationView* m_pView;

            public:
                MyPinCreationConfirmationViewModule(ExampleAppMessaging::TMessageBus& messageBus,
                                                    IMyPinCreationConfirmationViewModel& viewModel,
                                                    IMyPinCreationCompositeViewModel& compositeViewModel,
                                                    MyPinCreationDetails::View::IMyPinCreationDetailsViewModel& detailsViewModel,
                                                    const Eegeo::Rendering::ScreenProperties& screenProperties,
                                                    Metrics::IMetricsService& metricsService);

                ~MyPinCreationConfirmationViewModule();

                MyPinCreationConfirmationController& GetMyPinCreationConfirmationController() const;

                MyPinCreationConfirmationView& GetMyPinCreationConfirmationView() const;
            };
        }
    }
}


text:
using System.Configuration;
using System.Web.Configuration;

namespace DearLee.Toolkit.Config {

  /// <summary>
  /// 提供对 Web 应用程序配置文件的访问协助
  /// </summary>
  public class WebConfigurationManagerHelper {

    /// <summary>
    /// 将值写入指定配置文件节
    /// </summary>
    /// <param name="key">键</param>
    /// <param name="value">值</param>
    public static void SetValue(string key, string value) {

      var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

      if (config.AppSettings.Settings[key] == null) {
        config.AppSettings.Settings.Add(key, value);
      }
      else {
        config.AppSettings.Settings[key].Value = value;
      }

      config.Save(ConfigurationSaveMode.Modified);
      ConfigurationManager.RefreshSection("appSettings");
    }

    /// <summary>
    /// 读取指定配置文件节中的值
    /// </summary>
    /// <param name="key">键</param>
    /// <returns>值</returns>
    public static string GetValue(string key) {

      var config = WebConfigurationManager.OpenWebConfiguration("~");
      var value = string.Empty;

      if (config.AppSettings.Settings[key] != null) {
        value = config.AppSettings.Settings[key].Value;
      }

      return value;
    }
  }
}


text:
import {csvHeader} from '../request-headers';

export default function SubscriptionsResource({apiHandler}) {
    return {
        async getAll({limit = null, offset = null, sort = null, expand = null, filter = null, q = null, criteria = null} = {}) {
            const params = {
                limit,
                offset,
                sort,
                expand,
                filter,
                q,
                criteria
            };
            return await apiHandler.getAll(`subscriptions`, params);
        },

        async downloadCSV({limit = null, offset = null, sort = null, expand = null, filter = null, q = null, criteria = null} = {}) {
            const config = {
                params: {
                    limit,
                    offset,
                    sort,
                    expand,
                    filter,
                    q,
                    criteria
                },
                headers: csvHeader
            };
            return await apiHandler.download(`subscriptions`, config);
        },

        async get({id}) {
            return await apiHandler.get(`subscriptions/${id}`);
        },

        async create({id = '', data}) {
            return await apiHandler.create(`subscriptions/${id}`, id, data);
        },

        async update({id, data}) {
            return await apiHandler.put(`subscriptions/${id}`, data);
        },

        async cancel({id, data}) {
            return await apiHandler.post(`subscriptions/${id}/cancel`, data);
        },

        async switch({id, data}) {
            return await apiHandler.post(`subscriptions/${id}/switch`, data);
        },

        async getLeadSource({id}) {
            return await apiHandler.get(`subscriptions/${id}/lead-source`);
        },

        async createLeadSource({id, data}) {
            return await apiHandler.put(`subscriptions/${id}/lead-source`, data);
        },

        async deleteLeadSource({id}) {
            return await apiHandler.delete(`subscriptions/${id}/lead-source`);
        }
    };
};


text:
import requests
import datetime
import re

def prevLastDay():
    today = datetime.date.today()
    first = datetime.date(day=1, month=today.month, year=today.year)
    return first - datetime.timedelta(days=1)

def prevFirstDay():
    l_day = prevLastDay()
    return datetime.date(day = 1, month=l_day.month, year = l_day.year)

def yesterday():
    return datetime.date.today() - datetime.timedelta(days = 1)

def q_transform(string):
    return ''.join(re.findall('[a-zA-Z]', string)).lower()

class AppAnnieAPI(object):
    DEFAULT_ENDPOINT = 'https://api.appannie.com/'

    def __init__(self, api_key, endpoint=DEFAULT_ENDPOINT):
        self.endpoint = endpoint
        self.api_key = api_key

    def meta_regions(self):
        method = 'v1.1/meta/countries'
        return self._request(method)

    def meta_categories(self, market = 'google-play'):
        method = 'v1.1/meta/apps/{}/categories'.format(market)
        return self._request(method)

    def meta_platforms(self):
        method = 'v1/meta/platforms'
        return self._request(method)

    def meta_currencies(self):
        method = 'v1/meta/currencies'
        return self._request(method)

    def account_connections(self, page = 0):
        method = 'v1/accounts?page_index={}'.format(page)
        return self._request(method)

    def account_connections_apps(self, acc_id, page=0):
        method = 'v1/accounts/{}/apps?page_index={}'.format(acc_id, page)
        return self._request(method)

    def account_in_app_purchase(self, acc_id, app_id, page = 0):
        method = 'v1/{}/apps/{}/iaps?page_index={}'.format(acc_id, app_id, page)
        return self._request(method)

    def account_shared_apps(self, page = 0):
        method = 'v1/sharing/apps?page_index={}'.format(page)
        return self._request(method)

    def account_sales(self, acc_id, break_down = 'application+country+date', start_date = None,
                      end_date = None, currency='USD', countries='WW', page=0):
        return self._get_sales('account', acc_id, None, break_down, start_date, end_date, currency, countries, page)

    def app_sales(self, app_id, acc_id, break_down = 'application+country+date', start_date = None,
                      end_date = None, currency='USD', countries='WW', page=0):
        return self._get_sales('app', acc_id, app_id, break_down, start_date, end_date, currency, countries, page)

    def app_top(self, market = 'google-play', countries = 'WW', categories = 'OVERALL',
                device = 'android', feeds = 'free paid grossing', ranks = 100,
                granularity = 'daily', date = None):
        return self._get_top('apps', market, countries, categories, device, feeds, ranks,
               granularity, date)

    def pub_top(self, market = 'google-play', countries = 'WW', categories = 'OVERALL',
                device = 'android', feeds = 'free paid grossing', ranks = 100,
                granularity = 'daily', date = None):
        return self._get_top('pubs', market, countries, categories, device, feeds, ranks,
               granularity, date)

    def store_top(self, market = 'google-play', countries = 'WW', categories = 'OVERALL',
                device = 'android', feeds = 'free paid grossing', ranks = 100,
                date = yesterday().strftime('%Y-%m-%d')):
        return self._get_top('store', market, countries, categories, device, feeds, ranks,
               None, date)

    def app_search(self, query, market = 'google-play', countries = 'WW', categories = 'OVERALL',
                   device = 'android', feeds = 'free paid grossing', granularity = 'monthly',
                   date = None):
        response = self.app_top(market = market, countries = countries,
                                categories = categories, device = device, feeds = feeds,
                                ranks = None, granularity = granularity, date = date)
        print len(response['list'])
        response['query'] = query
        query = q_transform(query)
        result = []
        for app in response['list']:
            if query in q_transform(app['company_name']) or\
               query in q_transform(app['parent_company_name']) or\
               query in q_transform(app['product_franchise_name']) or\
               query in q_transform(app['product_name']) or\
               query in q_transform(app['publisher_name']) or\
               query in q_transform(app['unified_product_name']):
                result.append(app)
        response['list'] = result
        return response

    def app_details(self, app_id, market = 'google-play'):
        method = 'v1.1/apps/{}/app/{}/details'.format(market, app_id)
        return self._request(method)

    def app_ranks(self, app_id, market = 'google-play', start_date = None, end_date = None,
                  interval = 'daily', countries = 'WW', categories = 'OVERALL',
                  feeds = 'free', device = 'android'):
        if market != 'google-play' and device == 'android':
            device = 'iphone'
        if not start_date:
            start_date = prevFirstDay().strftime('%Y-%m-%d')
        if not end_date:
            end_date = prevLastDay().strftime('%Y-%m-%d')
        method = 'v1.1/apps/{}/app/{}/ranks'.format(market, app_id)
        params = {'start_date':start_date, 'end_date':end_date, 'interval':interval,
                  'countries':countries, 'category':categories, 'feed':feeds, 'device':device}
        return self._request(method, params)

    def app_features(self, app_id, market = 'google-play', start_date = None, end_date = None,
                     countries = 'WW', page = 0):
        if not start_date:
            start_date = prevFirstDay().strftime('%Y-%m-%d')
        if not end_date:
            end_date = prevLastDay().strftime('%Y-%m-%d')
        method = 'v1.1/apps/{}/app/{}/features'.format(market, app_id)
        params = {'start_date':start_date, 'end_date':end_date, 'countries':countries,
                  'page_index':page}
        return self._request(method, params)

    def app_reviews(self, app_id, acc_id, start_date = None, end_date = None, countries = 'WW',
                    version = 'all', rating = '5', page = 0):
        if not start_date:
            start_date = prevFirstDay().strftime('%Y-%m-%d')
        if not end_date:
            end_date = prevLastDay().strftime('%Y-%m-%d')
        method = 'v1/accounts/{}/apps/{}/reviews'.format(acc_id, app_id)
        params = {'start_date':start_date, 'end_date':end_date, 'countries':countries,
                  'page_index':page, 'version':version, 'rating':rating}
        return self._request(method, params)

    def app_ratings(self, app_id, market = 'google-play', page=0):
        method = 'v1.1/apps/{}/app/{}/ratings'.format(market, app_id)
        params = {'page_index':page}
        return self._request(method, params)

    def app_downloads(self, app_id, market = 'google-play', countries = 'WW',
                    device = None, granularity = 'daily',
                    start_date = None, end_date = None):
        return self._get_history('app', 'downloads', app_id, market, None, countries, device,
                                 granularity, start_date, end_date)

    def app_revenue(self, app_id, market = 'google-play', countries = 'WW',
                    device = None, granularity = 'daily',
                    start_date = None, end_date = None):
        return self._get_history('app', 'revenue', app_id, market, None, countries, device,
                                 granularity, start_date, end_date)

    def pub_downloads(self, pub_id, market = 'google-play', categories = 'OVERALL',
                    countries = 'WW', device = None, granularity = 'daily',
                    start_date = None, end_date = None):
        return self._get_history('pub', 'downloads', pub_id, market, categories, countries,
                                 device, granularity, start_date, end_date)

    def pub_revenue(self, pub_id, market = 'google-play', categories = 'OVERALL',
                    countries = 'WW', device = None, granularity = 'daily',
                    start_date = None, end_date = None):
        return self._get_history('pub', 'revenue', pub_id, market, categories, countries,
                                 device, granularity, start_date, end_date)

    def _get_sales(self, sales_for, acc_id, app_id, break_down, start_date, end_date, currency, countries, page):
        if sales_for == 'account':
            method = 'v1/accounts/{}/sales'.format(acc_d)
        elif sales_for == 'app':
            method = 'v1/accounts/{}/apps/{}/sales'.format(acc_id, app_id)
        if not start_date:
            start_date = prevFirstDay().strftime('%Y-%m-%d')
        if not end_date:
            end_date = prevLastDay().strftime('%Y-%m-%d')
        params = {'break_down':break_down, 'start_date':start_date, 'end_date':end_date,
                  'currency':currency, 'countries':countries, 'page_index':page}
        return self._request(method, params)

    def _get_top(self, top_of, market, countries, categories, device, feeds, ranks,
                granularity, date):
        if top_of == 'apps':
            method = 'v1.1/intelligence/apps/{}/ranking'.format(market)
        elif top_of == 'pubs':
            method = 'v1.1/intelligence/apps/{}/publisher-ranking'.format(market)
        elif top_of == 'store':
            method = 'v1.1/apps/{}/ranking'.format(market)

        if market == 'ios' and device == 'android':
            device = 'ios'
        if not date:
            date = prevLastDay().strftime('%Y-%m-%d')
        params = {'countries':countries, 'categories':categories, 'device':device,
                  'feeds':feeds, 'date':date}
        if top_of != 'store':
            params['granularity'] = granularity
        if ranks:
            params['ranks'] = ranks
        return self._request(method, params)

    def _get_history(self, history_of, feed, id, market, categories, countries, device,
                    granularity, start_date, end_date):
        if history_of == 'pub':
            history_of = 'publisher'
        method = 'v1.1/intelligence/apps/{}/{}/{}/history'.format(market, history_of, id)

        if not device:
            if market == 'google-play':
                device = 'android'
            else:
                device = 'all'
        if not start_date:
            start_date = prevFirstDay().strftime('%Y-%m-%d')
        if not end_date:
            end_date = prevLastDay().strftime('%Y-%m-%d')
        params = {'countries':countries, 'feeds':feed, 'device':device,
                  'granularity':granularity, 'start_date':start_date,
                  'end_date':end_date}
        if history_of == 'publisher':
            params['categories'] = categories
        return self._request(method, params)

    def _request(self, method, params = {}):
        response = requests.get(self.endpoint + method,
                                headers = {'Authorization':'Bearer {}'.format(self.api_key),
                                           'Accept':'application/json'},
                                params = params
                                )
        response = response.json()
        if response['code'] == 200:
            return response
        else:
            raise AppAnnieError(response)

class AppAnnieError(Exception):
    def __init__(self, value = {'error':'', 'code':0}):
        self.value = value
        if self.value['code'] == 400:
            self.value['reason'] = 'Bad Request'
        elif self.value['code'] == 401:
            self.value['reason'] = 'Unauthorized access'
        elif self.value['code'] == 403:
            self.value['reason'] = 'Forbidden'
        elif self.value['code'] == 404:
            self.value['reason'] = 'Not found'
        elif self.value['code'] == 405:
            self.value['reason'] = 'HTTP method is not supported'
        elif self.value['code'] == 429:
            self.value['reason'] = 'Rate limit exceeded'
        elif self.value['code'] == 500:
            self.value['reason'] = 'Internal service error'
        elif self.value['code'] == 503:
            self.value['reason'] = 'Service unavailable due to maintenance'
        else:
            self.value['reason'] = 'Something went wrong'

    def __str__(self):
        return '[{}] {}'.format(self.value['reason'], self.value['error'])


text:
from flexget.plugins.filter.movie_queue import queue_add, queue_get
from tests import FlexGetBase

class TestMovieQueue(FlexGetBase):
    __yaml__ = """
         templates:
           global:
             mock:
               - {title: 'MovieInQueue', imdb_id: 'tt1931533', tmdb_id: 603, movie_name: MovieInQueue}
             accept_all: yes
             seen: local
         tasks:
           movie_queue_accept:
             movie_queue: accept

           movie_queue_add:
             movie_queue: add

           movie_queue_add_properties:
             movie_queue:
               action: add
               quality: 720p

           movie_queue_remove:
             movie_queue: remove

           movie_queue_forget:
             movie_queue: forget
    """

    def test_movie_queue_accept(self):
        queue_add(title=u'MovieInQueue', imdb_id=u'tt1931533', tmdb_id=603)
        self.execute_task('movie_queue_accept')
        assert len(self.task.entries) == 1

        entry = self.task.entries[0]
        assert entry.get('imdb_id', eval_lazy=False) == 'tt1931533'
        assert entry.get('tmdb_id', eval_lazy=False) == 603

        self.execute_task('movie_queue_accept')
        assert len(self.task.entries) == 0, 'Movie should only be accepted once'

    def test_movie_queue_add(self):
        self.execute_task('movie_queue_add')

        assert len(self.task.entries) == 1

        queue = queue_get()
        assert len(queue) == 1

        entry = queue[0]
        assert entry.imdb_id == 'tt1931533'
        assert entry.tmdb_id == 603
        assert entry.quality == 'any'

    def test_movie_queue_add_properties(self):
        self.execute_task('movie_queue_add_properties')

        assert len(self.task.entries) == 1

        queue = queue_get()
        assert len(queue) == 1

        entry = queue[0]
        assert entry.imdb_id == 'tt1931533'
        assert entry.tmdb_id == 603
        assert entry.quality == '720p'

    def test_movie_queue_remove(self):
        queue_add(title=u'MovieInQueue', imdb_id=u'tt1931533', tmdb_id=603)
        queue_add(title=u'KeepMe', imdb_id=u'tt1933533', tmdb_id=604)

        self.execute_task('movie_queue_remove')

        assert len(self.task.entries) == 1

        queue = queue_get()
        assert len(queue) == 1

        entry = queue[0]
        assert entry.imdb_id == 'tt1933533'
        assert entry.tmdb_id == 604

    def test_movie_queue_forget(self):
        queue_add(title=u'MovieInQueue', imdb_id=u'tt1931533', tmdb_id=603)
        self.execute_task('movie_queue_accept')
        assert len(queue_get(downloaded=True)) == 1
        self.execute_task('movie_queue_forget')
        assert not queue_get(downloaded=True)
        assert len(queue_get()) == 1


text:
<?php

/*
 * This file is part of Sulu.
 *
 * (c) MASSIVE ART WebServices GmbH
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Sulu\Bundle\MediaBundle\Media\FormatManager;

use Imagine\Image\ImageInterface;
use Prophecy\Argument;
use Prophecy\Prediction\NoCallsPrediction;
use Sulu\Bundle\MediaBundle\Entity\File;
use Sulu\Bundle\MediaBundle\Entity\FileVersion;
use Sulu\Bundle\MediaBundle\Entity\Media;

class FormatManagerTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        parent::setUp();
    }

    public function testReturnImage()
    {
        $mediaRepository = $this->prophesize('Sulu\Bundle\MediaBundle\Entity\MediaRepository');
        $originalStorage = $this->prophesize('Sulu\Bundle\MediaBundle\Media\Storage\StorageInterface');
        $formatCache = $this->prophesize('Sulu\Bundle\MediaBundle\Media\FormatCache\FormatCacheInterface');
        $converter = $this->prophesize('Sulu\Bundle\MediaBundle\Media\ImageConverter\ImageConverterInterface');
        $videoThumbnailService = $this->prophesize('Sulu\Bundle\MediaBundle\Media\Video\VideoThumbnailServiceInterface');

        $ghostScriptPath = '';
        $saveImage = true;
        $previewMimeTypes = ['gif'];
        $responseHeaders = [];
        $formats = [
            '640x480' => [
                'name' => '640x480',
                'commands' => [
                    [
                        'action' => 'resize',
                        'parameters' => [
                            'x' => 640,
                            'y' => 480,
                        ],
                    ],
                ],
                'options' => [
                    'jpeg_quality' => 70,
                    'png_compression_level' => 6,
                ],
            ],
        ];

        $image = $this->prophesize('Imagine\Image\ImageInterface');
        $image->strip()->willReturn(null);
        $image->layers()->willReturn(null);
        $image->interlace(ImageInterface::INTERLACE_PLANE)->willReturn(null);
        $image->get('gif', $formats['640x480']['options'])->willReturn('Image-Content');

        $media = new Media();
        $reflection = new \ReflectionClass(get_class($media));
        $property = $reflection->getProperty('id');
        $property->setAccessible(true);
        $property->setValue($media, 1);

        $file = new File();
        $file->setVersion(1);
        $fileVersion = new FileVersion();
        $fileVersion->setVersion(1);
        $fileVersion->setName('dummy.gif');
        $fileVersion->setMimeType('gif');
        $fileVersion->setStorageOptions(['a' => 'b']);
        $file->addFileVersion($fileVersion);
        $media->addFile($file);

        $mediaRepository->findMediaById(1)->willReturn($media);

        $originalStorage->load('dummy.gif', 1, ['a' => 'b'])->willReturn(
            dirname(__DIR__) . '/../../Fixtures/image/data/dummy.gif'
        );

        $converter->convert(Argument::type('string'), $formats['640x480'])->willReturn($image->reveal());

        $formatCache->save(
            Argument::type('string'),
            1,
            'dummy.gif',
            ['a' => 'b'],
            '640x480'
        )->willReturn(null);

        $formatManager = new FormatManager(
            $mediaRepository->reveal(),
            $originalStorage->reveal(),
            $formatCache->reveal(),
            $converter->reveal(),
            $videoThumbnailService->reveal(),
            $ghostScriptPath,
            $saveImage,
            $previewMimeTypes,
            $responseHeaders,
            $formats
        );

        $result = $formatManager->returnImage(1, '640x480');

        $this->assertEquals('Image-Content', $result->getContent());
        $this->assertEquals(200, $result->getStatusCode());
    }

    public function testGetFormats()
    {
        $mediaRepository = $this->prophesize('Sulu\Bundle\MediaBundle\Entity\MediaRepository');
        $originalStorage = $this->prophesize('Sulu\Bundle\MediaBundle\Media\Storage\StorageInterface');
        $formatCache = $this->prophesize('Sulu\Bundle\MediaBundle\Media\FormatCache\FormatCacheInterface');
        $converter = $this->prophesize('Sulu\Bundle\MediaBundle\Media\ImageConverter\ImageConverterInterface');
        $videoThumbnailService = $this->prophesize('Sulu\Bundle\MediaBundle\Media\Video\VideoThumbnailServiceInterface');

        $ghostScriptPath = '';
        $saveImage = true;
        $previewMimeTypes = ['gif'];
        $responseHeaders = [];
        $formats = [
            '640x480' => [
                'name' => '640x480',
                'commands' => [
                    [
                        'action' => 'resize',
                        'parameters' => [
                            'x' => 640,
                            'y' => 480,
                        ],
                    ],
                ],
                'options' => [
                    'jpeg_quality' => 70,
                    'png_compression_level' => 6,
                ],
            ],
        ];

        $formatCache->getMediaUrl(1, 'dummy.gif', ['a' => 'b'], '640x480', 1)->willReturn('/my-url.gif');

        $formatManager = new FormatManager(
            $mediaRepository->reveal(),
            $originalStorage->reveal(),
            $formatCache->reveal(),
            $converter->reveal(),
            $videoThumbnailService->reveal(),
            $ghostScriptPath,
            $saveImage,
            $previewMimeTypes,
            $responseHeaders,
            $formats
        );

        $result = $formatManager->getFormats(
            1,
            'dummy.gif',
            ['a' => 'b'],
            1,
            'gif'
        );

        $this->assertEquals(['640x480' => '/my-url.gif'], $result);
    }

    public function testGetFormatsNotSupportedMimeType()
    {
        $mediaRepository = $this->prophesize('Sulu\Bundle\MediaBundle\Entity\MediaRepository');
        $originalStorage = $this->prophesize('Sulu\Bundle\MediaBundle\Media\Storage\StorageInterface');
        $formatCache = $this->prophesize('Sulu\Bundle\MediaBundle\Media\FormatCache\FormatCacheInterface');
        $converter = $this->prophesize('Sulu\Bundle\MediaBundle\Media\ImageConverter\ImageConverterInterface');
        $videoThumbnailService = $this->prophesize('Sulu\Bundle\MediaBundle\Media\Video\VideoThumbnailServiceInterface');

        $ghostScriptPath = '';
        $saveImage = true;
        $previewMimeTypes = ['gif'];
        $responseHeaders = [];
        $formats = [
            '640x480' => [
                'name' => '640x480',
                'commands' => [
                    [
                        'action' => 'resize',
                        'parameters' => [
                            'x' => 640,
                            'y' => 480,
                        ],
                    ],
                ],
                'options' => [
                    'jpeg_quality' => 70,
                    'png_compression_level' => 6,
                ],
            ],
        ];

        $formatCache->getMediaUrl(1, 'dummy.mp3', ['a' => 'b'], '640x480', 1)->should(new NoCallsPrediction());

        $formatManager = new FormatManager(
            $mediaRepository->reveal(),
            $originalStorage->reveal(),
            $formatCache->reveal(),
            $converter->reveal(),
            $videoThumbnailService->reveal(),
            $ghostScriptPath,
            $saveImage,
            $previewMimeTypes,
            $responseHeaders,
            $formats
        );

        $result = $formatManager->getFormats(
            1,
            'dummy.mp3',
            ['a' => 'b'],
            1,
            'mp3'
        );

        $this->assertEquals([], $result);
    }
}


text: Ready to code


text:
<?php
namespace Chamilo\Core\Repository\ContentObject\Glossary\Display\Component\Renderer\Type;

use Chamilo\Core\Repository\Common\Rendition\ContentObjectRendition;
use Chamilo\Core\Repository\Common\Rendition\ContentObjectRenditionImplementation;
use Chamilo\Core\Repository\ContentObject\Glossary\Display\Component\Renderer\GlossaryRenderer;
use Chamilo\Libraries\Format\Structure\Toolbar;
use Chamilo\Libraries\Format\Structure\ToolbarItem;
use Chamilo\Libraries\Format\Theme;
use Chamilo\Libraries\Translation\Translation;
use Chamilo\Libraries\Utilities\Utilities;

/**
 * Class to render the glossary as a list
 *
 * @package repository\content_object\glossary
 * @author Sven Vanpoucke - Hogeschool Gent
 */
class ListGlossaryRenderer extends GlossaryRenderer
{

    /**
     * Renders the glossary
     *
     * @return string
     */
    public function render()
    {
        $complex_content_object_items = $this->get_objects();

        if ($complex_content_object_items->size() == 0)
        {
            $html = array();

            $html[] = '
';
            $html[] = Translation::get('NoSearchResults', null, Utilities::COMMON_LIBRARIES);
            $html[] = '
';
        }

        while ($complex_content_object_item = $complex_content_object_items->next_result())
        {
            $html[] = $this->display_content_object(
                $complex_content_object_item->get_ref_object(),
                $complex_content_object_item);
        }

        return implode(PHP_EOL, $html);
    }

    /**
     * Displays a single glossary item
     *
     * @param GlossaryItem $content_object
     * @param ComplexcontentObjectItem $complex_content_object_item
     *
     * @return string
     */
    public function display_content_object($content_object, $complex_content_object_item)
    {
        $html = array();

        $html[] = '
';
        $html[] = '
';
        $html[] = $content_object->get_title();
        $html[] = '
';
        $html[] = '
';
        $html[] = $this->get_actions($complex_content_object_item);
        $html[] = '
';
        $html[] = '
&nbsp
';
        $html[] = '
';
        $html[] = '
';

        $html[] = ContentObjectRenditionImplementation::launch(
            $content_object,
            ContentObjectRendition::FORMAT_HTML,
            ContentObjectRendition::VIEW_DESCRIPTION,
            $this->get_component());

        $html[] = '

';

        return implode(PHP_EOL, $html);
    }

    /**
     * Returns the actions for a single glossary item
     *
     * @param ComplexContentObjectItem $complex_content_object_item
     *
     * @return string
     */
    public function get_actions($complex_content_object_item)
    {
        $component = $this->get_component();

        $toolbar = new Toolbar();
        if ($component->is_allowed_to_edit_content_object(EDIT_RIGHT))
        {
            $toolbar->add_item(
                new ToolbarItem(
                    Translation::get('Edit'),
                    Theme::getInstance()->getCommonImagePath('Action/Edit'),
                    $component->get_complex_content_object_item_update_url($complex_content_object_item),
                    ToolbarItem::DISPLAY_ICON));
        }

        if ($component->is_allowed_to_delete_child())
        {
            $toolbar->add_item(
                new ToolbarItem(
                    Translation::get('Delete'),
                    Theme::getInstance()->getCommonImagePath('Action/Delete'),
                    $component->get_complex_content_object_item_delete_url($complex_content_object_item),
                    ToolbarItem::DISPLAY_ICON,
                    true));
        }

        return $toolbar->as_html();
    }
}


text:
This cookbook is used by Chef's engineering services team to build the Chef Server infrastructure that runs our continuous delivery and integration pipelines used to build Chef products for our customers and the community. It is provided as an example of how we write a "wrapper" cookbook that consumes resources from another cookbook, deliver a cookbook through Chef Delivery, and use the ChefDK `chef provision` command. It is open source so that we can share this with others, but as it runs critical infrastructure for us, it cannot support every use case. It attempts to be as flexible as possible, and provide a common basis which can be extended for other infrastructures.

Our goal is to provide a cookbook that can also show off emerging patterns and practices in the Chef ecosystem, including:

1. Chef Provisioning
1. Chef Policies
1. Chef Delivery

## Chef Provisioning

We use `chef provision` with the `provision` cookbook in this repository. By default, it is configured to use AWS, as that is our reference use case for the CI/CD infrastructure. It also includes a local dev cluster recipe for using Vagrant.

The `Rakefile` at the toplevel of this repository has two tasks, `default` and `dev`. The `default` task will launch the cluster in AWS using `provision::cluster` recipe. See [the AWS scenario doc](./scenario-aws.md). The `dev` task will launch the cluster using Vagrant with the VMware Fusion plugin, but at the time of this writing it isn't working with the latest changes in the cluster recipe.

## Chef Policies

This cookbook uses Chef Policies for dependency resolution and cookbook workflow. At the toplevel, `Policyfile.rb` is used for running the ChefSpec unit tests. The other policies in the `policies` directory are used for the nodes that are brought up for the cluster in the `provision` cookbook. Depending on the state of the world on your local machine, to use the policies you may need to do:

```
chef update
```

to update the `Policyfile.lock.json`, and then:

```
rake update
```

to update all the `policies/*.lock.json`.

## Chef Delivery

We use this cookbook in a Chef Delivery pipeline. The build cookbook is located in the `.delivery/build-cookbook`. This doesn't need to be modified under normal circumstances as it is consumed by Delivery. For local development and testing, Test Kitchen can be used to bring up a local build node to run the verify phase. For example:

```
% cd .delivery/build-cookbook

% kitchen list
Instance             Driver   Provisioner  Verifier  Transport  Last Action
default-ubuntu-1404  Vagrant  ChefZero     Busser    Ssh        <Not Created>
default-centos-71    Vagrant  ChefZero     Busser    Ssh        <Not Created>

% kitchen test default-centos-71
OUTPUT SNIPPED
```

## Use Cases

This directory contains various use case "scenarios."

* [AWS (default)](./scenario-aws.md): Stand up the default cluster in AWS
* [Alternative Chef Server](./scenario-alternative-chef-server.md): Use a Chef Server other than Chef Zero, e.g., Hosted Chef
* [Custom Policies](./scenario-custom-policies.md): Customize the policies for using custom cookbooks, or set options for `chef provisioning` to change provisioning behavior
* [Wildcard SSL Certificate](./scenario-wildcard-ssl.md): Include a wildcard SSL certificate instead of using self-signed certificates


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Creative - Bootstrap 3 Responsive Admin Template">
    <meta name="author" content="GeeksLabs">
    <meta name="keyword" content="Creative, Dashboard, Admin, Template, Theme, Bootstrap, Responsive, Retina, Minimal">
    <link rel="shortcut icon" href="img/favicon.png">

    <title>Homepage</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/bootstrap-theme.css" rel="stylesheet">

    <link href="css/elegant-icons-style.css" rel="stylesheet" />
    <link href="css/font-awesome.min.css" rel="stylesheet" />

    <link href="css/style.css" rel="stylesheet">
    <link href="css/style-responsive.css" rel="stylesheet" />

    <link href="css/vendor/font-awesome.min.css" type="text/css" rel="stylesheet">
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,600' rel='stylesheet' type='text/css'>
    <link href="css/jquery.bdt.css" type="text/css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" type="text/css" rel="stylesheet">

<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">

Course Name

Team Number:  Minimun:3, Maximum:6

                                <button class="btn btn-success" onclick="window.location.href='teamform.html'">Status</button>
                                <button class="btn btn-primary" onclick="window.location.href='teamcreate.html'">Create Team</button>
                                <button class="btn btn-danger" onclick="window.location.href='search.html'">Search</button>

 Search Team

                                    Groupname
                                    No.of people
                                    Detail
                                    Send Request

                                    TeamK
                                    3
                                    <button class="btn btn-primary" onclick="window.location.href='team.html'">Detail</ button>
                                    <button class="btn btn-danger" onclick="">Request</button>

 Search Person

                                    Groupname
                                    Team Belong
                                    Detail
                                    Send Request

                                    Girl
                                    TeamC
                                    <button class="btn btn-primary" onclick="window.location.href='grace.html'; return false;">Detail</button>
                                    <button class="btn btn-danger" onclick="">Request</button>

    !--

            Team Noname by Comp3111

-->

Show


text:
package org.fest.swing.hierarchy;

import static org.fest.assertions.Assertions.assertThat;
import static org.fest.swing.edt.GuiActionRunner.execute;
import static org.fest.swing.test.builder.JButtons.button;
import static org.fest.swing.test.builder.JDialogs.dialog;

import java.awt.Component;

import javax.swing.JDialog;

import org.fest.swing.annotation.RunsInEDT;
import org.fest.swing.edt.GuiTask;
import org.fest.swing.test.swing.TestDialog;
import org.fest.swing.test.swing.TestWindow;
import org.junit.Test;

/**
 * Tests for {@link WindowFilter#ignore(Component)}.
 *
 * @author Alex Ruiz
 */
public class WindowFilter_ignore_Test extends WindowFilter_TestCase {
  @Test
  public void should_ignore_Component() {
    Component c = button().createNew();
    addToImplicitlyIgnoredMap(c);
    ignore(filter, c);
    assertThat(allIgnored()).containsOnly(c);
    assertThatNoComponentsAreImplicitlyIgnored();
  }

  @Test
  public void should_ignore_owned_Windows() {
    TestWindow window = TestWindow.createNewWindow(getClass());
    TestDialog dialog = TestDialog.createNewDialog(window);
    addToImplicitlyIgnoredMap(window, dialog);
    ignore(filter, window);
    assertThat(allIgnored()).containsOnly(window, dialog);
    assertThatNoComponentsAreImplicitlyIgnored();
  }

  @Test
  public void should_ignore_children_of_shared_invisible_Frame() {
    JDialog dialog = dialog().createNew();
    addToImplicitlyIgnoredMap(dialog);
    ignore(filter, dialog.getOwner());
    assertThat(allIgnored()).containsOnly(dialog);
    assertThatNoComponentsAreImplicitlyIgnored();
  }

  @RunsInEDT
  private static void ignore(final WindowFilter filter, final Component c) {
    execute(new GuiTask() {
      @Override
      protected void executeInEDT() {
        filter.ignore(c);
      }
    });
  }
}


text:
<?php

namespace MongoDB\Operation;

use MongoDB\Driver\Command;
use MongoDB\Driver\Server;
use MongoDB\Exception\InvalidArgumentException;
use MongoDB\Exception\InvalidArgumentTypeException;
use MongoDB\Exception\RuntimeException;
use MongoDB\Exception\UnexpectedValueException;

/**
 * Operation for the findAndModify command.
 *
 * This class is used internally by the FindOneAndDelete, FindOneAndReplace, and
 * FindOneAndUpdate operation classes.
 *
 * @internal
 * @see http://docs.mongodb.org/manual/reference/command/findAndModify/
 */
class FindAndModify implements Executable
{
    private $databaseName;
    private $collectionName;
    private $options;

    /**
     * Constructs a findAndModify command.
     *
     * Supported options:
     *
     *  * fields (document): Limits the fields to return for the matching
     *    document.
     *
     *  * maxTimeMS (integer): The maximum amount of time to allow the query to
     *    run.
     *
     *  * new (boolean): When true, returns the modified document rather than
     *    the original. This option is ignored for remove operations. The
     *    The default is false.
     *
     *  * query (document): Query by which to filter documents.
     *
     *  * remove (boolean): When true, removes the matched document. This option
     *    cannot be true if the update option is set. The default is false.
     *
     *  * sort (document): Determines which document the operation modifies if
     *    the query selects multiple documents.
     *
     *  * update (document): Update or replacement to apply to the matched
     *    document. This option cannot be set if the remove option is true.
     *
     *  * upsert (boolean): When true, a new document is created if no document
     *    matches the query. This option is ignored for remove operations. The
     *    default is false.
     *
     * @param string $databaseName   Database name
     * @param string $collectionName Collection name
     * @param array  $options        Command options
     * @throws InvalidArgumentException
     */
    public function __construct($databaseName, $collectionName, array $options)
    {
        $options += array(
            'new' => false,
            'remove' => false,
            'upsert' => false,
        );

        if (isset($options['fields']) && ! is_array($options['fields']) && ! is_object($options['fields'])) {
            throw new InvalidArgumentTypeException('"fields" option', $options['fields'], 'array or object');
        }

        if (isset($options['maxTimeMS']) && ! is_integer($options['maxTimeMS'])) {
            throw new InvalidArgumentTypeException('"maxTimeMS" option', $options['maxTimeMS'], 'integer');
        }

        if ( ! is_bool($options['new'])) {
            throw new InvalidArgumentTypeException('"new" option', $options['new'], 'boolean');
        }

        if (isset($options['query']) && ! is_array($options['query']) && ! is_object($options['query'])) {
            throw new InvalidArgumentTypeException('"query" option', $options['query'], 'array or object');
        }

        if ( ! is_bool($options['remove'])) {
            throw new InvalidArgumentTypeException('"remove" option', $options['remove'], 'boolean');
        }

        if (isset($options['sort']) && ! is_array($options['sort']) && ! is_object($options['sort'])) {
            throw new InvalidArgumentTypeException('"sort" option', $options['sort'], 'array or object');
        }

        if (isset($options['update']) && ! is_array($options['update']) && ! is_object($options['update'])) {
            throw new InvalidArgumentTypeException('"update" option', $options['update'], 'array or object');
        }

        if ( ! is_bool($options['upsert'])) {
            throw new InvalidArgumentTypeException('"upsert" option', $options['upsert'], 'boolean');
        }

        if ( ! (isset($options['update']) xor $options['remove'])) {
            throw new InvalidArgumentException('The "remove" option must be true or an "update" document must be specified, but not both');
        }

        $this->databaseName = (string) $databaseName;
        $this->collectionName = (string) $collectionName;
        $this->options = $options;
    }

    /**
     * Execute the operation.
     *
     * @see Executable::execute()
     * @param Server $server
     * @return object|null
     */
    public function execute(Server $server)
    {
        $cursor = $server->executeCommand($this->databaseName, $this->createCommand());
        $result = current($cursor->toArray());

        if (empty($result->ok)) {
            throw new RuntimeException(isset($result->errmsg) ? $result->errmsg : 'Unknown error');
        }

        if ( ! isset($result->value)) {
            return null;
        }

        /* Prior to 3.0, findAndModify returns an empty document instead of null
         * when an upsert is performed and the pre-modified document was
         * requested.
         */
        if ($this->options['upsert'] && ! $this->options['new'] &&
            isset($result->lastErrorObject->updatedExisting) &&
            ! $result->lastErrorObject->updatedExisting) {

            return null;
        }

        if ( ! is_object($result->value)) {
            throw new UnexpectedValueException('findAndModify command did not return a "value" document');
        }

        return $result->value;
    }

    /**
     * Create the findAndModify command.
     *
     * @return Command
     */
    private function createCommand()
    {
        $cmd = array(
            'findAndModify' => $this->collectionName,
        );

        if ($this->options['remove']) {
            $cmd['remove'] = true;
        } else {
            $cmd['new'] = $this->options['new'];
            $cmd['upsert'] = $this->options['upsert'];
        }

        foreach (array('fields', 'query', 'sort', 'update') as $option) {
            if (isset($this->options[$option])) {
                $cmd[$option] = (object) $this->options[$option];
            }
        }

        if (isset($this->options['maxTimeMS'])) {
            $cmd['maxTimeMS'] = $this->options['maxTimeMS'];
        }

        return new Command($cmd);
    }
}


text:
Muscle Hustle

<a href="<?php echo home_url(); ?>"><img src="<?php echo get_template_directory_uri(); ?>/assets/img/images/ram-fitness-logo-small.png" />

            <?php foundationPress_top_bar_l(); ?>
            <?php foundationPress_top_bar_r(); ?>


text:
define([
  'app/views/recentSearches',
  'use!backbone'
], function(RecentSearches, Backbone) {
  describe("Recent searches", function() {
    var el, rs, data, searches,
        search = {
          term : 'foo'
        };

    beforeEach(function() {
      el = $('#test').empty();
      var Searches = Backbone.Collection.extend({
        comparator : function() {
          return -1;
        }
      });
      searches = new Searches([
        { term : 'foo' },
        { term : 'bar' }
      ]);

      rs = new RecentSearches({
        collection : searches,
        currentSearch : function() {
          return 'foo';
        }
      }).render().placeAt(el);
    });

    it("should create the component", function() {
      expect(el.find('.component.recent-searches').length).to.be(1);
    });

    it("should display the recent searches", function() {
      expect(el.html()).to.contain('foo');
      expect(el.html()).to.contain('bar');
    });

    it("should mark the current search term", function() {
      expect(el.find('li.active').text()).to.contain('foo');
    });

    it("should update when there is a new search", function() {
      expect(el.html()).not.to.contain('baz');
      rs.options.currentSearch = function() { return 'baz'; };
      searches.add({ term : 'baz' });
      expect(el.html()).to.contain('baz');
      expect(el.find('.active').html()).to.contain('baz');
    });

    it("should throw an error if currentSearch is not defined", function() {
      expect(function() {
        new RecentSearches({
          searches : searches
        });
      }).to.throwError();
    });

    it("should throw an error if searches is not defined", function() {
      expect(function() {
        new RecentSearches({
          currentSearch : function() {}
        });
      }).to.throwError();
    });
  });
});


text:
<?php
/**
 * Extension to add extra settings into siteconfig
 *
 * @author i-lateral (http://www.i-lateral.com)
 * @package checkout
 */
class CheckoutSiteConfigExtension extends DataExtension
{
    private static $db = array(
        "PaymentNumberPrefix" => "Varchar(6)",
        'PaymentSuccessContent' => 'Text',
        'PaymentFailerContent'  => 'Text',
    );

    private static $has_many = array(
        'PostageAreas'      => 'PostageArea',
        'Discounts'         => 'Discount',
        'PaymentMethods'    => 'PaymentMethod',
    );

    public function updateCMSFields(FieldList $fields)
    {

        // Payment Methods
        $payment_table = GridField::create(
            'PaymentMethods',
            _t("CheckoutAdmin.PaymentMethods", "Payment Methods"),
            $this->owner->PaymentMethods(),
            GridFieldConfig::create()->addComponents(
                new GridFieldToolbarHeader(),
                new GridFieldAddNewButton('toolbar-header-right'),
                new GridFieldSortableHeader(),
                new GridFieldDataColumns(),
                new GridFieldPaginator(20),
                new GridFieldEditButton(),
                new GridFieldDeleteAction(),
                new GridFieldDetailForm()
            )
        );

        // setup compressed payment options
        $payment_fields = ToggleCompositeField::create(
            'PaymentSettings',
            _t("CheckoutAdmin.Payments", "Payment Settings"),
            array(
                TextField::create(
                    'PaymentNumberPrefix',
                    _t("CheckoutAdmin.OrderPrefix", "Add prefix to order numbers"),
                    null,
                    9
                )->setAttribute(
                    "placeholder",
                    _t("CheckoutAdmin.OrderPrefixPlaceholder", "EG 'abc'")
                ),

                TextAreaField::create(
                    'PaymentSuccessContent',
                    _t("CheckoutAdmin.PaymentSuccessContent", "Payment successfull content")
                )->setRows(4)
                ->setColumns(30)
                ->addExtraClass('stacked'),

                TextAreaField::create(
                    'PaymentFailerContent',
                    _t("CheckoutAdmin.PaymentFailerContent", "Payment failer content")
                )->setRows(4)
                ->setColumns(30)
                ->addExtraClass('stacked'),

                $payment_table
            )
        );

        // Add html description of how to edit contries
        $country_html = "
";
        $country_html .= "
First select valid countries using the 2 character ";
        $country_html .= "shortcode (see http://fasteri.com/list/2/short-names-of-countries-and-iso-3166-codes).
";
        $country_html .= "
You can add multiple countries seperating them with";
        $country_html .= "a comma or use a '*' for all countries.
";
        $country_html .= "
";

        $country_html_field = LiteralField::create("CountryDescription", $country_html);

        // Deal with product features
        $postage_field = new GridField(
            'PostageAreas',
            '',
            $this->owner->PostageAreas(),
            GridFieldConfig::create()
                ->addComponents(
                    new GridFieldButtonRow('before'),
                    new GridFieldToolbarHeader(),
                    new GridFieldTitleHeader(),
                    new GridFieldEditableColumns(),
                    new GridFieldDeleteAction(),
                    new GridFieldAddNewInlineButton('toolbar-header-left')
                )
        );

        // Add country dropdown to inline editing
        $postage_field
            ->getConfig()
            ->getComponentByType('GridFieldEditableColumns')
            ->setDisplayFields(array(
                'Title' => array(
                    'title' => 'Title',
                    'field' => 'TextField'
                ),
                'Country' => array(
                    'title' => 'ISO 3166 codes',
                    'field' => 'TextField'
                ),
                'ZipCode' => array(
                    'title' => 'Zip/Post Codes',
                    'field' => 'TextField'
                ),
                'Calculation'  => array(
                    'title' => 'Base unit',
                    'callback' => function ($record, $column, $grid) {
                        return DropdownField::create(
                            $column,
                            "Based on",
                            singleton('PostageArea')
                                ->dbObject('Calculation')
                                ->enumValues()
                        )->setValue("Weight");
                    }
                ),
                'Unit' => array(
                    'title' => 'Unit (equals or above)',
                    'field' => 'NumericField'
                ),
                'Cost' => array(
                    'title' => 'Cost',
                    'field' => 'NumericField'
                ),
                'Tax' => array(
                    'title' => 'Tax (percentage)',
                    'field' => 'NumericField'
                )
            ));

        // Setup compressed postage options
        $postage_fields = ToggleCompositeField::create(
            'PostageFields',
            'Postage Options',
            array(
                $country_html_field,
                $postage_field
            )
        );

        // Setup compressed postage options
        $discount_fields = ToggleCompositeField::create(
            'DiscountFields',
            'Discounts',
            array(
                GridField::create(
                    'Discounts',
                    '',
                    $this->owner->Discounts(),
                    GridFieldConfig_RecordEditor::create()
                )
            )
        );

        // Add config sets
        $fields->addFieldToTab('Root.Checkout', $payment_fields);
        $fields->addFieldToTab('Root.Checkout', $postage_fields);
        $fields->addFieldToTab('Root.Checkout', $discount_fields);
    }
}


text:
  # => I'm going to have to use a random or shuffle method to call a container containing bingo and then randomly call a number from 1-100. I can store this value into a variable that can be accessed outside of this method.

# Check the called column for the number called.
  # => I have to check if the first character that is returned from the random letter and number generation is the same as the corresponding column. If so I need to look through those columns and see if the numeric value matches any of the existing values.

# If the number is in the column, replace with an 'x'
  # => When the numeric value matches, then I need to destructively replace that number with an "X"

# Display a column to the console
  # => how all numbers that have the same integer value in the array

# Display the board to the console (prettily)
  # => print the entire board

# Initial Solution

class BingoBoard
  attr_accessor :bingo_board

  def initialize(board)
    @bingo_board = board
    @combo = 0
  end

  def new_game
    counter = 0
    @bingo_board = Array.new(5){Array.new (5)}

    b = (1...16).to_a.sample(5)
    i = (16...31).to_a.sample(5)
    n = (31...46).to_a.sample(5)
    g = (46...61).to_a.sample(5)
    o = (61...76).to_a.sample(5)

    until counter == 5
      b.each do |element|
        @bingo_board[counter][0] = element
        counter += 1
      end
    end

    counter = 0

    until counter == 5
      i.each do |element|
        @bingo_board[counter][1] = element
        counter += 1
      end
    end

    counter = 0

    until counter == 5
      n.each do |element|
        @bingo_board[counter][2] = element
        counter += 1
      end
    end

    counter = 0

    until counter == 5
      g.each do |element|
        @bingo_board[counter][3] = element
        counter += 1
      end
    end

    counter = 0

    until counter == 5
      o.each do |element|
        @bingo_board[counter][4] = element
        counter += 1
      end
    end

    @bingo_board[2][2] = "X"

    puts "Here is your Bingo board!"
    print_board
  end

  def call
    bingo = ["B", "I", "N", "G", "O"]
    letter = bingo.sample
    @bingo_column =  bingo.find_index(letter)
    if @bingo_column == 0
      @combo = letter + (rand(15) + 1).to_s
    elsif @bingo_column == 1
      @combo = letter + (rand(15) + 16).to_s
    elsif @bingo_column == 2
      @combo = letter + (rand(15) + 31).to_s
    elsif @bingo_column == 3
      @combo = letter + (rand(15) + 46).to_s
    elsif @bingo_column == 4
      @combo = letter + (rand(15) + 61).to_s
    end
    puts @combo
  end

  def print_board
    p @bingo_board[0]
    p @bingo_board[1]
    p @bingo_board[2]
    p @bingo_board[3]
    p @bingo_board[4]
  end

  def check
    puts call
    number = @combo.slice(1..-1).to_i
    @bingo_board.each do |big_array|
      big_array.map!.with_index do |element, index|
        if (index == @bingo_column) && (element == number)
          element = "X"
        else
          element
        end
       end
    end
    print_board
  end

  def play
    puts "Are you ready to play some bingo!? (y/n)"
    answer = gets.chomp
    if answer.downcase == "y"
      new_game
      winner = "n"
        while winner == "n"
          puts "Ok! Here we go! The next bingo call is...."
          check
          puts "Did you win? (y/n)"
          winner = gets.chomp
        end
        if winner == "y"
          puts "BBBBBBIIIIINNNNNNGGGGGOOOOOOOOOOO!!!!!!!!!!!"
          puts "do you want to play again? (y/n)"
          play_again = gets.chomp
          if play_again == "y"
            play
          else
            puts "I'm pretty sure what you meant to say was mas Bingo por favor"
            play
          end
        end
    elsif answer.downcase == "n"
      puts "Ok well then you should have thought of that before you started playing a bingo game..."
    else
      puts "That is not a valid response"
    end
  end
end

# Refactored Solution

#I spent hours trying to refactor my new_game method, but I was not able to get the iteration right. too many infinite loops.

#DRIVER CODE (I.E. METHOD CALLS) GO BELOW THIS LINE
board = [[47, 44, 71, 8, 88],
        [22, 69, 75, 65, 73],
        [83, 85, 97, 89, 57],
        [25, 31, 96, 68, 51],
        [75, 70, 54, 80, 83]]

new_game = BingoBoard.new(board)

new_game.play

#Reflection
=begin
 How difficult was pseudocoding this challenge? What do you think of your pseudocoding style?
I'm terrible at pseudocoding. So if I were to identify my style I would say it is awful. It's hard for me to pseudocode unless i play around with the code a little bit.

What are the benefits of using a class for this challenge?
It was beneficial to use a class for this challenge so that I could call a method multiple times throughout the class. Instead of writing a print for the end of each method, I could just call my print method at the end of other methods.

How can you access coordinates in a nested array?
You can iterate through them twice (see lines 126 and 127) or you can access them by their indexes. For example the top left corner of the bingo board could be accessed like this => @bingo_board[0][0]

What methods did you use to access and modify the array?
I actually used a lot of new methods here that I hadn't used before. I used map!.with_index so that I could iterate through the index. I also used the each method with reassignment in the block to modify the original array.

Give an example of a new method you learned while reviewing the Ruby docs. Based on what you see in the docs, what purpose does it serve, and how is it called?
Well I wasn't able to use this method, although not because I didn't try. I really wanted to use the transpose method. It takes an array of similarly sized arrays and turns the columns of the array into a new array. For example:

array = [[1,2], [3,4], [5,6]]
array.transpose   => [[1, 3, 5], [2, 4, 6]]

I tried for at least an hour to use this but I'm guessing because it is not destructive it didn't really help. One day. One day I will use this method.

How did you determine what should be an instance variable versus a local variable?
My general rule of thumb for this has been if I'm going to need this value somewhere else in the class, I should make it an instance variable. I made my bingo call (@combo) an instance variable so I could use it in my check method.

What do you feel is most improved in your refactored solution?
I spent a lot of time trying to refactor my multiple until statements in my new_game method, but I wasn't able to get it. So I gave up.

=end


text:
cd "$(cygpath "${PWD}")"
if [[ ${PWD} != */native_client ]]; then
  echo "ERROR: must be run in native_client!"
  exit 1
fi

set -x
set -e
set -u

# Transitionally, even though our new toolchain location is under
# toolchain/win_x86/nacl_x86_glibc we have to keep the old format
# inside of the tar (toolchain/win_x86) so that the untar toolchain script
# is backwards compatible and can untar old tars. Eventually this will be
# unnecessary with the new package_version scheme since how to untar the
# tar file will be embedded inside of the package file so they can differ
# between revisions.
export TOOLCHAINLOC=toolchain
export TOOLCHAINNAME=win_x86

# This is where we want the toolchain when moving to native_client/toolchain.
OUT_TOOLCHAINLOC=toolchain/win_x86
OUT_TOOLCHAINNAME=nacl_x86_glibc
CORE_SDK=core_sdk
CORE_SDK_WORK=core_sdk_work

TOOL_TOOLCHAIN="$TOOLCHAINLOC/$TOOLCHAINNAME"
OUT_TOOLCHAIN="${OUT_TOOLCHAINLOC}/${OUT_TOOLCHAINNAME}"

export INST_GLIBC_PROGRAM="$PWD/tools/glibc_download.sh"
# Workaround for broken autoconf mmap test (WOW64 limitation)
# More info here: http://cygwin.com/ml/cygwin/2011-03/msg00596.html
export ac_cv_func_mmap_fixed_mapped=yes

echo @@@BUILD_STEP clobber_toolchain@@@
rm -rf scons-out tools/BUILD/* tools/out tools/toolchain \
  tools/glibc tools/glibc.tar tools/toolchain.t* "${OUT_TOOLCHAIN}" \
  tools/${CORE_SDK} tools/${CORE_SDK_WORK} .tmp ||
  echo already_clean
mkdir -p "tools/${TOOL_TOOLCHAIN}"
ln -sfn "$PWD"/cygwin/tmp "tools/${TOOL_TOOLCHAIN}"

echo @@@BUILD_STEP clean_sources@@@
tools/update_all_repos_to_latest.sh

# glibc_download.sh can return three return codes:
#  0 - glibc is successfully downloaded and installed
#  1 - glibc is not downloaded but another run may help
#  2+ - glibc is not downloaded and can not be downloaded later
#
# If the error result is 2 or more we are stopping the build
echo @@@BUILD_STEP check_glibc_revision_sanity@@@
echo "Try to download glibc revision $(tools/glibc_revision.sh)"
if tools/glibc_download.sh "tools/${TOOL_TOOLCHAIN}" 1; then
  INST_GLIBC_PROGRAM=true
elif (($?>1)); then
  echo @@@STEP_FAILURE@@@
  exit 100
fi

if [[ "${BUILDBOT_SLAVE_TYPE:-Trybot}" == "Trybot" ]]; then
echo @@@BUILD_STEP setup source@@@
(cd tools; ./buildbot_patch-toolchain-tries.sh)
fi

echo @@@BUILD_STEP compile_toolchain@@@
(
  cd tools
  make -j8 buildbot-build-with-glibc
  rm "${TOOL_TOOLCHAIN}/tmp"
)

echo @@@BUILD_STEP build_core_sdk@@@
# Use scons to generate the SDK headers and libraries.
${NATIVE_PYTHON} scons.py --nacl_glibc MODE=nacl naclsdk_validate=0 \
  nacl_glibc_dir="tools/${TOOL_TOOLCHAIN}" \
  DESTINATION_ROOT="tools/${CORE_SDK_WORK}" \
  includedir="tools/${CORE_SDK}/x86_64-nacl/include" \
  install_headers

${NATIVE_PYTHON} scons.py --nacl_glibc MODE=nacl naclsdk_validate=0 \
  platform=x86-32 \
  nacl_glibc_dir="tools/${TOOL_TOOLCHAIN}" \
  DESTINATION_ROOT="tools/${CORE_SDK_WORK}" \
  libdir="tools/${CORE_SDK}/x86_64-nacl/lib32" \
  install_lib

${NATIVE_PYTHON} scons.py --nacl_glibc MODE=nacl naclsdk_validate=0 \
  platform=x86-64 \
  nacl_glibc_dir="tools/${TOOL_TOOLCHAIN}" \
  DESTINATION_ROOT="tools/${CORE_SDK_WORK}" \
  libdir="tools/${CORE_SDK}/x86_64-nacl/lib" \
  install_lib

if [[ "${BUILDBOT_SLAVE_TYPE:-Trybot}" != "Trybot" ]]; then
  GSD_BUCKET=nativeclient-archive2
  UPLOAD_REV=${BUILDBOT_GOT_REVISION}
  UPLOAD_LOC=x86_toolchain/r${UPLOAD_REV}
else
  GSD_BUCKET=nativeclient-trybot/packages
  UPLOAD_REV=${BUILDBOT_BUILDERNAME}/${BUILDBOT_BUILDNUMBER}
  UPLOAD_LOC=x86_toolchain/${UPLOAD_REV}
fi

(
  cd tools
  echo @@@BUILD_STEP canonicalize timestamps@@@
  ./canonicalize_timestamps.sh "${TOOL_TOOLCHAIN}"
  ./canonicalize_timestamps.sh "${CORE_SDK}"

  echo @@@BUILD_STEP tar_toolchain@@@
  tar Scf toolchain.tar "${TOOL_TOOLCHAIN}"
  xz -k -9 toolchain.tar
  bzip2 -k -9 toolchain.tar
  gzip -n -9 toolchain.tar

  echo @@@BUILD_STEP tar_core_sdk@@@
  tar Scf core_sdk.tar "${CORE_SDK}"
  xz -k -9 core_sdk.tar
  bzip2 -k -9 core_sdk.tar
  gzip -n -9 core_sdk.tar
)

echo @@@BUILD_STEP archive_build@@@
for suffix in gz bz2 xz ; do
  ${NATIVE_PYTHON} ${GSUTIL} cp -a public-read \
    tools/toolchain.tar.$suffix \
    gs://${GSD_BUCKET}/${UPLOAD_LOC}/toolchain_win_x86.tar.$suffix
  ${NATIVE_PYTHON} ${GSUTIL} cp -a public-read \
    tools/core_sdk.tar.$suffix \
    gs://${GSD_BUCKET}/${UPLOAD_LOC}/core_sdk_win_x86.tar.$suffix
done
echo @@@STEP_LINK@download@http://gsdview.appspot.com/${GSD_BUCKET}/${UPLOAD_LOC}/@@@

echo @@@BUILD_STEP archive_extract_packages@@@
${NATIVE_PYTHON} build/package_version/package_version.py \
  archive --archive-package=${TOOLCHAINNAME}/nacl_x86_glibc --extract \
  --extra-archive gdb_i686_w64_mingw32.tgz \
  tools/toolchain.tar.bz2,${TOOL_TOOLCHAIN}@https://storage.googleapis.com/${GSD_BUCKET}/${UPLOAD_LOC}/toolchain_win_x86.tar.bz2 \
  tools/core_sdk.tar.bz2,${CORE_SDK}@https://storage.googleapis.com/${GSD_BUCKET}/${UPLOAD_LOC}/core_sdk_win_x86.tar.bz2

${NATIVE_PYTHON} build/package_version/package_version.py \
  archive --archive-package=${TOOLCHAINNAME}/nacl_x86_glibc_raw --extract \
  --extra-archive gdb_i686_w64_mingw32.tgz \
  tools/toolchain.tar.bz2,${TOOL_TOOLCHAIN}@https://storage.googleapis.com/${GSD_BUCKET}/${UPLOAD_LOC}/toolchain_win_x86.tar.bz2

echo @@@BUILD_STEP upload_package_info@@@
${NATIVE_PYTHON} build/package_version/package_version.py \
  --cloud-bucket=${GSD_BUCKET} --annotate \
  upload --skip-missing \
  --upload-package=${TOOLCHAINNAME}/nacl_x86_glibc --revision=${UPLOAD_REV}

${NATIVE_PYTHON} build/package_version/package_version.py \
  --cloud-bucket=${GSD_BUCKET} --annotate \
  upload --skip-missing \
  --upload-package=${TOOLCHAINNAME}/nacl_x86_glibc_raw --revision=${UPLOAD_REV}

# Before we start testing, put in dummy mock archives so gyp can still untar
# the entire package.
python build/package_version/package_version.py fillemptytars \
  --fill-package nacl_x86_glibc

# sync_backports is obsolete and should probably be removed.
# if [[ "${BUILD_COMPATIBLE_TOOLCHAINS:-yes}" != "no" ]]; then
#   echo @@@BUILD_STEP sync backports@@@
#   rm -rf tools/BACKPORTS/ppapi*
#   tools/BACKPORTS/build_backports.sh VERSIONS win glibc
# fi


text:
package com.mgmtp.jfunk.web;

import static org.apache.commons.io.IOUtils.closeQuietly;
import static org.fest.assertions.api.Assertions.assertThat;

import java.io.IOException;
import java.io.Reader;
import java.util.List;
import java.util.Map;

import org.openqa.selenium.Capabilities;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Test;

import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import com.google.inject.util.Providers;
import com.mgmtp.jfunk.common.util.Configuration;

/**
 * @author rnaegele
 */
public class CapabilitiesProviderTest {

	@Test
	public void testGet() throws IOException {
		Configuration config = new Configuration(Charsets.UTF_8);
		Reader reader = null;
		try {
			reader = Resources.asCharSource(Resources.getResource("test_capabilities.properties"), Charsets.UTF_8)
					.openStream();
			config.load(reader);

			CapabilitiesProvider provider = new CapabilitiesProvider(Providers.of(config));
			Map<String, DesiredCapabilities> capabilitiesMap = provider.get();

			assertThat(capabilitiesMap).hasSize(2);
			assertThat(capabilitiesMap).containsKey("firefox");
			assertThat(capabilitiesMap).containsKey("remote");

			Capabilities capabilities = capabilitiesMap.get("firefox");
			assertThat(capabilities.getCapability("globalCapability")).isEqualTo("globalCapabilityValueOverride");
			assertThat(capabilities.getCapability("firefoxCapability")).isEqualTo("firefoxCapabilityValue");

			capabilities = capabilitiesMap.get("remote");
			assertThat(capabilities.getCapability("globalCapability")).isEqualTo("globalCapabilityValue");
			assertThat(capabilities.getCapability("stringCapability")).isEqualTo("stringCapabilityValue");
			assertThat(capabilities.getCapability("listCapability")).isInstanceOf(List.class);

			@SuppressWarnings("unchecked")
			List<String> list = (List<String>) capabilities.getCapability("listCapability");
			assertThat(list).contains("listCapabilityValue1", "listCapabilityValue2");

			Object proxy = capabilities.getCapability(CapabilityType.PROXY);
			assertThat(proxy).isInstanceOf(Proxy.class);
			assertThat(((Proxy) proxy).getHttpProxy()).isEqualTo("localhost:8080");
		} finally {
			closeQuietly(reader);
		}
	}

	@Test
	public void testGetWithProxyOnly() {
		Configuration config = new Configuration(Charsets.UTF_8);
		String proxyString = "localhost:8080";
		config.put("webdriver.proxy.httpProxy", proxyString);

		CapabilitiesProvider provider = new CapabilitiesProvider(Providers.of(config));
		Capabilities capabilities = provider.get().get("anykey");
		Object proxy = capabilities.getCapability(CapabilityType.PROXY);

		assertThat(proxy).isInstanceOf(Proxy.class);
		assertThat(((Proxy) proxy).getHttpProxy()).isEqualTo(proxyString);
	}
}