text:
/**
 * Created by lu on 2017/7/20.
 */
import React, { Component } from 'react';
import { Slider, Icon, InputNumber } from 'antd';
import styles from './SuperResolutionSlider.css';

class SRSlider extends Component {
  constructor(props) {
    super(props);
    this.state = {
      cHeight: this.props.pre_height,
      sliderValue: this.props.value,
      cWidth: this.props.pre_width,
    };
  }
  handleChange = (v) => {
    this.setState({
      cWidth: v * this.props.pre_width,
      sliderValue: v,
      cHeight: v * this.props.pre_height,
    });
    this.props.handleSlider(v * this.props.pre_width, v * this.props.pre_height);
  }
  handleWidthChange=(v) => {
    this.setState({
      cWidth: v,
      sliderValue: (v / this.props.pre_width),
      cHeight: ((v / this.props.pre_width) * this.props.pre_height),
    });
    this.props.handleSlider(v, ((v / this.props.pre_width) * this.props.pre_height));
  }
  handleHeightChange=(v) => {
    this.setState({
      cHeight: v,
      sliderValue: (v / this.props.pre_height),
      cWidth: ((v / this.props.pre_height) * this.props.pre_width),
    });
    this.props.handleSlider(((v / this.props.pre_height) * this.props.pre_width), v);
  }

  render() {
    return (

        <Icon className={styles.anticon1} type="minus-circle" />
        <Slider
          {...this.props}
          className={styles.anticon}
          tipFormatter={formatter}
          value={this.state.sliderValue}
          onChange={this.handleChange}
          step={0.1}
        />
        <Icon className={styles.anticon2} type="plus-circle" />
        <InputNumber
          {...this.props}
          className={styles.inputWidth}
          min={this.props.pre_width}
          max={this.props.pre_width * 2}
          value={this.state.sliderValue * this.props.pre_width}
          onChange={this.handleWidthChange}
        />
        <InputNumber
          {...this.props}
          className={styles.inputHeight}
          min={this.props.pre_height}
          max={this.props.pre_height * 2}
          value={this.state.sliderValue * this.props.pre_height}
          onChange={this.handleHeightChange}
        />
        <label className={`${styles.note_label} ${styles.px1_label}`} htmlFor={`${styles.try}`} >px
        <label className={`${styles.note_label} ${styles.px2_label}`} htmlFor={`${styles.try}`} >px

    );
  }
}
function formatter(value) {
  return `x${value}`;
}

export default SRSlider;
SRSlider.propTypes = {
  pre_width: React.PropTypes.number.isRequired,
  pre_height: React.PropTypes.number.isRequired,
  value: React.PropTypes.number.isRequired,
  handleSlider: React.PropTypes.func.isRequired,
};


text:
require 'rubyXL/objects/ooxml_object'

module RubyXL

  # http://www.schemacentral.com/sc/ooxml/e-ssml_color-4.html
  class Color < OOXMLObject
    define_attribute(:auto,    :bool)
    define_attribute(:indexed, :uint)
    define_attribute(:rgb,     :string)
    define_attribute(:theme,   :uint)
    define_attribute(:tint,    :double, :default => 0.0)
    define_element_name 'color'

    #validates hex color code, no '#' allowed
    def self.validate_color(color)
      if color =~ /\A([a-f]|[A-F]|[0-9]){6}\Z/
        return true
      else
        raise 'invalid color'
      end
    end

  end

end

redpajama_set_name: RedPajamaGithub


text:
module CanTango::Api
  module Session
    autoload_modules :User, :Account
  end
end


text:
/**
 * Created by VIJETA on 28/12/2014.
 */
angular.module("paginatorModule", []).constant("globalPageSize",3).directive("paginatorHolder",[function(){
        return {
            restrict: "E",
            transclude : true,
            scope: {
                page : "=selectedPage",
                pageSize: "=pageSize"
            },
            replace: true,
            controller : function($scope,globalPageSize) {
                $scope.pageNo = 1;
                $scope.maxPaginationLen = 10;

                this.moveLeft = function () {
                    $scope.$apply(function(){
                        if ($scope.pageNo - 1 >= 1) {
                            $scope.pageNo = $scope.pageNo - 1;
                            $scope.page = $scope.pageNo;
                        }
                    });
                };

                this.moveRight = function () {
                    $scope.$apply(function(){
                        if ((($scope.pageNo+1) * $scope.pageSize) <= $scope.maxPaginationLen
                            || ($scope.maxPaginationLen - ($scope.pageSize* $scope.pageNo)) >= 0) {
                            $scope.pageNo = $scope.pageNo + 1;
                            $scope.page = $scope.pageNo;
                        }
                    });
                };

                this.updateMaxLength = function(val) {
                    if (val && angular.isNumber(Number(val))) {
                        $scope.maxPaginationLen = val;
                    }
                };

                $scope.$watch("pageNo", function(newVal) {
                    $scope.page = newVal;
                    $scope.pageSize = globalPageSize;
                });
            },
            templateUrl : "views/paginatorHolder.html"
        };
    }]).directive("pagination", [function () {
        return {
            restrict: "E",
            templateUrl: "views/paginatorView.html",
            require: "^paginatorHolder",
            scope: {
              data: "@data"
            },
            link: function (scope,element,attr,ctrl) {
                //calling children would have fetched direct descendent while find would get all the tags specified.,
                var items = element.find("a");
                for (var i = 0; i < items.length; i++) {
                    if (items.eq(i).attr("id") == "leftNav") {
                        items.eq(i).on("click",function(e){
                            ctrl.moveLeft();
                        });
                    } else if (items.eq(i).attr("id") == "rightNav") {
                        items.eq(i).on("click",function(e){
                            ctrl.moveRight();
                        });
                    }
                }
                scope.$watch("data",function(newVal){
                    ctrl.updateMaxLength(newVal);
                });
            }
        };
    }]
).filter("range", function($filter){
        return function(data,page,size) {
            if (angular.isArray(data) && angular.isNumber(page) && angular.isNumber(size)) {
                var start_index = (page - 1) * size;
                if (data.length < start_index) {
                    return [];
                } else {
                    return $filter("limitTo")(data.slice(start_index),size);
                }
            } else {
                return data;
            }
        }
    });


text:
<!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.0, user-scalable=no">
    <link rel="icon" href="assets/favicon.ico" />
    <title>Angular directives for Bootstrap</title>
    <meta name="description" content="AngularJS (Angular) native directives for Bootstrap. Small footprint (5kB gzipped!), no 3rd party JS dependencies (jQuery, bootstrap JS) required! Widgets: <% demoModules.forEach(function(module) { %><%= module.displayName %>, <% }); %>">
    <meta name="google-site-verification" content="7lc5HyceLDqpV_6oNHteYFfxDJH7-S3DwnJKtNUKcRg" />

    <link href="//netdna.bootstrapcdn.com/bootstrap/<%= bsversion %>/css/bootstrap.min.css" rel="stylesheet"/>
    <link rel="stylesheet" href="assets/rainbow.css"/>
    <link rel="stylesheet" href="assets/demo.css"/>
    <link rel="author" href="https://github.com/angular-ui/bootstrap/graphs/contributors">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-3" ng-click="isCollapsed = !isCollapsed">
                    Toggle navigation

                </button>
                UI Bootstrap

                        UI Bootstrap

                            Directives

                            <% demoModules.forEach(function(module) {  %>
<a href="#<%= module.name %>"><%= module.displayName %>
<% }); %>

Getting started

Getting started

Directives

                UI Bootstrap

Bootstrap components written in pure AngularJS by the AngularUI Team

                Code on Github
                <button type="button" class="btn btn-outline-inverse btn-lg" ng-click="showDownloadModal()">
                     Download (<%= pkg.version%>)
                </button>
                <button type="button" class="btn btn-outline-inverse btn-lg" ng-click="showBuildModal()"> Create a Build</button>

                    Tweet

Directives

                        <% demoModules.forEach(function(module) {  %>

<a href="#<%= module.name %>"><%= module.displayName %>

                        <% }); %>

Getting started

Dependencies

                        This repository contains a set of native AngularJS directives based on
                        Bootstrap's markup and CSS. As a result no dependency on jQuery or Bootstrap's
                        JavaScript is required. The only required dependencies are:

AngularJS (requires AngularJS 1.3.x, tested with <%= ngversion %>).
                            0.12.0 is the last version of this library that supports AngularJS 1.2.x.

Bootstrap CSS (tested with version <%= bsversion %>).
                            This version of the library (<%= pkg.version%>) works only with Bootstrap CSS in version 3.x.
                            0.8.0 is the last version of this library that supports Bootstrap CSS in version 2.3.x.

Files to download

                        Build files for all directives are distributed in several flavours: minified for production usage, un-minified
                        for development, with or without templates. All the options are described and can be
                        downloaded from here.

Alternativelly, if you are only interested in a subset of directives, you can
                        create your own build.

Whichever method you choose the good news that the overall size of a download is very small:
                       <20kB for all directives (~5kB with gzip compression!)

Installation

As soon as you've got all the files downloaded and included in your page you just need to declare
                       a dependency on the ui.bootstrap module:

angular.module('myModule', ['ui.bootstrap']);

You can fork one of the plunkers from this page to see a working example of what is described here.

CSS

Original Bootstrap's CSS depends on empty href attributes to style cursors for several components (pagination, tabs etc.).
                    But in AngularJS adding empty href attributes to link tags will cause unwanted route changes. This is why we need to remove empty href attributes from directive templates and as a result styling is not applied correctly. The remedy is simple, just add the following styling to your application:
.nav, .pagination, .carousel, .panel-title a { cursor: pointer; }

FAQ

Please check our FAQ section for common problems / solutions.

                <% demoModules.forEach(function(module) { %>
                    <section id="<%= module.name %>">

<%= module.displayName %>
                              (<a target="_blank" href="https://github.com/angular-ui/bootstrap/tree/master/src/<%= module.name %>">ui.bootstrap.<%= module.name %>)

                                <%= module.docs.html %>

                                <%= module.docs.md %>

                                    <button class="btn btn-info" id="plunk-btn" ng-click="edit('<%= ngversion%>', '<%= bsversion %>', '<%= pkg.version%>', '<%= module.name %>')"> Edit in plunker</button>

                                <tabset>
                                    <tab heading="Markup">

<%- module.docs.html %>

                                    </tab>
                                    <tab heading="JavaScript">

<%- module.docs.js %>

                                    </tab>
                                </tabset>

                <% }); %>

Designed and built by Angular-UI team and contributors.

Code licensed under <%= pkg.license %> License.

Issues


text: import './list-autorollers-sk';


text:
package org.apache.hadoop.hive.ql.io;

import java.io.IOException;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.serde2.SerDeStats;

/**
 * API for supporting updating records.
 */
public interface RecordUpdater {

  /**
   * Insert a new record into the table.
   * @param currentWriteId the table write id of the current transaction.
   * @param row the row of data to insert
   * @throws IOException
   */
  void insert(long currentWriteId, Object row) throws IOException;

  /**
   * Update an old record with a new set of values.
   * @param currentWriteId the current write id
   * @param row the new values for the row
   * @throws IOException
   */
  void update(long currentWriteId, Object row) throws IOException;

  /**
   * Delete a row from the table.
   * @param currentWriteId the current write id
   * @throws IOException
   */
  void delete(long currentWriteId, Object row) throws IOException;

  /**
   * Flush the current set of rows to the underlying file system, so that
   * they are available to readers. Most implementations will need to write
   * additional state information when this is called, so it should only be
   * called during streaming when a transaction is finished, but the
   * RecordUpdater can't be closed yet.
   * @throws IOException
   */
  void flush() throws IOException;

  /**
   * Close this updater. No further calls are legal after this.
   * @param abort Can the data since the last flush be discarded?
   * @throws IOException
   */
  void close(boolean abort) throws IOException;

  /**
   * Returns the statistics information
   * @return SerDeStats
   */
  SerDeStats getStats();

  /**
   * Returns the number of rows in memory before flush().
   *
   * @return - buffered row count
   */
  long getBufferedRowCount();

  /**
   * Returns the path of the file this updater wrote to
   */
  public Path getUpdatedFilePath();
}


text:
package org.springframework.boot.autoconfigure.amqp;

import org.springframework.amqp.rabbit.config.AbstractRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.config.RetryInterceptorBuilder;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.RabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RejectAndDontRequeueRecoverer;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties.ListenerRetry;
import org.springframework.util.Assert;

/**
 * Configure {@link RabbitListenerContainerFactory} with sensible defaults.
 *
 * @param <T> the container factory type.
 * @author Gary Russell
 * @author Stephane Nicoll
 * @since 2.0.0
 */
public abstract class AbstractRabbitListenerContainerFactoryConfigurer<T extends AbstractRabbitListenerContainerFactory<?>> {

	private MessageConverter messageConverter;

	private MessageRecoverer messageRecoverer;

