text:
import {RouteConfig, setModuleLoader} from 'angular2less';
import {AsyncRoute} from 'angular2/router';

describe('RouteConfig decorator', function() {
  let TestApp, route, loadModule;

  beforeEach(function() {
    route = { path: '/test', name: 'Test', componentId: 'core/app' };
    loadModule = spy(() => new Promise(function() {}));
    TestApp = function TestApp(){}
    setModuleLoader(loadModule);
  });

  it('throws exception if "componentId" is missed', function() {
    expect(function() {
      RouteConfig([{}]);
    }).to.throw(Error);
  });

  it('wraps routes in AsyncRoute', function() {
    let routes = defineRoutes([route], TestApp);

    expect(routes[0]).to.be.instanceof(AsyncRoute);
  });

  it('invokes "loadModule" with "componentId" as an argument when route resolves the component', function() {
    let routes = defineRoutes([route], TestApp);

    routes[0].loader();

    expect(loadModule).to.have.been.called.with(route.componentId);
  });

  function defineRoutes(routes, App) {
    RouteConfig(routes)(App);
    let annotations = Reflect.getMetadata('annotations', App);

    return annotations[0].configs;
  }
})


text:
<!--
  ~ Copyright 2014 toxbee.se
  ~
  ~ 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.
  -->
<resources>

    <string name="title_activity_alarm_settings">Alarm</string>

    <!-- Menu strings -->
    <string name="menu_set_alarm_time">Set time</string>
    <string name="menu_set_alarm_countdown">Set countdown</string>

    <!-- Strings related to Settings -->

    <string name="pref_alarm_time">Time</string>
    <string name="pref_alarm_name">Name</string>
    <string name="pref_alarm_default_name">Untitled Alarm</string>
    <string name="pref_alarm_enabled_days">Days</string>
    <string name="general_category_title">General</string>
    <string name="misc_category_title">Miscellaneous</string>
    <string name="ringer_category_title">Ringtone</string>

    <string-array name="week_days">
        <item>Monday</item>
        <item>Tuesday</item>
        <item>Wednesday</item>
        <item>Thursday</item>
        <item>Friday</item>
        <item>Saturday</item>
        <item>Sunday</item>
    </string-array>
    <string-array name="default_week_days">
        <item>true</item>
        <item>true</item>
        <item>true</item>
        <item>true</item>
        <item>true</item>
        <item>true</item>
        <item>true</item>
    </string-array>

    <string name="pref_alarm_repeat">Repeat</string>
    <string name="pref_delete_alarm">Delete this alarm</string>
    <string name="pref_alarm_ringtone">Ringtone</string>
    <string name="pref_alarm_vibration">Vibration</string>
    <string name="pref_challenge">Challenges</string>
    <string name="alarm_settings_action_remove">Delete</string>
    <string name="alarm_settings_action_toggle">Toggle</string>
    <string name="pref_alarm_snooze_enabled">Enable snooze</string>
    <string name="pref_alarm_snooze_time">Snooze length</string>
    <string name="pref_alarm_flash_enabled">Enable flash</string>

    <string name="pref_volume">Volume</string>

    <string name="snooze_category_title">Snooze</string>

     <string name="speech_category_title">Speech</string>
     <string name="pref_use_speech_summary">Read out the time and weather when the alarm goes off</string>
     <string name="pref_use_speech_title">Use Speech</string>
     <string name="pref_speech_sample">Sample</string>

</resources>

redpajama_set_name: RedPajamaGithub


text:
package org.grails.ignite;

/**
 * Created by dstieglitz on 4/1/16.
 */
public class DistributedRunnableException extends Exception {
    public DistributedRunnableException(String message) {
        super(message);
    }

    public DistributedRunnableException(String message, Throwable cause) {
        super(message, cause);
    }
}


text:
:man_page: bson_new

bson_new()
==========

Synopsis
--------

.. code-block:: c

  bson_t *
  bson_new (void);

Description
-----------

The :symbol:`bson_new()` function shall create a new :symbol:`bson_t` structure on the heap. It should be freed with :symbol:`bson_destroy()` when it is no longer in use.

Returns
-------

A newly allocated :symbol:`bson_t` that should be freed with :symbol:`bson_destroy()`.

.. only:: html

  .. include:: includes/seealso/create-bson.txt


text:
package org.apache.spark.streaming;

import org.apache.spark.annotation.DeveloperApi;

/**
 * :: DeveloperApi ::
 *
 * Represents the state of a StreamingContext.
 */
@DeveloperApi
public enum StreamingContextState {
  /**
   * The context has been created, but not been started yet.
   * Input DStreams, transformations and output operations can be created on the context.
   * 创建应用上下文件,但尚未开始
   */
  INITIALIZED,

  /**
   * The context has been started, and been not stopped.
   * 上下文已开始,并没有停止.
   * Input DStreams, transformations and output operations cannot be created on the context.
   */
  ACTIVE,

  /**
   * The context has been stopped and cannot be used any more.
   * 上下文已被停止,不能再使用了
   */
  STOPPED
}


text:
'use strict';

import React from 'react';
import { Input, Button, Glyphicon, Grid, Row, Col } from 'react-bootstrap';
import tinycolor from 'tinycolor2';

require('styles/EditColor.css');

class EditColorComponent extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			code: props.color.code,
			name: props.color.name
		};
	}

	handleSubmit(e) {
		e.preventDefault();

		let code = this.state.code.trim();
		let name = this.state.name.trim();

		if (!code || !tinycolor(code).isValid()) {
			return;
		}

		name = name ? name : code;
		code = tinycolor(code).toString();

		this.setState({
			code: code,
			name: name
		}, () => {
			this.props.onChange({
				id: this.props.color.id,
				code: code,
				name: name
			});
		});
	}

	render() {
		return (
			<div
				className="editcolor-component"
				style={{ backgroundColor: this.state.code }}
			>
				<form onSubmit={this.handleSubmit.bind(this)}>
					<Grid fluid={true}>
						<Row>
							<Col xs={5}>
								<Input
									type="text"
									placeholder="#ff0000"
									ref="code"
									value={this.state.code}
									onChange={e => this.setState({code: e.target.value})}
								/>
							</Col>

							<Col xs={5}>
								<Input
									type="text"
									placeholder="Red"
									ref="name"
									value={this.state.name}
									onChange={e => this.setState({name: e.target.value})}
								/>
							</Col>

							<Col xs={2}>
								<Button type="submit"><Glyphicon glyph="ok" /></Button>
							</Col>
						</Row>
					</Grid>
				</form>
			</div>
		);
	}
}

EditColorComponent.propTypes = {
	onChange: React.PropTypes.func,
	color: React.PropTypes.object
};
// EditColorComponent.defaultProps = {};

export default EditColorComponent;


text:
(function() {

function EmbeddedRenderingEngine(viewResolver) {
	if (viewResolver) {
		this.setViewResolver(viewResolver);
	}
}

EmbeddedRenderingEngine.prototype.render = function render(name, data, elementOrId) {
	var promise = new Bloodhound.RenderPromise(this),
	    template = this.viewResolver.find(name),
	    result = "",
	    element = null,
	    doc = this.viewResolver.getDocument();

	if (!template) {
		throw new Error("Could not find template named: " + name);
	}

	result = template.render(data);

	if (elementOrId) {
		element = typeof elementOrId === "string"
		        ? doc.getElementById(elementOrId)
		        : elementOrId;

		if (!element) {
			throw new Error("Cannot find element: " + elementOrId);
		}

		element.innerHTML = result;
	}

	promise.fulfill("done", result, template, element);

	element = template = data = elementOrId = null;

	return promise;
};

EmbeddedRenderingEngine.prototype.setViewResolver = function setViewResolver(viewResolver) {
	this.viewResolver = viewResolver;
};

Bloodhound.RenderingEngines.EmbeddedRenderingEngine = EmbeddedRenderingEngine;

})();


text:
#pragma once
#include <aws/inspector/Inspector_EXPORTS.h>
#include <aws/inspector/model/PreviewStatus.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/inspector/model/ExclusionPreview.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace Inspector
{
namespace Model
{
  class AWS_INSPECTOR_API GetExclusionsPreviewResult
  {
  public:
    GetExclusionsPreviewResult();
    GetExclusionsPreviewResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    GetExclusionsPreviewResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
Specifies the status of the request to generate an exclusions preview.

     */
    inline const PreviewStatus& GetPreviewStatus() const{ return m_previewStatus; }

    /**
     *
Specifies the status of the request to generate an exclusions preview.

     */
    inline void SetPreviewStatus(const PreviewStatus& value) { m_previewStatus = value; }

    /**
     *
Specifies the status of the request to generate an exclusions preview.

     */
    inline void SetPreviewStatus(PreviewStatus&& value) { m_previewStatus = std::move(value); }

    /**
     *
Specifies the status of the request to generate an exclusions preview.

     */
    inline GetExclusionsPreviewResult& WithPreviewStatus(const PreviewStatus& value) { SetPreviewStatus(value); return *this;}

    /**
     *
Specifies the status of the request to generate an exclusions preview.

     */
    inline GetExclusionsPreviewResult& WithPreviewStatus(PreviewStatus&& value) { SetPreviewStatus(std::move(value)); return *this;}

    /**
     *
Information about the exclusions included in the preview.

     */
    inline const Aws::Vector<ExclusionPreview>& GetExclusionPreviews() const{ return m_exclusionPreviews; }

    /**
     *
Information about the exclusions included in the preview.

     */
    inline void SetExclusionPreviews(const Aws::Vector<ExclusionPreview>& value) { m_exclusionPreviews = value; }

    /**
     *
Information about the exclusions included in the preview.

     */
    inline void SetExclusionPreviews(Aws::Vector<ExclusionPreview>&& value) { m_exclusionPreviews = std::move(value); }

    /**
     *
Information about the exclusions included in the preview.

     */
    inline GetExclusionsPreviewResult& WithExclusionPreviews(const Aws::Vector<ExclusionPreview>& value) { SetExclusionPreviews(value); return *this;}

    /**
     *
Information about the exclusions included in the preview.

     */
    inline GetExclusionsPreviewResult& WithExclusionPreviews(Aws::Vector<ExclusionPreview>&& value) { SetExclusionPreviews(std::move(value)); return *this;}

    /**
     *
Information about the exclusions included in the preview.

     */
    inline GetExclusionsPreviewResult& AddExclusionPreviews(const ExclusionPreview& value) { m_exclusionPreviews.push_back(value); return *this; }

    /**
     *
Information about the exclusions included in the preview.

     */
    inline GetExclusionsPreviewResult& AddExclusionPreviews(ExclusionPreview&& value) { m_exclusionPreviews.push_back(std::move(value)); return *this; }

    /**
     *
When a response is generated, if there is more data to be listed, this
     * parameters is present in the response and contains the value to use for the
     * nextToken parameter in a subsequent pagination request. If there is no more data
     * to be listed, this parameter is set to null.

     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     *
When a response is generated, if there is more data to be listed, this
     * parameters is present in the response and contains the value to use for the
     * nextToken parameter in a subsequent pagination request. If there is no more data
     * to be listed, this parameter is set to null.

     */
    inline void SetNextToken(const Aws::String& value) { m_nextToken = value; }

    /**
     *
When a response is generated, if there is more data to be listed, this
     * parameters is present in the response and contains the value to use for the
     * nextToken parameter in a subsequent pagination request. If there is no more data
     * to be listed, this parameter is set to null.

     */
    inline void SetNextToken(Aws::String&& value) { m_nextToken = std::move(value); }

    /**
     *
When a response is generated, if there is more data to be listed, this
     * parameters is present in the response and contains the value to use for the
     * nextToken parameter in a subsequent pagination request. If there is no more data
     * to be listed, this parameter is set to null.

     */
    inline void SetNextToken(const char* value) { m_nextToken.assign(value); }

    /**
     *
When a response is generated, if there is more data to be listed, this
     * parameters is present in the response and contains the value to use for the
     * nextToken parameter in a subsequent pagination request. If there is no more data
     * to be listed, this parameter is set to null.

     */
    inline GetExclusionsPreviewResult& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     *
When a response is generated, if there is more data to be listed, this
     * parameters is present in the response and contains the value to use for the
     * nextToken parameter in a subsequent pagination request. If there is no more data
     * to be listed, this parameter is set to null.

     */
    inline GetExclusionsPreviewResult& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    /**
     *
When a response is generated, if there is more data to be listed, this
     * parameters is present in the response and contains the value to use for the
     * nextToken parameter in a subsequent pagination request. If there is no more data
     * to be listed, this parameter is set to null.

     */
    inline GetExclusionsPreviewResult& WithNextToken(const char* value) { SetNextToken(value); return *this;}

  private:

    PreviewStatus m_previewStatus;

    Aws::Vector<ExclusionPreview> m_exclusionPreviews;

    Aws::String m_nextToken;
  };

} // namespace Model
} // namespace Inspector
} // namespace Aws


