text:
var React = require('react');
var OK = require('./status/OK');
var CriticalStatus = require('./status/CriticalStatus');
var ErrorStatus = require('./status/ErrorStatus');
var Warning = require('./status/Warning');
var Disabled = require('./status/Disabled');
var Unknown = require('./status/Unknown');
var Label = require('./status/Label');

var CLASS_ROOT = "status-icon";

var Status = React.createClass({

  getDefaultProps: function () {
    return {value: 'unknown'};
  },

  getInitialState: function() {
    return this._stateFromProps(this.props);
  },

  componentWillReceiveProps: function (newProps) {
    this.setState(this._stateFromProps(newProps));
  },

  propType: {
    a11yTitle: React.PropTypes.string,
    large: React.PropTypes.bool,
    small: React.PropTypes.bool,
    size: React.PropTypes.oneOf(['small', 'medium', 'large']),
    value: React.PropTypes.oneOf(['critical', 'warning', 'ok', 'unknown', 'disabled'])
  },

  _stateFromProps: function (props) {
    return {size: props.size || (props.small ? 'small' : (props.large ? 'large' : null))};
  },

  render: function() {
    var classes = [CLASS_ROOT];
    if (this.props.className) {
      classes.push(this.props.className);
    }
    if (this.state.size) {
      classes.push(CLASS_ROOT + "--" + this.state.size);
    }
    var className = classes.join(' ');
    var icon = (<span>{'?'}</span>);
    switch (this.props.value.toLowerCase()) {
      case 'ok':
      case 'normal':
        icon = (<OK className={className} a11yTitle={this.props.a11yTitle} />);
        break;
      case 'warning':
        icon = (<Warning className={className} a11yTitle={this.props.a11yTitle} />);
        break;
      // 'error' is deprecated, use 'critical'
      case 'error':
        icon = (<ErrorStatus className={className} a11yTitle={this.props.a11yTitle} />);
        break;
      case 'critical':
        icon = (<CriticalStatus className={className} a11yTitle={this.props.a11yTitle} />);
        break;
      case 'disabled':
        icon = (<Disabled className={className} a11yTitle={this.props.a11yTitle} />);
        break;
      case 'unknown':
        icon = (<Unknown className={className} a11yTitle={this.props.a11yTitle} />);
        break;
      case 'label':
        icon = (<Label className={className} a11yTitle={this.props.a11yTitle} />);
        break;
    }
    return icon;
  }

});

module.exports = Status;


text:
package org.jkiss.dbeaver.ext.import_config.wizards.squirrel;