	private RabbitProperties rabbitProperties;

	/**
	 * Set the {@link MessageConverter} to use or {@code null} if the out-of-the-box
	 * converter should be used.
	 * @param messageConverter the {@link MessageConverter}
	 */
	protected void setMessageConverter(MessageConverter messageConverter) {
		this.messageConverter = messageConverter;
	}

	/**
	 * Set the {@link MessageRecoverer} to use or {@code null} to rely on the default.
	 * @param messageRecoverer the {@link MessageRecoverer}
	 */
	protected void setMessageRecoverer(MessageRecoverer messageRecoverer) {
		this.messageRecoverer = messageRecoverer;
	}

	/**
	 * Set the {@link RabbitProperties} to use.
	 * @param rabbitProperties the {@link RabbitProperties}
	 */
	protected void setRabbitProperties(RabbitProperties rabbitProperties) {
		this.rabbitProperties = rabbitProperties;
	}

	protected final RabbitProperties getRabbitProperties() {
		return this.rabbitProperties;
	}

	/**
	 * Configure the specified rabbit listener container factory. The factory can be
	 * further tuned and default settings can be overridden.
	 * @param factory the {@link AbstractRabbitListenerContainerFactory} instance to
	 * configure
	 * @param connectionFactory the {@link ConnectionFactory} to use
	 */
	public abstract void configure(T factory, ConnectionFactory connectionFactory);

	protected void configure(T factory, ConnectionFactory connectionFactory,
			RabbitProperties.AmqpContainer configuration) {
		Assert.notNull(factory, "Factory must not be null");
		Assert.notNull(connectionFactory, "ConnectionFactory must not be null");
		Assert.notNull(configuration, "Configuration must not be null");
		factory.setConnectionFactory(connectionFactory);
		if (this.messageConverter != null) {
			factory.setMessageConverter(this.messageConverter);
		}
		factory.setAutoStartup(configuration.isAutoStartup());
		if (configuration.getAcknowledgeMode() != null) {
			factory.setAcknowledgeMode(configuration.getAcknowledgeMode());
		}
		if (configuration.getPrefetch() != null) {
			factory.setPrefetchCount(configuration.getPrefetch());
		}
		if (configuration.getDefaultRequeueRejected() != null) {
			factory.setDefaultRequeueRejected(configuration.getDefaultRequeueRejected());
		}
		if (configuration.getIdleEventInterval() != null) {
			factory.setIdleEventInterval(configuration.getIdleEventInterval().toMillis());
		}
		ListenerRetry retryConfig = configuration.getRetry();
		if (retryConfig.isEnabled()) {
			RetryInterceptorBuilder<?> builder = (retryConfig.isStateless()
					? RetryInterceptorBuilder.stateless()
					: RetryInterceptorBuilder.stateful());
			builder.maxAttempts(retryConfig.getMaxAttempts());
			builder.backOffOptions(retryConfig.getInitialInterval(),
					retryConfig.getMultiplier(), retryConfig.getMaxInterval());
			MessageRecoverer recoverer = (this.messageRecoverer != null
					? this.messageRecoverer : new RejectAndDontRequeueRecoverer());
			builder.recoverer(recoverer);
			factory.setAdviceChain(builder.build());
		}
	}

}


text:
<?php
namespace GuzzleHttp\Subscriber;

use GuzzleHttp\Event\BeforeEvent;
use GuzzleHttp\Event\RequestEvents;
use GuzzleHttp\Event\SubscriberInterface;
use GuzzleHttp\Message\AppliesHeadersInterface;
use GuzzleHttp\Message\RequestInterface;
use GuzzleHttp\Mimetypes;
use GuzzleHttp\Stream\StreamInterface;

/**
 * Prepares requests with a body before sending
 *
 * **Request Options**
 *
 * - expect: Set to true to enable the "Expect: 100-Continue" header for a
 *   request that send a body. Set to false to disable "Expect: 100-Continue".
 *   Set to a number so that the size of the payload must be greater than the
 *   number in order to send the Expect header. Setting to a number will send
 *   the Expect header for all requests in which the size of the payload cannot
 *   be determined or where the body is not rewindable.
 */
class Prepare implements SubscriberInterface
{
    public function getEvents()
    {
        return ['before' => ['onBefore', RequestEvents::PREPARE_REQUEST]];
    }

    public function onBefore(BeforeEvent $event)
    {
        $request = $event->getRequest();

        // Set the appropriate Content-Type for a request if one is not set and
        // there are form fields
        if (!($body = $request->getBody())) {
            return;
        }

        $this->addContentLength($request, $body);

        if ($body instanceof AppliesHeadersInterface) {
            // Synchronize the body with the request headers
            $body->applyRequestHeaders($request);
        } elseif (!$request->hasHeader('Content-Type')) {
            $this->addContentType($request, $body);
        }

        $this->addExpectHeader($request, $body);
    }

    private function addContentType(
        RequestInterface $request,
        StreamInterface $body
    ) {
        if (!($uri = $body->getMetadata('uri'))) {
            return;
        }

        // Guess the content-type based on the stream's "uri" metadata value.
        // The file extension is used to determine the appropriate mime-type.
        if ($contentType = Mimetypes::getInstance()->fromFilename($uri)) {
            $request->setHeader('Content-Type', $contentType);
        }
    }

    private function addContentLength(
        RequestInterface $request,
        StreamInterface $body
    ) {
        // Set the Content-Length header if it can be determined, and never
        // send a Transfer-Encoding: chunked and Content-Length header in
        // the same request.
        if ($request->hasHeader('Content-Length')) {
            // Remove transfer-encoding if content-length is set.
            $request->removeHeader('Transfer-Encoding');
            return;
        }

        if ($request->hasHeader('Transfer-Encoding')) {
            return;
        }

        if (null !== ($size = $body->getSize())) {
            $request->setHeader('Content-Length', $size);
            $request->removeHeader('Transfer-Encoding');
        } elseif ('1.1' == $request->getProtocolVersion()) {
            // Use chunked Transfer-Encoding if there is no determinable
            // content-length header and we're using HTTP/1.1.
            $request->setHeader('Transfer-Encoding', 'chunked');
            $request->removeHeader('Content-Length');
        }
    }

    private function addExpectHeader(
        RequestInterface $request,
        StreamInterface $body
    ) {
        // Determine if the Expect header should be used
        if ($request->hasHeader('Expect')) {
            return;
        }

        $expect = $request->getConfig()['expect'];

        // Return if disabled or if you're not using HTTP/1.1
        if ($expect === false || $request->getProtocolVersion() !== '1.1') {
            return;
        }

        // The expect header is unconditionally enabled
        if ($expect === true) {
            $request->setHeader('Expect', '100-Continue');
            return;
        }

        // By default, send the expect header when the payload is > 1mb
        if ($expect === null) {
            $expect = 1048576;
        }

        // Always add if the body cannot be rewound, the size cannot be
        // determined, or the size is greater than the cutoff threshold
        $size = $body->getSize();
        if ($size === null || $size >= (int) $expect || !$body->isSeekable()) {
            $request->setHeader('Expect', '100-Continue');
        }
    }
}


text:
A cookbook with recipes to personalize my OS X workstation

## License and Authors

License: MIT

This work is derived from multiple sources:

* Mathias Bynens https://github.com/mathiasbynens/dotfiles
* Pivotal Labs https://github.com/pivotal-sprout/sprout-osx-settings
* Pivotal Labs https://github.com/pivotal-sprout/osx
* Roderik van der Veer https://github.com/kitchenplan/chef-osxdefaults


text:
/* ----------------------------------------------------------------------------
 * This file was automatically generated by SWIG (http://www.swig.org).
 * Version 4.0.2
 *
 * Do not make changes to this file unless you know what you are doing--modify
 * the SWIG interface file instead.
 * ----------------------------------------------------------------------------- */

package org.opensim.modeling;

/**
 * An abstract class for specifying the interface for an investigation.

 *

 * @author Frank C. Anderson

 * @version 1.0
 */
public class RRATool extends AbstractTool {
  private transient long swigCPtr;

  public RRATool(long cPtr, boolean cMemoryOwn) {
    super(opensimActuatorsAnalysesToolsJNI.RRATool_SWIGUpcast(cPtr), cMemoryOwn);
    swigCPtr = cPtr;
  }

  public static long getCPtr(RRATool obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }

  @SuppressWarnings("deprecation")
  protected void finalize() {
    delete();
  }

  public synchronized void delete() {
    if (swigCPtr != 0) {
      if (swigCMemOwn) {
        swigCMemOwn = false;
        opensimActuatorsAnalysesToolsJNI.delete_RRATool(swigCPtr);
      }
      swigCPtr = 0;
    }
    super.delete();
  }

  public static RRATool safeDownCast(OpenSimObject obj) {
    long cPtr = opensimActuatorsAnalysesToolsJNI.RRATool_safeDownCast(OpenSimObject.getCPtr(obj), obj);
    return (cPtr == 0) ? null : new RRATool(cPtr, false);
  }

  public void assign(OpenSimObject aObject) {
    opensimActuatorsAnalysesToolsJNI.RRATool_assign(swigCPtr, this, OpenSimObject.getCPtr(aObject), aObject);
  }

  public static String getClassName() {
    return opensimActuatorsAnalysesToolsJNI.RRATool_getClassName();
  }

  public OpenSimObject clone() {
    long cPtr = opensimActuatorsAnalysesToolsJNI.RRATool_clone(swigCPtr, this);
    return (cPtr == 0) ? null : new RRATool(cPtr, true);
  }

  public String getConcreteClassName() {
    return opensimActuatorsAnalysesToolsJNI.RRATool_getConcreteClassName(swigCPtr, this);
  }

  public RRATool() {
    this(opensimActuatorsAnalysesToolsJNI.new_RRATool__SWIG_0(), true);
  }

  public RRATool(String aFileName, boolean aLoadModel) throws java.io.IOException {
    this(opensimActuatorsAnalysesToolsJNI.new_RRATool__SWIG_1(aFileName, aLoadModel), true);
  }

  public RRATool(String aFileName) throws java.io.IOException {
    this(opensimActuatorsAnalysesToolsJNI.new_RRATool__SWIG_2(aFileName), true);
  }

  public RRATool(RRATool aObject) {
    this(opensimActuatorsAnalysesToolsJNI.new_RRATool__SWIG_3(RRATool.getCPtr(aObject), aObject), true);
  }

  public String getDesiredPointsFileName() {
    return opensimActuatorsAnalysesToolsJNI.RRATool_getDesiredPointsFileName(swigCPtr, this);
  }

  public void setDesiredPointsFileName(String aFileName) {
    opensimActuatorsAnalysesToolsJNI.RRATool_setDesiredPointsFileName(swigCPtr, this, aFileName);
  }

  public String getDesiredKinematicsFileName() {
    return opensimActuatorsAnalysesToolsJNI.RRATool_getDesiredKinematicsFileName(swigCPtr, this);
  }

  public void setDesiredKinematicsFileName(String aFileName) {
    opensimActuatorsAnalysesToolsJNI.RRATool_setDesiredKinematicsFileName(swigCPtr, this, aFileName);
  }

  public String getConstraintsFileName() {
    return opensimActuatorsAnalysesToolsJNI.RRATool_getConstraintsFileName(swigCPtr, this);
  }

  public void setConstraintsFileName(String aFileName) {
    opensimActuatorsAnalysesToolsJNI.RRATool_setConstraintsFileName(swigCPtr, this, aFileName);
  }

  public String getTaskSetFileName() {
    return opensimActuatorsAnalysesToolsJNI.RRATool_getTaskSetFileName(swigCPtr, this);
  }

  public void setTaskSetFileName(String aFileName) {
    opensimActuatorsAnalysesToolsJNI.RRATool_setTaskSetFileName(swigCPtr, this, aFileName);
  }

  public String getOutputModelFileName() {
    return opensimActuatorsAnalysesToolsJNI.RRATool_getOutputModelFileName(swigCPtr, this);
  }

  public void setOutputModelFileName(String aFileName) {
    opensimActuatorsAnalysesToolsJNI.RRATool_setOutputModelFileName(swigCPtr, this, aFileName);
  }

  public boolean getAdjustCOMToReduceResiduals() {
    return opensimActuatorsAnalysesToolsJNI.RRATool_getAdjustCOMToReduceResiduals(swigCPtr, this);
  }

  public void setAdjustCOMToReduceResiduals(boolean aAdjust) {
    opensimActuatorsAnalysesToolsJNI.RRATool_setAdjustCOMToReduceResiduals(swigCPtr, this, aAdjust);
  }

  public String getAdjustedCOMBody() {
    return opensimActuatorsAnalysesToolsJNI.RRATool_getAdjustedCOMBody(swigCPtr, this);
  }

  public void setAdjustedCOMBody(String aBody) {
    opensimActuatorsAnalysesToolsJNI.RRATool_setAdjustedCOMBody(swigCPtr, this, aBody);
  }