text:
layout: question
title: "Use the phone quote process."
origin:
  -
    text: "Is the item between $10,000 and $30,000?"
    url: between-10-and-30-thousand
---

In order to do a phone quote, you must provide the Office of Management and Budget's procurement team with detailed specifications and contact information for at least three likely bidders.

More information on the phone quote process is coming soon.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DroneLander.Services
{
    public interface IAuthenticationService
    {
        Task<bool> SignInAsync();
        Task<bool> SignOutAsync();
    }
}


text:
namespace BattleField.Test
{
    using System;
    using System.Text;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class GameEngineTest
    {
        [TestMethod]
        public void IsGameOverTest_IfBombAtTopLeft()
        {
            Random random = new Random();
            for (int i = 1; i <= 10; i++)
            {
                int gameFieldSize = i;
                string randomBombNumber = random.Next(1, 6).ToString();
                Board board = new Board(gameFieldSize);

                board.GameBoard[0, 0] = randomBombNumber;

                Assert.IsFalse(GameEngine.IsGameOver(board));
            }
        }

        [TestMethod]
        public void IsGameOverTest_IfBombAtTopRight()
        {
            Random random = new Random();
            for (int i = 1; i <= 10; i++)
            {
                int gameFieldSize = i;
                string randomBombNumber = random.Next(1, 6).ToString();
                Board board = new Board(gameFieldSize);

                board.GameBoard[0, gameFieldSize - 1] = randomBombNumber;

                Assert.IsFalse(GameEngine.IsGameOver(board));
            }
        }

        [TestMethod]
        public void IsGameOverTest_IfBombAtBottomLeft()
        {
            Random random = new Random();
            for (int i = 1; i <= 10; i++)
            {
                int gameFieldSize = i;
                string randomBombNumber = random.Next(1, 6).ToString();
                Board board = new Board(gameFieldSize);

                board.GameBoard[gameFieldSize - 1, 0] = randomBombNumber;

                Assert.IsFalse(GameEngine.IsGameOver(board));
            }
        }

        [TestMethod]
        public void IsGameOverTest_IfBombAtBottomRight()
        {
            Random random = new Random();
            for (int i = 1; i <= 10; i++)
            {
                int gameFieldSize = i;
                string randomBombNumber = random.Next(1, 6).ToString();
                Board board = new Board(gameFieldSize);

                board.GameBoard[gameFieldSize - 1, gameFieldSize - 1] = randomBombNumber;

                Assert.IsFalse(GameEngine.IsGameOver(board));
            }
        }

        [TestMethod]
        public void IsGameOverTest_NoBombsLeft()
        {
            for (int i = 1; i <= 10; i++)
            {
                int gameFieldSize = i;
                Board board = new Board(gameFieldSize);
                ClearGameBoard(board);

                Assert.IsTrue(GameEngine.IsGameOver(board));
            }
        }

        [TestMethod]
        public void ReadBoardSizeTest_ValidSize5()
        {
            TestConsoleUI testConsole = new TestConsoleUI();
            testConsole.Input = "5";
            StringBuilder expectedOutput = new StringBuilder();
            expectedOutput.Append("Welcome to \"Battle Field game.\" Enter battlefield size: N = ");

            int boardSize = GameEngine.ReadBoardSize(testConsole);

            Assert.AreEqual(5, boardSize);
            Assert.AreEqual(expectedOutput.ToString(), testConsole.Output.ToString());
        }

        [TestMethod]
        public void ReadBoardSizeTest_ValidSize1()
        {
            TestConsoleUI testConsole = new TestConsoleUI();
            testConsole.Input = "1";
            StringBuilder expectedOutput = new StringBuilder();
            expectedOutput.Append("Welcome to \"Battle Field game.\" Enter battlefield size: N = ");

            int boardSize = GameEngine.ReadBoardSize(testConsole);

            Assert.AreEqual(1, boardSize);
            Assert.AreEqual(expectedOutput.ToString(), testConsole.Output.ToString());
        }

        [TestMethod]
        public void ReadBoardSizeTest_ValidSize10()
        {
            TestConsoleUI testConsole = new TestConsoleUI();
            testConsole.Input = "10";
            StringBuilder expectedOutput = new StringBuilder();
            expectedOutput.Append("Welcome to \"Battle Field game.\" Enter battlefield size: N = ");

            int boardSize = GameEngine.ReadBoardSize(testConsole);

            Assert.AreEqual(10, boardSize);
            Assert.AreEqual(expectedOutput.ToString(), testConsole.Output.ToString());
        }

        [TestMethod]
        public void ReadBoardSizeTest_InvalidSize0ThenValid5()
        {
            TestConsoleUI testConsole = new TestConsoleUI();
            testConsole.Input = "0\n5";
            StringBuilder expectedOutput = new StringBuilder();
            expectedOutput.Append("Welcome to \"Battle Field game.\" Enter battlefield size: N = ");
            expectedOutput.AppendLine("Enter a number between 1 and 10!");

            int boardSize = GameEngine.ReadBoardSize(testConsole);

            Assert.AreEqual(5, boardSize);
            Assert.AreEqual(expectedOutput.ToString(), testConsole.Output.ToString());
        }

        [TestMethod]
        public void ReadBoardSizeTest_TwiceInvalidSize0ThenValid5()
        {
            TestConsoleUI testConsole = new TestConsoleUI();
            testConsole.Input = "0\n0\n5";
            StringBuilder expectedOutput = new StringBuilder();
            expectedOutput.Append("Welcome to \"Battle Field game.\" Enter battlefield size: N = ");
            expectedOutput.AppendLine("Enter a number between 1 and 10!");
            expectedOutput.AppendLine("Enter a number between 1 and 10!");

            int boardSize = GameEngine.ReadBoardSize(testConsole);

            Assert.AreEqual(5, boardSize);
            Assert.AreEqual(expectedOutput.ToString(), testConsole.Output.ToString());
        }

        [TestMethod]
        public void PlayGameTest_SuccessfulGamePlayed1Bomb()
        {
            TestConsoleUI testConsole = new TestConsoleUI();
            testConsole.Input = "1 1";
            StringBuilder expectedOutput = new StringBuilder();
            Board board = new Board(3);
            var initialBoard = new string[3,3]
                {
                    {"-", "-", "-"},
                    {"-", "1", "-"},
                    {"-", "-", "-"}
                };
            var expectedBoard = new string[3,3]
                {
                    {"X", "-", "X"},
                    {"-", "X", "-"},
                    {"X", "-", "X"}
                };
            SetBoard(board, initialBoard);
            expectedOutput.AppendLine("Please enter coordinates: ");
            expectedOutput.AppendLine("  0 1 2");
            expectedOutput.AppendLine("  -----");
            expectedOutput.AppendLine("0|X - X ");
            expectedOutput.AppendLine("1|- X - ");
            expectedOutput.AppendLine("2|X - X ");
            expectedOutput.AppendLine();
            expectedOutput.AppendLine("Game over. Detonated mines: 1");

            GameEngine.PlayGame(board, testConsole);

            Assert.IsTrue(EqualBoards(expectedBoard, board.GameBoard));
            Assert.AreEqual(expectedOutput.ToString(), testConsole.Output.ToString());
        }

        [TestMethod]
        public void PlayGameTest_SuccessfulGamePlayedTryInvalidMove()
        {
            TestConsoleUI testConsole = new TestConsoleUI();
            testConsole.Input = "-1 0\n1 1\n1 1\n0 1";
            StringBuilder expectedOutput = new StringBuilder();
            Board board = new Board(3);
            var initialBoard = new string[3,3]
                {
                    {"-", "1", "-"},
                    {"-", "1", "-"},
                    {"-", "-", "-"}
                };
            var expectedBoard = new string[3,3]
                {
                    {"X", "X", "X"},
                    {"X", "X", "X"},
                    {"X", "-", "X"}
                };
            SetBoard(board, initialBoard);
            expectedOutput.AppendLine("Please enter coordinates: ");
            expectedOutput.AppendLine("Invalid move!");
            expectedOutput.AppendLine("Please enter coordinates: ");
            expectedOutput.AppendLine("  0 1 2");
            expectedOutput.AppendLine("  -----");
            expectedOutput.AppendLine("0|X 1 X ");
            expectedOutput.AppendLine("1|- X - ");
            expectedOutput.AppendLine("2|X - X ");
            expectedOutput.AppendLine();
            expectedOutput.AppendLine("Please enter coordinates: ");
            expectedOutput.AppendLine("Invalid move!");
            expectedOutput.AppendLine("Please enter coordinates: ");
            expectedOutput.AppendLine("  0 1 2");
            expectedOutput.AppendLine("  -----");
            expectedOutput.AppendLine("0|X X X ");
            expectedOutput.AppendLine("1|X X X ");
            expectedOutput.AppendLine("2|X - X ");
            expectedOutput.AppendLine();
            expectedOutput.AppendLine("Game over. Detonated mines: 2");

            GameEngine.PlayGame(board, testConsole);

            Assert.IsTrue(EqualBoards(expectedBoard, board.GameBoard));
            Assert.AreEqual(expectedOutput.ToString(), testConsole.Output.ToString());
        }

        private static void ClearGameBoard(Board board)
        {
            Random rand = new Random();

            for (int row = 0; row < board.Rows; row++)
            {
                for (int col = 0; col < board.Cols; col++)
                {
                    board.GameBoard[row, col] = (rand.Next(2) == 0 ? "-" : "X");
                }
            }
        }

        private static void SetBoard(Board board, string[,] initialBoard)
        {
            for (int row = 0; row < board.Rows; row++)
            {
                for (int col = 0; col < board.Cols; col++)
                {
                    board.GameBoard[row, col] = initialBoard[row, col];
                }
            }
        }

        private static bool EqualBoards(string[,] expected, string[,] actual)
        {
            try
            {
                for (int row = 0; row < expected.GetLength(0); row++)
                {
                    for (int col = 0; col < expected.GetLength(1); col++)
                    {
                        if (expected[row, col] != actual[row, col])
                        {
                            return false;
                        }
                    }
                }

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        private class TestConsoleUI : IConsole
        {
            public TestConsoleUI()
            {
                Output = new StringBuilder();
            }

            public StringBuilder Output { get; set; }
            public string Input { get; set; }

            public void Write(string message)
            {
                Output.Append(message);
            }

            public void WriteLine(string message)
            {
                Output.AppendLine(message);
            }

            public string ReadLine()
            {
                int endOfLineIndex = Input.IndexOf('\n');
                if (endOfLineIndex < 0)
                {
                    return Input;
                }

                string result = Input.Substring(0, endOfLineIndex);
                Input = Input.Remove(0, endOfLineIndex + 1);

                return result;
            }
        }
    }
}


text:
def load_current_resource
  @lxc = ::Lxc.new(
    new_resource.container,
    :base_dir => node[:lxc][:container_directory],
    :dnsmasq_lease_file => node[:lxc][:dnsmasq_lease_file]
  )
  @loaded ||= {}
  # value checks
  unless(new_resource.dynamic)
    %w(address netmask).each do |key|
      raise "#{key} is required for static interfaces" if new_resource.send(key).nil?
    end
  end
  node.run_state[:lxc] ||= Mash.new
  node.run_state[:lxc][:interfaces] ||= Mash.new
  node.run_state[:lxc][:interfaces][new_resource.container] ||= []
end

action :create do
  raise 'Device is required for creating an LXC interface!' unless new_resource.device

  unless(@loaded[new_resource.container])
    @loaded[new_resource.container] = true
  end

  net_set = Mash.new(:device => new_resource.device)
  if(new_resource.dynamic)
    net_set[:dynamic] = true
  else
    net_set[:auto] = new_resource.auto
    net_set[:address] = new_resource.address
    net_set[:gateway] = new_resource.gateway
    net_set[:netmask] = new_resource.netmask
    net_set[:up] = new_resource.up if new_resource.up
    net_set[:down] = new_resource.down if new_resource.down
    net_set[:ipv6] = new_resource.ipv6
  end

  node.run_state[:lxc][:interfaces][new_resource.container] << net_set
end

action :delete do
  # do nothing, simply not provided to run_state, and thus implicitly
  # deleted
end


text:
var gulp = require('gulp');
var sass = require('gulp-sass');
var watch = require('gulp-watch');
var shell = require('gulp-shell')

gulp.task('sass', function() {
  gulp.src('src/client/sass/*.scss', {base: 'src/client/sass'})
	.pipe(watch('src/client/sass/*.scss', {base: 'src/client/sass'}))
	.pipe(sass({style: 'expanded'}))
	.pipe(gulp.dest('dist/public/css'));
})

gulp.task('client', function() {
	gulp.src(['src/client/js/**','src/client/img/**'], {base: 'src/client'})
	.pipe(watch(['src/client/**/*'], {base: 'src/client'}))
	.pipe(gulp.dest('dist/public'))
});

gulp.task('index', function() {
	gulp.src('src/client/templates/index.html', {base: 'src/client'})
	.pipe(watch('src/client/templates/index.html', {base: 'src/client'}))
	.pipe(gulp.dest('dist'))
});

gulp.task('partials', function() {
	gulp.src('src/client/templates/partials/**/*.html', {base: 'src/client/templates'})
	.pipe(watch('src/client/templates/partials/**/*.html', {base: 'src/client/templates'}))
	.pipe(gulp.dest('dist/public'))
});

gulp.task('config', function() {
	gulp.src('config/*.ini', {base: '.'})
	.pipe(watch('config/*'))
	.pipe(gulp.dest('dist'))
});

gulp.task('go', function() {
	gulp.src('src/server/**/*.go', {read: false})
	  .pipe(watch('src/server/**/*.go', {base: 'src/server'}))
		.pipe(shell([
		'go build -o dist/server src/server/*.go',
		'pid=`ps ax|grep \'dist/server\'|grep -v grep|awk -F " " \'{print $1}\'`;if [ "$pid" != "" ];then kill -9 $pid;fi',
		'./dist/server'
		]))
});

gulp.task('default', ['sass', 'client', 'index', 'partials', 'go', 'config'], function () {});


text:
package de.newsarea.homecockpit.fsuipc2net.net.domain;

import org.testng.annotations.Test;

import static org.testng.AssertJUnit.assertEquals;

public class NetMessageItemTest {

    @Test
    public void shouldCreateFromString() throws Exception {
        assertEquals("0x0001:2:0xAFFA", NetMessageItem.fromString("0x0001:2:0xAFFA").toString());
        assertEquals("0x0001:2", NetMessageItem.fromString("0x0001:2").toString());
        assertEquals("0xFFFF:16", NetMessageItem.fromString("0xFFFF:16").toString());
        assertEquals("0x0FFF:16", NetMessageItem.fromString("0xFFF:16").toString());
        assertEquals("0x00FF:16", NetMessageItem.fromString("0xFF:16").toString());
        assertEquals("0x000F:16", NetMessageItem.fromString("0xF:16").toString());
    }

    @Test(expectedExceptions = IllegalArgumentException.class)
    public void shouldNotCreateFromString_ToBigOffset() throws Exception {
        NetMessageItem.fromString("0xFFFFF:16");
    }

}


text: Tests that database names are correctly loaded and saved in IndexedDBModel.


text:
> Summary of the proposed change

Research 3rd party API testing strategies.

# References
> Link to supporting documentation, GitHub tickets, etc.

- [Testing Third Party Interactions](https://thoughtbot.com/blog/testing-third-party-interactions)

# Motivation
> What problem is this project solving?

Rapidly detect regressions in API clients.

# Goals
> Identify success metrics and measurable goals.

* Test suite performance
* Test suite stability

# Non-Goals
> Identify what's not in scope.

End to end testing with real network requests is not in scope because E2E tests are slow and flaky.

## Definitions

Here are four ways to test a 3rd party API.

|  | **Adapter** | **HTTP** |
| --- | --- | --- |
| **Stubbed** | Stub methods on adapter | Stub HTTP requests |
| **Real** | Real request to fake adapter | Real HTTP request to fake service |

**Adapter** is a class that provides high level methods on top of a lower level HTTP client.
Each adapter makes requests to the third party API through a **HTTP** client.

## [Stubbing the adapter](https://thoughtbot.com/blog/testing-third-party-interactions#stubbing-the-adapter)
Unit-test objects that depend on data from other services.

- Dart mock package inspired by Mockito: [mockito](https://pub.dev/packages/mockito)

## [Stubbing the network](https://thoughtbot.com/blog/testing-third-party-interactions#stubbing-the-network)
Execute the service without making a real network request.

- Dart Nock HTTP requests mocking package: [nock](https://pub.dev/packages/nock)

## [Swapping out the adapter](https://thoughtbot.com/blog/testing-third-party-interactions#swapping-out-the-adapter)
Assert on data that has been sent or received from the service.

- Dart HTTP package: [http](https://pub.dev/packages/http) (has [mock client](https://pub.dev/documentation/http/latest/testing/MockClient-class.html))
- Dart Nock HTTP requests mocking package: [nock](https://pub.dev/packages/nock)

## [Swapping out the server](https://thoughtbot.com/blog/testing-third-party-interactions#swapping-out-the-server)
Instead of trying to prevent HTTP, you make **real HTTP requests** to a **local mock server**.
Allows full end-to-end testing of an app.

- Dart HTTP server: [http_server](https://pub.dev/packages/http_server)
- Dart MockWebServer package: [mock_web_server](https://pub.dev/packages/mock_web_server)

# Design
> Identify risks and edge cases

Server API changes will break the client. The above approaches test the client in isolation. The client tests will continue to pass even if the server breaks the API contract.

# API
> What will the proposed API look like?

See the document in [Implementing Swapping out the server approach](04_mock_server.md)

# Dependencies
> What is the project blocked on?

No blockers.

> What will be impacted by the project?

All 3rd party API integrations are impacted by the API testing strategy.

# Alternatives Considered
> Summarize alternative designs (pros & cons)

- Making real HTTP requests to real service. End to end tests will detect when server API changes have broken clients, however they are slow and flaky.

# Timeline
> Document milestones and deadlines.

DONE:
  - Investigate third-party API testing approaches.
  - Added implementing e2e API testing document.

# Results
> What was the outcome of the project?

Work in progress.


text:
package eu.ydp.empiria.player.client.module.choice;

import eu.ydp.empiria.player.client.module.choice.presenter.SimpleChoicePresenter;

public interface ChoiceModuleListener {

    void onChoiceClick(SimpleChoicePresenter choice);

}


text:
Go implementation of using [HTTPS Everywhere](https://github.com/EFForg/https-everywhere) rule sets to send traffic over HTTPS. Many thanks to the EFF team maintaining such an amazing project!

Example usage:

```go
import "url"
import "github.com/getlantern/httpseverywhere"

...

httpURL, _ := url.Parse("http://name.com")
rewrite := httpseverywhere.Default()
httpsURL, changed := rewrite(httpURL)
if changed {
	// Redirect to httpsURL
	...
}
```

Please note that this library does not support any rules that include backtracking, specifically any rules with `(?!` or `(?=`, because those are not supported in Go's regular expressions packages for performance reasons. That excludes approximately 6,000 out of around 22,000 rule sets.


text:
package org.sagebionetworks.web.client.jsinterop;

import jsinterop.annotations.JsFunction;
import jsinterop.annotations.JsOverlay;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsType;

@JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "Object")
public class EvaluationCardProps extends ReactComponentProps {

  @JsFunction
  public interface Callback {
    void run();
  }

  public EvaluationJSObject evaluation;

  public Callback onEdit;
  public Callback onModifyAccess;
  public Callback onSubmit;
  public Callback onDeleteSuccess;

  @JsOverlay
  public static EvaluationCardProps create(
    EvaluationJSObject evaluation,
    Callback onEdit,
    Callback onModifyAccess,
    Callback onSubmit,
    Callback onDeleteSuccess
  ) {
    EvaluationCardProps props = new EvaluationCardProps();
    props.evaluation = evaluation;
    props.onEdit = onEdit;
    props.onModifyAccess = onModifyAccess;
    props.onSubmit = onSubmit;
    props.onDeleteSuccess = onDeleteSuccess;
    return props;
  }
}


text:
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.unity3d.player"
    xmlns:tools="http://schemas.android.com/tools"
    android:versionCode="1"
    android:versionName="1.0">
    <application>
        <activity android:name="com.example.urlschemeplugin.URLSchemePlugin">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <!-- この部分に直書きになるの本当にダサいと思う、アプリ側で編集する箇所がUnityから乖離している。Xcodeならあそこに書く、とかが定番なのに、Androidはそうなってない。なんとか逃げ場がないものか。 -->
                <data android:scheme="autoyascheme" />
            </intent-filter>
        </activity>
    </application>
</manifest>


text:
//*******************************************************************************************//
//                                                                                //
// Download Free Evaluation Version From: https://bytescout.com/download/web-installer       //
//                                                                                //
// Also available as Web API! Get Your Free API Key: https://app.pdf.co/signup               //
//                                                                                //
// Copyright © 2017-2020 ByteScout, Inc. All rights reserved.                                //
// https://www.bytescout.com                                                                 //
// https://pdf.co                                                                            //
//                                                                                //
//*******************************************************************************************//

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ByteScoutWebApiExample
{
	class Program
	{
		// The authentication key (API Key).
		// Get your own by registering at https://app.pdf.co/documentation/api
		const String API_KEY = "***********************************";

		// Source PDF file
		const string SourceFile = @".\sample.pdf";
		// Comma-separated list of page indices (or ranges) to process. Leave empty for all pages. Example: '0,2-5,7-'.
		const string Pages = "";
		// PDF document password. Leave empty for unprotected documents.
		const string Password = "";
		// Destination TXT file name
		const string DestinationFile = @".\result.txt";
        // (!) Make asynchronous job
        const bool Async = true;

        static void Main(string[] args)
		{
			// Create standard .NET web client instance
			WebClient webClient = new WebClient();

			// Set API Key
			webClient.Headers.Add("x-api-key", API_KEY);

			// 1. RETRIEVE THE PRESIGNED URL TO UPLOAD THE FILE.
			// * If you already have a direct file URL, skip to the step 3.

			// Prepare URL for `Get Presigned URL` API call
			string query = Uri.EscapeUriString(string.Format(
				"https://api.pdf.co/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name={0}",
				Path.GetFileName(SourceFile)));

			try
			{
				// Execute request
				string response = webClient.DownloadString(query);

				// Parse JSON response
				JObject json = JObject.Parse(response);

				if (json["error"].ToObject<bool>() == false)
				{
					// Get URL to use for the file upload
					string uploadUrl = json["presignedUrl"].ToString();
					string uploadedFileUrl = json["url"].ToString();

					// 2. UPLOAD THE FILE TO CLOUD.

					webClient.Headers.Add("content-type", "application/octet-stream");
					webClient.UploadFile(uploadUrl, "PUT", SourceFile); // You can use UploadData() instead if your file is byte[] or Stream
					webClient.Headers.Remove("content-type");

                    // 3. CONVERT UPLOADED PDF FILE TO TXT

                    // URL for `PDF To Text` API call
                    var url = "https://api.pdf.co/v1/pdf/convert/to/text";

                    // Prepare requests params as JSON
                    Dictionary<string, object> parameters = new Dictionary<string, object>();
                    parameters.Add("name", Path.GetFileName(DestinationFile));
                    parameters.Add("password", Password);
                    parameters.Add("pages", Pages);
                    parameters.Add("url", uploadedFileUrl);
                    parameters.Add("async", Async);

                    // Convert dictionary of params to JSON
                    string jsonPayload = JsonConvert.SerializeObject(parameters);

                    try
                    {
                        // Execute POST request with JSON payload
                        response = webClient.UploadString(url, jsonPayload);

                        // Parse JSON response
                        json = JObject.Parse(response);

                        if (json["error"].ToObject<bool>() == false)
                        {
                            // Asynchronous job ID
                            string jobId = json["jobId"].ToString();
                            // URL of generated TXT file that will be available after the job completion
                            string resultFileUrl = json["url"].ToString();

                            // Check the job status in a loop.
                            // If you don't want to pause the main thread you can rework the code
                            // to use a separate thread for the status checking and completion.
                            do
                            {
                                string status = CheckJobStatus(jobId); // Possible statuses: "working", "failed", "aborted", "success".

                                // Display timestamp and status (for demo purposes)
                                Console.WriteLine(DateTime.Now.ToLongTimeString() + ": " + status);

                                if (status == "success")
                                {
                                    // Download TXT file
                                    webClient.DownloadFile(resultFileUrl, DestinationFile);

                                    Console.WriteLine("Generated TXT file saved as \"{0}\" file.", DestinationFile);
                                    break;
                                }
                                else if (status == "working")
                                {
                                    // Pause for a few seconds
                                    Thread.Sleep(3000);
                                }
                                else
                                {
                                    Console.WriteLine(status);
                                    break;
                                }
                            }
                            while (true);
                        }
                        else
                        {
                            Console.WriteLine(json["message"].ToString());
                        }
                    }
                    catch (WebException e)
                    {
                        Console.WriteLine(e.ToString());
                    }
                }
				else
				{
					Console.WriteLine(json["message"].ToString());
				}
			}
			catch (WebException e)
			{
				Console.WriteLine(e.ToString());
			}

			webClient.Dispose();

			Console.WriteLine();
			Console.WriteLine("Press any key...");
			Console.ReadKey();
		}

        /// <summary>
        /// Check Job Status
        /// </summary>
        static string CheckJobStatus(string jobId)
        {
            using (WebClient webClient = new WebClient())
            {
                // Set API Key
                webClient.Headers.Add("x-api-key", API_KEY);

                string url = "https://api.pdf.co/v1/job/check?jobid=" + jobId;

                string response = webClient.DownloadString(url);
                JObject json = JObject.Parse(response);

                return Convert.ToString(json["status"]);
            }
        }

    }
}


text:
// ------------------------------------------------------------------------------
//  <auto-generated>
//      This code was generated by SpecFlow (http://www.specflow.org/).
//      SpecFlow Version:1.9.0.77
//      SpecFlow Generator Version:1.9.0.0
//      Runtime Version:4.0.30319.42000
//
//      Changes to this file may cause incorrect behavior and will be lost if
//      the code is regenerated.
//  </auto-generated>
// ------------------------------------------------------------------------------
#region Designer generated code
#pragma warning disable
namespace DailySoccer.Specs
{
    using TechTalk.SpecFlow;

    [System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "1.9.0.77")]
    [System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute()]
    public partial class RegisterFeature
    {

        private static TechTalk.SpecFlow.ITestRunner testRunner;

#line 1 "Register.feature"
#line hidden

        [Microsoft.VisualStudio.TestTools.UnitTesting.ClassInitializeAttribute()]
        public static void FeatureSetup(Microsoft.VisualStudio.TestTools.UnitTesting.TestContext testContext)
        {
            testRunner = TechTalk.SpecFlow.TestRunnerManager.GetTestRunner();
            TechTalk.SpecFlow.FeatureInfo featureInfo = new TechTalk.SpecFlow.FeatureInfo(new System.Globalization.CultureInfo("en-US"), "Register", "In order to avoid silly mistakes\nAs a math idiot\nI want to be told the sum of two" +
                    " numbers", ProgrammingLanguage.CSharp, ((string[])(null)));
            testRunner.OnFeatureStart(featureInfo);
        }

        [Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupAttribute()]
        public static void FeatureTearDown()
        {
            testRunner.OnFeatureEnd();
            testRunner = null;
        }

        [Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute()]
        public virtual void TestInitialize()
        {
            if (((TechTalk.SpecFlow.FeatureContext.Current != null)
                        && (TechTalk.SpecFlow.FeatureContext.Current.FeatureInfo.Title != "Register")))
            {
                DailySoccer.Specs.RegisterFeature.FeatureSetup(null);
            }
        }

        [Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute()]
        public virtual void ScenarioTearDown()
        {
            testRunner.OnScenarioEnd();
        }

        public virtual void ScenarioSetup(TechTalk.SpecFlow.ScenarioInfo scenarioInfo)
        {
            testRunner.OnScenarioStart(scenarioInfo);
        }

        public virtual void ScenarioCleanup()
        {
            testRunner.CollectScenarioErrors();
        }

        public virtual void FeatureBackground()
        {
#line 6
#line 7
 testRunner.Given("Create mocking", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given ");
#line hidden
            TechTalk.SpecFlow.Table table1 = new TechTalk.SpecFlow.Table(new string[] {
                        "id",
                        "UserId"});
            table1.AddRow(new string[] {
                        "f01",
                        "u01"});
#line 8
 testRunner.And("Facebook accounts in the system are", ((string)(null)), table1, "And ");
#line hidden
            TechTalk.SpecFlow.Table table2 = new TechTalk.SpecFlow.Table(new string[] {
                        "id",
                        "Points",
                        "OrderedCoupon",
                        "PhoneNo",
                        "VerifierCode",
                        "VerifiedPhoneDate",
                        "IsFacebookVerified",
                        "FavouriteTeamId"});
            table2.AddRow(new string[] {
                        "u01",
                        "0",
                        "0",
                        "",
                        "",
                        "",
                        "true",
                        ""});
            table2.AddRow(new string[] {
                        "u02",
                        "1000",
                        "5",
                        "",
                        "",
                        "",
                        "false",
                        "t01"});
#line 11
 testRunner.And("UserProfile accounts in the system are", ((string)(null)), table2, "And ");
#line hidden
        }

        [Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute()]
        [Microsoft.VisualStudio.TestTools.UnitTesting.DescriptionAttribute("Create new guest account, system create new account success")]
        [Microsoft.VisualStudio.TestTools.UnitTesting.TestPropertyAttribute("FeatureTitle", "Register")]
        [Microsoft.VisualStudio.TestTools.UnitTesting.TestCategoryAttribute("mock")]
        public virtual void CreateNewGuestAccountSystemCreateNewAccountSuccess()
        {
            TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Create new guest account, system create new account success", new string[] {
                        "mock"});
#line 17
this.ScenarioSetup(scenarioInfo);
#line 6
this.FeatureBackground();
#line 18
 testRunner.When("Call POST api/profile", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line 19
 testRunner.Then("System create new guest account", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line 20
 testRunner.And("the new account data should be newly account", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line hidden
            this.ScenarioCleanup();
        }

        [Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute()]
        [Microsoft.VisualStudio.TestTools.UnitTesting.DescriptionAttribute("Create new account with tie facebook (isConfirmed = true), system create new acco" +
            "unt success")]
        [Microsoft.VisualStudio.TestTools.UnitTesting.TestPropertyAttribute("FeatureTitle", "Register")]
        [Microsoft.VisualStudio.TestTools.UnitTesting.TestCategoryAttribute("mock")]
        public virtual void CreateNewAccountWithTieFacebookIsConfirmedTrueSystemCreateNewAccountSuccess()
        {
            TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Create new account with tie facebook (isConfirmed = true), system create new acco" +
                    "unt success", new string[] {
                        "mock"});
#line 23
this.ScenarioSetup(scenarioInfo);
#line 6
this.FeatureBackground();
#line 24
 testRunner.When("Call POST api/profile/facebook [FacebookId: \'new-facebook-id\', UserId: \'\', IsConf" +
                    "irmed: \'true\']", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line 25
 testRunner.Then("System create new guest account", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line 26
 testRunner.And("the new account data should be newly account", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line hidden
            this.ScenarioCleanup();
        }

        [Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute()]
        [Microsoft.VisualStudio.TestTools.UnitTesting.DescriptionAttribute("Create new account with tie facebook (isConfirmed = false), system create new acc" +
            "ount success")]
        [Microsoft.VisualStudio.TestTools.UnitTesting.TestPropertyAttribute("FeatureTitle", "Register")]
        [Microsoft.VisualStudio.TestTools.UnitTesting.TestCategoryAttribute("mock")]
        public virtual void CreateNewAccountWithTieFacebookIsConfirmedFalseSystemCreateNewAccountSuccess()
        {
            TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Create new account with tie facebook (isConfirmed = false), system create new acc" +
                    "ount success", new string[] {
                        "mock"});
#line 29
this.ScenarioSetup(scenarioInfo);
#line 6
this.FeatureBackground();
#line 30
 testRunner.When("Call POST api/profile/facebook [FacebookId: \'new-facebook-id\', UserId: \'\', IsConf" +
                    "irmed: \'false\']", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line 31
 testRunner.Then("System create new guest account", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line 32
 testRunner.And("the new account data should be newly account", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line hidden
            this.ScenarioCleanup();
        }

        [Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute()]
        [Microsoft.VisualStudio.TestTools.UnitTesting.DescriptionAttribute("Tie facebook with existing user profile, system tie user profile success")]
        [Microsoft.VisualStudio.TestTools.UnitTesting.TestPropertyAttribute("FeatureTitle", "Register")]
        [Microsoft.VisualStudio.TestTools.UnitTesting.TestCategoryAttribute("mock")]
        public virtual void TieFacebookWithExistingUserProfileSystemTieUserProfileSuccess()
        {
            TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Tie facebook with existing user profile, system tie user profile success", new string[] {
                        "mock"});
#line 35
this.ScenarioSetup(scenarioInfo);
#line 6
this.FeatureBackground();
#line 36
 testRunner.When("Call POST api/profile/facebook [FacebookId: \'new-facebook-id\', UserId: \'u02\', IsC" +
                    "onfirmed: \'true\']", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line 37
 testRunner.Then("System not create new guest account", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line hidden
            TechTalk.SpecFlow.Table table3 = new TechTalk.SpecFlow.Table(new string[] {
                        "id",
                        "Points",
                        "OrderedCoupon",
                        "PhoneNo",
                        "VerifierCode",
                        "VerifiedPhoneDate",
                        "IsFacebookVerified",
                        "FavouriteTeamId"});
            table3.AddRow(new string[] {
                        "u02",
                        "1000",
                        "5",
                        "",
                        "",
                        "",
                        "true",
                        "t01"});
#line 38
 testRunner.And("system return account data are", ((string)(null)), table3, "And ");
#line hidden
            this.ScenarioCleanup();
        }

        [Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute()]
        [Microsoft.VisualStudio.TestTools.UnitTesting.DescriptionAttribute("Get facebook account, system return the selected user profile")]
        [Microsoft.VisualStudio.TestTools.UnitTesting.TestPropertyAttribute("FeatureTitle", "Register")]
        [Microsoft.VisualStudio.TestTools.UnitTesting.TestCategoryAttribute("mock")]
        public virtual void GetFacebookAccountSystemReturnTheSelectedUserProfile()
        {
            TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Get facebook account, system return the selected user profile", new string[] {
                        "mock"});
#line 43
this.ScenarioSetup(scenarioInfo);
#line 6
this.FeatureBackground();
#line 44
 testRunner.When("Call POST api/profile/facebook [FacebookId: \'f01\', UserId: \'u02\', IsConfirmed: \'f" +
                    "alse\']", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line 45
 testRunner.Then("System not create new guest account", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line hidden
            TechTalk.SpecFlow.Table table4 = new TechTalk.SpecFlow.Table(new string[] {
                        "id",
                        "Points",
                        "OrderedCoupon",
                        "PhoneNo",
                        "VerifierCode",
                        "VerifiedPhoneDate",
                        "IsFacebookVerified",
                        "FavouriteTeamId"});
            table4.AddRow(new string[] {
                        "u01",
                        "0",
                        "0",
                        "",
                        "",
                        "",
                        "true",
                        ""});
#line 46
 testRunner.And("system return account data are", ((string)(null)), table4, "And ");
#line hidden
            this.ScenarioCleanup();
        }

        [Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute()]
        [Microsoft.VisualStudio.TestTools.UnitTesting.DescriptionAttribute("Try to create new account by incorrect facebook id, then system reject the reques" +
            "t")]
        [Microsoft.VisualStudio.TestTools.UnitTesting.TestPropertyAttribute("FeatureTitle", "Register")]
        [Microsoft.VisualStudio.TestTools.UnitTesting.TestCategoryAttribute("mock")]
        public virtual void TryToCreateNewAccountByIncorrectFacebookIdThenSystemRejectTheRequest()
        {
            TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Try to create new account by incorrect facebook id, then system reject the reques" +
                    "t", new string[] {
                        "mock"});
#line 51
this.ScenarioSetup(scenarioInfo);
#line 6
this.FeatureBackground();
#line 52
 testRunner.When("Call POST api/profile/facebook [FacebookId: \'\', UserId: \'\', IsConfirmed: \'false\']" +
                    "", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line 53
 testRunner.Then("System not create new guest account", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line 54
 testRunner.And("system return null", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line hidden
            this.ScenarioCleanup();
        }

        [Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute()]
        [Microsoft.VisualStudio.TestTools.UnitTesting.DescriptionAttribute("Try to tie account by incorrect facebook id (isConfirmed = true), then system rej" +
            "ect the request")]
        [Microsoft.VisualStudio.TestTools.UnitTesting.TestPropertyAttribute("FeatureTitle", "Register")]
        [Microsoft.VisualStudio.TestTools.UnitTesting.TestCategoryAttribute("mock")]
        public virtual void TryToTieAccountByIncorrectFacebookIdIsConfirmedTrueThenSystemRejectTheRequest()
        {
            TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Try to tie account by incorrect facebook id (isConfirmed = true), then system rej" +
                    "ect the request", new string[] {
                        "mock"});
#line 57
this.ScenarioSetup(scenarioInfo);
#line 6
this.FeatureBackground();
#line 58
 testRunner.When("Call POST api/profile/facebook [FacebookId: \'f01\', UserId: \'unknow-user-id\', IsCo" +
                    "nfirmed: \'true\']", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line 59
 testRunner.Then("System not create new guest account", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line 60
 testRunner.And("system return null", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And ");
#line hidden
            this.ScenarioCleanup();
        }

        [Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute()]
        [Microsoft.VisualStudio.TestTools.UnitTesting.DescriptionAttribute("Try to tie account by incorrect facebook id (isConfirmed = false), then system re" +
            "ject the request")]
        [Microsoft.VisualStudio.TestTools.UnitTesting.TestPropertyAttribute("FeatureTitle", "Register")]
        [Microsoft.VisualStudio.TestTools.UnitTesting.TestCategoryAttribute("mock")]
        public virtual void TryToTieAccountByIncorrectFacebookIdIsConfirmedFalseThenSystemRejectTheRequest()
        {
            TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Try to tie account by incorrect facebook id (isConfirmed = false), then system re" +
                    "ject the request", new string[] {
                        "mock"});
#line 63
this.ScenarioSetup(scenarioInfo);
#line 6
this.FeatureBackground();
#line 64
 testRunner.When("Call POST api/profile/facebook [FacebookId: \'f01\', UserId: \'unknow-user-id\', IsCo" +
                    "nfirmed: \'false\']", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line 65
 testRunner.Then("System not create new guest account", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line hidden
            TechTalk.SpecFlow.Table table5 = new TechTalk.SpecFlow.Table(new string[] {
                        "id",
                        "Points",
                        "OrderedCoupon",
                        "PhoneNo",
                        "VerifierCode",
                        "VerifiedPhoneDate",
                        "IsFacebookVerified",
                        "FavouriteTeamId"});
            table5.AddRow(new string[] {
                        "u01",
                        "0",
                        "0",
                        "",
                        "",
                        "",
                        "true",
                        ""});
#line 66
 testRunner.And("system return account data are", ((string)(null)), table5, "And ");
#line hidden
            this.ScenarioCleanup();
        }
    }
}
#pragma warning restore
#endregion


text:
/**
 *  @file ImplicitSurfChem.cpp
 * Definitions for the implicit integration of surface site density equations
 *  (see \ref  kineticsmgr and class
 *  \link Cantera::ImplicitSurfChem ImplicitSurfChem\endlink).
 */
// Copyright 2001  California Institute of Technology

#include "cantera/kinetics/ImplicitSurfChem.h"
#include "cantera/kinetics/solveSP.h"
#include "cantera/thermo/SurfPhase.h"

using namespace std;

namespace Cantera
{

ImplicitSurfChem::ImplicitSurfChem(vector<InterfaceKinetics*> k) :
    m_nsurf(0),
    m_nv(0),
    m_numBulkPhases(0),
    m_numTotalBulkSpecies(0),
    m_numTotalSpecies(0),
    m_integ(0),
    m_atol(1.e-14),
    m_rtol(1.e-7),
    m_maxstep(0.0),
    m_mediumSpeciesStart(-1),
    m_bulkSpeciesStart(-1),
    m_surfSpeciesStart(-1),
    m_surfSolver(0),
    m_commonTempPressForPhases(true),
    m_ioFlag(0)
{
    m_nsurf = k.size();
    size_t ns, nsp;
    size_t nt, ntmax = 0;
    size_t kinSpIndex = 0;
    // Loop over the number of surface kinetics objects
    for (size_t n = 0; n < m_nsurf; n++) {
        InterfaceKinetics* kinPtr = k[n];
        m_vecKinPtrs.push_back(kinPtr);
        ns = k[n]->surfacePhaseIndex();
        if (ns == npos)
            throw CanteraError("ImplicitSurfChem",
                               "kinetics manager contains no surface phase");
        m_surfindex.push_back(ns);
        m_surf.push_back((SurfPhase*)&k[n]->thermo(ns));
        nsp = m_surf.back()->nSpecies();
        m_nsp.push_back(nsp);
        m_nv += m_nsp.back();
        nt = k[n]->nTotalSpecies();
        ntmax = std::max(nt, ntmax);
        m_specStartIndex.push_back(kinSpIndex);
        kinSpIndex += nsp;

        size_t nPhases = kinPtr->nPhases();
        vector_int pLocTmp(nPhases);
        size_t imatch = npos;
        for (size_t ip = 0; ip < nPhases; ip++) {
            if (ip != ns) {
                ThermoPhase* thPtr = & kinPtr->thermo(ip);
                if ((imatch = checkMatch(m_bulkPhases, thPtr)) == npos) {
                    m_bulkPhases.push_back(thPtr);
                    m_numBulkPhases++;
                    nsp = thPtr->nSpecies();
                    m_nspBulkPhases.push_back(nsp);
                    m_numTotalBulkSpecies += nsp;
                    imatch = m_bulkPhases.size() - 1;
                }
                pLocTmp[ip] = int(imatch);
            } else {
                pLocTmp[ip] = -int(n);
            }
        }
        pLocVec.push_back(pLocTmp);

    }
    m_numTotalSpecies = m_nv + m_numTotalBulkSpecies;
    m_concSpecies.resize(m_numTotalSpecies, 0.0);
    m_concSpeciesSave.resize(m_numTotalSpecies, 0.0);

    m_integ = newIntegrator("CVODE");

    // use backward differencing, with a full Jacobian computed
    // numerically, and use a Newton linear iterator

    m_integ->setMethod(BDF_Method);
    m_integ->setProblemType(DENSE + NOJAC);
    m_integ->setIterator(Newton_Iter);
    m_work.resize(ntmax);
}

int ImplicitSurfChem::checkMatch(std::vector<ThermoPhase*> m_vec, ThermoPhase* thPtr)
{
    int retn = -1;
    for (int i = 0; i < (int) m_vec.size(); i++) {
        ThermoPhase* th = m_vec[i];
        if (th == thPtr) {
            return i;
        }
    }
    return retn;
}

ImplicitSurfChem::~ImplicitSurfChem()
{
    delete m_integ;
    delete m_surfSolver;
}

void ImplicitSurfChem::getInitialConditions(doublereal t0, size_t lenc,
        doublereal* c)
{
    size_t loc = 0;
    for (size_t n = 0; n < m_nsurf; n++) {
        m_surf[n]->getCoverages(c + loc);
        loc += m_nsp[n];
    }
}

void ImplicitSurfChem::initialize(doublereal t0)
{
    m_integ->setTolerances(m_rtol, m_atol);
    m_integ->initialize(t0, *this);
}

void ImplicitSurfChem::integrate(doublereal t0, doublereal t1)
{
    m_integ->initialize(t0, *this);
    m_integ->setMaxStepSize(t1 - t0);
    m_integ->integrate(t1);
    updateState(m_integ->solution());
}

void ImplicitSurfChem::integrate0(doublereal t0, doublereal t1)
{
    m_integ->integrate(t1);
    updateState(m_integ->solution());
}

void ImplicitSurfChem::updateState(doublereal* c)
{
    size_t loc = 0;
    for (size_t n = 0; n < m_nsurf; n++) {
        m_surf[n]->setCoverages(c + loc);
        loc += m_nsp[n];
    }
}

void ImplicitSurfChem::eval(doublereal time, doublereal* y,
                            doublereal* ydot, doublereal* p)
{
    updateState(y);   // synchronize the surface state(s) with y
    doublereal rs0, sum;
    size_t loc, kstart;
    for (size_t n = 0; n < m_nsurf; n++) {
        rs0 = 1.0/m_surf[n]->siteDensity();
        m_vecKinPtrs[n]->getNetProductionRates(DATA_PTR(m_work));
        kstart = m_vecKinPtrs[n]->kineticsSpeciesIndex(0,m_surfindex[n]);
        sum = 0.0;
        loc = 0;
        for (size_t k = 1; k < m_nsp[n]; k++) {
            ydot[k + loc] = m_work[kstart + k] * rs0 * m_surf[n]->size(k);
            sum -= ydot[k];
        }
        ydot[loc] = sum;
        loc += m_nsp[n];
    }
}

void ImplicitSurfChem::solvePseudoSteadyStateProblem(int ifuncOverride,
        doublereal timeScaleOverride)
{
    int ifunc;
    /*
     * set bulkFunc
     *    -> We assume that the bulk concentrations are constant.
     */
    int bulkFunc = BULK_ETCH;
    /*
     * time scale - time over which to integrate equations
     */
    doublereal time_scale = timeScaleOverride;
    if (!m_surfSolver) {
        m_surfSolver = new solveSP(this, bulkFunc);
        /*
         * set ifunc, which sets the algorithm.
         */
        ifunc = SFLUX_INITIALIZE;
    } else {
        ifunc = SFLUX_RESIDUAL;
    }

    // Possibly override the ifunc value
    if (ifuncOverride >= 0) {
        ifunc = ifuncOverride;
    }

    /*
     * Get the specifications for the problem from the values
     * in the ThermoPhase objects for all phases.
     *
     *  1) concentrations of all species in all phases, m_concSpecies[]
     *  2) Temperature and pressure
     */
    getConcSpecies(DATA_PTR(m_concSpecies));
    InterfaceKinetics* ik = m_vecKinPtrs[0];
    ThermoPhase& tp = ik->thermo(0);
    doublereal TKelvin = tp.temperature();
    doublereal PGas  = tp.pressure();
    /*
     * Make sure that there is a common temperature and
     * pressure for all ThermoPhase objects belonging to the
     * interfacial kinetics object, if it is required by
     * the problem statement.
     */
    if (m_commonTempPressForPhases) {
        setCommonState_TP(TKelvin, PGas);
    }

    doublereal reltol = 1.0E-6;
    doublereal atol = 1.0E-20;

    /*
     * Install a filter for negative concentrations. One of the
     * few ways solveSS can fail is if concentrations on input
     * are below zero.
     */
    bool rset = false;
    for (size_t k = 0; k < m_nv; k++) {
        if (m_concSpecies[k] < 0.0) {
            rset = true;
            m_concSpecies[k] = 0.0;
        }
    }
    if (rset) {
        setConcSpecies(DATA_PTR(m_concSpecies));
    }

    m_surfSolver->m_ioflag = m_ioFlag;

    // Save the current solution
    copy(m_concSpecies.begin(), m_concSpecies.end(), m_concSpeciesSave.begin());

    int retn = m_surfSolver->solveSurfProb(ifunc, time_scale, TKelvin, PGas,
                                           reltol, atol);
    if (retn != 1) {
        // reset the concentrations
        copy(m_concSpeciesSave.begin(), m_concSpeciesSave.end(), m_concSpecies.begin());
        setConcSpecies(DATA_PTR(m_concSpeciesSave));
        ifunc = SFLUX_INITIALIZE;
        retn = m_surfSolver->solveSurfProb(ifunc, time_scale, TKelvin, PGas,
                                           reltol, atol);

        if (retn != 1) {
            throw CanteraError("ImplicitSurfChem::solvePseudoSteadyStateProblem",
                               "solveSP return an error condition!");
        }
    }
}

void ImplicitSurfChem::getConcSpecies(doublereal* const vecConcSpecies) const
{
    size_t kstart;
    for (size_t ip = 0; ip < m_nsurf; ip++) {
        ThermoPhase* TP_ptr = m_surf[ip];
        kstart = m_specStartIndex[ip];
        TP_ptr->getConcentrations(vecConcSpecies + kstart);
    }
    kstart = m_nv;
    for (size_t ip = 0; ip <  m_numBulkPhases; ip++) {
        ThermoPhase* TP_ptr = m_bulkPhases[ip];
        TP_ptr->getConcentrations(vecConcSpecies + kstart);
        kstart += TP_ptr->nSpecies();
    }
}

void ImplicitSurfChem::setConcSpecies(const doublereal* const vecConcSpecies)
{
    size_t kstart;
    for (size_t ip = 0; ip < m_nsurf; ip++) {
        ThermoPhase* TP_ptr = m_surf[ip];
        kstart = m_specStartIndex[ip];
        TP_ptr->setConcentrations(vecConcSpecies + kstart);
    }
    kstart = m_nv;
    for (size_t ip = 0; ip <  m_numBulkPhases; ip++) {
        ThermoPhase* TP_ptr = m_bulkPhases[ip];
        TP_ptr->setConcentrations(vecConcSpecies + kstart);
        kstart += TP_ptr->nSpecies();
    }
}

void ImplicitSurfChem::setCommonState_TP(doublereal TKelvin, doublereal PresPa)
{
    for (size_t ip = 0; ip < m_nsurf; ip++) {
        ThermoPhase* TP_ptr = m_surf[ip];
        TP_ptr->setState_TP(TKelvin, PresPa);
    }
    for (size_t ip = 0; ip < m_numBulkPhases; ip++) {
        ThermoPhase* TP_ptr = m_bulkPhases[ip];
        TP_ptr->setState_TP(TKelvin, PresPa);
    }
}

}


text:
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "Xlibint.h"

int
XChangeKeyboardControl(
    register Display *dpy,
    unsigned long mask,
    XKeyboardControl *value_list)
{
    unsigned long values[8];
    register unsigned long *value = values;
    long nvalues;
    register xChangeKeyboardControlReq *req;

    LockDisplay(dpy);
    GetReq(ChangeKeyboardControl, req);
    req->mask = mask;

    if (mask & KBKeyClickPercent)
	*value++ = value_list->key_click_percent;

    if (mask & KBBellPercent)
    	*value++ = value_list->bell_percent;

    if (mask & KBBellPitch)
    	*value++ = value_list->bell_pitch;

    if (mask & KBBellDuration)
    	*value++ = value_list->bell_duration;

    if (mask & KBLed)
    	*value++ = value_list->led;

    if (mask & KBLedMode)
	*value++ = value_list->led_mode;

    if (mask & KBKey)
        *value++ = value_list->key;

    if (mask & KBAutoRepeatMode)
        *value++ = value_list->auto_repeat_mode;

    req->length += (nvalues = value - values);

    /* note: Data is a macro that uses its arguments multiple
       times, so "nvalues" is changed in a separate assignment
       statement */

    nvalues <<= 2;
    Data32 (dpy, (long *) values, nvalues);
    UnlockDisplay(dpy);
    SyncHandle();
    return 1;
    }


text:
from __future__ import absolute_import, division, print_function

import multiprocessing as mp
import os

import falcon
import falcon.testing as testing

import requests

from twisted.internet import reactor, ssl
from twisted.web.server import Site
from twisted.web.wsgi import WSGIResource

from falcon_mutualauth.mutualauth import Authorize, MutualAuthRequest

class HelloResource(object):
    def on_get(self, req, resp):
        resp.body = req.get_header('X-User')

class TestTLSCerts(testing.TestCase):
    def setUp(self):
        super(TestTLSCerts, self).setUp()

        tests_dir = os.path.dirname(__file__)
        self._certs_dir = os.path.join(
            tests_dir,
            'fixtures',
            'certs'
        )

        self._skeypath = self._cert_path('server-key.pem')
        self._scrtpath = self._cert_path('server-cert.pem')
        self._ccertpath = self._cert_path('ca-cert.pem')

        self._server_key = self._load_text_file(self._skeypath)
        self._server_crt = self._load_text_file(self._scrtpath)
        self._ca_cert = self._load_text_file(self._ccertpath)

        self._session = requests.Session()
        self._session.verify = self._cert_path('ca-cert.pem')
        self._session.cert = (self._cert_path('client-cert.pem'),
                              self._cert_path('client-key.pem'))

        self._server = mp.Process(target=self._server_run)
        self._server.start()

        self._server.join(0.2)

    def tearDown(self):
        self._server.terminate()

    def _load_text_file(self, filename):
        with open(filename, 'r') as infile:
            return infile.read()

    def _cert_path(self, filename):
        return os.path.join(self._certs_dir, filename)

    def _create(self):
        hellos = HelloResource()
        middleware = [Authorize('user')]
        api = falcon.API(middleware=middleware)

        api.add_route('/', hellos)

        return api

    def _create_tls_context(self, server_cert, server_key, ca_cert):
        """Create a twisted TLS context factory.

        :param server_cert: PEM-formatted server cert as a string.
        :param server_key: PEM-formatted private key as a string.
        :param ca_cert: PEM-formatted CA bundle as a string.
        """
        certificate = ssl.PrivateCertificate.loadPEM(server_cert +
                                                     '\n' + server_key)
        authority = ssl.Certificate.loadPEM(ca_cert)

        return certificate.options(authority)

    def _server_run(self):
        app = self._create()
        resource = WSGIResource(reactor, reactor.getThreadPool(), app)

        MutualAuthRequest.roles_map = {'Alice': ['user']}
        site = Site(resource, requestFactory=MutualAuthRequest)

        ctx = self._create_tls_context(self._server_crt,
                                       self._server_key,
                                       self._ca_cert)

        reactor.listenSSL(interface='localhost',
                          port=8080,
                          factory=site,
                          contextFactory=ctx)

        reactor.run()

    def test_authorized(self):
        resp = self._session.get('https://127.0.0.1:8080/')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.text, 'Alice')

    def test_unauthorized(self):
        cert = (self._cert_path('client-cert-eve.pem'),
                self._cert_path('client-key-eve.pem'))

        resp = self._session.get('https://127.0.0.1:8080/', cert=cert)
        self.assertEqual(resp.status_code, 403)

        headers = {'X-User-Roles': 'user'}
        resp = self._session.get('https://127.0.0.1:8080/', cert=cert,
                                 headers=headers)
        self.assertEqual(resp.status_code, 403)


text:
import tempfile

from usb.config.base import *

db_file = tempfile.NamedTemporaryFile()

# Enable debug mode
DEBUG = True

# Enable testing mode
TESTING = True

SQLALCHEMY_DATABASE_URI = 'sqlite:///' + db_file.name


text:
set -e
set -x

DOWNLOAD_NAME=allele_sequences
SCRATCH_DIR=${TMPDIR-/tmp}/mhcflurry-downloads-generation
SCRIPT_ABSOLUTE_PATH="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/$(basename "${BASH_SOURCE[0]}")"
SCRIPT_DIR=$(dirname "$SCRIPT_ABSOLUTE_PATH")
export PYTHONUNBUFFERED=1

mkdir -p "$SCRATCH_DIR"
rm -rf "$SCRATCH_DIR/$DOWNLOAD_NAME"
mkdir "$SCRATCH_DIR/$DOWNLOAD_NAME"

# Send stdout and stderr to a logfile included with the archive.
exec >  >(tee -ia "$SCRATCH_DIR/$DOWNLOAD_NAME/LOG.txt")
exec 2> >(tee -ia "$SCRATCH_DIR/$DOWNLOAD_NAME/LOG.txt" >&2)

# Log some environment info
date
pip freeze
git status
which clustalo
clustalo --version

cd $SCRATCH_DIR/$DOWNLOAD_NAME
cp $SCRIPT_DIR/make_allele_sequences.py .
cp $SCRIPT_DIR/select_alleles_to_disambiguate.py .
cp $SCRIPT_DIR/filter_sequences.py .

cp $SCRIPT_DIR/class1_pseudosequences.csv .

cp $SCRIPT_ABSOLUTE_PATH .

# Generate sequences
# Training data is used to decide which additional positions to include in the
# allele sequences to differentiate alleles that have identical traditional
# pseudosequences but have associated training data
TRAINING_DATA="$(mhcflurry-downloads path data_curated)/curated_training_data.csv.bz2"

python select_alleles_to_disambiguate.py \
    "$TRAINING_DATA" \
    --min-count 1000 \
    --out training_data.alleles.txt

# Human
wget -q ftp://ftp.ebi.ac.uk/pub/databases/ipd/imgt/hla/fasta/A_prot.fasta
wget -q ftp://ftp.ebi.ac.uk/pub/databases/ipd/imgt/hla/fasta/B_prot.fasta
wget -q ftp://ftp.ebi.ac.uk/pub/databases/ipd/imgt/hla/fasta/C_prot.fasta
wget -q ftp://ftp.ebi.ac.uk/pub/databases/ipd/imgt/hla/fasta/E_prot.fasta
wget -q ftp://ftp.ebi.ac.uk/pub/databases/ipd/imgt/hla/fasta/F_prot.fasta
wget -q ftp://ftp.ebi.ac.uk/pub/databases/ipd/imgt/hla/fasta/G_prot.fasta

# Mouse
wget -q https://www.uniprot.org/uniprot/P01899.fasta  # H-2 Db
wget -q https://www.uniprot.org/uniprot/P01900.fasta  # H-2 Dd
wget -q https://www.uniprot.org/uniprot/P14427.fasta  # H-2 Dp
wget -q https://www.uniprot.org/uniprot/P14426.fasta  # H-2 Dk
wget -q https://www.uniprot.org/uniprot/Q31145.fasta  # H-2 Dq

wget -q https://www.uniprot.org/uniprot/P01901.fasta  # H-2 Kb
wget -q https://www.uniprot.org/uniprot/P01902.fasta  # H-2 Kd
wget -q https://www.uniprot.org/uniprot/P04223.fasta  # H-2 Kk
wget -q https://www.uniprot.org/uniprot/P14428.fasta  # H-2 Kq

wget -q https://www.uniprot.org/uniprot/P01897.fasta  # H-2 Ld
wget -q https://www.uniprot.org/uniprot/Q31151.fasta  # H-2 Lq

# Various
wget -q ftp://ftp.ebi.ac.uk/pub/databases/ipd/mhc/MHC_prot.fasta

python filter_sequences.py *.fasta --out class1.fasta

time clustalo -i class1.fasta -o class1.aligned.fasta

time python make_allele_sequences.py \
    class1.aligned.fasta \
    --recapitulate-sequences class1_pseudosequences.csv \
    --differentiate-alleles training_data.alleles.txt \
    --out-csv allele_sequences.csv

time python make_allele_sequences.py \
    class1.aligned.fasta \
    --recapitulate-sequences class1_pseudosequences.csv \
    --out-csv allele_sequences.no_differentiation.csv

# Cleanup
gzip -f class1.fasta
gzip -f class1.aligned.fasta
rm *.fasta

cp $SCRIPT_ABSOLUTE_PATH .
bzip2 LOG.txt
RESULT="$SCRATCH_DIR/${DOWNLOAD_NAME}.$(date +%Y%m%d).tar.bz2"
tar -cjf "$RESULT" *
echo "Created archive: $RESULT"


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Schlechtendalia 4: 24 (2000)

#### Original name
Erysiphe udaipurensis var. udaipurensis

### Remarks
null


text: - Fixed an issue that dates with values of day/month/year were '0' raised an exception.


text:
namespace asio {
namespace ip {

/// The resolver_base class is used as a base for the basic_resolver class
/// templates to provide a common place to define the flag constants.
class resolver_base
{
public:
#if defined(GENERATING_DOCUMENTATION)
  /// A bitmask type (C++ Std [lib.bitmask.types]).
  typedef unspecified flags;

  /// Determine the canonical name of the host specified in the query.
  static const flags canonical_name = implementation_defined;

  /// Indicate that returned endpoint is intended for use as a locally bound
  /// socket endpoint.
  static const flags passive = implementation_defined;

  /// Host name should be treated as a numeric string defining an IPv4 or IPv6
  /// address and no name resolution should be attempted.
  static const flags numeric_host = implementation_defined;

  /// Service name should be treated as a numeric string defining a port number
  /// and no name resolution should be attempted.
  static const flags numeric_service = implementation_defined;

  /// If the query protocol family is specified as IPv6, return IPv4-mapped
  /// IPv6 addresses on finding no IPv6 addresses.
  static const flags v4_mapped = implementation_defined;

  /// If used with v4_mapped, return all matching IPv6 and IPv4 addresses.
  static const flags all_matching = implementation_defined;

  /// Only return IPv4 addresses if a non-loopback IPv4 address is configured
  /// for the system. Only return IPv6 addresses if a non-loopback IPv6 address
  /// is configured for the system.
  static const flags address_configured = implementation_defined;
#else
  enum flags
  {
    canonical_name = ASIO_OS_DEF(AI_CANONNAME),
    passive = ASIO_OS_DEF(AI_PASSIVE),
    numeric_host = ASIO_OS_DEF(AI_NUMERICHOST),
    numeric_service = ASIO_OS_DEF(AI_NUMERICSERV),
    v4_mapped = ASIO_OS_DEF(AI_V4MAPPED),
    all_matching = ASIO_OS_DEF(AI_ALL),
    address_configured = ASIO_OS_DEF(AI_ADDRCONFIG)
  };

  // Implement bitmask operations as shown in C++ Std [lib.bitmask.types].

  friend flags operator&(flags x, flags y)
  {
    return static_cast<flags>(
        static_cast<unsigned int>(x) & static_cast<unsigned int>(y));
  }

  friend flags operator|(flags x, flags y)
  {
    return static_cast<flags>(
        static_cast<unsigned int>(x) | static_cast<unsigned int>(y));
  }

  friend flags operator^(flags x, flags y)
  {
    return static_cast<flags>(
        static_cast<unsigned int>(x) ^ static_cast<unsigned int>(y));
  }

  friend flags operator~(flags x)
  {
    return static_cast<flags>(~static_cast<unsigned int>(x));
  }

  friend flags& operator&=(flags& x, flags y)
  {
    x = x & y;
    return x;
  }

  friend flags& operator|=(flags& x, flags y)
  {
    x = x | y;
    return x;
  }

  friend flags& operator^=(flags& x, flags y)
  {
    x = x ^ y;
    return x;
  }
#endif

protected:
  /// Protected destructor to prevent deletion through this type.
  ~resolver_base()
  {
  }
};

} // namespace ip
} // namespace asio

#include "asio/detail/pop_options.hpp"

#endif // ASIO_IP_RESOLVER_BASE_HPP


text:
package com.blogspot.toomuchcoding.book.chapter6._7_VerifyingIgnoringStubs.assertj;

import com.blogspot.toomuchcoding.book.chapter6._7_VerifyingIgnoringStubs.TaxService;
import com.blogspot.toomuchcoding.book.chapter6._7_VerifyingIgnoringStubs.TaxTransferer;
import com.blogspot.toomuchcoding.person.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.exceptions.verification.NoInteractionsWanted;
import org.mockito.runners.MockitoJUnitRunner;

import static org.assertj.core.api.BDDAssertions.then;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class TaxTransfererTest {

    @Mock TaxService taxService;

    @InjectMocks TaxTransferer systemUnderTest;

	@Test
	public void should_verify_that_ignoring_stubbed_method_there_was_a_single_interaction_with_mock() {
		// given
		Person person = new Person();
		given(taxService.sendStatisticsReport()).willReturn(true);

		// when
		boolean success = systemUnderTest.transferTaxFor(person);

		// then
		verify(taxService).transferTaxFor(person);
		verifyNoMoreInteractions(ignoreStubs(taxService));
		then(success).isTrue();
	}

    /** contains expected only for the test to pass **/
    @Test(expected = NoInteractionsWanted.class)
    public void should_fail_on_verifying_no_more_interactions_due_to_existing_stubbing() {
        // given
        Person person = new Person();
        given(taxService.sendStatisticsReport()).willReturn(true);

        // when
        boolean success = systemUnderTest.transferTaxFor(person);

        // then
        verify(taxService).transferTaxFor(person);
        verifyNoMoreInteractions(taxService);
	    then(success).isTrue();
    }

}


text:
package ro.nextreports.server.web.core.validation;

import org.apache.wicket.validation.validator.StringValidator;

/**
 * @author Decebal Suiu
 */
public abstract class BaseMessageStringValidator extends StringValidator {

	private static final long serialVersionUID = 1L;

	protected final String errorMessage;

    public BaseMessageStringValidator(String errorMessage) {
        this.errorMessage = errorMessage;
    }

}


text:
require 'travis/cli/setup'

module Travis
  module CLI
    class Setup
      class Cloud_66 < Service
        description "Automatic deployment to Cloud 66"
        service_name 'cloud66'

        def run
          deploy 'cloud66', 'release' do |config|
            config['redeployment_hook'] ||= ask("Cloud 66 Redeployment Hook Url: ") { |q| q.echo = "*" }.to_s

            encrypt(config, 'redeployment_hook') if agree("Encrypt Redeployment Hook?") { |q| q.default = 'yes' }
          end
        end
      end
    end
  end
end


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Cat. afr. pl. 1:73. 1896 (Welwitsch ex Ficalho, Bol. Soc. Geogr. Lisb. 2:608. 1881, nom. nud. )

#### Original name
null

### Remarks
null


text:
<?php

use paslandau\DataFiltering\Events\DataEmitterInterface;
use paslandau\DataFiltering\Events\DataProcessedEvent;
use paslandau\DataFiltering\Extraction\AbstractBaseExtractor;
use paslandau\DataFiltering\Extraction\InputDataExtractor;
use paslandau\DataFiltering\Transformation\DataTransformerInterface;

class InputDataExtractorTest extends PHPUnit_Framework_TestCase
{
    public function test_extract()
    {
        $mock = $this->getMock(DataTransformerInterface::class);
        $f = function ($data) {
            return ($data + 1);
        };
        $mock->expects($this->once())->method("transform")->will($this->returnCallback($f));
        /** @var DataTransformerInterface $mock */

        $input = 1;
        $e = new InputDataExtractor($input);
        $e->setTransformer($mock);

        $event = new stdClass();
        $collector = function (DataProcessedEvent $e) use (&$event) {
            $event = $e;
        };
        $e->getDispatcher()->addListener(DataEmitterInterface::EVENT_ON_PROCESSED, $collector);

        $expected = $input + 1;
        $actual = $e->getData(100000);

        $this->assertEquals($expected, $actual, "Wrong value extracted");
        $this->assertEquals(DataProcessedEvent::class, get_class($event), "Didn't receive an event");
        /** @var DataProcessedEvent $event */
        $this->assertEquals($input, $event->getDataBefore(), "Before-Data is wrong");
        $this->assertEquals($expected, $event->getDataAfter(), "After-Data is wrong");

    }

    public function test_extractWithoutTransformer()
    {
        $input = 1;
        $e = new InputDataExtractor($input);

        $event = new stdClass();
        $collector = function (DataProcessedEvent $e) use (&$event) {
            $event = $e;
        };
        $e->getDispatcher()->addListener(DataEmitterInterface::EVENT_ON_PROCESSED, $collector);

        $expected = $input;
        $actual = $e->getData(10000);

        $this->assertEquals($expected, $actual, "Wrong value extracted");
        $this->assertEquals(DataProcessedEvent::class, get_class($event), "Didn't receive an event");
        /** @var DataProcessedEvent $event */
        $this->assertEquals($input, $event->getDataBefore(), "Before-Data is wrong");
        $this->assertEquals($expected, $event->getDataAfter(), "After-Data is wrong");
    }
}


text:
module Qmin
  module Reporting
    class Honeybadger
      def report(exception)
        ::Honeybadger.notify_or_ignore(exception)
      end
    end
  end
end


text:
<refentry xmlns="http://docbook.org/ns/docbook"
          xmlns:xlink="http://www.w3.org/1999/xlink"
          xmlns:xi="http://www.w3.org/2001/XInclude"
          xmlns:src="http://nwalsh.com/xmlns/litprog/fragment"
          xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
          version="5.0" xml:id="toc.blank.text">
<refmeta>
<refentrytitle>toc.blank.text</refentrytitle>
<refmiscinfo class="other" otherclass="datatype">string</refmiscinfo>
</refmeta>
<refnamediv>
<refname>toc.blank.text</refname>
<refpurpose>The text for "blanks" in the TOC</refpurpose>
</refnamediv>

<refsynopsisdiv>
<src:fragment xml:id="toc.blank.text.frag">
<xsl:param name="toc.blank.text">   </xsl:param>
</src:fragment>
</refsynopsisdiv>

<refsection><info><title>Description</title></info>
<para>If <varname>toc.blank.graphic</varname> is zero, this text string
will be used for "blanks" in the TOC.</para>
<para>Only applies with the tabular presentation is being used.</para>
</refsection>
</refentry>


text:
define(function () {

// Utility function to append a 0 to single-digit numbers
    Date.LZ = function (x) {
        return(x < 0 || x > 9 ? "" : "0") + x;
    };
// Full month names. Change this for local month names
    Date.monthNames = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
// Month abbreviations. Change this for local month names
    Date.monthAbbreviations = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
// Full day names. Change this for local month names
    Date.dayNames = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
// Day abbreviations. Change this for local month names
    Date.dayAbbreviations = new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
// Used for parsing ambiguous dates like 1/2/2000 - default to preferring 'American' format meaning Jan 2.
// Set to false to prefer 'European' format meaning Feb 1
    Date.preferAmericanFormat = true;

// If the getFullYear() method is not defined, create it
    if (!Date.prototype.getFullYear) {
        Date.prototype.getFullYear = function () {
            var yy = this.getYear();
            return (yy < 1900 ? yy + 1900 : yy);
        };
    }

// Check if a date string is valid
    Date.isValid = function (val, format) {
        return (Date.parseString(val, format) !== null);
    };

// Check if a date object is before another date object
    Date.prototype.isBefore = function (date2) {
        if (date2 === null) {
            return false;
        }
        return (this.getTime() < date2.getTime());
    };

// Check if a date object is after another date object
    Date.prototype.isAfter = function (date2) {
        if (date2 === null) {
            return false;
        }
        return (this.getTime() > date2.getTime());
    };

// Check if two date objects have equal dates and times
    Date.prototype.equals = function (date2) {
        if (date2 === null) {
            return false;
        }
        return (this.getTime() === date2.getTime());
    };

// Check if two date objects have equal dates, disregarding times
    Date.prototype.equalsIgnoreTime = function (date2) {
        if (date2 === null) {
            return false;
        }
        var d1 = new Date(this.getTime()).clearTime();
        var d2 = new Date(date2.getTime()).clearTime();
        return (d1.getTime() === d2.getTime());
    };

// Format a date into a string using a given format string
    Date.prototype.format = function (format) {
        format = format + "";
        var result = "";
        var i_format = 0;
        var c = "";
        var token = "";
        var y = this.getYear() + "";
        var M = this.getMonth() + 1;
        var d = this.getDate();
        var E = this.getDay();
        var H = this.getHours();
        var m = this.getMinutes();
        var s = this.getSeconds();
        var yyyy, yy, MMM, MM, dd, hh, h, mm, ss, ampm, HH, H, KK, K, kk, k;
        // Convert real date parts into formatted versions
        var value = new Object();
        if (y.length < 4) {
            y = "" + (+y + 1900);
        }
        value["y"] = "" + y;
        value["yyyy"] = y;
        value["yy"] = y.substring(2, 4);
        value["M"] = M;
        value["MM"] = Date.LZ(M);
        value["MMM"] = Date.monthNames[M - 1];
        value["NNN"] = Date.monthAbbreviations[M - 1];
        value["d"] = d;
        value["dd"] = Date.LZ(d);
        value["E"] = Date.dayAbbreviations[E];
        value["EE"] = Date.dayNames[E];
        value["H"] = H;
        value["HH"] = Date.LZ(H);
        if (H === 0) {
            value["h"] = 12;
        } else if (H > 12) {
            value["h"] = H - 12;
        } else {
            value["h"] = H;
        }
        value["hh"] = Date.LZ(value["h"]);
        value["K"] = value["h"] - 1;
        value["k"] = value["H"] + 1;
        value["KK"] = Date.LZ(value["K"]);
        value["kk"] = Date.LZ(value["k"]);
        if (H > 11) {
            value["a"] = "PM";
        } else {
            value["a"] = "AM";
        }
        value["m"] = m;
        value["mm"] = Date.LZ(m);
        value["s"] = s;
        value["ss"] = Date.LZ(s);
        while (i_format < format.length) {
            c = format.charAt(i_format);
            token = "";
            while ((format.charAt(i_format) === c) && (i_format < format.length)) {
                token += format.charAt(i_format++);
            }
            if (typeof (value[token]) !== "undefined") {
                result = result + value[token];
            } else {
                result = result + token;
            }
        }
        return result;
    };

// Get the full name of the day for a date
    Date.prototype.getDayName = function () {
        return Date.dayNames[this.getDay()];
    };

// Get the abbreviation of the day for a date
    Date.prototype.getDayAbbreviation = function () {
        return Date.dayAbbreviations[this.getDay()];
    };

// Get the full name of the month for a date
    Date.prototype.getMonthName = function () {
        return Date.monthNames[this.getMonth()];
    };

// Get the abbreviation of the month for a date
    Date.prototype.getMonthAbbreviation = function () {
        return Date.monthAbbreviations[this.getMonth()];
    };

// Clear all time information in a date object
    Date.prototype.clearTime = function () {
        this.setHours(0);
        this.setMinutes(0);
        this.setSeconds(0);
        this.setMilliseconds(0);
        return this;
    };

// Add an amount of time to a date. Negative numbers can be passed to subtract time.
    Date.prototype.add = function (interval, number) {
        if (typeof (interval) === "undefined" || interval === null || typeof (number) === "undefined" || number === null) {
            return this;
        }
        number = +number;
        if (interval === 'y') { // year
            this.setFullYear(this.getFullYear() + number);
        } else if (interval === 'M') { // Month
            this.setMonth(this.getMonth() + number);
        } else if (interval === 'd') { // Day
            this.setDate(this.getDate() + number);
        } else if (interval === 'w') { // Weekday
            var step = (number > 0) ? 1 : -1;
            while (number !== 0) {
                this.add('d', step);
                while (this.getDay() === 0 || this.getDay() === 6) {
                    this.add('d', step);
                }
                number -= step;
            }
        } else if (interval === 'h') { // Hour
            this.setHours(this.getHours() + number);
        } else if (interval === 'm') { // Minute
            this.setMinutes(this.getMinutes() + number);
        } else if (interval === 's') { // Second
            this.setSeconds(this.getSeconds() + number);
        }
        return this;
    };
    return   Date;
});