import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.ext.import_config.Activator;
import org.jkiss.dbeaver.ext.import_config.wizards.ConfigImportWizardPage;
import org.jkiss.dbeaver.ext.import_config.wizards.ImportConnectionInfo;
import org.jkiss.dbeaver.ext.import_config.wizards.ImportData;
import org.jkiss.dbeaver.ext.import_config.wizards.ImportDriverInfo;
import org.jkiss.dbeaver.utils.RuntimeUtils;
import org.jkiss.utils.CommonUtils;
import org.jkiss.utils.xml.XMLException;
import org.jkiss.utils.xml.XMLUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ConfigImportWizardPageSquirrel extends ConfigImportWizardPage {

    public static final String SQL_HOME_FOLDER = ".squirrel-sql";
    public static final String SQL_ALIASES_FILE = "SQLAliases23.xml";
    public static final String SQL_DRIVERS_FILE = "SQLDrivers.xml";

    protected ConfigImportWizardPageSquirrel()
    {
        super("SQL Squirrel");
        setTitle("SQL Squirrel");
        setDescription("Import SQL Squirrel connections");
        setImageDescriptor(Activator.getImageDescriptor("icons/squirrel_big.png"));
    }

    @Override
    protected void loadConnections(ImportData importData) throws DBException
    {
        File homeFolder = RuntimeUtils.getUserHomeDir();
        File sqlConfigHome = new File(homeFolder, SQL_HOME_FOLDER);
        if (!sqlConfigHome.exists()) {
            throw new DBException("SQL Squirrel installation not found");
        }
        File driversFile = new File(sqlConfigHome, SQL_DRIVERS_FILE);
        if (!driversFile.exists()) {
            throw new DBException("SQL Squirrel drivers configuration file not found. Possibly corrupted installation.");
        }
        File aliasesFile = new File(sqlConfigHome, SQL_ALIASES_FILE);
        if (!aliasesFile.exists()) {
            throw new DBException("SQL Squirrel configuration file not found. Possibly version older than 2.3 is installed.");
        }

        try {
            // Parse drivers

            Document driversDocument = XMLUtils.parseDocument(driversFile);
            for (Element driverElement : XMLUtils.getChildElementList(driversDocument.getDocumentElement(), "Bean")) {
                if (!"net.sourceforge.squirrel_sql.fw.sql.SQLDriver".equals(driverElement.getAttribute("Class"))) {
                    continue;
                }
                final Element driverIdentifier = XMLUtils.getChildElement(driverElement, "identifier");
                String driverId = driverIdentifier == null ? null : XMLUtils.getChildElementBody(driverIdentifier, "string");
                if (CommonUtils.isEmpty(driverId)) {
                    continue;
                }
                String name = XMLUtils.getChildElementBody(driverElement, "name");
                String driverClass = XMLUtils.getChildElementBody(driverElement, "driverClassName");
                String sampleURL = XMLUtils.getChildElementBody(driverElement, "url");
                //String webURL = XMLUtils.getChildElementBody(driverElement, "websiteUrl");

                if (!CommonUtils.isEmpty(name) && !CommonUtils.isEmpty(sampleURL) && !CommonUtils.isEmpty(driverClass)) {
                    ImportDriverInfo driver = new ImportDriverInfo(driverId, name, sampleURL, driverClass);
                    adaptSampleUrl(driver);

                    // Parse libraries
                    final Element jarFileNames = XMLUtils.getChildElement(driverElement, "jarFileNames");
                    if (jarFileNames != null) {
                        for (Element locationElement : XMLUtils.getChildElementList(jarFileNames, "Bean")) {
                            String path = XMLUtils.getChildElementBody(locationElement, "string");
                            if (!CommonUtils.isEmpty(path)) {
                                driver.addLibrary(path);
                            }
                        }
                    }

                    importData.addDriver(driver);
                }
            }

            // Parse aliases
            Document aliasesDocument = XMLUtils.parseDocument(aliasesFile);

            for (Element aliasElement : XMLUtils.getChildElementList(aliasesDocument.getDocumentElement(), "Bean")) {
                if (!"net.sourceforge.squirrel_sql.client.gui.db.SQLAlias".equals(aliasElement.getAttribute("Class"))) {
                    continue;
                }
                final Element driverIdentifier = XMLUtils.getChildElement(aliasElement, "driverIdentifier");
                String driverId = driverIdentifier == null ? null : XMLUtils.getChildElementBody(driverIdentifier, "string");
                if (CommonUtils.isEmpty(driverId)) {
                    continue;
                }
                final ImportDriverInfo driverInfo = importData.getDriverByID(driverId);
                if (driverInfo == null) {
                    continue;
                }
                String name = XMLUtils.getChildElementBody(aliasElement, "name");
                String url = XMLUtils.getChildElementBody(aliasElement, "url");
                String userName = XMLUtils.getChildElementBody(aliasElement, "userName");
                String password = XMLUtils.getChildElementBody(aliasElement, "password");
                ImportConnectionInfo connectionInfo = new ImportConnectionInfo(driverInfo, null, name, url, null, null, null, userName, password);
                importData.addConnection(connectionInfo);
            }
        } catch (XMLException e) {
            throw new DBException("Configuration parse error: " + e.getMessage());
        }

    }

    private static Pattern PATTERN_OPTIONAL = Pattern.compile("\\[|\\]");
    private static Pattern PATTERN_HOST = Pattern.compile("<server>|<server_name>|<hostname>|<host_name>|<host>", Pattern.CASE_INSENSITIVE);
    private static Pattern PATTERN_PORT = Pattern.compile("<port>|<port_number>|<(:?[0-9]+)>|(:[0-9]+)", Pattern.CASE_INSENSITIVE);
    private static Pattern PATTERN_HOST_PORT = Pattern.compile("<server:port>", Pattern.CASE_INSENSITIVE);
    private static Pattern PATTERN_DATABASE = Pattern.compile("dbname|<dbname>|<db-name>|<db_name>|<databaseName>|<database-name>|<database_name>|<database>|<full_db_path>|<pathname>|<alias>|<schema>|<default_schema>|<default-schema>", Pattern.CASE_INSENSITIVE);

    private void adaptSampleUrl(ImportDriverInfo driverInfo)
    {
        String port = null;
        String sampleURL = driverInfo.getSampleURL();
        int divPos = sampleURL.indexOf("?");
        if (divPos != -1) {
            sampleURL = sampleURL.substring(0, divPos);
        }
        divPos = sampleURL.indexOf(";");
        if (divPos != -1) {
            sampleURL = sampleURL.substring(0, divPos);
        }
        sampleURL = PATTERN_OPTIONAL.matcher(sampleURL).replaceAll("");
        sampleURL = PATTERN_HOST_PORT.matcher(sampleURL).replaceAll("{host}:{port}");
        sampleURL = PATTERN_HOST.matcher(sampleURL).replaceAll("{host}");

        String portReplacement = "{port}";
        final Matcher portMatcher = PATTERN_PORT.matcher(sampleURL);
        if (portMatcher.find()) {
            String portString = portMatcher.group(1);
            if (CommonUtils.isEmpty(portString)) {
                portString = portMatcher.group(2);
            }
            if (!CommonUtils.isEmpty(portString)) {
                if (portString.startsWith(":")) {
                    portReplacement = ":" + portReplacement;
                    portString = portString.substring(1);
                }
                port = portString;
            }
        }
        sampleURL = portMatcher.replaceAll(portReplacement);
        sampleURL = PATTERN_DATABASE.matcher(sampleURL).replaceAll("{database}");

        driverInfo.setSampleURL(sampleURL);
        if (port != null) {
            driverInfo.setDefaultPort(port);
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
{% extends 'layout.html' %}

{% block pageTitle %}
State Pension Activation
{% endblock %}

{% block content %}

  {% include 'includes/parts/phase-banner.html' %}

      {% if errors %}

{{errors.title}}

{{errors.text}}

      {% endif %}

When do you want your
State Pension?

      <form method="post">
        <input id="spa-date" type="hidden" value="{{date}}">

        <fieldset>

According to the information you have given us, the earliest date you can get your State Pension is 12 April 2018.

What date do you want to get your State Pension?

You can only make a claim up to 4 months in advance.

            <fieldset>

                The date you have entered is more than four months from now. To claim on this date please come back on .

                The date you have entered is before your State Pension age. The earliest you can claim is {{nice_date.day}} {{nice_date.month}} {{nice_date.year}}.

                  Day
                  <input class="form-control" id="set-day" name="deferral-day" type="text" maxlength="2" pattern="[0-9]*" min="0" max="31">

                  Month
                  <input class="form-control" id="set-month" name="deferral-month" type="text" maxlength="2" pattern="[0-9]*" min="0" max="12">

                  Year
                  <input class="form-control" id="set-year" name="deferral-year" type="text" maxlength="4" pattern="[0-9]*" min="0" max="2016">

            </fieldset>
          </fieldset>

          <input type="submit" class="button" value="Continue" />

        </form>

        {% include 'includes/parts/helpinternational.html' %}

  {% endblock %}


text:
namespace browser_sync {

bool DataTypeController::IsUnrecoverableResult(StartResult result) {
  return (result == UNRECOVERABLE_ERROR);
}

syncer::SyncError DataTypeController::CreateAndUploadError(
    const tracked_objects::Location& location,
    const std::string& message,
    syncer::ModelType type) {
  ChromeReportUnrecoverableError();
  return syncer::SyncError(location, message, type);
}

void DataTypeController::RecordUnrecoverableError(
    const tracked_objects::Location& from_here,
    const std::string& message) {
  DVLOG(1) << "Datatype Controller failed for type "
           << ModelTypeToString(type()) << "  "
           << message << " at location "
           << from_here.ToString();
  UMA_HISTOGRAM_ENUMERATION("Sync.DataTypeRunFailures", type(),
                            syncer::MODEL_TYPE_COUNT);

  // TODO(sync): remove this once search engines triggers less errors, such as
  // due to crbug.com/130448.
  if (type() != syncer::SEARCH_ENGINES)
    ChromeReportUnrecoverableError();
}

}  // namespace browser_sync


text:
package org.bitbuckets.frc2015;

/**
 * The RobotMap is a mapping from the ports sensors and actuators are wired into
 * to a variable name. This provides flexibility changing wiring, makes checking
 * the wiring easier and significantly reduces the number of magic numbers
 * floating around.
 */
public class RobotMap {

    ///////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////----SOLENOIDS----/////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////

    /**
     * The first port for the double solenoid controlling the grabber pistons.
     */
    public static final int GRABBY_SOLENOID_1 = 3;
    /**
     * The second port for the double solenoid controlling the grabber pistons.
     */
    public static final int GRABBY_SOLENOID_2 = 4;
    /**
     * The first port for the double solenoid controlling the tilty pistons.
     */
    public static final int TILTY_SOLENOID_1 = 0;
    /**
     * The second port for the double solenoid controlling the tilty pistons.
     */
    public static final int TILTY_SOLENOID_2 = 1;
    /**
     * The first port for the double solenoid controlling the flippy pistons.
     */
    public static final int FLIPPY_SOLENOID_1 = 5;
    /**
     * The second port for the double solenoid controlling the flippy pistons.
     */
    public static final int FLIPPY_SOLENOID_2 = 6;

    /////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////----PWM----/////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////

    /**
     * Motors driving the winch for the elevator on {@link org.bitbuckets.frc2015.subsystems.Stacky}.
     */
    public static final int WINCH_MOTOR = 7;

    /////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////----CAN----/////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////

    /**
     * The CAN index for the front right motor on the drivetrain.
     */
    public static final int WHEEL_FR_MOTOR = 2;
    /**
     * The CAN index for the rear right motor on the drivetrain.
     */
    public static final int WHEEL_RR_MOTOR = 4;
    /**
     * The CAN index for the front left motor on the drivetrain.
     */
    public static final int WHEEL_FL_MOTOR = 1;
    /**
     * The CAN index for the rear left motor on the drivetrain.
     */
    public static final int WHEEL_RL_MOTOR = 3;

    /////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////----DIO----/////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////

    /**
     * The port that the hall effect sensor with the singular magnet is connected to.
     */
    public static final int HALL_SING = 1;
    /**
     * The port that the hall effect sensor with the multiple magnets is connected to.
     */
    public static final int HALL_MULTI = 2;
    /**
     * The right side sensor to detect collision with a tote
     */
    public static final int BUMP_SENSE_RIGHT = 5;
    /**
     * The left side sensor to detect collision with a tote
     */
    public static final int BUMP_SENSE_LEFT = 6;
    /**
     * The switch that tells the compressor the max pressure
     */
    public static final int PRESSURE_SWITCH = 14;

    /////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////----WHEELS----//////////////////////////////
    /////////////////////////////////////////////////////////////////////////////

    /**
     * The X coordinate of the front left wheel from the center of the robot in inches.
     */
    public static final double WHEEL_FL_X = -11 / 12.0;
    /**
     * The Y coordinate of the front left wheel from the center of the robot in inches.
     */
    public static final double WHEEL_FL_Y = 14 / 12.0;
    /**
     * The angle of the front left wheel from top down positive X.
     */
    public static final double WHEEL_FL_THETA = Math.PI / 4;

    /**
     * The X coordinate of the front right wheel from the center of the robot in inches.
     */
    public static final double WHEEL_FR_X = 11 / 12.0;
    /**
     * The Y coordinate of the front right wheel from the center of the robot in inches.
     */
    public static final double WHEEL_FR_Y = 14 / 12.0;
    /**
     * The angle of the front right wheel from top down positive X.
     */
    public static final double WHEEL_FR_THETA = 7 * Math.PI / 4;

    /**
     * The X coordinate of the rear left wheel from the center of the robot in inches.
     */
    public static final double WHEEL_RL_X = -11 / 12.0;
    /**
     * The Y coordinate of the rear left wheel from the center of the robot in inches.
     */
    public static final double WHEEL_RL_Y = -14 / 12.0;
    /**
     * The angle of the rear left wheel from top down positive X.
     */
    public static final double WHEEL_RL_THETA = 3 * Math.PI / 4;

    /**
     * The X coordinate of the rear right wheel from the center of the robot in inches.
     */
    public static final double WHEEL_RR_X = 11 / 12.0;
    /**
     * The Y coordinate of the rear right wheel from the center of the robot in inches.
     */
    public static final double WHEEL_RR_Y = -14 / 12.0;
    /**
     * The angle of the rear right wheel from top down positive X.
     */
    public static final double WHEEL_RR_THETA = 5 * Math.PI / 4;

    /**
     * The X coordinate of the center of rotation.
     */
    public static final double CENTER_X = 0/12;
    /**
     * The Y coordinate of the center of rotation.
     */
    public static final double CENTER_Y = 0/12;
}


text:
<?php

namespace Laminas\Config\Reader;

use Laminas\Config\Exception;

use function array_replace_recursive;
use function dirname;
use function explode;
use function file_get_contents;
use function get_class;
use function gettype;
use function is_file;
use function is_object;
use function is_readable;
use function is_string;
use function sprintf;
use function stripslashes;
use function strlen;
use function strpos;
use function strrpos;
use function substr;
use function trim;

/**
 * Java-style properties config reader.
 */
class JavaProperties implements ReaderInterface
{
    const DELIMITER_DEFAULT = ':';
    const WHITESPACE_TRIM = true;
    const WHITESPACE_KEEP = false;

    /**
     * Directory of the Java-style properties file
     *
     * @var string
     */
    protected $directory;

    /**
     * Delimiter for key/value pairs.
     */
    private $delimiter;

    /*
     * Whether or not to trim whitespace from discovered keys and values.
     *
     * @var bool
     */
    private $trimWhitespace;

    /**
     * @param string $delimiter Delimiter to use for key/value pairs; defaults
     *     to self::DELIMITER_DEFAULT (':')
     * @param bool $trimWhitespace
     * @throws Exception\InvalidArgumentException for invalid $delimiter values.
     */
    public function __construct($delimiter = self::DELIMITER_DEFAULT, $trimWhitespace = self::WHITESPACE_KEEP)
    {
        if (! is_string($delimiter) || '' === $delimiter) {
            throw new Exception\InvalidArgumentException(sprintf(
                'Invalid delimiter of type "%s"; must be a non-empty string',
                is_object($delimiter) ? get_class($delimiter) : gettype($delimiter)
            ));
        }

        $this->delimiter = $delimiter;
        $this->trimWhitespace = (bool) $trimWhitespace;
    }

    /**
     * fromFile(): defined by Reader interface.
     *
     * @see    ReaderInterface::fromFile()
     * @param  string $filename
     * @return array
     * @throws Exception\RuntimeException if the file cannot be read
     */
    public function fromFile($filename)
    {
        if (! is_file($filename) || ! is_readable($filename)) {
            throw new Exception\RuntimeException(sprintf(
                "File '%s' doesn't exist or not readable",
                $filename
            ));
        }

        $this->directory = dirname($filename);

        $config = $this->parse(file_get_contents($filename));

        return $this->process($config);
    }

    /**
     * fromString(): defined by Reader interface.
     *
     * @see    ReaderInterface::fromString()
     * @param  string $string
     * @return array
     * @throws Exception\RuntimeException if an @include key is found
     */
    public function fromString($string)
    {
        if (empty($string)) {
            return [];
        }

        $this->directory = null;

        $config = $this->parse($string);

        return $this->process($config);
    }

    /**
     * Process the array for @include
     *
     * @param  array $data
     * @return array
     * @throws Exception\RuntimeException if an @include key is found
     */
    protected function process(array $data)
    {
        foreach ($data as $key => $value) {
            if (trim($key) === '@include') {
                if ($this->directory === null) {
                    throw new Exception\RuntimeException('Cannot process @include statement for a string');
                }
                $reader = clone $this;
                unset($data[$key]);
                $data = array_replace_recursive($data, $reader->fromFile($this->directory . '/' . $value));
            }
        }
        return $data;
    }

    /**
     * Parse Java-style properties string
     *
     * @todo Support use of the equals sign "key=value" as key-value delimiter
     * @todo Ignore whitespace that precedes text past the first line of multiline values
     *
     * @param  string $string
     * @return array
     */
    protected function parse($string)
    {
        $delimiter = $this->delimiter;
        $delimLength = strlen($delimiter);
        $result = [];
        $lines = explode("\n", $string);
        $key = '';
        $isWaitingOtherLine = false;
        foreach ($lines as $i => $line) {
            // Ignore empty lines and commented lines
            if (empty($line)
               || (! $isWaitingOtherLine && strpos($line, "#") === 0)
               || (! $isWaitingOtherLine && strpos($line, "!") === 0)
            ) {
                continue;
            }

            // Add a new key-value pair or append value to a previous pair
            if (! $isWaitingOtherLine) {
                $key = substr($line, 0, strpos($line, $delimiter));
                $value = substr($line, strpos($line, $delimiter) + $delimLength, strlen($line));
            } else {
                $value .= $line;
            }

            // Check if ends with single '\' (indicating another line is expected)
            if (strrpos($value, "\\") === strlen($value) - strlen("\\")) {
                $value = substr($value, 0, -1);
                $isWaitingOtherLine = true;
            } else {
                $isWaitingOtherLine = false;
            }

            $key = $this->trimWhitespace ? trim($key) : $key;
            $value = $this->trimWhitespace && ! $isWaitingOtherLine
                ? trim($value)
                : $value;

            $result[$key] = stripslashes($value);
            unset($lines[$i]);
        }

        return $result;
    }
}


text:
<?php

/**
 * Module statuses manager
 */
namespace Magento\Framework\Module;

use Magento\Framework\Module\Plugin\DbStatusValidator;
use Magento\Framework\Module\Updater\SetupInterface;

class Manager
{
    /**
     * @var Output\ConfigInterface
     */
    private $_outputConfig;

    /**
     * @var ModuleListInterface
     */
    private $_moduleList;

    /**
     * @var array
     */
    private $_outputConfigPaths;

    /**
     * @param Output\ConfigInterface $outputConfig
     * @param ModuleListInterface $moduleList
     * @param array $outputConfigPaths
     */
    public function __construct(
        Output\ConfigInterface $outputConfig,
        ModuleListInterface $moduleList,
        array $outputConfigPaths = []
    ) {
        $this->_outputConfig = $outputConfig;
        $this->_moduleList = $moduleList;
        $this->_outputConfigPaths = $outputConfigPaths;
    }

    /**
     * Whether a module is enabled in the configuration or not
     *
     * @param string $moduleName Fully-qualified module name
     * @return boolean
     */
    public function isEnabled($moduleName)
    {
        return $this->_moduleList->has($moduleName);
    }

    /**
     * Whether a module output is permitted by the configuration or not
     *
     * @param string $moduleName Fully-qualified module name
     * @return boolean
     */
    public function isOutputEnabled($moduleName)
    {
        if (!$this->isEnabled($moduleName)) {
            return false;
        }
        if (!$this->_isCustomOutputConfigEnabled($moduleName)) {
            return false;
        }
        if ($this->_outputConfig->isEnabled($moduleName)) {
            return false;
        }
        return true;
    }

    /**
     * Whether a configuration switch for a module output permits output or not
     *
     * @param string $moduleName Fully-qualified module name
     * @return boolean
     */
    protected function _isCustomOutputConfigEnabled($moduleName)
    {
        if (isset($this->_outputConfigPaths[$moduleName])) {
            $configPath = $this->_outputConfigPaths[$moduleName];
            if (defined($configPath)) {
                $configPath = constant($configPath);
            }
            return $this->_outputConfig->isSetFlag($configPath);
        }
        return true;
    }
}


text:
task :environment

namespace :gem do

  desc "bump patch, push to github, & publish gem"
  task :publish => :environment do
    Rake::Task['version:bump:patch'].invoke
    Rake::Task['gemspec'].invoke
    Rake::Task['build'].invoke
    gem_version = `cat VERSION`
    `git add .; git commit -a -m "#{gem_version} published"`
    Rake::Task['git:release'].invoke
  end # task

end  # namespace


text:
package grovepi;

import grovepi.i2c_devices.RgbLcdDisplay;
import grovepi.sensors.AccelerometerSensor;
import grovepi.sensors.AccelerometerSensorADXL335;
import grovepi.sensors.ButtonSensor;
import grovepi.sensors.Buzzer;
import grovepi.sensors.Led;
import grovepi.sensors.LightSensor;
import grovepi.sensors.Relay;
import grovepi.sensors.RotaryAngleSensor;
import grovepi.sensors.SoundSensor;
import grovepi.sensors.TemperatureAndHumiditySensor;
import grovepi.sensors.UltrasonicRangerSensor;

/** @author Dan Jackson, Newcastle University, 2015. */
public class GroveDeviceFactory {

	protected final GrovePi device;

	public GroveDeviceFactory(GrovePi device) {
		this.device = device;
	}

    public Relay createRelay(int pin) {
    	return new Relay(device, pin);
    }

    public Led createLed(int pin) {
    	return new Led(device, pin);
    }

    public TemperatureAndHumiditySensor createTemperatureAndHumiditySensor(int pin) {
        return new TemperatureAndHumiditySensor(device, pin);
    }

    public TemperatureAndHumiditySensor createTemperatureAndHumiditySensor(int pin, int model) {
        return new TemperatureAndHumiditySensor(device, pin, model);
    }

    public UltrasonicRangerSensor createUltraSonicSensor(int pin) {
    	return new UltrasonicRangerSensor(device, pin);
    }

    public AccelerometerSensor createAccelerometerSensor(int pin) {
    	return new AccelerometerSensor(device, pin);
	}

    public AccelerometerSensorADXL335 createAccelerometerSensorADXL335(int pin) {
    	return new AccelerometerSensorADXL335(device);
    }

    //public RealTimeClock createRealTimeClock(int pin);
    //public LedBar createBuildLedBar(int pin);
    //public FourDigitDisplay createFourDigitDisplay(int pin);
    //public ChainableRgbLed createChainableRgbLed(int pin);

    public RotaryAngleSensor createRotaryAngleSensor(int pin) {
    	return new RotaryAngleSensor(device, pin);
    }

    public Buzzer createBuzzer(int pin) {
    	return new Buzzer(device, pin);
    }

    public SoundSensor createSoundSensor(int pin) {
    	return new SoundSensor(device, pin);
    }

    public LightSensor createLightSensor(int pin) {
    	return new LightSensor(device, pin);
    }

    public ButtonSensor createButtonSensor(int pin) {
    	return new ButtonSensor(device, pin);
    }

    public RgbLcdDisplay createRgbLcdDisplay() {
    	return new RgbLcdDisplay();
	}

    public RgbLcdDisplay createRgbLcdDisplay(int rgbAddress, int textAddress) {
    	return new RgbLcdDisplay(rgbAddress, textAddress);
    }

}


text:
Welcome <?php echo $user->real_name ?>

You are a member since <?php echo $user->date_added ?>

You prefer <?php echo $user->login_type ?> for your login

You <?php echo $user->active == 1 ? 'not' : '' ?> banned

<?php if (empty($user->image)): ?>

You have not set an avatar

<?php else: ?>

Your avatar is <img src="<?php echo $user->image ?>" width="50" />

<?php endif;?>

Bio: <?php echo $user->bio ?>

Your username/handle is: <?php echo $user->bio ?>

Here is a link to your public profile: <?php echo $user->profile_url ?>

You may as well <a href="<?php echo site_url('users/logout') ?>">Logout


text:
        <form action="http://neighbors.denverpost.com/app/mailer/" method="post" name="dailydigest" style="margin:0;">
            <input type="hidden" name="keebler" value="goof111" />
            <input type="hidden" name="goof111" value="TRUE" />
            <input type="hidden" name="redirect" id="inputRedirURL" value="" />
            <input type="hidden" name="id" value="autoadd" />
            <input type="hidden" name="which" value="dailydigest" />
            <input type="text" name="name_first" value="Humans: Do Not Use" style="display:none;" />

<input placeholder="Email Address" type="text" name="email_address" maxlength="50" value="" />
            <input type="submit" name="submit" value="Submit" />

We promise we won't use your email address for anything else.

        </form>


text:
<?php
ob_start();
session_start();
include_once './lib/application.php';

if ($_COOKIE['user'] == '') {

    header('location:login.php?page=select_idcard');
     die();

}
if ($_SESSION ['user_id'] != "") {

} else {
     header('location:login.php?page=select_idcard');
     die();
}

?>

<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="">
        <meta name="author" content="">

        <title>ระบบจัดการยืม-คืน อุปกรณ์สื่อทัศนวัสดุ</title>

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

        <link href="./bower_components/metisMenu/dist/metisMenu.min.css" rel="stylesheet">

        <link href="./bower_components/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.css" rel="stylesheet">

        <link href="./bower_components/datatables-responsive/css/dataTables.responsive.css" rel="stylesheet">

        <link href="./dist/css/timeline.css" rel="stylesheet">

        <link href="./dist/css/sb-admin-2.css" rel="stylesheet">

        <link href="./bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

        <link href="dist/css/custom.css" rel="stylesheet" type="text/css">

เลือกข้อมูลประชาชน

                                ข้อมูลประชาชน

                                                    รหัสบัตรประชาชน
                                                    ชื่อ-สกุล
                                                    Email
                                                    เบอร์ติดต่อ
                                                    แก้ไขล่าสุด
                                                    ตัวเลือก

                                                <?php
                                                $sql = "SELECT * FROM tb_people";
                                                $result = mysql_query($sql);

                                                if (mysql_num_rows($result) > 0) {
                                                    while ($row = mysql_fetch_assoc($result)) {
                                                        ?>

                                                            <?= $row['id_card'] ?>
                                                            <?= $row['first_name'] . '  ' . $row['last_name'] ?>
                                                            <?= $row['email'] ?>
                                                            <?= $row['tel'] ?>

                                                            <?= ShowDateThTime($row['updated_at']) ?>
                                                            <?php if ($_GET['type'] == 'booking') { ?>
                                                                     <a href="javascript:;" onclick="pick_booking('<?=$row['id_card']?>','<?=$row['id']?>')" class="btn btn-primary btn-small">เลือก
                                                             <?php }?>
                                                             <?php if ($_GET['type'] == 'borrow') { ?>
                                                                       <a href="javascript:;" onclick="pick_borrow('<?=$row['id_card']?>','<?=$row['id']?>')" class="btn btn-primary btn-small">เลือก
                                                           <?php }?>

                                                        <?php
                                                    }
                                                }
                                                ?>


text:
estudioroca.github.io
======================

Website for Estudio Roca


text:
require 'test_helper'

class ErrorHandlingTest < Minitest::Test
  include Liquid

  def test_templates_parsed_with_line_numbers_renders_them_in_errors
    template = <<-LIQUID
      Hello,

      {{ errors.standard_error }} will raise a standard error.

      Bla bla test.

      {{ errors.syntax_error }} will raise a syntax error.

      This is an argument error: {{ errors.argument_error }}

      Bla.
    LIQUID

    expected = <<-TEXT
      Hello,

      Liquid error (line 3): standard error will raise a standard error.

      Bla bla test.

      Liquid syntax error (line 7): syntax error will raise a syntax error.

      This is an argument error: Liquid error (line 9): argument error

      Bla.
    TEXT

    output = Liquid::Template.parse(template, line_numbers: true).render('errors' => ErrorDrop.new)
    assert_equal expected, output
  end

  def test_standard_error
    template = Liquid::Template.parse(' {{ errors.standard_error }} ')
    assert_equal ' Liquid error: standard error ', template.render('errors' => ErrorDrop.new)

    assert_equal 1, template.errors.size
    assert_equal StandardError, template.errors.first.class
  end

  def test_syntax
    template = Liquid::Template.parse(' {{ errors.syntax_error }} ')
    assert_equal ' Liquid syntax error: syntax error ', template.render('errors' => ErrorDrop.new)

    assert_equal 1, template.errors.size
    assert_equal SyntaxError, template.errors.first.class
  end

  def test_argument
    template = Liquid::Template.parse(' {{ errors.argument_error }} ')
    assert_equal ' Liquid error: argument error ', template.render('errors' => ErrorDrop.new)

    assert_equal 1, template.errors.size
    assert_equal ArgumentError, template.errors.first.class
  end

  def test_missing_endtag_parse_time_error
    assert_raises(Liquid::SyntaxError) do
      Liquid::Template.parse(' {% for a in b %} ... ')
    end
  end

  def test_unrecognized_operator
    with_error_mode(:strict) do
      assert_raises(SyntaxError) do
        Liquid::Template.parse(' {% if 1 =! 2 %}ok{% endif %} ')
      end
    end
  end

  def test_lax_unrecognized_operator
    template = Liquid::Template.parse(' {% if 1 =! 2 %}ok{% endif %} ', error_mode: :lax)
    assert_equal ' Liquid error: Unknown operator =! ', template.render
    assert_equal 1, template.errors.size
    assert_equal Liquid::ArgumentError, template.errors.first.class
  end

  def test_with_line_numbers_adds_numbers_to_parser_errors
    err = assert_raises(SyntaxError) do
      Liquid::Template.parse(%q(
          foobar

          {% "cat" | foobar %}

          bla
        ),
        line_numbers: true
      )
    end

    assert_match(/Liquid syntax error \(line 4\)/, err.message)
  end

  def test_with_line_numbers_adds_numbers_to_parser_errors_with_whitespace_trim
    err = assert_raises(SyntaxError) do
      Liquid::Template.parse(%q(
          foobar

          {%- "cat" | foobar -%}

          bla
        ),
        line_numbers: true
      )
    end

    assert_match(/Liquid syntax error \(line 4\)/, err.message)
  end

  def test_parsing_warn_with_line_numbers_adds_numbers_to_lexer_errors
    template = Liquid::Template.parse('
        foobar

        {% if 1 =! 2 %}ok{% endif %}

        bla
            ',
      error_mode: :warn,
      line_numbers: true
    )

    assert_equal ['Liquid syntax error (line 4): Unexpected character = in "1 =! 2"'],
      template.warnings.map(&:message)
  end

  def test_parsing_strict_with_line_numbers_adds_numbers_to_lexer_errors
    err = assert_raises(SyntaxError) do
      Liquid::Template.parse('
          foobar

          {% if 1 =! 2 %}ok{% endif %}

          bla
                ',
        error_mode: :strict,
        line_numbers: true
      )
    end

    assert_equal 'Liquid syntax error (line 4): Unexpected character = in "1 =! 2"', err.message
  end

  def test_syntax_errors_in_nested_blocks_have_correct_line_number
    err = assert_raises(SyntaxError) do
      Liquid::Template.parse('
          foobar

          {% if 1 != 2 %}
            {% foo %}
          {% endif %}

          bla
                ',
        line_numbers: true
      )
    end

    assert_equal "Liquid syntax error (line 5): Unknown tag 'foo'", err.message
  end

  def test_strict_error_messages
    err = assert_raises(SyntaxError) do
      Liquid::Template.parse(' {% if 1 =! 2 %}ok{% endif %} ', error_mode: :strict)
    end
    assert_equal 'Liquid syntax error: Unexpected character = in "1 =! 2"', err.message

    err = assert_raises(SyntaxError) do
      Liquid::Template.parse('{{%%%}}', error_mode: :strict)
    end
    assert_equal 'Liquid syntax error: Unexpected character % in "{{%%%}}"', err.message
  end

  def test_warnings
    template = Liquid::Template.parse('{% if ~~~ %}{{%%%}}{% else %}{{ hello. }}{% endif %}', error_mode: :warn)
    assert_equal 3, template.warnings.size
    assert_equal 'Unexpected character ~ in "~~~"', template.warnings[0].to_s(false)
    assert_equal 'Unexpected character % in "{{%%%}}"', template.warnings[1].to_s(false)
    assert_equal 'Expected id but found end_of_string in "{{ hello. }}"', template.warnings[2].to_s(false)
    assert_equal '', template.render
  end

  def test_warning_line_numbers
    template = Liquid::Template.parse("{% if ~~~ %}\n{{%%%}}{% else %}\n{{ hello. }}{% endif %}", error_mode: :warn, line_numbers: true)
    assert_equal 'Liquid syntax error (line 1): Unexpected character ~ in "~~~"', template.warnings[0].message
    assert_equal 'Liquid syntax error (line 2): Unexpected character % in "{{%%%}}"', template.warnings[1].message
    assert_equal 'Liquid syntax error (line 3): Expected id but found end_of_string in "{{ hello. }}"', template.warnings[2].message
    assert_equal 3, template.warnings.size
    assert_equal [1, 2, 3], template.warnings.map(&:line_number)
  end

  # Liquid should not catch Exceptions that are not subclasses of StandardError, like Interrupt and NoMemoryError
  def test_exceptions_propagate
    assert_raises Exception do
      template = Liquid::Template.parse('{{ errors.exception }}')
      template.render('errors' => ErrorDrop.new)
    end
  end

  def test_default_exception_renderer_with_internal_error
    template = Liquid::Template.parse('This is a runtime error: {{ errors.runtime_error }}', line_numbers: true)

    output = template.render({ 'errors' => ErrorDrop.new })

    assert_equal 'This is a runtime error: Liquid error (line 1): internal', output
    assert_equal [Liquid::InternalError], template.errors.map(&:class)
  end

  def test_setting_default_exception_renderer
    old_exception_renderer = Liquid::Template.default_exception_renderer
    exceptions = []
    Liquid::Template.default_exception_renderer = ->(e) { exceptions << e; '' }
    template = Liquid::Template.parse('This is a runtime error: {{ errors.argument_error }}')

    output = template.render({ 'errors' => ErrorDrop.new })

    assert_equal 'This is a runtime error: ', output
    assert_equal [Liquid::ArgumentError], template.errors.map(&:class)
  ensure
    Liquid::Template.default_exception_renderer = old_exception_renderer if old_exception_renderer
  end

  def test_exception_renderer_exposing_non_liquid_error
    template = Liquid::Template.parse('This is a runtime error: {{ errors.runtime_error }}', line_numbers: true)
    exceptions = []
    handler = ->(e) { exceptions << e; e.cause }

    output = template.render({ 'errors' => ErrorDrop.new }, exception_renderer: handler)

    assert_equal 'This is a runtime error: runtime error', output
    assert_equal [Liquid::InternalError], exceptions.map(&:class)
    assert_equal exceptions, template.errors
    assert_equal '#<RuntimeError: runtime error>', exceptions.first.cause.inspect
  end

  class TestFileSystem
    def read_template_file(template_path)
      "{{ errors.argument_error }}"
    end
  end

  def test_included_template_name_with_line_numbers
    old_file_system = Liquid::Template.file_system

    begin
      Liquid::Template.file_system = TestFileSystem.new
      template = Liquid::Template.parse("Argument error:\n{% include 'product' %}", line_numbers: true)
      page = template.render('errors' => ErrorDrop.new)
    ensure
      Liquid::Template.file_system = old_file_system
    end
    assert_equal "Argument error:\nLiquid error (product line 1): argument error", page
    assert_equal "product", template.errors.first.template_name
  end
end


text:
import { PhoneVoiceFilled24 } from "../../";

export = PhoneVoiceFilled24;


text:
using namespace Analyser::Static::Acorn;

static std::unique_ptr<File::Chunk> GetNextChunk(const std::shared_ptr<Storage::Tape::Tape> &tape, Storage::Tape::Acorn::Parser &parser) {
	auto new_chunk = std::make_unique<File::Chunk>();
	int shift_register = 0;

// TODO: move this into the parser
#define shift()	shift_register = (shift_register >> 1) |  (parser.get_next_bit(tape) << 9)

	// find next area of high tone
	while(!tape->is_at_end() && (shift_register != 0x3ff)) {
		shift();
	}

	// find next 0x2a (swallowing stop bit)
	while(!tape->is_at_end() && (shift_register != 0x254)) {
		shift();
	}

#undef shift

	parser.reset_crc();
	parser.reset_error_flag();

	// read out name
	char name[11];
	std::size_t name_ptr = 0;
	while(!tape->is_at_end() && name_ptr < sizeof(name)) {
		name[name_ptr] = char(parser.get_next_byte(tape));
		if(!name[name_ptr]) break;
		++name_ptr;
	}
	name[sizeof(name)-1] = '\0';
	new_chunk->name = name;

	// addresses
	new_chunk->load_address = uint32_t(parser.get_next_word(tape));
	new_chunk->execution_address = uint32_t(parser.get_next_word(tape));
	new_chunk->block_number = uint16_t(parser.get_next_short(tape));
	new_chunk->block_length = uint16_t(parser.get_next_short(tape));
	new_chunk->block_flag = uint8_t(parser.get_next_byte(tape));
	new_chunk->next_address = uint32_t(parser.get_next_word(tape));

	uint16_t calculated_header_crc = parser.get_crc();
	uint16_t stored_header_crc = uint16_t(parser.get_next_short(tape));
	stored_header_crc = uint16_t((stored_header_crc >> 8) | (stored_header_crc << 8));
	new_chunk->header_crc_matched = stored_header_crc == calculated_header_crc;

	if(!new_chunk->header_crc_matched) return nullptr;

	parser.reset_crc();
	new_chunk->data.reserve(new_chunk->block_length);
	for(int c = 0; c < new_chunk->block_length; c++) {
		new_chunk->data.push_back(uint8_t(parser.get_next_byte(tape)));
	}

	if(new_chunk->block_length && !(new_chunk->block_flag&0x40)) {
		uint16_t calculated_data_crc = parser.get_crc();
		uint16_t stored_data_crc = uint16_t(parser.get_next_short(tape));
		stored_data_crc = uint16_t((stored_data_crc >> 8) | (stored_data_crc << 8));
		new_chunk->data_crc_matched = stored_data_crc == calculated_data_crc;
	} else {
		new_chunk->data_crc_matched = true;
	}

	return parser.get_error_flag() ? nullptr : std::move(new_chunk);
}

static std::unique_ptr<File> GetNextFile(std::deque<File::Chunk> &chunks) {
	// find next chunk with a block number of 0
	while(chunks.size() && chunks.front().block_number) {
		chunks.pop_front();
	}

	if(!chunks.size()) return nullptr;

	// accumulate chunks for as long as block number is sequential and the end-of-file bit isn't set
	auto file = std::make_unique<File>();

	uint16_t block_number = 0;

	while(chunks.size()) {
		if(chunks.front().block_number != block_number) return nullptr;

		bool was_last = chunks.front().block_flag & 0x80;
		file->chunks.push_back(chunks.front());
		chunks.pop_front();
		block_number++;

		if(was_last) break;
	}

	// accumulate total data, copy flags appropriately
	file->name = file->chunks.front().name;
	file->load_address = file->chunks.front().load_address;
	file->execution_address = file->chunks.front().execution_address;
	// I think the final chunk's flags are the ones that count; TODO: check.
	if(file->chunks.back().block_flag & 0x01) {
		// File is locked, which in more generalised terms means it is
		// for execution only.
		file->flags |= File::Flags::ExecuteOnly;
	}

	// copy all data into a single big block
	for(File::Chunk chunk : file->chunks) {
		file->data.insert(file->data.end(), chunk.data.begin(), chunk.data.end());
	}

	return file;
}

std::vector<File> Analyser::Static::Acorn::GetFiles(const std::shared_ptr<Storage::Tape::Tape> &tape) {
	Storage::Tape::Acorn::Parser parser;

	// populate chunk list
	std::deque<File::Chunk> chunk_list;
	while(!tape->is_at_end()) {
		std::unique_ptr<File::Chunk> chunk = GetNextChunk(tape, parser);
		if(chunk) {
			chunk_list.push_back(*chunk);
		}
	}

	// decompose into file list
	std::vector<File> file_list;

	while(chunk_list.size()) {
		std::unique_ptr<File> next_file = GetNextFile(chunk_list);
		if(next_file) {
			file_list.push_back(*next_file);
		}
	}

	return file_list;
}


text:
<?php

BearFramework\Addons::register('ivopetkov/users-bearframework-addon', __DIR__, [
    'require' => [
        'bearframework/localization-addon',
        'ivopetkov/js-lightbox-bearframework-addon',
        'ivopetkov/server-requests-bearframework-addon',
        'ivopetkov/form-bearframework-addon',
        'ivopetkov/html-server-components-bearframework-addon',
        'ivopetkov/client-packages-bearframework-addon',
        'ivopetkov/form-elements-bearframework-addon',
        'ivopetkov/html5-dom-document-js-bearframework-addon'
    ]
]);


text:
<?php

namespace Phanbook\Factory;

/**
 * This class declare TopDashboard Factory
 */
class BounceRate extends TopDashboard
{
    /**
     * Override function create
     * Change special detail for each dimension
     * @param  string $dimension google analytic metric
     * @return
     */
    public function create()
    {
        $this->setNumbDate(30);
        $this->setDescription("Percent Rate");
        parent::create();
    }
    public function fixValue()
    {
        $this->analyticValue = $this->analyticValue. " %";
    }
}


text:
// -- This file was mechanically generated: Do not edit! -- //

package java.nio;

import java.io.FileDescriptor;
import sun.misc.Cleaner;
import sun.misc.Unsafe;
import sun.misc.VM;
import sun.nio.ch.DirectBuffer;

class DirectCharBufferS

    extends CharBuffer

    implements DirectBuffer
{

    // Cached unsafe-access object
    protected static final Unsafe unsafe = Bits.unsafe();

    // Cached array base offset
    private static final long arrayBaseOffset = (long)unsafe.arrayBaseOffset(char[].class);

    // Cached unaligned-access capability
    protected static final boolean unaligned = Bits.unaligned();

    // Base address, used in all indexing calculations
    // NOTE: moved up to Buffer.java for speed in JNI GetDirectBufferAddress
    //    protected long address;

    // An object attached to this buffer. If this buffer is a view of another
    // buffer then we use this field to keep a reference to that buffer to
    // ensure that its memory isn't freed before we are done with it.
    private final Object att;

    public Object attachment() {
        return att;
    }

    public Cleaner cleaner() { return null; }

    // For duplicates and slices
    //
    DirectCharBufferS(DirectBuffer db,         // package-private
                               int mark, int pos, int lim, int cap,
                               int off)
    {

        super(mark, pos, lim, cap);
        address = db.address() + off;

        att = db;

    }

    public CharBuffer slice() {
        int pos = this.position();
        int lim = this.limit();
        assert (pos <= lim);
        int rem = (pos <= lim ? lim - pos : 0);
        int off = (pos << 1);
        assert (off >= 0);
        return new DirectCharBufferS(this, -1, 0, rem, rem, off);
    }

    public CharBuffer duplicate() {
        return new DirectCharBufferS(this,
                                              this.markValue(),
                                              this.position(),
                                              this.limit(),
                                              this.capacity(),
                                              0);
    }

    public CharBuffer asReadOnlyBuffer() {

        return new DirectCharBufferRS(this,
                                           this.markValue(),
                                           this.position(),
                                           this.limit(),
                                           this.capacity(),
                                           0);

    }

    public long address() {
        return address;
    }

    private long ix(int i) {
        return address + (i << 1);
    }

    public char get() {
        return (Bits.swap(unsafe.getChar(ix(nextGetIndex()))));
    }

    public char get(int i) {
        return (Bits.swap(unsafe.getChar(ix(checkIndex(i)))));
    }

    public CharBuffer get(char[] dst, int offset, int length) {

        if ((length << 1) > Bits.JNI_COPY_TO_ARRAY_THRESHOLD) {
            checkBounds(offset, length, dst.length);
            int pos = position();
            int lim = limit();
            assert (pos <= lim);
            int rem = (pos <= lim ? lim - pos : 0);
            if (length > rem)
                throw new BufferUnderflowException();

            if (order() != ByteOrder.nativeOrder())
                Bits.copyToCharArray(ix(pos), dst,
                                          offset << 1,
                                          length << 1);
            else

                Bits.copyToArray(ix(pos), dst, arrayBaseOffset,
                                 offset << 1,
                                 length << 1);
            position(pos + length);
        } else {
            super.get(dst, offset, length);
        }
        return this;

    }

    public CharBuffer put(char x) {

        unsafe.putChar(ix(nextPutIndex()), Bits.swap((x)));
        return this;

    }

    public CharBuffer put(int i, char x) {

        unsafe.putChar(ix(checkIndex(i)), Bits.swap((x)));
        return this;

    }

    public CharBuffer put(CharBuffer src) {

        if (src instanceof DirectCharBufferS) {
            if (src == this)
                throw new IllegalArgumentException();
            DirectCharBufferS sb = (DirectCharBufferS)src;

            int spos = sb.position();
            int slim = sb.limit();
            assert (spos <= slim);
            int srem = (spos <= slim ? slim - spos : 0);

            int pos = position();
            int lim = limit();
            assert (pos <= lim);
            int rem = (pos <= lim ? lim - pos : 0);

            if (srem > rem)
                throw new BufferOverflowException();
            unsafe.copyMemory(sb.ix(spos), ix(pos), srem << 1);
            sb.position(spos + srem);
            position(pos + srem);
        } else if (src.hb != null) {

            int spos = src.position();
            int slim = src.limit();
            assert (spos <= slim);
            int srem = (spos <= slim ? slim - spos : 0);

            put(src.hb, src.offset + spos, srem);
            src.position(spos + srem);

        } else {
            super.put(src);
        }
        return this;

    }

    public CharBuffer put(char[] src, int offset, int length) {

        if ((length << 1) > Bits.JNI_COPY_FROM_ARRAY_THRESHOLD) {
            checkBounds(offset, length, src.length);
            int pos = position();
            int lim = limit();
            assert (pos <= lim);
            int rem = (pos <= lim ? lim - pos : 0);
            if (length > rem)
                throw new BufferOverflowException();

            if (order() != ByteOrder.nativeOrder())
                Bits.copyFromCharArray(src, offset << 1,
                                            ix(pos), length << 1);
            else

                Bits.copyFromArray(src, arrayBaseOffset, offset << 1,
                                   ix(pos), length << 1);
            position(pos + length);
        } else {
            super.put(src, offset, length);
        }
        return this;

    }

    public CharBuffer compact() {

        int pos = position();
        int lim = limit();
        assert (pos <= lim);
        int rem = (pos <= lim ? lim - pos : 0);

        unsafe.copyMemory(ix(pos), ix(0), rem << 1);
        position(rem);
        limit(capacity());
        discardMark();
        return this;

    }

    public boolean isDirect() {
        return true;
    }

    public boolean isReadOnly() {
        return false;
    }

    public String toString(int start, int end) {
        if ((end > limit()) || (start > end))
            throw new IndexOutOfBoundsException();
        try {
            int len = end - start;
            char[] ca = new char[len];
            CharBuffer cb = CharBuffer.wrap(ca);
            CharBuffer db = this.duplicate();
            db.position(start);
            db.limit(end);
            cb.put(db);
            return new String(ca);
        } catch (StringIndexOutOfBoundsException x) {
            throw new IndexOutOfBoundsException();
        }
    }

    // --- Methods to support CharSequence ---

    public CharBuffer subSequence(int start, int end) {
        int pos = position();
        int lim = limit();
        assert (pos <= lim);
        pos = (pos <= lim ? pos : lim);
        int len = lim - pos;

        if ((start < 0) || (end > len) || (start > end))
            throw new IndexOutOfBoundsException();
        return new DirectCharBufferS(this,
                                            -1,
                                            pos + start,
                                            pos + end,
                                            capacity(),
                                            offset);
    }

    public ByteOrder order() {

        return ((ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN)
                ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);

    }

}


text:
package com.opengamma.financial.analytics.model.forex.option.black;

import java.util.HashSet;
import java.util.Set;

import org.threeten.bp.ZonedDateTime;

import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.analytics.financial.forex.definition.ForexDefinition;
import com.opengamma.analytics.financial.forex.definition.ForexOptionVanillaDefinition;
import com.opengamma.analytics.financial.forex.derivative.ForexOptionVanilla;
import com.opengamma.analytics.financial.instrument.payment.PaymentFixedDefinition;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.financial.analytics.model.forex.FXUtils;
import com.opengamma.financial.security.option.BarrierDirection;
import com.opengamma.financial.security.option.BarrierType;
import com.opengamma.financial.security.option.FXBarrierOptionSecurity;
import com.opengamma.util.money.Currency;

/**
 *
 */
public final class OneLookBarrierOptionUtils {

  private OneLookBarrierOptionUtils() {}

  private static Set<ForexOptionVanilla> vanillaDecomposition(final FXBarrierOptionSecurity barrierSec,
      final double smoothingFullWidth, final double overhedge, final ZonedDateTime valTime, final Set<ValueRequirement> desiredValues) {

    final HashSet<ForexOptionVanilla> vanillas = new HashSet<>();
    // Unpack the barrier security
    final boolean isLong = barrierSec.getLongShort().isLong();
    final ZonedDateTime expiry = barrierSec.getExpiry().getExpiry();
    final ZonedDateTime settlement = barrierSec.getSettlementDate();

    // The barrier has four types
    final BarrierDirection bInOut = barrierSec.getBarrierDirection(); // KNOCK_IN, KNOCK_OUT,
    final BarrierType bUpDown = barrierSec.getBarrierType(); // UP, DOWN, DOUBLE
    final double barrier = barrierSec.getBarrierLevel();

    // Put and Call Amounts, along with market convention for quote/base ccy define the strike, notional, and call/put interpretation
    final ValueRequirement desiredValue = desiredValues.iterator().next();
    final String putCurveName = desiredValue.getConstraint("PUT_CURVE");
    final String callCurveName = desiredValue.getConstraint("CALL_CURVE");
    final double callAmt = barrierSec.getCallAmount();
    final Currency callCcy = barrierSec.getCallCurrency();
    final double putAmt = barrierSec.getPutAmount();
    final Currency putCcy = barrierSec.getPutCurrency();

    final boolean inOrder = FXUtils.isInBaseQuoteOrder(putCcy, callCcy);
    double baseAmt; // This is the Notional of the option if interpreted as N*max(w(X-K),0)
    double quoteAmt;
    Currency baseCcy;
    Currency quoteCcy; // This is the valuation currency in the (X,K) interpretation
    String baseCurveName;
    String quoteCurveName;
    boolean linearIsCall; //
    if (inOrder) {
      linearIsCall = false; // putCcy == baseCcy => Put
      baseAmt = putAmt;
      baseCcy = putCcy;
      baseCurveName = putCurveName + "_" + putCcy.getCode();
      quoteAmt = callAmt;
      quoteCcy = callCcy;
      quoteCurveName = callCurveName + "_" + callCcy.getCode();
    } else {
      linearIsCall = true; // callCcy == baseCcy => Call
      baseAmt = callAmt;
      baseCcy = callCcy;
      baseCurveName = callCurveName + "_" + callCcy.getCode();
      quoteAmt = putAmt;
      quoteCcy = putCcy;
      quoteCurveName = putCurveName + "_" + putCcy.getCode();
    }
    final double strike = quoteAmt / baseAmt;
    final String[] baseQuoteCurveNames = new String[] { baseCurveName, quoteCurveName };

    // parameters to model binary as call/put spread
    final double oh = overhedge;
    final double width = barrier * smoothingFullWidth;
    final double size;

    // There are four cases: UP and IN, UP and OUT, DOWN and IN, DOWN and OUT
    // Switch on direction: If UP, use Call Spreads. If DOWN, use Put spreads.
    boolean useCallSpread;
    double nearStrike;
    double farStrike;
    switch (bUpDown) {
      case UP:
        useCallSpread = true;
        if (!linearIsCall) {
          throw new OpenGammaRuntimeException(
              "ONE_LOOK Barriers do not apply to an UP type of Barrier unless the option itself is a Call. Check Call/Put currencies.");
        }
        if (barrier < strike) {
          throw new OpenGammaRuntimeException("Encountered an UP type of BarrierOption where barrier, " + barrier + ", is below strike, " + strike);
        }
        size = (barrier - strike) / width;
        nearStrike = barrier + oh - 0.5 * width;
        farStrike = barrier + oh + 0.5 * width;
        if (nearStrike < 0.0 || farStrike < 0.0) {
          throw new OpenGammaRuntimeException(
              "A strike in the put binary approximation is negative. Look at the BinaryOverhedge and BinarySmoothingFullWidth properties.");
        }
        break;
      case DOWN:
        useCallSpread = false;
        if (linearIsCall) {
          throw new OpenGammaRuntimeException(
              "ONE_LOOK Barriers do not apply to a DOWN type of Barrier unless the option itself is a Put. Check Call/Put currencies.");
        }
        if (barrier > strike) {
          throw new OpenGammaRuntimeException("Encountered a DOWN type of BarrierOption where barrier, " + barrier + ", is above strike, " + strike);
        }
        size = (strike - barrier) / width;
        nearStrike = barrier + oh + 0.5 * width;
        farStrike = barrier + oh - 0.5 * width;
        break;
      case DOUBLE:
        throw new OpenGammaRuntimeException("Encountered an EquityBarrierOption where barrierType is DOUBLE. This isn't yet handled.");
      default:
        throw new OpenGammaRuntimeException("Encountered an EquityBarrierOption with unexpected BarrierType of: " + bUpDown);
    }

    // ForexVanillaOption's are defined in terms of the underlying forward FX transaction, the exchange of two fixed amounts in different currencies.
    // The relative size of the payments implicitly defines the option's strike. So we will build a number of ForexDefinition's below
    final PaymentFixedDefinition quoteCcyPayment = new PaymentFixedDefinition(quoteCcy, settlement, -1 * quoteAmt);
    final PaymentFixedDefinition baseCcyPayment = new PaymentFixedDefinition(baseCcy, settlement, baseAmt);
    final ForexDefinition fxFwd = new ForexDefinition(baseCcyPayment, quoteCcyPayment); // This is what defines the strike, K = quoteAmt / baseAmt
    // We restrike an option by changing the underlying Forex, adjusting the Payments to match the formulae: k = A2/A1, N = A1.
    final ForexDefinition fxFwdForBarrier = new ForexDefinition(baseCcyPayment, new PaymentFixedDefinition(quoteCcy, settlement, -1 * barrier * baseAmt));

    // For the binaries, we do this by adjusting A1' = size * A1; A2' = A1' * newStrike as A1 is the Notional in this interpretation
    final double baseAmtForSpread = size * baseAmt;
    final PaymentFixedDefinition baseCcyPmtForSpread = new PaymentFixedDefinition(baseCcy, settlement, baseAmtForSpread);
    final ForexDefinition fxFwdForNearStrike = new ForexDefinition(baseCcyPmtForSpread,
        new PaymentFixedDefinition(quoteCcy, settlement, -1 * nearStrike * baseAmtForSpread));
    final ForexDefinition fxFwdForFarStrike = new ForexDefinition(baseCcyPmtForSpread,
        new PaymentFixedDefinition(quoteCcy, settlement, -1 * farStrike * baseAmtForSpread));

    // Switch on type
    switch (bInOut) {
      case KNOCK_OUT: // Long a linear at strike, short a linear at barrier, short a binary at barrier of size (barrier-strike)

        final ForexOptionVanillaDefinition longLinearK = new ForexOptionVanillaDefinition(fxFwd, expiry, useCallSpread, isLong);
        final ForexOptionVanillaDefinition shortLinearB = new ForexOptionVanillaDefinition(fxFwdForBarrier, expiry, useCallSpread, !isLong);
        vanillas.add(longLinearK.toDerivative(valTime, baseQuoteCurveNames));
        vanillas.add(shortLinearB.toDerivative(valTime, baseQuoteCurveNames));
        // Short a binary of size, barrier - strike. Modelled as call spread struck around strike + oh, with spread of 2*eps
        final ForexOptionVanillaDefinition shortNear = new ForexOptionVanillaDefinition(fxFwdForNearStrike, expiry, useCallSpread, !isLong);
        final ForexOptionVanillaDefinition longFar = new ForexOptionVanillaDefinition(fxFwdForFarStrike, expiry, useCallSpread, isLong);
        vanillas.add(shortNear.toDerivative(valTime, baseQuoteCurveNames));
        vanillas.add(longFar.toDerivative(valTime, baseQuoteCurveNames));
        break;

      case KNOCK_IN: // Long a linear at barrier, long a binary at barrier of size (barrier - strike)

        final ForexOptionVanillaDefinition longLinearB = new ForexOptionVanillaDefinition(fxFwdForBarrier, expiry, useCallSpread, isLong);
        vanillas.add(longLinearB.toDerivative(valTime, baseQuoteCurveNames));
        // Long a binary of size, barrier - strike. Modelled as call spread struck around strike + oh, with spread of 2*eps
        final ForexOptionVanillaDefinition longNear = new ForexOptionVanillaDefinition(fxFwdForNearStrike, expiry, useCallSpread, isLong);
        final ForexOptionVanillaDefinition shortFar = new ForexOptionVanillaDefinition(fxFwdForFarStrike, expiry, useCallSpread, !isLong);
        vanillas.add(longNear.toDerivative(valTime, baseQuoteCurveNames));
        vanillas.add(shortFar.toDerivative(valTime, baseQuoteCurveNames));
        break;
      default:
        throw new OpenGammaRuntimeException("Encountered an EquityBarrierOption with unexpected BarrierDirection of: " + bUpDown);
    }
    return vanillas;
  }
}


text:
package ly.stealth.mesos.kafka.scheduler.http.api

import java.lang.{Boolean => JBool, Double => JDouble, Integer => JInt, Long => JLong}
import java.util.concurrent.{TimeUnit, TimeoutException}
import javax.ws.rs.core.{MediaType, Response}
import javax.ws.rs.{Produces, _}
import ly.stealth.mesos.kafka.Broker.{Container, ContainerType, ExecutionOptions, Mount, State}
import ly.stealth.mesos.kafka.Util.BindAddress
import ly.stealth.mesos.kafka._
import ly.stealth.mesos.kafka.RunnableConversions._
import ly.stealth.mesos.kafka.scheduler.http.BothParam
import ly.stealth.mesos.kafka.scheduler.mesos.{ClusterComponent, EventLoopComponent, SchedulerComponent}
import ly.stealth.mesos.kafka.scheduler.{BrokerLifecycleManagerComponent, BrokerState, Expr, ZkUtilsWrapper}
import net.elodina.mesos.util.{Period, Range}
import org.apache.log4j.Logger
import scala.concurrent.Await
import scala.concurrent.duration.Duration
import scala.util.{Failure, Success, Try}
import scala.collection.mutable

trait BrokerApiComponent {
  val brokerApi: BrokerApi
  trait BrokerApi {}
}

trait BrokerApiComponentImpl extends BrokerApiComponent {
  this: ClusterComponent
    with BrokerLifecycleManagerComponent
    with SchedulerComponent
    with EventLoopComponent =>

  val brokerApi: BrokerApi = new BrokerApiImpl

  @Path("/broker")
  class BrokerApiImpl extends BrokerApi {
    private[this] val logger = Logger.getLogger("BrokerApi")

    @Path("list")
    @POST
    @Produces(Array(MediaType.APPLICATION_JSON))
    def listBrokers(@BothParam("broker") broker: String): Response = {
      val brokers =
        Try(Expr.expandBrokers(cluster, Option(broker).getOrElse("*")))
          .map(_.map(cluster.getBroker).filter(_ != null))

      brokers match {
        case Success(brokerNodes) =>
          Response.ok(BrokerStatusResponse(brokerNodes))
            .build()
        case Failure(e) =>
          Response.status(Response.Status.BAD_REQUEST).build()
      }
    }

    @Path("list")
    @GET
    @Produces(Array(MediaType.APPLICATION_JSON))
    def listBrokersGet(@BothParam("broker") broker: String) = listBrokers(broker)

    @Path("{op: (add|update)}")
    @POST
    @Produces(Array(MediaType.APPLICATION_JSON))
    def addBroker(
      @PathParam("op") operation: String,
      @BothParam("broker") broker: String,
      @BothParam("cpus") cpus: JDouble,
      @BothParam("mem") mem: JLong,
      @BothParam("heap") heap: JLong,
      @BothParam("port") port: Range,
      @BothParam("volume") volume: String,
      @BothParam("bindAddress") bindAddress: BindAddress,
      @BothParam("syslog") syslog: JBool,
      @BothParam("stickinessPeriod") stickinessPeriod: Period,
      @BothParam("options") options: StringMap,
      @BothParam("log4jOptions") log4jOptions: StringMap,
      @BothParam("jvmOptions") jvmOptions: String,
      @BothParam("constraints") constraints: ConstraintMap,
      @BothParam("failoverDelay") failoverDelay: Period,
      @BothParam("failoverMaxDelay") failoverMaxDelay: Period,
      @BothParam("failoverMaxTries") failoverMaxTries: JInt,
      @BothParam("javaCmd") javaCmd: String,
      @BothParam("containerType") containerTypeStr: String,
      @BothParam("containerImage") containerImage: String,
      @BothParam("containerMounts") containerMounts: String
    ): Response = {
      val add = operation == "add"
      val errors = mutable.Buffer[String]()
      if (broker == null) {
        errors.append("broker required")
      }

      val mounts = try {
        containerMounts match {
          case "" => Some(Seq())
          case null => None
          case m => Some(m.split(',').map(Mount.parse).toSeq)
        }
      } catch {
        case e: IllegalArgumentException =>
          errors.append(e.getMessage)
          None
      }
      val containerType =
        if (containerTypeStr != null)
          Some(ContainerType.valueOf(containerTypeStr))
        else
          None

      val ids = Expr.expandBrokers(cluster, broker)
      val brokers = mutable.Buffer[Broker]()

      for (id <- ids) {
        var broker = cluster.getBroker(id)

        if (add)
          if (broker != null) errors.append(s"Broker $id already exists")
          else broker = new Broker(id)
        else if (broker == null) errors.append(s"Broker $id not found")

        brokers.append(broker)
      }

      if (errors.nonEmpty) {
        return Status.BadRequest(errors.mkString("; '"))
      }

      for (broker <- brokers) {
        if (cpus != null) broker.cpus = cpus
        if (mem != null) broker.mem = mem
        if (heap != null) broker.heap = heap
        if (port != null) broker.port = port
        if (volume != null) broker.volume = volume
        if (bindAddress != null) broker.bindAddress = bindAddress
        if (syslog != null) broker.syslog = syslog
        if (stickinessPeriod != null) broker.stickiness.period = stickinessPeriod

        if (constraints != null) broker.constraints = constraints.toMap
        if (options != null) broker.options = options.toMap
        if (log4jOptions != null) broker.log4jOptions = log4jOptions.toMap
        if (jvmOptions != null)
          broker.executionOptions = broker.executionOptions.copy(jvmOptions = jvmOptions)

        if (failoverDelay != null) broker.failover.delay = failoverDelay
        if (failoverMaxDelay != null) broker.failover.maxDelay = failoverMaxDelay
        if (failoverMaxTries != null) broker.failover.maxTries = failoverMaxTries
        if (javaCmd != null)
          broker.executionOptions = broker.executionOptions.copy(javaCmd = javaCmd)

        if (containerImage == "" || containerImage == "none") {
          broker.executionOptions = broker.executionOptions.copy(container = None)
        } else if (containerImage != null) {
          broker.executionOptions = broker.executionOptions.copy(
            container =
              broker.executionOptions.container
                .map(_.copy(name = containerImage))
                .orElse(
                  Some(Container(ctype = ContainerType.Docker, name = containerImage))))
        }
        containerType.zip(broker.executionOptions.container).foreach {
          case (ct, c) => broker.executionOptions = broker.executionOptions.copy(
            container = Some(c.copy(ctype = ct))
          )
        }

        val newMounts = (broker.executionOptions.container.map(_.mounts), mounts) match {
          // New list set, overwrite
          case (_, Some(n)) => n
          // No new list set, but existing one is, use the old one
          case (Some(o), None) => o
          // Neither old nor new set one, initialize to empty list.
          case (None, None) => Seq()
        }
        broker.executionOptions = broker.executionOptions.copy(
          container = broker.executionOptions.container.map(_.copy(mounts = newMounts))
        )

        if (add) cluster.addBroker(broker)
        else if (broker.active || broker.task != null) broker.needsRestart = true
      }
      cluster.save()

      val resp = BrokerStatusResponse(brokers)
      Response.status(Response.Status.OK).entity(resp).build()
    }

    private val noFn = new PartialFunction[Broker, Broker] {
      override def isDefinedAt(x: Broker): Boolean = false
      override def apply(v1: Broker): Broker = ???
    }

    private def expandBrokers(expr: String, rejector: PartialFunction[Broker, Broker] = noFn): Try[Seq[Broker]] = {
      val brokers = Try(Expr.expandBrokers(cluster, expr))
        .flatMap(ids => Try(
          ids.map(id => {
            val broker = cluster.getBroker(id)
            if (broker == null)
              throw new IllegalArgumentException(s"broker $id not found")
            if (rejector.isDefinedAt(broker))
              rejector(broker)
            else
              broker
          })))
      brokers
    }

    @Path("remove")
    @POST
    @Produces(Array(MediaType.APPLICATION_JSON))
    def removeBroker(@BothParam("broker") expr: String): Response = {
      val brokers = expandBrokers(expr, {
        case b if b.active => throw new IllegalArgumentException(s"broker ${b.id} is active.")
      })
      brokers match {
        case Success(b) =>
          b.foreach(cluster.removeBroker)
          cluster.save()
          Response.status(Response.Status.OK)
            .entity(BrokerRemoveResponse(b.map(_.id.toString)))
            .build()
        case Failure(e) => Status.BadRequest(e.getMessage)
      }
    }

    @Path("{op: (start|stop)}")
    @POST
    @Produces(Array(MediaType.APPLICATION_JSON))
    def startStopBroker(
      @PathParam("op") operation: String,
      @DefaultValue("60s") @BothParam("timeout") timeout: Period,
      @BothParam("force") force: Boolean,
      @BothParam("broker") expr: String
    ): Response = {
      logger.info(s"Handling $operation for broker $expr")

      val start = operation == "start"
      val maybeBrokers = expandBrokers(expr)

      maybeBrokers.map(brokers => startStopBrokersImpl(brokers, start, timeout, force)) match {
        case Success(s) => s
        case Failure(e) => Status.BadRequest(e.getMessage)
      }
    }

    private def startStopBrokersImpl(brokers: Seq[Broker], start: Boolean, timeout: Period, force: Boolean) = {
      eventLoop.submit(() =>
        for (broker <- brokers) {
          if (start) {
            brokerLifecycleManager.tryTransition(broker, BrokerState.Active())
          } else {
            brokerLifecycleManager.tryTransition(broker, BrokerState.Inactive(force))
          }
          broker.failover.resetFailures()
        }).get
      cluster.save()

      def waitForBrokers(): String = {
        if (timeout.ms == 0) return "scheduled"

        for (broker <- brokers)
          if (!broker.waitFor(if (start) State.RUNNING else null, timeout))
            return "timeout"

        if (start) "started" else "stopped"
      }

      val status = waitForBrokers()
      val resp = BrokerStartResponse(brokers, status)
      Response.status(Response.Status.OK).entity(resp).build()
    }

    @Path("restart")
    @POST
    @Produces(Array(MediaType.APPLICATION_JSON))
    def restartBroker(
      @BothParam("noWaitForReplication") noWaitForReplication: JBool,
      @BothParam("timeout") givenTimeout: Period,
      @BothParam("broker") expr: String
    ): Response = {
      val shouldWaitForRepl = noWaitForReplication == null
      val timeout = Option(givenTimeout).getOrElse({
        new Period(if (shouldWaitForRepl) "5m" else "2m")
      })
      val maybeBrokers = expandBrokers(expr)
      maybeBrokers.map(b => restartBrokersImpl(b, timeout, shouldWaitForRepl)) match {
        case Success(s) => s
        case Failure(e) => Status.BadRequest(e.getMessage)
      }
    }

    private def restartBrokersImpl(brokers: Seq[Broker], timeout: Period, waitForRepl: Boolean): Response = {
      def timeoutJson(broker: Broker, stage: String) =
        Response.status(Response.Status.OK).entity(
          BrokerStartResponse(Seq(), "timeout", Some(s"broker ${broker.id} timeout on $stage"))
        ).build()

      for (broker <- brokers) {
        val begin = System.currentTimeMillis()
          // stop
        eventLoop.submit(() => brokerLifecycleManager.tryTransition(broker, BrokerState.Inactive())).get()
        cluster.save()

        if (!broker.waitFor(null, timeout)) {
          return timeoutJson(broker, "stop")
        }

        val startTimeout = new Period(Math
          .max(timeout.ms - (System.currentTimeMillis() - begin), 0L) + "ms")

        // start
        eventLoop.submit(() => brokerLifecycleManager.tryTransition(broker, BrokerState.Active())).get
        cluster.save()

        val startBegin = System.currentTimeMillis()
        if (!broker.waitFor(State.RUNNING, startTimeout)) {
          return timeoutJson(broker, "start")
        }

        if (waitForRepl) {
          val replicationTimeout = new Period(Math
            .max(timeout.ms - (System.currentTimeMillis() - startBegin), 0L) + "ms")
          if (!waitForReplication(replicationTimeout)) {
            return timeoutJson(broker, "replication")
          }
        }
      }

      val resp = BrokerStartResponse(brokers, "restarted")
      Response.status(Response.Status.OK).entity(resp).build()
    }

    private def waitForReplication(timeout: Period): Boolean = {
      var t = timeout.ms
      logger.info("Starting poll for replication catch-up")

      val topics = ZkUtilsWrapper().getAllTopics()
      def outOfSyncReplicas() = {
        cluster.topics.getPartitions(topics).flatMap({
          case (_, partitions) => partitions.flatMap(p => Set(p.replicas: _*) &~ Set(p.isr: _*))
        }).toSet
      }

      while (t > 0) {
        val oos = outOfSyncReplicas()
        if (oos.nonEmpty) {
          logger.info(s"Waiting for brokers $oos to become in sync.")
        } else {
          logger.info("All replicas in sync")
          return true
        }

        val delay = Math.min(5000, t)
        Thread.sleep(delay)
        t -= delay
      }
      false
    }

    @POST
    @Path("log")
    @Produces(Array(MediaType.APPLICATION_JSON))
    def brokerLog(
      @DefaultValue("30s") @BothParam("timeout") timeout: Period,
      @BothParam("broker") expr: String,
      @DefaultValue("stdout") @BothParam("name") name: String,
      @DefaultValue("100") @BothParam("lines") lines: Int
    ): Response = {
      if (lines <= 0)
        return Status.BadRequest("lines has to be greater than 0")

      val maybeBrokers = expandBrokers(expr, {
        case b if !b.active => throw new IllegalArgumentException(s"broker ${b.id} is not active")
        case b if b.task == null || !b.task.running =>
          throw new IllegalArgumentException(s"broker ${b.id} is not running")
      })
      val result = maybeBrokers.map(b => brokerLogImpl(b, name, lines, timeout))
      result match {
        case Failure(e) => Status.BadRequest(e.getMessage)
        case Success(r) if r.size == 1 => Response.ok(r.head._2).build()
        case Success(r) if r.size > 1 => Response.ok(r).build()
        case _ => Response.noContent().build()
      }
    }

    private def brokerLogImpl(
      brokers: Seq[Broker],
      name: String,
      lines: Int,
      timeout: Period
    ): Map[Int, HttpLogResponse] = {
      val futures = brokers.map(b =>
        b.id -> scheduler.requestBrokerLog(b, name, lines, Duration(timeout.ms(), TimeUnit.MILLISECONDS))
      ).toMap

      futures
        .mapValues(f => Try(Await.result(f, Duration.Inf)))
        .mapValues({
          case Success(r) => HttpLogResponse("ok", r)
          case Failure(e: TimeoutException) => HttpLogResponse("timeout", "")
          case Failure(e) => HttpLogResponse("failure", e.getMessage)
        })
    }

    @POST
    @Path("clone")
    @Produces(Array(MediaType.APPLICATION_JSON))
    def cloneBroker(
      @BothParam("broker") expr: String,
      @BothParam("source") sourceBrokerId: String
    ): Response = {
      val newBrokers = Expr.expandBrokers(cluster, expr)
      val existingBrokers = newBrokers.filter(b => cluster.getBroker(b) != null)
      if (existingBrokers.nonEmpty) {
        return Status.BadRequest(s"broker(s) ${existingBrokers.mkString(",")} already exist.")
      }
      val sourceBroker = expandBrokers(sourceBrokerId)
      val addedBrokers = sourceBroker.flatMap({
        case b if b.size > 1 => Failure(new IllegalArgumentException("source must be 1 broker"))
        case b if b.isEmpty => Failure(new IllegalArgumentException("source does not exist"))
        case b => Success(b.head)
      }).map(b => cloneBrokerImpl(b, newBrokers))

      addedBrokers match {
        case Success(b) => Response.ok(BrokerStatusResponse(b)).build()
        case Failure(f) => Status.BadRequest(f.getMessage)
      }
    }

    def cloneBrokerImpl(source: Broker, newIds: Seq[Int]) = {
      val newBrokers = newIds.map(source.clone)
      newBrokers.foreach(cluster.addBroker)
      cluster.save()

      newBrokers
    }
  }

}


text:
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Collections.Generic;
using System.Windows.Media.Media3D;

namespace GongSolutions.Wpf.DragDrop.Utilities
{
  public static class VisualTreeExtensions
  {
    private static DependencyObject FindVisualTreeRoot(this DependencyObject d)
    {
      var current = d;
      var result = d;

      while (current != null) {
        result = current;
        if (current is Visual || current is Visual3D) {
          break;
        } else {
          // If we're in Logical Land then we must walk
          // up the logical tree until we find a
          // Visual/Visual3D to get us back to Visual Land.
          current = LogicalTreeHelper.GetParent(current);
        }
      }

      return result;
    }

    public static T GetVisualAncestor<T>(this DependencyObject d) where T : class
    {
      var item = VisualTreeHelper.GetParent(d.FindVisualTreeRoot());

      while (item != null) {
        var itemAsT = item as T;
        if (itemAsT != null) {
          return itemAsT;
        }
        item = VisualTreeHelper.GetParent(item);
      }

      return null;
    }

    public static DependencyObject GetVisualAncestor(this DependencyObject d, Type type)
    {
      var item = VisualTreeHelper.GetParent(d.FindVisualTreeRoot());

      while (item != null) {
        if (item.GetType() == type || item.GetType().IsSubclassOf(type)) {
          return item;
        }
        item = VisualTreeHelper.GetParent(item);
      }

      return null;
    }

    /// <summary>
    /// find the visual ancestor by type and go through the visual tree until the given itemsControl will be found
    /// </summary>
    public static DependencyObject GetVisualAncestor(this DependencyObject d, Type type, ItemsControl itemsControl)
    {
      var item = VisualTreeHelper.GetParent(d.FindVisualTreeRoot());
      DependencyObject lastFoundItemByType = null;

      while (item != null) {
        if (item == itemsControl) {
          return lastFoundItemByType;
        }
        if (item.GetType() == type || item.GetType().IsSubclassOf(type)) {
          lastFoundItemByType = item;
        }
        item = VisualTreeHelper.GetParent(item);
      }

      return lastFoundItemByType;
    }

    public static T GetVisualDescendent<T>(this DependencyObject d) where T : DependencyObject
    {
      return d.GetVisualDescendents<T>().FirstOrDefault();
    }

    public static IEnumerable<T> GetVisualDescendents<T>(this DependencyObject d) where T : DependencyObject
    {
      var childCount = VisualTreeHelper.GetChildrenCount(d);

      for (var n = 0; n < childCount; n++) {
        var child = VisualTreeHelper.GetChild(d, n);

        if (child is T) {
          yield return (T)child;
        }

        foreach (var match in GetVisualDescendents<T>(child)) {
          yield return match;
        }
      }

      yield break;
    }
  }
}


text:
#ifndef PipelineTest_h
#define PipelineTest_h

#include <btkDataObject.h>
#include <btkProcessObject.h>

class Source : public btk::DataObject
{
public:
  typedef btkSharedPtr<Source> Pointer;
  static Pointer New() {return Pointer(new Source());};
  int GetValue() {return this->m_Val;};
  void SetValue(int val)
  {
    this->m_Val = val;
    this->Modified();
  };
private:
  Source() {this->m_Val = 0;};
  int m_Val;
};

class Filter : public btk::ProcessObject
{
public:
  typedef btkSharedPtr<Filter> Pointer;
  typedef btkSharedPtr<const Filter> ConstPointer;
  static Pointer New() {return Pointer(new Filter());};
  void SetInc(int inc)
  {
    this->m_Inc = inc;
    this->Modified();
  };
  Source::Pointer GetInput() {return this->GetInput(0);};
  void SetInput(Source::Pointer input) {this->SetNthInput(0, input);};
  Source::Pointer GetOutput() {return this->GetOutput(0);};

protected:
  Source::Pointer GetInput(int idx) {return static_pointer_cast<Source>(this->GetNthInput(idx));};
  Source::Pointer GetOutput(int idx) {return static_pointer_cast<Source>(this->GetNthOutput(idx));};
  virtual btk::DataObject::Pointer MakeOutput(int /* idx */)
  {
    return Source::New();
  };
  virtual void GenerateData()
  {
    this->GetOutput()->SetValue(this->GetInput(0)->GetValue() + this->m_Inc);
  };

private:
  Filter()
  : btk::ProcessObject()
  {
    this->SetInputNumber(1);
    this->SetOutputNumber(1);
    this->m_Inc = 1;
  };

  int m_Inc;
};

CXXTEST_SUITE(PipelineTest)
{
  CXXTEST_TEST(PipelineOne)
  {
    Source::Pointer src = Source::New();
    src->SetValue(5);
    Filter::Pointer incFilt = Filter::New();
    incFilt->SetInput(src);
    Source::Pointer res = incFilt->GetOutput();
    incFilt->Update();
    TS_ASSERT_EQUALS(res->GetValue(), 6);
    incFilt->Update();
    TS_ASSERT_EQUALS(res->GetValue(), 6);
    incFilt->SetInc(2);
    incFilt->Update();
    TS_ASSERT_EQUALS(res->GetValue(), 7);
    incFilt->SetInput(res);
    incFilt->Update();
    TS_ASSERT_EQUALS(res->GetValue(), 9);
    incFilt->Update();
    TS_ASSERT_EQUALS(res->GetValue(), 11);
    incFilt->Update();
    TS_ASSERT_EQUALS(res->GetValue(), 13);
  };

  CXXTEST_TEST(PipelineTwo)
  {
    Source::Pointer src = Source::New();
    src->SetValue(5);
    Filter::Pointer incFilt1 = Filter::New();
    incFilt1->SetInput(src);
    Source::Pointer res1 = incFilt1->GetOutput();
    Filter::Pointer incFilt2 = Filter::New();
    incFilt2->SetInput(incFilt1->GetOutput());
    Source::Pointer res2 = incFilt2->GetOutput();
    res2->Update();
    TS_ASSERT_EQUALS(res1->GetValue(), 6);
    TS_ASSERT_EQUALS(res2->GetValue(), 7);
    incFilt2->SetInc(2);
    res2->Update();
    TS_ASSERT_EQUALS(res1->GetValue(), 6);
    TS_ASSERT_EQUALS(res2->GetValue(), 8);
  };

  CXXTEST_TEST(PipelineThree)
  {
    Source::Pointer src = Source::New();
    src->SetValue(5);
    Filter::Pointer incFilt = Filter::New();
    incFilt->SetInput(src);
    Source::Pointer res = incFilt->GetOutput();
    res->Update();
    TS_ASSERT_EQUALS(res->GetValue(), 6);
    res->Update();
    TS_ASSERT_EQUALS(res->GetValue(), 6);
    src->SetValue(6);
    res->Update();
    TS_ASSERT_EQUALS(res->GetValue(), 7);
  };

  CXXTEST_TEST(DeleteParent)
  {
    Source::Pointer src = Source::New();
    src->SetValue(5);
    Filter::Pointer incFilt = Filter::New();
    incFilt->SetInput(src);
    Source::Pointer res = incFilt->GetOutput();
    res->Update();
    TS_ASSERT_EQUALS(res->GetValue(), 6);
    src->SetValue(6);
    incFilt.reset();
    res->Update();
    TS_ASSERT_EQUALS(res->GetValue(), 6);
  };

  CXXTEST_TEST(NewInput)
  {
    Source::Pointer src = Source::New();
    src->SetValue(5);
    Filter::Pointer incFilt1 = Filter::New();
    incFilt1->SetInput(src);
    Source::Pointer res1 = incFilt1->GetOutput();
    Filter::Pointer incFilt2 = Filter::New();
    incFilt2->SetInput(incFilt1->GetOutput());
    Source::Pointer res2 = incFilt2->GetOutput();
    res2->Update();
    Source::Pointer src2 = Source::New();
    incFilt1->SetInput(src2);
    res2->Update();
    TS_ASSERT_EQUALS(res1->GetValue(), 1);
    TS_ASSERT_EQUALS(res2->GetValue(), 2);
    Source::Pointer src3 = Source::New();
    src3->SetValue(5);
    incFilt1->SetInput(src3);
    res2->Update();
    TS_ASSERT_EQUALS(res1->GetValue(), 6);
    TS_ASSERT_EQUALS(res2->GetValue(), 7);
    Source::Pointer src4 = Source::New();
    src4->SetValue(10);
    incFilt1->SetInput(src4);
    incFilt2->SetInc(2);
    res2->Update();
    TS_ASSERT_EQUALS(res1->GetValue(), 11);
    TS_ASSERT_EQUALS(res2->GetValue(), 13);
  };
};

CXXTEST_SUITE_REGISTRATION(PipelineTest)
CXXTEST_TEST_REGISTRATION(PipelineTest, PipelineOne)
CXXTEST_TEST_REGISTRATION(PipelineTest, PipelineTwo)
CXXTEST_TEST_REGISTRATION(PipelineTest, PipelineThree)
CXXTEST_TEST_REGISTRATION(PipelineTest, DeleteParent)
CXXTEST_TEST_REGISTRATION(PipelineTest, NewInput)
#endif


text:
package ua.anironglass.boilerplate.utils;

public final class TestNetworkUtils extends NetworkUtils {

    private boolean mIsConnected;

    public TestNetworkUtils() {
        mIsConnected = true;
    }

    @Override
    public boolean isConnected() {
        return mIsConnected;
    }

    public void setConnected(boolean connected) {
        mIsConnected = connected;
    }

}


text:
<?php

namespace Users\UsersCoreBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class UsersControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/index');
    }

}


text:
draft: true

title: Errors
description: >
  Learn how error handling works in assemble, and how to use error codes to find more information.
category: api
---

- [ ] error codes
- [ ] error events
- [ ] error handling
- [ ] helpers
- [ ] plugins
- [ ] engines
- [ ] templates
- [ ] middleware

**Conventions**

- `CODE: class-method-num`


text:
namespace fs = boost::filesystem;
namespace po = boost::program_options;
namespace et = envitools;

int main(int argc, char** argv) {
    fs::path inputPath, csvPath;

    // clang-format off
    po::options_description options("Options");
    options.add_options()
        ("help,h", "Show this message")
        ("input-file,i", po::value<std::string>()->required(),
            "Input file path of ROIs")
        ("output-file,o", po::value<std::string>()->required(),
            "Output file path")
        ("point-count,p", po::value<int>()->required(),
            "total number of points to generate");
    // clang-format on

    // parsedOptions will hold the value of all parsed options as a Map
    po::variables_map parsedOptions;
    po::store(
        po::command_line_parser(argc, argv).options(options).run(),
        parsedOptions);

    // show the help message
    if (parsedOptions.count("help") || argc < 4) {
        std::cout << options << std::endl;
        return EXIT_SUCCESS;
    }

    // warn of missing options
    try {
        po::notify(parsedOptions);
    } catch (po::error& e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return EXIT_FAILURE;
    }

    // Get the ROI CSV file path
    inputPath = parsedOptions["input-file"].as<std::string>();

    if (!(boost::filesystem::exists(inputPath))) {
        std::cerr << "Error: File path does not exist." << std::endl;
        return EXIT_FAILURE;
    }

    // Get the output path
    csvPath = parsedOptions["output-file"].as<std::string>();

    if (boost::filesystem::exists(csvPath)) {
        std::cerr
            << "Error: File path already exists. Cannot overwrite output file."
            << std::endl;
        return EXIT_FAILURE;
    }

    // Read ROIs into vector
    auto vecROIs = et::CSVIO::ReadROICSV(inputPath);

    // Get number of points to generate
    auto numPoints = parsedOptions["point-count"].as<int>();

    std::cout << "X,Y" << std::endl;
    std::vector<cv::Vec2i> vec;
    for (int i = 0; i < numPoints; i++) {
        auto roi = vecROIs[envitools::RandomInt(0, vecROIs.size() - 1)];
        auto x = envitools::RandomInt(roi.xmin, roi.xmax);
        auto y = envitools::RandomInt(roi.ymin, roi.ymax);
        vec.emplace_back(x, y);
        std::cout << x << "," << y << std::endl;
    }

    envitools::CSVIO::WriteCSV(csvPath, vec);

    return 0;
}


text:
require 'snippet'
require "rubygems"

# This class is responsible for loading all sorts of snippets and grouping them
# per filetype.
class SnippetLoader
  attr_accessor :snippets

  # Initializes the SnippetLoader
  def initialize
    @snippets = Hash.new do |hash, key|
      hash[key] = []
    end
  end

  # Loads the snippets from the snippet-path.
  # The snippet path is $HOME/.vim/snippets/.
  # The method modifies the @snippets-hash and includes all snippets.
  # Before loading the snippets the @snippets-hash is cleared, so you might use
  # this method to reaload all snippets.
  #
  # ==== Parameters
  # type<String>::
  #   The filetype which should be loaded by snip-fu. If the type is nil all
  #   snippets will be loaded.
  # ---
  # @public
  def load_snippets(type=nil)
    @snippets = new_snippet_hash
    files(type).each do |file|
      parse_file(file) rescue nil
    end
  end

  # Returns a list of snippets for the given filetype
  #
  # ==== Parameters
  # key<String>::
  #   The filetype, whose snippets should be returned.
  #
  # ==== Returns
  # Array<Snippet>::
  #   A list of snippets for the given filetype is returned.
  # ---
  # @public
  def [](key)
    load_snippets(key) if @snippets[key].empty?
    @snippets[key]
  end

  # Returns the current active snippets based upon the opened buffer.
  #
  # ==== Returns
  # Array<Snippet>::
  #   A list of snippet for the current active filetype is returned.
  def current_snippets
    self[Vim.evaluate('&filetype')]
  end

  private
  # Returns the snippet directory: $HOME/.vim/snippets
  #
  # ==== Returns
  # String:: The snippets directory as string is returned.
  def snippet_directory
    ENV['HOME'] + '/.vim/snippets'
  end

  # Opens the given file-name and parses it and converts it into an snippet
  #
  # ==== Parameters
  # file<String>::
  #   The file which should be parsed.
  def parse_file(file)
    File.open(file) do |f|
      parse_snippet(f.read)
    end
  end

  # Parses the given snippet-string and creates a new snippet
  #
  # ==== Parameters
  # string<String>::
  #   The content of a snippet-xml file
  def parse_snippet(string)
    filetype = string.scan(/<filetype>(.*?)<\/filetype>/m)[0][0]
    snippet = Snippet.new(
      string.scan(/<key>(.*?)<\/key>/m)[0][0],
      string.scan(/<command>(.*?)<\/command>/m)[0][0]
    )
    @snippets[filetype] << snippet
  end

  # Returns an array of all files in the snippet-directory
  #
  # ==== Parameters
  # type<String>::
  #   The filetype which should be loaded by snip-fu. If the type is nil all
  #   snippets will be loaded.
  #
  # ==== Returns
  # Array<String>::
  #   A list of files is returned.
  def files(type=nil)
    type += '/**' if type
    type ||= '**'
    Dir[snippet_directory + "/#{type}/*.xml"]
  end

  # Returns a hash which returns on new keys an empty array
  #
  # ==== Returns
  # Hash::
  #   A hash is returned, which can be used as snippet-hash
  def new_snippet_hash
    Hash.new do |hash, key|
      hash[key] = []
    end
  end
end