  public double getLowpassCutoffFrequency() {
    return opensimActuatorsAnalysesToolsJNI.RRATool_getLowpassCutoffFrequency(swigCPtr, this);
  }

  public void setLowpassCutoffFrequency(double aLowpassCutoffFrequency) {
    opensimActuatorsAnalysesToolsJNI.RRATool_setLowpassCutoffFrequency(swigCPtr, this, aLowpassCutoffFrequency);
  }

  public String getExternalLoadsFileName() {
    return opensimActuatorsAnalysesToolsJNI.RRATool_getExternalLoadsFileName(swigCPtr, this);
  }

  public void setExternalLoadsFileName(String aFileName) {
    opensimActuatorsAnalysesToolsJNI.RRATool_setExternalLoadsFileName(swigCPtr, this, aFileName);
  }

  public boolean run() throws java.io.IOException {
    return opensimActuatorsAnalysesToolsJNI.RRATool_run(swigCPtr, this);
  }

  public Storage getForceStorage() {
    return new Storage(opensimActuatorsAnalysesToolsJNI.RRATool_getForceStorage(swigCPtr, this), false);
  }

  public void setOriginalForceSet(ForceSet aForceSet) {
    opensimActuatorsAnalysesToolsJNI.RRATool_setOriginalForceSet(swigCPtr, this, ForceSet.getCPtr(aForceSet), aForceSet);
  }

  public void updateFromXMLNode(SWIGTYPE_p_SimTK__Xml__Element aNode, int versionNumber) {
    opensimActuatorsAnalysesToolsJNI.RRATool_updateFromXMLNode__SWIG_0(swigCPtr, this, SWIGTYPE_p_SimTK__Xml__Element.getCPtr(aNode), versionNumber);
  }

  public void updateFromXMLNode(SWIGTYPE_p_SimTK__Xml__Element aNode) {
    opensimActuatorsAnalysesToolsJNI.RRATool_updateFromXMLNode__SWIG_1(swigCPtr, this, SWIGTYPE_p_SimTK__Xml__Element.getCPtr(aNode));
  }

}


text:
		   (((l) & 0x00ff0000) >> 8)  | \
		   (((l) & 0x0000ff00) << 8)  | \
		   (((l) & 0x000000ff) << 24))
#else
#error "Swap32 has already been defined"
#endif

OMNI_USING_NAMESPACE(omni)

cdrValueChunkStream::
~cdrValueChunkStream()
{
  if (!pd_exception) {
    if (pd_reader && pd_nestLevel > 0) {
      try {
        endInputValue();
      }
      catch (...) {
        omniORB::logs(1, "Caught unexpected exception in "
                      "cdrValueChunkStream destructor.");
        copyStateToActual();
        pd_valueTracker = 0;
        return;
      }
    }
    OMNIORB_ASSERT(pd_nestLevel == 0);
  }
  copyStateToActual();
  pd_valueTracker = 0;
}

ValueIndirectionTracker::~ValueIndirectionTracker()
{
}

void
cdrValueChunkStream::initialiseInput()
{
  OMNIORB_ASSERT(pd_nestLevel == 0);
  pd_reader    = 1;
  pd_nestLevel = 1;
  pd_inHeader  = 1;
}

void
cdrValueChunkStream::startOutputChunk()
{
  omniORB::logs(25, "Start writing value chunk.");

  OMNIORB_ASSERT(!pd_reader);
  OMNIORB_ASSERT(!pd_inChunk);
  OMNIORB_ASSERT(pd_nestLevel > 0);

  // We have to marshal the chunk length manually, so we can keep a
  // record of its address in the buffer.
  omni::ptr_arith_t p1, p2;

  copyStateToActual();
  while (1) {
    p1 = omni::align_to((omni::ptr_arith_t)pd_actual.pd_outb_mkr,
			omni::ALIGN_4);
    p2 = p1 + sizeof(_CORBA_Long);
    if ((void*)p2 > pd_actual.pd_outb_end) {
      if (pd_actual.reserveOutputSpaceForPrimitiveType(omni::ALIGN_4,
						       sizeof(_CORBA_Long))) {
	continue;
      }
      else {
	// Cannot reserve space, most likely because this is a
	// counting stream. We cannot continue.
	OMNIORB_THROW(MARSHAL, MARSHAL_CannotReserveOutputSpace,
		      (CORBA::CompletionStatus)completion());
      }
    }
    break;
  }
  pd_actual.pd_outb_mkr = (void*)p2;
  pd_lengthPtr  = (CORBA::Long*)p1;
  *pd_lengthPtr = 0;

  copyStateFromActual();
  pd_inChunk   = 1;
  pd_justEnded = 0;
}

void
cdrValueChunkStream::endOutputChunk()
{
  OMNIORB_ASSERT(!pd_reader);
  OMNIORB_ASSERT(pd_inChunk);
  OMNIORB_ASSERT(pd_lengthPtr);

  // Calculate length of the chunk we're ending
  omni::ptr_arith_t start = (omni::ptr_arith_t)pd_lengthPtr + 4;
  omni::ptr_arith_t end   = (omni::ptr_arith_t)pd_outb_mkr;

  CORBA::ULong len = end - start;
  OMNIORB_ASSERT(len > 0);

  setLength(len);

  if (omniORB::trace(25)) {
    omniORB::logger l;
    l << "End writing value chunk. Length = " << *pd_lengthPtr << ".\n";
  }
  pd_lengthPtr = 0;
  pd_inChunk   = 0;

  copyStateToActual();
}

void
cdrValueChunkStream::maybeStartNewChunk(omni::alignment_t align, size_t size)
{
  OMNIORB_ASSERT(!pd_reader);
  OMNIORB_ASSERT(pd_inChunk);
  OMNIORB_ASSERT(pd_lengthPtr);

  // Calculate length of the chunk we're ending
  omni::ptr_arith_t start = (omni::ptr_arith_t)pd_lengthPtr + 4;
  omni::ptr_arith_t end   = (omni::ptr_arith_t)pd_outb_mkr;

  setLength(end - start);

  if (*pd_lengthPtr > 0) {
    // OK to end here
    if (omniORB::trace(25)) {
      omniORB::logger l;
      l << "End writing value chunk. Length = " << getLength() << ".\n";
    }
    pd_lengthPtr  = 0;
    pd_inChunk    = 0;

    copyStateToActual();
    startOutputChunk();
  }
  else {
    if (omniORB::trace(25)) {
      omniORB::logger l;
      l << "Cannot end value chunk with zero length; extending to "
	<< (int)size << " octets.\n";
    }
    OMNIORB_ASSERT(size);
    declareArrayLength(align, size);
  }
}

void
cdrValueChunkStream::startOutputValueHeader(_CORBA_Long valueTag)
{
  OMNIORB_ASSERT(valueTag >= 0x7fffff00); // Valid tag range
  OMNIORB_ASSERT(valueTag &  0x00000008); // Chunked encoding flag

  if (pd_inChunk)
    endOutputChunk();
  else
    copyStateToActual();

  omniORB::logs(25, "Start output value header.");

  pd_inHeader = 1;

  // Marshal value tag for new value. Since we're currently outside a
  // chunk, marshal straight into the actual stream, to prevent our
  // virtual functions running if the buffer is full.
  valueTag >>= pd_actual;
  copyStateFromActual();
  pd_justEnded = 0;
}

void
cdrValueChunkStream::startOutputValueBody()
{
  OMNIORB_ASSERT(pd_inHeader);

  pd_inHeader = 0;
  ++pd_nestLevel;

  if (omniORB::trace(25)) {
    omniORB::logger l;
    l << "Start writing chunked value body. Nest level = "
      << pd_nestLevel << ".\n";
  }
  pd_outb_end = pd_outb_mkr;
}

void
cdrValueChunkStream::endOutputValue()
{
  OMNIORB_ASSERT(pd_nestLevel > 0);
  OMNIORB_ASSERT(!pd_remaining);

  if (pd_inChunk)
    endOutputChunk();
  else
    copyStateToActual();

  if (pd_justEnded) {
    // Ending a nested value

    if (omniORB::trace(25)) {
      omniORB::logger l;
      l << "End writing nested chunked value. Nest level = "
	<< pd_nestLevel << ".\n";
    }

    CORBA::Long* endp = (CORBA::Long*)((omni::ptr_arith_t)pd_outb_mkr - 4);

    OMNIORB_ASSERT(*endp == -(pd_nestLevel + 1));
    *endp = -pd_nestLevel;
  }
  else {
    if (omniORB::trace(25)) {
      omniORB::logger l;
      l << "End writing chunked value. Nest level = " << pd_nestLevel << ".\n";
    }

    // Marshal the end tag into the actual stream
    CORBA::Long endTag = -pd_nestLevel;
    endTag >>= pd_actual;
    copyStateFromActual();
  }

  --pd_nestLevel;

  // Ensure next marshal results in a call to one of our virtual
  // functions, so we can start a new chunk.
  pd_outb_end  = pd_outb_mkr;
  pd_justEnded = 1;
}

void
cdrValueChunkStream::
startInputValueBody()
{
  if (!pd_inHeader)
    OMNIORB_THROW(MARSHAL, MARSHAL_InvalidChunkedEncoding,
		  (CORBA::CompletionStatus)completion());
  pd_inHeader = 0;
  startInputChunk();
}

_CORBA_Boolean
cdrValueChunkStream::
reserveOutputSpaceForPrimitiveType(omni::alignment_t align, size_t required)
{
  omni::ptr_arith_t p1, p2;

  for (int i=0; i < 5; i++) {

    if (pd_remaining) {
      // Some pre-reserved octets to go before finishing a chunk
      OMNIORB_ASSERT(!pd_inChunk);
      OMNIORB_ASSERT(!pd_inHeader);
      OMNIORB_ASSERT(pd_outb_mkr <= pd_outb_end);

      p1 = omni::align_to((omni::ptr_arith_t)pd_outb_mkr, align);
      p2 = p1 + required;
      if (p2 <= (omni::ptr_arith_t)pd_outb_end) {
	// Not got to the end of the current buffer yet
	return 1;
      }

      // If there is room for any data in the current buffer, it will
      // be "lost" when the buffer is changed below. Increase
      // pd_remaining to reflect the octets that would have fitted in
      // the current buffer, but were not used.
      pd_remaining += (omni::ptr_arith_t)pd_outb_end - p1;

      copyStateToActual();
      if (!pd_actual.reserveOutputSpaceForPrimitiveType(align, required))
	OMNIORB_THROW(MARSHAL, MARSHAL_CannotReserveOutputSpace,
		      (CORBA::CompletionStatus)completion());
      copyStateFromActual();

      p1 = omni::align_to((omni::ptr_arith_t)pd_outb_mkr, align);
      p2 = p1 + pd_remaining;
      if (p2 > (omni::ptr_arith_t)pd_outb_end) {
	pd_remaining = p2 - (omni::ptr_arith_t)pd_outb_end;
      }
      else {
	pd_outb_end  = (void*)p2;
	pd_remaining = 0;
      }
      return 1;
    }

    if (pd_inHeader) {
      OMNIORB_ASSERT(!pd_inChunk);
      copyStateToActual();
      if (!pd_actual.reserveOutputSpaceForPrimitiveType(align, required))
	OMNIORB_THROW(MARSHAL, MARSHAL_CannotReserveOutputSpace,
		      (CORBA::CompletionStatus)completion());
      copyStateFromActual();
      return 1;
    }

    if (!pd_inChunk) {
      if (required) {
	// Start a new chunk
	OMNIORB_ASSERT(pd_nestLevel);
	OMNIORB_ASSERT(pd_lengthPtr == 0);
	startOutputChunk();
      }
      else {
	// No data to marshal, merely aligning output. Ask actual to
	// reserve and set pd_outb_end to ensure we re-evaluate when
	// there is something to marshal.
	copyStateToActual();
	if (!pd_actual.reserveOutputSpaceForPrimitiveType(align, required))
	  OMNIORB_THROW(MARSHAL, MARSHAL_CannotReserveOutputSpace,
			(CORBA::CompletionStatus)completion());
	copyStateFromActual();
	pd_outb_end = pd_outb_mkr;
	return 1;
      }
    }

    p1 = omni::align_to((omni::ptr_arith_t)pd_outb_mkr, align);
    p2 = p1 + required;

    if (p2 <= (omni::ptr_arith_t)pd_outb_end) {
      // Enough space
      return 1;
    }
    maybeStartNewChunk(align, required);
  }
  // If we've been round five times without getting enough space, the
  // stream must be being awkward and allocating the precise amount we
  // ask it for each time. We could choose to preset the chunk length
  // to the required size, meaning we don't have to go back later to
  // end it. There's not much point, though, since doing that would
  // end up with one chunk per primitive type, which is so inefficient
  // as to be ridiculous. We throw a MARSHAL exception.
  OMNIORB_THROW(MARSHAL, MARSHAL_CannotReserveOutputSpace,
		(CORBA::CompletionStatus)completion());
  return 0;
}

_CORBA_Boolean
cdrValueChunkStream::
maybeReserveOutputSpace(omni::alignment_t align, size_t required)
{
  omni::ptr_arith_t p1, p2;

  if (pd_remaining) {
    // Some pre-reserved octets to go before finishing a chunk
    OMNIORB_ASSERT(!pd_inChunk);
    OMNIORB_ASSERT(!pd_inHeader);

    p1 = omni::align_to((omni::ptr_arith_t)pd_outb_mkr, align);
    p2 = p1 + required;
    if (p2 <= (omni::ptr_arith_t)pd_outb_end) {
      // Not got to the end of the current buffer yet
      return 1;
    }

    // If there is room for any data in the current buffer, it will
    // be "lost" when the buffer is changed below. Increase
    // pd_remaining to reflect the octets that would have fitted in
    // the current buffer, but were not used.
    pd_remaining += (omni::ptr_arith_t)pd_outb_end - p1;

    copyStateToActual();
    if (!pd_actual.maybeReserveOutputSpace(align, required))
      OMNIORB_THROW(MARSHAL, MARSHAL_CannotReserveOutputSpace,
		    (CORBA::CompletionStatus)completion());
    copyStateFromActual();
    p1 = omni::align_to((omni::ptr_arith_t)pd_outb_mkr, align);
    p2 = p1 + pd_remaining;
    if (p2 > (omni::ptr_arith_t)pd_outb_end) {
      pd_remaining = p2 - (omni::ptr_arith_t)pd_outb_end;
    }
    else {
      pd_outb_end  = (void*)p2;
      pd_remaining = 0;
    }
    return 1;
  }

  if (pd_inHeader) {
    OMNIORB_ASSERT(!pd_inChunk);
    copyStateToActual();
    CORBA::Boolean r = pd_actual.maybeReserveOutputSpace(align, required);
    copyStateFromActual();
    return r;
  }

  if (!pd_inChunk) {
    // Start a new chunk
    OMNIORB_ASSERT(pd_nestLevel);
    OMNIORB_ASSERT(pd_lengthPtr == 0);
    startOutputChunk();
  }

  p1 = omni::align_to((omni::ptr_arith_t)pd_outb_mkr, align);
  p2 = p1 + required;

  if (p2 <= (omni::ptr_arith_t)pd_outb_end) {
    // Enough space already
    return 1;
  }

  omni::ptr_arith_t start = (omni::ptr_arith_t)pd_lengthPtr + 4;
  setLength(p2 - start);
  pd_remaining = required;
  pd_outb_mkr  = pd_outb_end = (void*)p2;

  // The call to maybeReserveOutputSpace can either succeed, in which
  // case we set our pointers to allow the caller to fill the reserved
  // space, or it can throw BAD_PARAM, in which case our pointers and
  // pd_remaining are set correctly for the caller to fill the stream
  // some other way.
  if (!pd_actual.maybeReserveOutputSpace(align, required))
    OMNIORB_THROW(MARSHAL, MARSHAL_CannotReserveOutputSpace,
		  (CORBA::CompletionStatus)completion());

  copyStateFromActual();
  p1 = omni::align_to((omni::ptr_arith_t)pd_outb_mkr, align);
  p2 = p1 + required;

  OMNIORB_ASSERT(p2 <= (omni::ptr_arith_t)pd_outb_end);

  pd_outb_end  = (void*)p2;
  pd_remaining = 0;

  return 1;
}

void
cdrValueChunkStream::
put_octet_array(const _CORBA_Octet* b, int size, omni::alignment_t align)
{
  omni::ptr_arith_t p1, p2;

  if (pd_remaining) {
    OMNIORB_ASSERT(!pd_inChunk);
    OMNIORB_ASSERT(!pd_inHeader);

    p1 = omni::align_to((omni::ptr_arith_t)pd_outb_mkr, align);
    p2 = p1 + size;

    if (p2 > (omni::ptr_arith_t)pd_outb_end + (omni::ptr_arith_t)pd_remaining){
      // Not permitted to put an array longer that the reserved chunk size
      OMNIORB_THROW(MARSHAL, MARSHAL_MessageTooLong,
		    (CORBA::CompletionStatus)completion());
    }
    if (p2 <= (omni::ptr_arith_t)pd_outb_end) {
      memcpy((void*)p1, (const void*)b, size);
      pd_outb_mkr = (void*)p2;
    }
    else {
      copyStateToActual();
      pd_actual.put_octet_array(b, size, align);
      pd_remaining -= (p2 - (omni::ptr_arith_t)pd_outb_end);
      copyStateFromActual();
      pd_outb_end = pd_outb_mkr;
    }
    return;
  }

  if (pd_inHeader) {
    OMNIORB_ASSERT(!pd_inChunk);
    copyStateToActual();
    pd_actual.put_octet_array(b, size, align);
    copyStateFromActual();
    return;
  }

  p1 = omni::align_to((omni::ptr_arith_t)pd_outb_mkr, align);
  p2 = p1 + size;

  if (p2 <= (omni::ptr_arith_t)pd_outb_end) {
    // Enough space in buffer.
    memcpy((void*)p1, (const void*)b, size);
    pd_outb_mkr = (void*)p2;
    return;
  }

  if (!pd_inChunk) {
    // Start a new chunk.
    OMNIORB_ASSERT(pd_nestLevel);
    OMNIORB_ASSERT(pd_lengthPtr == 0);
    startOutputChunk();

    p1 = omni::align_to((omni::ptr_arith_t)pd_outb_mkr, align);
    p2 = p1 + size;

    if (p2 <= (omni::ptr_arith_t)pd_outb_end) {
      // There is now enough space in the buffer.
      memcpy((void*)p1, (const void*)b, size);
      pd_outb_mkr = (void*)p2;
      return;
    }
  }

  // There was not enough space in the buffer, so end the chunk,
  // setting its length to include the octet array.
  p1 = (omni::ptr_arith_t)pd_lengthPtr + 4;
  OMNIORB_ASSERT(p1 < p2);
  setLength(p2 - p1);

  pd_lengthPtr = 0;
  pd_inChunk   = 0;

  copyStateToActual();
  pd_actual.put_octet_array(b, size, align);
  copyStateFromActual();

  // Make sure the next insertion causes a new chunk to start.
  pd_outb_end = pd_outb_mkr;
}

void
cdrValueChunkStream::
declareArrayLength(omni::alignment_t align, size_t size)
{
  if (pd_inHeader)
    return;

  if (!pd_inChunk) {
    // Start a new chunk
    OMNIORB_ASSERT(pd_nestLevel);
    OMNIORB_ASSERT(pd_lengthPtr == 0);
    startOutputChunk();
  }

  omni::ptr_arith_t start, cur, end;
  cur = omni::align_to((omni::ptr_arith_t)pd_outb_mkr, align);
  end = cur + size;

  if (end <= (omni::ptr_arith_t)pd_outb_end) {
    // Enough space in buffer
    return;
  }
  else {
    // End the chunk, setting its length to include the array
    start = (omni::ptr_arith_t)pd_lengthPtr + 4;
    OMNIORB_ASSERT(start < end);
    setLength(end - start);

    // Number of octets remaining is the number we required, minus the
    // number we can fit into the current buffer with the required
    // alignment.
    pd_remaining = end - (omni::ptr_arith_t)pd_outb_end;

    if (omniORB::trace(25)) {
      omniORB::logger l;
      l << "End writing value chunk inside declareArrayLength. Length = "
	<< getLength() << ", remaining = " << pd_remaining << ".\n";
    }
    pd_lengthPtr = 0;
    pd_inChunk   = 0;
  }
}

void
cdrValueChunkStream::
fetchInputData(omni::alignment_t align,size_t required)
{
  OMNIORB_ASSERT(pd_reader);

  while (1) {
    omni::ptr_arith_t p1, p2;
    p1 = omni::align_to((omni::ptr_arith_t)pd_inb_mkr, align);
    p2 = p1 + required;
    if (p2 <= (omni::ptr_arith_t)pd_inb_end)
      return;

    if (pd_inHeader) {
      OMNIORB_ASSERT(!pd_inChunk);
      copyStateToActual();
      pd_actual.fetchInputData(align, required);
      copyStateFromActual();
      return;
    }

    if (pd_inChunk) {
      if (pd_remaining) {
	// More data to come in this chunk
	OMNIORB_ASSERT(pd_inb_end == pd_actual.pd_inb_end);

	copyStateToActual();
	pd_actual.fetchInputData(align, required);
	copyStateFromActual();

	p1 = (omni::ptr_arith_t)pd_inb_mkr;
	p2 = (omni::ptr_arith_t)pd_inb_end;

	if ((omni::ptr_arith_t)pd_remaining > (p2 - p1)) {
	  pd_remaining = pd_remaining - (p2 - p1);
	}
	else {
	  pd_inb_end   = (void*)(p1 + pd_remaining);
	  pd_remaining = 0;
	}
	return;
      }
      else {
	// End of chunk. Peek into the stream to see what comes next.
	CORBA::Long tag = peekChunkTag();
	if (tag < 0) {
	  // End of one or more values
	  endInputValue();
	}
	else if (tag == 0) {
	  // Zero value is reserved for future use.
	  OMNIORB_THROW(MARSHAL, MARSHAL_InvalidChunkedEncoding,
			(CORBA::CompletionStatus)completion());
	}
	else if (tag < 0x7fffff00) {
	  // Start of another chunk in this value
	  startInputChunk();
	}
	else {
	  // Start tag for a new value. Set the stream pointers so the
	  // caller can retrieve just the tag before we are called
	  // again.

	  // We should only be in this situation if the caller is asking
	  // for 4 octets, since they should be reading a tag.
	  if (required != 4)
	    OMNIORB_THROW(MARSHAL, MARSHAL_InvalidChunkedEncoding,
			  (CORBA::CompletionStatus)completion());

	  p1 = omni::align_to((omni::ptr_arith_t)pd_inb_mkr, align);
	  p2 = p1 + required;

	  // Given that we have already read the tag value, there _must_
	  // be enough space in the stream.
	  OMNIORB_ASSERT(p2 <= (omni::ptr_arith_t)pd_inb_end);
	  pd_inb_end = (void*)p2;

	  pd_inChunk  = 0;
	  pd_inHeader = 1;
	  pd_nestLevel++;
	  return;
	}
      }
    }
    else {
      startInputChunk();
    }
  }
}

_CORBA_Boolean
cdrValueChunkStream::
skipToNestedValue(_CORBA_Long level)
{
  omni::ptr_arith_t p1, p2;

  OMNIORB_ASSERT(!pd_inHeader);

  while (1) {
    if (pd_nestLevel < level) {
      return 0;
    }
    pd_inb_mkr = pd_inb_end;
    if (pd_inChunk) {
      if (pd_remaining) {
	// More data to come in this chunk
	copyStateToActual();
	pd_actual.fetchInputData(omni::ALIGN_1, 1);
	copyStateFromActual();

	p1 = (omni::ptr_arith_t)pd_inb_mkr;
	p2 = (omni::ptr_arith_t)pd_inb_end;

	if ((omni::ptr_arith_t)pd_remaining > (p2 - p1)) {
	  pd_remaining = pd_remaining - (p2 - p1);
	}
	else {
	  pd_inb_end   = (void*)(p1 + pd_remaining);
	  pd_remaining = 0;
	}
      }
      else {
	// End of chunk. Peek into the stream to see what comes next.
	CORBA::Long tag = peekChunkTag();
	if (tag < 0) {
	  // End of one or more values
	  endInputValue();
	}
	else if (tag == 0) {
	  // Zero value is reserved for future use.
	  OMNIORB_THROW(MARSHAL, MARSHAL_InvalidChunkedEncoding,
			(CORBA::CompletionStatus)completion());
	}
	else if (tag < 0x7fffff00) {
	  // Start of another chunk in this value
	  startInputChunk();
	}
	else {
	  p1 = omni::align_to((omni::ptr_arith_t)pd_inb_mkr, omni::ALIGN_4);
	  p2 = p1 + 4;

	  // Given that we have already read the tag value, there _must_
	  // be enough space in the stream.
	  OMNIORB_ASSERT(p2 <= (omni::ptr_arith_t)pd_inb_end);
	  pd_inb_end = (void*)p2;

	  pd_inChunk  = 0;
	  pd_inHeader = 1;
	  pd_nestLevel++;
	  return 1;
	}
      }
    }
    else {
      startInputChunk();
    }
  }
}

void
cdrValueChunkStream::
startInputChunk()
{
  CORBA::Long len = peekChunkTag();

  if (len <= 0) {
    // End of chunk -- chunk has zero length.
    len = 0;
    omniORB::logs(25, "Receive empty value chunk.");
  }
  else if (len >= 0x7fffff00) {
    // It's not the start of a chunk at all, but a nested value. Treat
    // it as if it was a zero-length chunk.
    len = 0;
    omniORB::logs(25, "Receive nested value instead of chunk length.");
  }
  else {
    len <<= pd_actual;

    if (omniORB::trace(25)) {
      omniORB::logger l;
      l << "Start reading value chunk. Length = " << len << ".\n";
    }
  }
  copyStateFromActual();

  omni::ptr_arith_t start = (omni::ptr_arith_t)pd_inb_mkr;
  omni::ptr_arith_t end   = (omni::ptr_arith_t)pd_inb_end;

  if ((omni::ptr_arith_t)len > (end - start)) {
    pd_remaining = len - (end - start);
  }
  else {
    pd_inb_end   = (void*)(start + len);
    pd_remaining = 0;
  }
  pd_inChunk = 1;
}

void
cdrValueChunkStream::
endInputValue()
{
  copyStateToActual();
  CORBA::Long tag;
  tag <<= pd_actual;
  copyStateFromActual();

  if (omniORB::trace(25)) {
    omniORB::logger l;
    l << "End reading value chunk. Nest level = " << -tag << ".\n";
  }

  if (tag >= 0)
    OMNIORB_THROW(MARSHAL, MARSHAL_InvalidChunkedEncoding,
		  (CORBA::CompletionStatus)completion());
  tag = -tag - 1;

  if (tag >= pd_nestLevel)
    OMNIORB_THROW(MARSHAL, MARSHAL_InvalidChunkedEncoding,
		  (CORBA::CompletionStatus)completion());

  pd_nestLevel = tag;
  pd_inChunk   = 0;
  pd_inb_end   = pd_inb_mkr;
}

_CORBA_Long
cdrValueChunkStream::
peekChunkTag()
{
  copyStateToActual();
  omni::ptr_arith_t p1, p2;
  while (1) {
    p1 = omni::align_to((omni::ptr_arith_t)pd_actual.pd_inb_mkr,
			omni::ALIGN_4);
    p2 = p1 + 4;
    if (p2 <= (omni::ptr_arith_t)pd_actual.pd_inb_end)
      break;
    pd_actual.fetchInputData(omni::ALIGN_4, 4);
  }
  copyStateFromActual();

  _CORBA_Long tag = *((_CORBA_Long*)p1);

  if (pd_unmarshal_byte_swap)
    return Swap32(tag);
  else
    return tag;
}

void
cdrValueChunkStream::
get_octet_array(_CORBA_Octet* b, int size, omni::alignment_t align)
{
  int orig_size = size;
  omni::ptr_arith_t p1, p2;

  p1 = omni::align_to((omni::ptr_arith_t)pd_inb_mkr, align);
  p2 = p1 + size;

  if (p2 <= (omni::ptr_arith_t)pd_inb_end) {
    memcpy((void*)b, (const void*)p1, size);
    pd_inb_mkr = (void*)p2;
    return;
  }

  if (pd_inHeader) {
    OMNIORB_ASSERT(!pd_inChunk);
    copyStateToActual();
    pd_actual.get_octet_array(b, size, align);
    copyStateFromActual();
    return;
  }

  // If we're not in a header, we should be in a chunk
  if (!pd_inChunk)
    OMNIORB_THROW(MARSHAL, MARSHAL_InvalidChunkedEncoding,
		  (CORBA::CompletionStatus)completion());

  // Copy as much as possible out of the buffer
  CORBA::Long inbuf = (omni::ptr_arith_t)pd_inb_end - p1;
  if (inbuf) {
    memcpy((void*)b, (const void*)p1, inbuf);
    size -= inbuf;
    b += inbuf;
    pd_inb_mkr = pd_inb_end;
  }

  if (pd_remaining) {
    // More octets left in this chunk (but not in the buffer)
    copyStateToActual();

    if (pd_remaining <= (_CORBA_ULong)size) {
      pd_actual.get_octet_array(b, pd_remaining, align);
      size -= pd_remaining;
      b += pd_remaining;
      pd_remaining = 0;

      copyStateFromActual();

      // Next read will start a new chunk
      pd_inb_end = pd_inb_mkr;
    }
    else {
      pd_actual.get_octet_array(b, size, align);
      pd_remaining -= size;

      copyStateFromActual();

      pd_inb_end = (void*)(((omni::ptr_arith_t)pd_inb_mkr) + pd_remaining);
    }
  }

  copyStateToActual();

  if (size == orig_size) {
    // If we have not yet read any data, we may reach here in a
    // situation that a chunk has just ended, but we have not yet read
    // the chunk end tag. That happens if an array of primitive types
    // follows a nested value, for example. In that case, we end the
    // value and continue reading the next chunk.
    CORBA::Long tag = peekChunkTag();
    if (tag < 0) {
      endInputValue();
      pd_inChunk = 1;
    }
  }

  while (size) {
    // More chunks to come
    CORBA::Long len;
    len <<= pd_actual;

    if (align == omni::ALIGN_8) {
      // If the alignment is 8, there may be 4 octets of padding after
      // the chunk length. In that case, we need to skip it and
      // subtract 4 from the chunk length that's available.
      p1 = (omni::ptr_arith_t)pd_actual.pd_inb_mkr;
      p2 = omni::align_to(p1, omni::ALIGN_8);
      if (p2 > p1)
	len -= 4;
    }

    if (len <= 0 || len >= 0x7fffff00) {
      OMNIORB_THROW(MARSHAL, MARSHAL_InvalidChunkedEncoding,
		    (CORBA::CompletionStatus)completion());
    }

    if (len < size) {
      pd_actual.get_octet_array(b, len, align);
      size -= len;
      b += len;
    }
    else {
      // Finish the read
      pd_actual.get_octet_array(b, size, align);
      len -= size;
      size = 0;

      // Sort out the input pointer
      copyStateFromActual();
      p1 = (omni::ptr_arith_t)pd_inb_mkr;
      p2 = p1 + len;
      if (p2 > (omni::ptr_arith_t)pd_inb_end)
	pd_remaining = p2 - (omni::ptr_arith_t)pd_inb_end;
      else
	pd_inb_end = (void*)p2;

      break;
    }
  }
}

void
cdrValueChunkStream::
skipInput(_CORBA_ULong size)
{
  _CORBA_ULong orig_size = size;
  omni::ptr_arith_t p1, p2;

  p1 = (omni::ptr_arith_t)pd_inb_mkr;
  p2 = p1 + size;
  if (p2 <= (omni::ptr_arith_t)pd_inb_end) {
    pd_inb_mkr = (void*)p2;
    return;
  }

  if (pd_inHeader) {
    OMNIORB_ASSERT(!pd_inChunk);
    copyStateToActual();
    pd_actual.skipInput(size);
    copyStateFromActual();
    return;
  }

  // If we're not in a header, we should be in a chunk
  if (!pd_inChunk)
    OMNIORB_THROW(MARSHAL, MARSHAL_InvalidChunkedEncoding,
		  (CORBA::CompletionStatus)completion());

  // Skip as much as possible from the buffer
  CORBA::Long inbuf = (omni::ptr_arith_t)pd_inb_end - p1;
  if (inbuf) {
    size -= inbuf;
    pd_inb_mkr = pd_inb_end;
  }

  if (pd_remaining) {
    // More octets left in this chunk
    copyStateToActual();
    pd_actual.skipInput(pd_remaining);
    size -= pd_remaining;
    pd_remaining = 0;
    copyStateFromActual();
  }

  copyStateToActual();

  if (size == orig_size) {
    // If we have not yet handled any data, we may reach here in a
    // situation that a chunk has just ended, but we have not yet read
    // the chunk end tag. In that case, we end the value and continue
    // reading the next chunk.
    CORBA::Long tag = peekChunkTag();
    if (tag < 0) {
      endInputValue();
      pd_inChunk = 1;
    }
  }

  while (size) {
    // More chunks to come
    CORBA::Long len;
    len <<= pd_actual;

    if (len <= 0 || len >= 0x7fffff00)
      OMNIORB_THROW(MARSHAL, MARSHAL_InvalidChunkedEncoding,
		    (CORBA::CompletionStatus)completion());

    if ((CORBA::ULong)len < size) {
      pd_actual.skipInput(len);
      size -= len;
    }
    else {
      // Finish the read
      pd_actual.skipInput(size);
      size = 0;

      // Sort out the input pointer
      copyStateFromActual();
      len -= size;
      p1 = (omni::ptr_arith_t)pd_inb_mkr;
      p2 = p1 + len;
      if (p2 > (omni::ptr_arith_t)pd_inb_end)
	pd_remaining = p2 - (omni::ptr_arith_t)pd_inb_end;
      else
	pd_inb_end = (void*)p2;

      break;
    }
  }
}

_CORBA_Boolean
cdrValueChunkStream::
checkInputOverrun(_CORBA_ULong itemSize,
		  _CORBA_ULong nItems,
		  omni::alignment_t align)
{
  copyStateToActual();
  return pd_actual.checkInputOverrun(itemSize, nItems, align);
}

_CORBA_Boolean
cdrValueChunkStream::
checkOutputOverrun(_CORBA_ULong itemSize,
		   _CORBA_ULong nItems,
		   omni::alignment_t align)
{
  copyStateToActual();
  return pd_actual.checkOutputOverrun(itemSize, nItems, align);
}

_CORBA_ULong
cdrValueChunkStream::currentInputPtr() const
{
  copyStateToActual();
  return pd_actual.currentInputPtr();
}

_CORBA_ULong
cdrValueChunkStream::currentOutputPtr() const
{
  copyStateToActual();
  return pd_actual.currentOutputPtr();
}

_CORBA_ULong
cdrValueChunkStream::completion()
{
  return pd_actual.completion();
}

void*
cdrValueChunkStream::ptrToClass(int* cptr)
{
  if (cptr == &cdrValueChunkStream::_classid)
    return (cdrValueChunkStream*)this;

  if (cptr == &cdrStream::_classid)
    return (cdrStream*)this;

  return 0;
}

int cdrValueChunkStream::_classid;


text:
app.config(['$stateProvider',
    function ($stateProvider) {

        $stateProvider
                .state('service', {
                    url: '/Service',
                    controller: 'SerCtrl',
                    templateUrl: '/locations/service/service.html'
                });
    }]);


text:
Low-TCB Linux Applications with SGX Enclaves

Please refer to the [Project Page](https://shwetasshinde24.github.io/Panoply) for documentation and setup details.

# Tor Case Study

## Compilation

### Go to the src directory of the case study

$ cd case-studies/tor/src/

### Ensure that you have all the necessary library files:

$ ls *.a

case-studies/tor/src/libcrypto.a
case-studies/tor/src/libevent.a
case-studies/tor/src/libevent_core.a
case-studies/tor/src/libevent_extra.a
case-studies/tor/src/libevent_openssl.a
case-studies/tor/src/libevent_pthreads.a
case-studies/tor/src/libssl.a
case-studies/tor/src/libz.a

### Compile the case study

$ make all

## Execution

### Start the Tor Node with the correct configuration files

$ ./app -f path_to_torrc_config_file

For example, you can start a chutney node with its custom configuration file

./app -f path_to_chutney/net/nodes/000a/torrc

## Setting up a Tor Network

Alternatively, you can setup your own Tor network, with custom configurations for nodes. We use Chutney for this purpose, similar to [OpenSGX Tor](https://github.com/sslab-gatech/opensgx/tree/master/Tor).

### Install Tor to generate all the default configuration files, and install the Tor client

$ sudo apt-get install libevent-dev

$ cd case-studies/tor/network-setup/tor-0.2.5.10

$ ./configure --disable-asciidoc

$ make

$ make install

### Create a Tor Network with Chutney

$ cd case-studies/tor/network-setup/chutney

$ ./chutney configure networks/testsuite

### Edit the Chutney configuration files
Change the value of RunAsDaemon flag from 1 to 0

$ vim case-studies/tor/network-setup/chutney/net/nodes/000a/torrc

Line 28: RunAsDaemon 0

### Launch the Tor network & Tor Client

Run each of the following commands in a new terminal

$ cd case-studies/tor/src/

$ ./app -f ../network-setup/chutney/net/nodes/000a/torrc

$ ./app -f ../network-setup/chutney/net/nodes/001a/torrc

$ ./app -f ../network-setup/chutney/net/nodes/002a/torrc

$ ./app -f ../network-setup/chutney/net/nodes/003r/torrc

$ ./app -f ../network-setup/chutney/net/nodes/004r/torrc

$ ./app -f ../network-setup/chutney/net/nodes/005r/torrc

$ tor -f ../network-setup/chutney/net/nodes/006c/torrc


text:
angular.module('cpWebApp')
    .controller('ModalInstanceCtrl', function ($scope, $modalInstance, $location) {

        $scope.ok = function () {
            $modalInstance.close($scope.newPlayList.name);
        };

        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
            $location.path("/player");
        };
    });


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent">

    <TableRow
        android:id="@+id/icon_chooser_dialog_imageview__row_1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:paddingBottom="10dp"
        android:gravity="center_horizontal">

        <ImageView
            android:id="@+id/icon_chooser_dialog_imageview_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:clickable="true"
            android:background="?android:selectableItemBackground"
            android:layout_weight="1"
            android:tag="white"
            />

        <ImageView
            android:id="@+id/icon_chooser_dialog_imageview_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:clickable="true"
            android:background="?android:selectableItemBackground"
            android:layout_weight="1"
            android:tag="yellow"
            />

        <ImageView
            android:id="@+id/icon_chooser_dialog_imageview_3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:clickable="true"
            android:background="?android:selectableItemBackground"
            android:layout_weight="1"
            android:tag="blue"
            />

        <ImageView
            android:id="@+id/icon_chooser_dialog_imageview_4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:clickable="true"
            android:background="?android:selectableItemBackground"
            android:layout_weight="1"
            android:tag="green"
            />

        <ImageView
            android:id="@+id/icon_chooser_dialog_imageview_5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:clickable="true"
            android:background="?android:selectableItemBackground"
            android:layout_weight="1"
            android:tag="red"
            />
    </TableRow>
</RelativeLayout>


text:
<?php

declare(strict_types=1);

namespace ShlinkioTest\Shlink\Core\Exception;

use PHPUnit\Framework\TestCase;
use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException;
use Shlinkio\Shlink\Core\Model\ShortUrlIdentifier;

class ShortUrlNotFoundExceptionTest extends TestCase
{
    /**
     * @test
     * @dataProvider provideMessages
     */
    public function properlyCreatesExceptionFromNotFoundShortCode(
        string $expectedMessage,
        string $shortCode,
        ?string $domain
    ): void {
        $expectedAdditional = ['shortCode' => $shortCode];
        if ($domain !== null) {
            $expectedAdditional['domain'] = $domain;
        }

        $e = ShortUrlNotFoundException::fromNotFound(new ShortUrlIdentifier($shortCode, $domain));

        $this->assertEquals($expectedMessage, $e->getMessage());
        $this->assertEquals($expectedMessage, $e->getDetail());
        $this->assertEquals('Short URL not found', $e->getTitle());
        $this->assertEquals('INVALID_SHORTCODE', $e->getType());
        $this->assertEquals(404, $e->getStatus());
        $this->assertEquals($expectedAdditional, $e->getAdditionalData());
    }

    public function provideMessages(): iterable
    {
        yield 'without domain' => [
            'No URL found with short code "abc123"',
            'abc123',
            null,
        ];
        yield 'with domain' => [
            'No URL found with short code "bar" for domain "foo"',
            'bar',
            'foo',
        ];
    }
}


text:
package main

import (
	"bufio"
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"time"

	ct "github.com/daviddengcn/go-colortext"
	"github.com/jpillora/backoff"
	"github.com/phrase/phraseapp-client/internal/paths"
	"github.com/phrase/phraseapp-client/internal/placeholders"
	"github.com/phrase/phraseapp-client/internal/print"
	"github.com/phrase/phraseapp-client/internal/spinner"
	"github.com/phrase/phraseapp-go/phraseapp"
)

type PushCommand struct {
	phraseapp.Config
	Wait               bool   `cli:"opt --wait desc='Wait for files to be processed'"`
	Branch             string `cli:"opt --branch"`
	UseLocalBranchName bool   `cli:"opt --use-local-branch-name desc='push from the branch with the name of your currently checked out branch (git or mercurial)'"`
}

func (cmd *PushCommand) Run() error {
	if cmd.Config.Debug {
		// suppresses content output
		cmd.Config.Debug = false
		Debug = true
	}

	client, err := newClient(cmd.Config.Credentials, cmd.Config.Debug)
	if err != nil {
		return err
	}

	sources, err := SourcesFromConfig(cmd.Config)
	if err != nil {
		return err
	}

	if err := sources.Validate(); err != nil {
		return err
	}

	formatMap, err := formatsByApiName(client)
	if err != nil {
		return fmt.Errorf("Error retrieving format list from PhraseApp: %s", err)
	}

	for _, source := range sources {
		formatName := source.GetFileFormat()
		if val, ok := formatMap[formatName]; ok {
			source.Format = val
		}

		if source.Format == nil {
			return fmt.Errorf("Format %q of source %q is not supported by PhraseApp!", formatName, source.File)
		}
	}

	projectsAffected := map[string]bool{}
	for _, source := range sources {
		projectsAffected[source.ProjectID] = true
	}

	branchName, err := usedBranchName(cmd.UseLocalBranchName, cmd.Branch)
	if err != nil {
		return err
	}
	cmd.Branch = branchName

	if cmd.Branch != "" {
		for projectID := range projectsAffected {
			_, err := client.BranchShow(projectID, cmd.Branch)
			if err != nil {
				if useLocalBranchName(cmd.UseLocalBranchName) {
					printCreateBranchQuestion(cmd.Branch)
					text, _ := bufio.NewReader(os.Stdin).ReadString('\n')

					if !isYes(strings.TrimSpace(text)) {
						return nil
					}
				}

				branchParams := &phraseapp.BranchParams{Name: &cmd.Branch}
				branch, _ := client.BranchCreate(projectID, branchParams)

				fmt.Println()

				taskResult := make(chan string, 1)
				taskErr := make(chan error, 1)

				fmt.Printf("Waiting for branch %s is created!", branch.Name)
				spinner.While(func() {
					branchCreateResult, err := getBranchCreateResult(client, projectID, branch)
					taskResult <- branchCreateResult
					taskErr <- err
				})
				fmt.Println()

				if err := <-taskErr; err != nil {
					return err
				}

				switch <-taskResult {
				case "success":
					print.Success("Successfully created branch %s", branch.Name)
				case "error":
					print.Failure("There was an error creating branch %s.", branch.Name)
				}
			}
		}
	}

	projectIdToLocales, err := LocalesForProjects(client, sources, cmd.Branch)
	if err != nil {
		return err
	}
	for _, source := range sources {
		val, ok := projectIdToLocales[LocaleCacheKey{source.ProjectID, cmd.Branch}]
		if ok {
			source.RemoteLocales = val
		}
	}

	for _, source := range sources {
		err := source.Push(client, cmd.Wait, cmd.Branch)
		if err != nil {
			return err
		}
	}

	return nil
}

func (source *Source) Push(client *phraseapp.Client, waitForResults bool, branch string) error {
	localeFiles, err := source.LocaleFiles()
	if err != nil {
		return err
	}

	for _, localeFile := range localeFiles {
		fmt.Printf("Uploading %s... ", localeFile.RelPath())

		if localeFile.shouldCreateLocale(source, branch) {
			localeDetails, err := source.createLocale(client, localeFile, branch)
			if err == nil {
				localeFile.ID = localeDetails.ID
				localeFile.Code = localeDetails.Code
				localeFile.Name = localeDetails.Name
			} else {
				fmt.Printf("failed to create locale: %s\n", err)
				continue
			}
		}

		upload, err := source.uploadFile(client, localeFile, branch)
		if err != nil {
			return err
		}

		if waitForResults {
			fmt.Println()

			taskResult := make(chan string, 1)
			taskErr := make(chan error, 1)

			fmt.Printf("Upload ID: %s, filename: %s succeeded. Waiting for your file to be processed... ", upload.ID, upload.Filename)
			spinner.While(func() {
				result, err := getUploadResult(client, source.ProjectID, upload, branch)
				taskResult <- result
				taskErr <- err
			})
			fmt.Println()

			if err := <-taskErr; err != nil {
				return err
			}

			switch <-taskResult {
			case "success":
				print.Success("Successfully uploaded and processed %s.", localeFile.RelPath())
			case "error":
				print.Failure("There was an error processing %s. Your changes were not saved online.", localeFile.RelPath())
			}
		} else {
			fmt.Println("done!")
			fmt.Printf("Check upload ID: %s, filename: %s for information about processing results.\n", upload.ID, upload.Filename)
		}

		if Debug {
			fmt.Fprintln(os.Stderr, strings.Repeat("-", 10))
		}
	}

	return nil
}

func formatsByApiName(client *phraseapp.Client) (map[string]*phraseapp.Format, error) {
	formats, err := client.FormatsList(1, 25)
	if err != nil {
		return nil, err
	}
	formatMap := map[string]*phraseapp.Format{}
	for _, format := range formats {
		formatMap[format.ApiName] = format
	}
	return formatMap, nil
}

// Return all locale files from disk that match the source pattern.
func (source *Source) LocaleFiles() (LocaleFiles, error) {
	filePaths, err := paths.Glob(placeholders.ToGlobbingPattern(source.File))
	if err != nil {
		return nil, err
	}

	var localeFiles LocaleFiles
	for _, path := range filePaths {
		if paths.IsPhraseAppYmlConfig(path) {
			continue
		}

		localeFile := new(LocaleFile)
		localeFile.fillFromPath(path, source.File)

		localeFile.Path, err = filepath.Abs(path)
		if err != nil {
			return nil, err
		}

		locale := source.getRemoteLocaleForLocaleFile(localeFile)
		// TODO: sinnvoll?
		if locale != nil {
			localeFile.ExistsRemote = true
			localeFile.Code = locale.Code
			localeFile.Name = locale.Name
			localeFile.ID = locale.ID
		}

		if Debug {
			fmt.Printf(
				"Code:%q, Name:%q, ID:%q, Tag:%q\n",
				localeFile.Code, localeFile.Name, localeFile.ID, localeFile.Tag,
			)
		}

		localeFiles = append(localeFiles, localeFile)
	}

	if len(localeFiles) == 0 {
		abs, err := filepath.Abs(source.File)
		if err != nil {
			abs = source.File
		}
		return nil, fmt.Errorf("Could not find any files on your system that matches: '%s'", abs)
	}

	return localeFiles, nil
}

func (source *Source) getRemoteLocaleForLocaleFile(localeFile *LocaleFile) *phraseapp.Locale {
	candidates := source.RemoteLocales

	filterApplied := false

	filter := func(cands []*phraseapp.Locale, preCond string, pred func(cand *phraseapp.Locale) bool) []*phraseapp.Locale {
		if preCond == "" {
			return cands
		}
		filterApplied = true
		tmpCands := []*phraseapp.Locale{}
		for _, cand := range cands {
			if pred(cand) {
				tmpCands = append(tmpCands, cand)
			}
		}
		return tmpCands
	}

	localeName := source.replacePlaceholderInParams(localeFile)
	if localeName != "" {
		// This means the name can contain the value specified in LocaleID, with
		// `<locale_code>` being substituted by the value of the currently handled
		// localeFile (like push only locales with name `en-US`).
		candidates = filter(candidates, localeName, func(cand *phraseapp.Locale) bool {
			return strings.Contains(cand.Name, localeName)
		})
	} else {
		localeID := source.GetLocaleID()
		candidates = filter(candidates, localeID, func(cand *phraseapp.Locale) bool {
			return cand.Name == localeID || cand.ID == localeID
		})
	}

	candidates = filter(candidates, localeFile.Name, func(cand *phraseapp.Locale) bool {
		return cand.Name == localeFile.Name
	})

	candidates = filter(candidates, localeFile.Code, func(cand *phraseapp.Locale) bool {
		return cand.Code == localeFile.Code
	})

	// If no filter was applied the candidates list still contains all remote
	// locales, while actually nothing matches.
	if !filterApplied {
		return nil
	}

	switch len(candidates) {
	case 0:
		return nil
	case 1:
		return candidates[0]
	default:
		// TODO I guess this should return an error, as this is a problem.
		return candidates[0]
	}
}

func (localeFile *LocaleFile) fillFromPath(path, pattern string) {
	path = filepath.ToSlash(path)
	pathStart, patternStart, pathEnd, patternEnd, err := paths.SplitAtDirGlobOperator(path, pattern)
	if err != nil {
		print.Error(err)
		return
	}

	fillFrom := func(path, pattern string) {
		params, err := placeholders.Resolve(path, pattern)
		if err != nil {
			print.Error(err)
			return
		}

		for placeholder, value := range params {
			switch placeholder {
			case "locale_code":
				localeFile.Code = value
			case "locale_name":
				localeFile.Name = value
			case "tag":
				localeFile.Tag = value
			}
		}
	}

	fillFrom(pathStart, patternStart)
	fillFrom(pathEnd, patternEnd)
}

func (localeFile *LocaleFile) shouldCreateLocale(source *Source, branch string) bool {
	if localeFile.ExistsRemote {
		return false
	}

	if source.Format.IncludesLocaleInformation {
		return false
	}

	// we could not find an existing locale in PhraseApp
	// if a locale_name or locale_code was provided by the placeholder logic
	// we assume that it should be created
	// every other source should be uploaded and validated in uploads#create
	return (localeFile.Name != "" || localeFile.Code != "")
}

func getUploadResult(client *phraseapp.Client, projectID string, upload *phraseapp.Upload, branch string) (result string, err error) {
	b := &backoff.Backoff{
		Min:    500 * time.Millisecond,
		Max:    10 * time.Second,
		Factor: 2,
		Jitter: true,
	}

	for ; result != "success" && result != "error"; result = upload.State {
		time.Sleep(b.Duration())
		uploadShowParams := &phraseapp.UploadShowParams{Branch: &branch}
		upload, err = client.UploadShow(projectID, upload.ID, uploadShowParams)
		if err != nil {
			break
		}
	}

	return
}

func getBranchCreateResult(client *phraseapp.Client, projectID string, branch *phraseapp.Branch) (result string, err error) {
	b := &backoff.Backoff{
		Min:    500 * time.Millisecond,
		Max:    10 * time.Second,
		Factor: 2,
		Jitter: true,
	}

	for ; result != "success" && result != "error"; result = branch.State {
		time.Sleep(b.Duration())
		branch, err = client.BranchShow(projectID, branch.Name)
		if err != nil {
			break
		}
	}

	return
}

func printCreateBranchQuestion(branch string) {
	fmt.Printf("\nYou have currently checked out the branch '")
	ct.ChangeColor(ct.Green, false, ct.None, false)
	fmt.Printf("%s", branch)
	ct.ResetColor()
	fmt.Printf("'.\nThere currently is no branch in PhraseApp with this name.\n\n")
	fmt.Printf("Should we create a new branch in PhraseApp with the same name and push to it? [y/N]: ")
}

func isYes(text string) bool {
	return text == "y" ||
		text == "Y" ||
		text == "yes" ||
		text == "Yes" ||
		text == "YES"
}


text:
class MainController < UIViewController

  def viewDidLoad
    setupVideoBackground()
    setupPaintForeground()
  end

  def setupVideoBackground
    @vImagePreview = UIView.alloc.initWithFrame(self.view.bounds)
    self.view.addSubview(@vImagePreview)

    @session = AVCaptureSession.alloc.init
    @session.sessionPreset = AVCaptureSessionPresetLow

    viewLayer = @vImagePreview.layer;

    captureVideoPreviewLayer = AVCaptureVideoPreviewLayer.alloc.initWithSession(@session)

    captureVideoPreviewLayer.frame = @vImagePreview.bounds

    @vImagePreview.layer.addSublayer(captureVideoPreviewLayer)

    device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)

    error_ptr = Pointer.new(:object)

    input = AVCaptureDeviceInput.deviceInputWithDevice(device, error: error_ptr)

    if input == nil
      error = error_ptr[0]
      p "Error => #{error}"
    end

    @session.addInput(input)

    @session.startRunning()
  end

  def setupPaintForeground
    @paint = PaintView.alloc.initWithFrame(self.view.bounds)
    self.view.addSubview(@paint)
  end

  def canBecomeFirstResponder
    true
  end

  def motionEnded(motion, withEvent:event)
    @paint.eraseContent if motion == UIEventSubtypeMotionShake
  end

end


text:
DCML.registerTag("Panel", {
    childHandler = function( self, element )
        self.nodesToAdd = DCML.parse( element.content )
    end;
    argumentType = {
        X = "number";
        Y = "number";
        width = "number";
        height = "number";
        backgroundColour = "colour";
        textColour = "colour";
    },
    callbackGenerator = "#generateNodeCallback";
})

class "Panel" extends "NodeScrollContainer" {
    width = 2;
    height = 2;
    __drawChildrenToCanvas = true;
}

function Panel:initialise( ... )
    local X, Y, width, height = ParseClassArguments( self, { ... }, {
        { "X", "number" },
        { "Y", "number" },
        { "width", "number" },
        { "height", "number" }
    }, false, true )

    self.super( X, Y, width or self.width, height or self.height ) -- this will call the Node.initialise because the super inherits that from the other super and so on...

    self:__overrideMetaMethod("__add", function( a, b )
        if classLib.typeOf(a, "Panel", true) then
            if classLib.isInstance( b ) and b.__node then
                return self:addNode( b )
            else
                return error("Invalid right hand assignment. Should be instance of DynaCode node. "..tostring( b ))
            end
        else
            return error("Invalid left hand assignment. Should be instance of Panel. "..tostring( a ))
        end
    end)
end


text:
<snippet id='formatted-string-button-html'/>
<snippet id='formatted-string-button-css'/>


text:
'use strict';

/**
 * The `LastScreenController` simply posts the object in `TrialData.data` to
 * the `/api/trials` API endpoint on the server to be written to a file.
 *
 * @class Angular.LastScreenController
 * @see Angular.TrialData
 * @see Node.module:TrialServerRoutes
 * @see Node.module:TrialServerController
 */

angular.module('core').controller(
    'LastScreenController',
    [
        '$scope',
        'TrialData',
        '$http',
        '$log',
        function($scope, TrialData, $http, $log) {

            $log.debug('Loading LastScreenController.');

            // Send TrialData.data to the backend
            $http
                .post('/api/trials', TrialData.toCompact())
                .catch(function(response) {
                    var errorMessage = 'The POST to /api/trials failed.';
                    $log.error(errorMessage, response);
                    throw new Error(errorMessage);
                });
        }
    ]);


text:
package report

/* Generic SQL funcs for reports */

import (
	"database/sql"
	"fmt"
	"github.com/ctdk/goiardi/config"
	"github.com/ctdk/goiardi/datastore"
	"log"
	"time"
)

func checkForReportSQL(dbhandle datastore.Dbhandle, runID string) (bool, error) {
	var f int
	var sqlStmt string
	if config.Config.UseMySQL {
		sqlStmt = "SELECT count(*) AS c FROM reports WHERE run_id = ?"
	} else if config.Config.UsePostgreSQL {
		sqlStmt = "SELECT count(*) AS c FROM goiardi.reports WHERE run_id = $1"
	}
	stmt, err := dbhandle.Prepare(sqlStmt)
	if err != nil {
		return false, err
	}
	defer stmt.Close()
	err = stmt.QueryRow(runID).Scan(&f)
	if err != nil {
		if err == sql.ErrNoRows {
			return false, nil
		}
		return false, err
	}
	if f > 0 {
		return true, nil
	}
	return false, nil
}

func (r *Report) fillReportFromSQL(row datastore.ResRow) error {
	if config.Config.UseMySQL {
		return r.fillReportFromMySQL(row)
	} else if config.Config.UsePostgreSQL {
		return r.fillReportFromPostgreSQL(row)
	}

	return nil
}

func getReportSQL(runID string) (*Report, error) {
	r := new(Report)
	var sqlStmt string
	if config.Config.UseMySQL {
		sqlStmt = "SELECT run_id, start_time, end_time, total_res_count, status, run_list, resources, data, node_name FROM reports WHERE run_id = ?"
	} else if config.Config.UsePostgreSQL {
		sqlStmt = "SELECT run_id, start_time, end_time, total_res_count, status, run_list, resources, data, node_name FROM goiardi.reports WHERE run_id = $1"
	}

	stmt, err := datastore.Dbh.Prepare(sqlStmt)
	if err != nil {
		return nil, err
	}
	defer stmt.Close()
	row := stmt.QueryRow(runID)
	err = r.fillReportFromSQL(row)
	if err != nil {
		return nil, err
	}
	return r, nil
}

func (r *Report) deleteSQL() error {
	tx, err := datastore.Dbh.Begin()
	if err != nil {
		return err
	}

	var sqlStmt string
	if config.Config.UseMySQL {
		sqlStmt = "DELETE FROM reports WHERE run_id = ?"
	} else if config.Config.UsePostgreSQL {
		sqlStmt = "DELETE FROM goiardi.reports WHERE run_id = $1"
	}

	_, err = tx.Exec(sqlStmt, r.RunID)
	if err != nil {
		terr := tx.Rollback()
		if terr != nil {
			err = fmt.Errorf("deleting report %s had an error '%s', and then rolling back the transaction gave another error '%s'", r.RunID, err.Error(), terr.Error())
		}
		return err
	}
	tx.Commit()
	return nil
}

func getListSQL() []string {
	var reportList []string

	var sqlStmt string
	if config.Config.UseMySQL {
		sqlStmt = "SELECT run_id FROM reports"
	} else if config.Config.UsePostgreSQL {
		sqlStmt = "SELECT run_id FROM goiardi.reports"
	}

	rows, err := datastore.Dbh.Query(sqlStmt)
	if err != nil {
		if err != sql.ErrNoRows {
			log.Fatal(err)
		}
		rows.Close()
		return reportList
	}
	for rows.Next() {
		var runID string
		err = rows.Scan(&runID)
		if err != nil {
			log.Fatal(err)
		}
		reportList = append(reportList, runID)
	}
	rows.Close()
	if err = rows.Err(); err != nil {
		log.Fatal(err)
	}
	return reportList
}

func getReportListSQL(from, until time.Time, retrows int, status string) ([]*Report, error) {
	var reports []*Report
	var sqlStmt string

	if status == "" {
		if config.Config.UseMySQL {
			sqlStmt = "SELECT run_id, start_time, end_time, total_res_count, status, run_list, resources, data, node_name FROM reports WHERE start_time >= ? AND start_time <= ? LIMIT ?"
		} else if config.Config.UsePostgreSQL {
			sqlStmt = "SELECT run_id, start_time, end_time, total_res_count, status, run_list, resources, data, node_name FROM goiardi.reports WHERE start_time >= $1 AND start_time <= $2 LIMIT $3"
		}
	} else {
		if config.Config.UseMySQL {
			sqlStmt = "SELECT run_id, start_time, end_time, total_res_count, status, run_list, resources, data, node_name FROM reports WHERE start_time >= ? AND start_time <= ? AND status = ? LIMIT ?"
		} else if config.Config.UsePostgreSQL {
			sqlStmt = "SELECT run_id, start_time, end_time, total_res_count, status, run_list, resources, data, node_name FROM goiardi.reports WHERE start_time >= $1 AND start_time <= $2 AND status = $3 LIMIT $4"
		}
	}

	stmt, err := datastore.Dbh.Prepare(sqlStmt)
	if err != nil {
		return nil, err
	}
	defer stmt.Close()
	var rows *sql.Rows
	var rerr error

	if status == "" {
		rows, rerr = stmt.Query(from, until, retrows)
	} else {
		rows, rerr = stmt.Query(from, until, status, retrows)
	}
	if rerr != nil {
		if rerr == sql.ErrNoRows {
			return reports, nil
		}
		return nil, rerr
	}
	for rows.Next() {
		r := new(Report)
		err = r.fillReportFromSQL(rows)
		if err != nil {
			rows.Close()
			return nil, err
		}
		reports = append(reports, r)
	}
	rows.Close()
	if err = rows.Err(); err != nil {
		return nil, err
	}
	return reports, nil
}

func getNodeListSQL(nodeName string, from, until time.Time, retrows int, status string) ([]*Report, error) {
	var reports []*Report

	var sqlStmt string
	if status == "" {
		if config.Config.UseMySQL {
			sqlStmt = "SELECT run_id, start_time, end_time, total_res_count, status, run_list, resources, data, node_name FROM reports WHERE node_name = ? AND start_time >= ? AND start_time <= ? LIMIT ?"
		} else if config.Config.UsePostgreSQL {
			sqlStmt = "SELECT run_id, start_time, end_time, total_res_count, status, run_list, resources, data, node_name FROM goiardi.reports WHERE node_name = $1 AND start_time >= $2 AND start_time <= $3 LIMIT $4"
		}
	} else {
		if config.Config.UseMySQL {
			sqlStmt = "SELECT run_id, start_time, end_time, total_res_count, status, run_list, resources, data, node_name FROM reports WHERE node_name = ? AND start_time >= ? AND start_time <= ? AND status = ? LIMIT ?"
		} else if config.Config.UsePostgreSQL {
			sqlStmt = "SELECT run_id, start_time, end_time, total_res_count, status, run_list, resources, data, node_name FROM goiardi.reports WHERE node_name = $1 AND start_time >= $2 AND start_time <= $3 AND status = $4 LIMIT $5"
		}
	}

	stmt, err := datastore.Dbh.Prepare(sqlStmt)
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	var rows *sql.Rows
	var rerr error
	if status == "" {
		rows, rerr = stmt.Query(nodeName, from, until, retrows)
	} else {
		rows, rerr = stmt.Query(nodeName, from, until, status, retrows)
	}
	if rerr != nil {
		if rerr == sql.ErrNoRows {
			return reports, nil
		}
		return nil, rerr
	}
	for rows.Next() {
		r := new(Report)
		err = r.fillReportFromSQL(rows)
		if err != nil {
			rows.Close()
			return nil, err
		}
		reports = append(reports, r)
	}
	rows.Close()
	if err = rows.Err(); err != nil {
		return nil, err
	}
	return reports, nil
}

func getReportsSQL() []*Report {
	var reports []*Report

	var sqlStmt string
	if config.Config.UseMySQL {
		sqlStmt = "SELECT run_id, start_time, end_time, total_res_count, status, run_list, resources, data, node_name FROM reports"
	} else if config.Config.UsePostgreSQL {
		sqlStmt = "SELECT run_id, start_time, end_time, total_res_count, status, run_list, resources, data, node_name FROM goiardi.reports"
	}

	stmt, err := datastore.Dbh.Prepare(sqlStmt)
	if err != nil {
		log.Fatal(err)
	}
	defer stmt.Close()
	rows, rerr := stmt.Query()
	if rerr != nil {
		if rerr == sql.ErrNoRows {
			return reports
		}
		log.Fatal(rerr)
	}
	for rows.Next() {
		r := new(Report)
		err = r.fillReportFromSQL(rows)
		if err != nil {
			rows.Close()
			log.Fatal(err)
		}
		reports = append(reports, r)
	}
	rows.Close()
	if err = rows.Err(); err != nil {
		log.Fatal(err)
	}
	return reports
}


text:
@interface NCCKeychainManager : NSObject

+ (instancetype)managerWithService:(NSString *)service;

- (BOOL)saveCredentials:(NSDictionary *)credentials forUser:(NSString *)username;
- (BOOL)deleteCredentialsForUser:(NSString *)username;
- (NSDictionary *)credentialsForUser:(NSString *)username;
- (BOOL)removeAllCredentialsForServer;

@end


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

export interface SaveData {
  label: string;
  variables: any;
  logs: Log[];
  description?: string;
}


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

package cmd

import (
	"os"
	"path/filepath"
	"strings"

	"github.com/minio/mc/pkg/probe"
)

// migrateSession migrates all previous migration to latest.
func migrateSession() {
	// We no longer support sessions older than v5. They will be removed.
	migrateSessionV5ToV6()

	// Migrate V6 to V7.
	migrateSessionV6ToV7()

	// Migrate V7 to V8
	migrateSessionV7ToV8()
}

// createSessionDir - create session directory.
func createSessionDir() *probe.Error {
	sessionDir, err := getSessionDir()
	if err != nil {
		return err.Trace()
	}

	if e := os.MkdirAll(sessionDir, 0700); e != nil {
		return probe.NewError(e)
	}
	return nil
}

// getSessionDir - get session directory.
func getSessionDir() (string, *probe.Error) {
	configDir, err := getMcConfigDir()
	if err != nil {
		return "", err.Trace()
	}

	sessionDir := filepath.Join(configDir, globalSessionDir)
	return sessionDir, nil
}

// isSessionDirExists - verify if session directory exists.
func isSessionDirExists() bool {
	sessionDir, err := getSessionDir()
	fatalIf(err.Trace(), "Unable to determine session folder.")

	if _, e := os.Stat(sessionDir); e != nil {
		return false
	}
	return true
}

// getSessionFile - get current session file.
func getSessionFile(sid string) (string, *probe.Error) {
	sessionDir, err := getSessionDir()
	if err != nil {
		return "", err.Trace()
	}

	sessionFile := filepath.Join(sessionDir, sid+".json")
	return sessionFile, nil
}

// isSessionExists verifies if given session exists.
func isSessionExists(sid string) bool {
	sessionFile, err := getSessionFile(sid)
	fatalIf(err.Trace(sid), "Unable to determine session filename for `"+sid+"`.")

	if _, e := os.Stat(sessionFile); e != nil {
		return false
	}

	return true // Session exists.
}

// getSessionDataFile - get session data file for a given session.
func getSessionDataFile(sid string) (string, *probe.Error) {
	sessionDir, err := getSessionDir()
	if err != nil {
		return "", err.Trace()
	}

	sessionDataFile := filepath.Join(sessionDir, sid+".data")
	return sessionDataFile, nil
}

// getSessionIDs - get all active sessions.
func getSessionIDs() (sids []string) {
	sessionDir, err := getSessionDir()
	fatalIf(err.Trace(), "Unable to access session folder.")

	sessionList, e := filepath.Glob(sessionDir + "/*.json")
	fatalIf(probe.NewError(e), "Unable to access session folder `"+sessionDir+"`.")

	for _, path := range sessionList {
		sids = append(sids, strings.TrimSuffix(filepath.Base(path), ".json"))
	}
	return sids
}

// removeSessionFile - remove the session file, ending with .json
func removeSessionFile(sid string) {
	sessionFile, err := getSessionFile(sid)
	if err != nil {
		return
	}
	os.Remove(sessionFile)
}

// removeSessionDataFile - remove the session data file, ending with .data
func removeSessionDataFile(sid string) {
	dataFile, err := getSessionDataFile(sid)
	if err != nil {
		return
	}
	os.Remove(dataFile)
}


text:
require 'spec_helper'

describe 'expect_json_types optional' do
  it 'should test optional nested hash when exists' do
    mock_get('simple_nested_path')
    get '/simple_nested_path'
    expect_json_types('address.coordinates', optional(lattitude: :float, longitutde: :float))
  end

  it 'should allow optional nested hash' do
    mock_get('simple_path_get')
    get '/simple_path_get'
    expect_json_types('address.coordinates', optional(lattitude: :float, longitutde: :float))
  end
end


text:
#include "third_party/blink/renderer/core/dom/document.h"

#include "base/auto_reset.h"
#include "base/metrics/histogram_functions.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_union_string_trustedhtml.h"
#include "third_party/blink/renderer/core/dom/events/scoped_event_queue.h"
#include "third_party/blink/renderer/core/editing/commands/editing_commands_utilities.h"
#include "third_party/blink/renderer/core/editing/commands/editor_command.h"
#include "third_party/blink/renderer/core/editing/editing_tri_state.h"
#include "third_party/blink/renderer/core/editing/editor.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/web_feature.h"
#include "third_party/blink/renderer/core/html/forms/text_control_element.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/trustedtypes/trusted_html.h"
#include "third_party/blink/renderer/core/trustedtypes/trusted_types_util.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"

namespace blink {

namespace {

EditorCommand GetCommand(Document* document, const String& command_name) {
  LocalFrame* frame = document->GetFrame();
  if (!frame || frame->GetDocument() != document)
    return EditorCommand();

  document->UpdateStyleAndLayoutTree();
  return frame->GetEditor().CreateCommand(command_name,
                                          EditorCommandSource::kDOM);
}

// Trusted Types requires that HTML (or Script, or script URLs) to be
// inserted into a Document go through a Trusted Types check first. This
// is a slightly awkward fit for execCommand API structure, which effectively
// dispatches to very different code based on its command name. Here, we'll
// check whether we need to run a Trusted Types check in the first place, and
// will also run the check if necessary.
String TrustedTypesCheck(Document* document,
                         const EditorCommand& editor_command,
                         const V8UnionStringOrTrustedHTML* value,
                         ExceptionState& exception_state) {
  // If we receive null or the value parameter is missing, then there's nothing
  // to check.
  if (!value)
    return g_empty_string;

  // TrustedHTML values always pass.
  if (value->IsTrustedHTML())
    return value->GetAsTrustedHTML()->toString();

  // We received a plain string. Most editor commands won't read the value as
  // HTML. Those commands can pass.
  DCHECK(value->IsString());
  if (!editor_command.IsValueInterpretedAsHTML())
    return value->GetAsString();

  // We received plain string, and it's one of the commands of interest.
  // Run the TT check.
  return TrustedTypesCheckForExecCommand(
      value->GetAsString(), document->GetExecutionContext(), exception_state);
}

}  // namespace

bool Document::execCommand(const String& command_name,
                           bool unused_bool,
                           const String& value,
                           ExceptionState& exception_state) {
  V8UnionStringOrTrustedHTML tmp(value);
  return execCommand(command_name, unused_bool, &tmp, exception_state);
}

bool Document::execCommand(const String& command_name,
                           bool,
                           const V8UnionStringOrTrustedHTML* value,
                           ExceptionState& exception_state) {
  if (!IsHTMLDocument() && !IsXHTMLDocument()) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kInvalidStateError,
        "execCommand is only supported on HTML documents.");
    return false;
  }
  if (FocusedElement() && IsTextControl(*FocusedElement()))
    UseCounter::Count(*this, WebFeature::kExecCommandOnInputOrTextarea);

  // We don't allow recursive |execCommand()| to protect against attack code.
  // Recursive call of |execCommand()| could be happened by moving iframe
  // with script triggered by insertion, e.g. <iframe src="javascript:...">
  // <iframe onload="...">. This usage is valid as of the specification
  // although, it isn't common use case, rather it is used as attack code.
  if (is_running_exec_command_) {
    String message =
        "We don't execute document.execCommand() this time, because it is "
        "called recursively.";
    AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>(
        mojom::ConsoleMessageSource::kJavaScript,
        mojom::ConsoleMessageLevel::kWarning, message));
    return false;
  }
  base::AutoReset<bool> execute_scope(&is_running_exec_command_, true);

  // Postpone DOM mutation events, which can execute scripts and change
  // DOM tree against implementation assumption.
  EventQueueScope event_queue_scope;
  TidyUpHTMLStructure(*this);
  const EditorCommand editor_command = GetCommand(this, command_name);

  String checked_value =
      TrustedTypesCheck(this, editor_command, value, exception_state);
  if (exception_state.HadException())
    return false;

  base::UmaHistogramSparse("WebCore.Document.execCommand",
                           editor_command.IdForHistogram());
  return editor_command.Execute(checked_value);
}

bool Document::queryCommandEnabled(const String& command_name,
                                   ExceptionState& exception_state) {
  if (!IsHTMLDocument() && !IsXHTMLDocument()) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kInvalidStateError,
        "queryCommandEnabled is only supported on HTML documents.");
    return false;
  }

  return GetCommand(this, command_name).IsEnabled();
}

bool Document::queryCommandIndeterm(const String& command_name,
                                    ExceptionState& exception_state) {
  if (!IsHTMLDocument() && !IsXHTMLDocument()) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kInvalidStateError,
        "queryCommandIndeterm is only supported on HTML documents.");
    return false;
  }

  return GetCommand(this, command_name).GetState() == EditingTriState::kMixed;
}

bool Document::queryCommandState(const String& command_name,
                                 ExceptionState& exception_state) {
  if (!IsHTMLDocument() && !IsXHTMLDocument()) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kInvalidStateError,
        "queryCommandState is only supported on HTML documents.");
    return false;
  }

  return GetCommand(this, command_name).GetState() == EditingTriState::kTrue;
}

bool Document::queryCommandSupported(const String& command_name,
                                     ExceptionState& exception_state) {
  if (!IsHTMLDocument() && !IsXHTMLDocument()) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kInvalidStateError,
        "queryCommandSupported is only supported on HTML documents.");
    return false;
  }

  return GetCommand(this, command_name).IsSupported();
}

String Document::queryCommandValue(const String& command_name,
                                   ExceptionState& exception_state) {
  if (!IsHTMLDocument() && !IsXHTMLDocument()) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kInvalidStateError,
        "queryCommandValue is only supported on HTML documents.");
    return "";
  }

  return GetCommand(this, command_name).Value();
}

}  // namespace blink


text:
describe("Further Information Form", function () {

  var formWithNoErrors =
    '<form id="further-information" novalidate="novalidate">' +
    '
' +
    '' +
    'Enter your National Insurance number' +
    '' +
    '<input required="required" pattern="^pear$" type="text" id="cycle_three_attribute_cycle_three_data" data-msg="validation message">' +
    '
' +
    '</form>';

  var furtherInformationForm;
  var $dom;

  function submitForm() {
    furtherInformationForm.triggerHandler('submit');
  }

  function expectNoError() {
    expect(furtherInformationForm.find('.error, .govuk-error-message').length).toBe(0);
  }

  beforeEach(function () {
    $dom = $('
' + formWithNoErrors + '
');
    $(document.body).append($dom);
    GOVUK.validation.init();
    GOVUK.furtherInformation.init();
    furtherInformationForm = GOVUK.furtherInformation.$form;
  });

  afterEach(function () {
    $dom.remove();
  });

  it("should have no errors on initialising the form.", function () {
    expect(furtherInformationForm.find('.form-group-error').length).toBe(0);
  });

  it("should have errors on submit when no details entered.", function () {
    submitForm();
    expect(furtherInformationForm.find('.govuk-error-message').eq(0).text()).toBe('validation message');
  });

  it("should have errors on submit when non-matching details entered.", function () {
    furtherInformationForm.find('input').val('banana');
    submitForm();
    expect(furtherInformationForm.find('.govuk-error-message').eq(0).text()).toBe('validation message');
  });

  it("should have no errors with correct details", function () {
    furtherInformationForm.find('input').val('pear');
    submitForm();
    expectNoError();
  });
});