text:
#include <unordered_map>

#include "dispatch-c++.h"

/*
 * For synchronous dispatch.
 */
static void call_func_void_void(void * context)
{
	std::function<void (void)> &func = *static_cast<std::function<void (void)> *>(context);

	func();
}

/*
 * For asynchronous dispatch.
 */
static void call_funcptr_void_void(void * context)
{
	std::function<void (void)> * func_ptr = static_cast<std::function<void (void)> *>(context);

	(*func_ptr)();

	delete func_ptr;
}

/*
 * For synchronous dispatch.
 */
static void call_func_void_size_t(void * context, size_t idx)
{
	std::function<void (size_t)> &func = *static_cast<std::function<void (size_t)> *>(context);

	func(idx);
}

namespace dispatch {
	void dispatch_after(dispatch_time_t when, dispatch_queue_t queue, const std::function<void (void)> &func)
	{
		std::function<void (void)> * func_ptr = new std::function<void (void)>(func);

		dispatch_after_f(when, queue, static_cast<void *>(func_ptr), call_funcptr_void_void);
	}

	void dispatch_apply(size_t iterations, dispatch_queue_t queue, const std::function<void (size_t)> &func)
	{
		dispatch_apply_f(iterations, queue, static_cast<void *>(const_cast<std::function<void (size_t)> *>(&func)), call_func_void_size_t);
	}

	void dispatch_async(dispatch_queue_t queue, const std::function<void (void)> &func)
	{
		std::function<void (void)> * func_ptr = new std::function<void (void)>(func);

		dispatch_async_f(queue, static_cast<void *>(func_ptr), call_funcptr_void_void);
	}
	void dispatch_sync(dispatch_queue_t queue,  const std::function<void (void)> &func)
	{
		dispatch_sync_f(queue, static_cast<void *>(const_cast<std::function<void (void)> *>(&func)), call_func_void_void);
	}

	void dispatch_group_async(dispatch_group_t group, dispatch_queue_t queue, const std::function<void (void)> &func)
	{
		std::function<void (void)> * func_ptr = new std::function<void (void)>(func);

		dispatch_group_async_f(group, queue, static_cast<void *>(func_ptr), call_funcptr_void_void);
	}
	void dispatch_group_notify(dispatch_group_t group, dispatch_queue_t queue, const std::function<void (void)> &func)
	{
		std::function<void (void)> * func_ptr = new std::function<void (void)>(func);

		dispatch_group_notify_f(group, queue, static_cast<void *>(func_ptr), call_funcptr_void_void);
	}

	void dispatch_once(dispatch_once_t * predicate, const std::function<void (void)> &func)
	{
		dispatch_once_f(predicate, static_cast<void *>(const_cast<std::function<void (void)> *>(&func)), call_funcptr_void_void);
	}

	queue::queue() : priQueue(nullptr)
	{
	}

	queue::queue(const std::string &label, const attr attr)
	{
		static const std::unordered_map<queue::attr, dispatch_queue_attr_t> mapAttr = {
			{attr::SERIAL,     DISPATCH_QUEUE_SERIAL},
			{attr::CONCURRENT, DISPATCH_QUEUE_CONCURRENT}
		};

		this->priQueue = dispatch_queue_create(label.c_str(), mapAttr.at(attr));
	}

	queue::queue(const queue &q)
	{
		this->priQueue = q.priQueue;

		dispatch_retain(this->priQueue);
	}

	queue::queue(queue &&q)
	{
		this->priQueue = q.priQueue;

		q.priQueue = nullptr;
	}

	queue::~queue()
	{
		if (this->priQueue != nullptr) {
			dispatch_release(this->priQueue);
		}
	}

	std::string queue::label()
	{
		return dispatch_queue_get_label(this->priQueue);
	}

	queue queue::globalQueue(const priority priority)
	{
		static const std::unordered_map<queue::priority, long> mapPriority = {
			{priority::HIGH,       DISPATCH_QUEUE_PRIORITY_HIGH},
			{priority::DEFAULT,    DISPATCH_QUEUE_PRIORITY_DEFAULT},
			{priority::LOW,        DISPATCH_QUEUE_PRIORITY_LOW},
			{priority::BACKGROUND, DISPATCH_QUEUE_PRIORITY_BACKGROUND},
		};

		queue q;

		 q.priQueue = dispatch_get_global_queue(mapPriority.at(priority), 0);

		return q;
	}

	queue queue::mainQueue()
	{
		queue q;

		q.priQueue = dispatch_get_main_queue();

		return q;
	}

	void queue::apply(const size_t iterations, const std::function<void (size_t)> &func)
	{
		dispatch_apply(iterations, this->priQueue, func);
	}

	void queue::async(const std::function<void (void)> &func)
	{
		dispatch_async(this->priQueue, func);
	}

	void queue::sync(const std::function<void (void)> &func)
	{
		dispatch_sync(this->priQueue, func);
	}

	void queue::suspend()
	{
		dispatch_suspend(this->priQueue);
	}

	void queue::resume()
	{
		dispatch_resume(this->priQueue);
	}

	group::group() : priGroup(dispatch_group_create())
	{
	}

	group::group(const group &grp)
	{
		this->priGroup = grp.priGroup;

		dispatch_retain(this->priGroup);
	}

	group::group(group &&grp)
	{
		this->priGroup = grp.priGroup;

		grp.priGroup = nullptr;
	}

	group::~group()
	{
		if (this->priGroup != nullptr) {
			dispatch_release(this->priGroup);
		}
	}

	void group::enter()
	{
		dispatch_group_enter(this->priGroup);
	}

	void group::leave()
	{
		dispatch_group_leave(this->priGroup);
	}

	long group::wait(dispatch_time_t timeout)
	{
		return dispatch_group_wait(this->priGroup, timeout);
	}

	void group::notify(queue &q, const std::function<void (void)> &func)
	{
		dispatch_group_notify(this->priGroup, q.priQueue, func);
	}

	void group::async(queue &q, const std::function<void (void)> &func)
	{
		dispatch_group_async(this->priGroup, q.priQueue, func);
	}

	semaphore::semaphore() : priSemaphore(dispatch_semaphore_create(0))
	{
	}

	semaphore::semaphore(long count) : priSemaphore(dispatch_semaphore_create(count))
	{
	}

	semaphore::semaphore(const semaphore &sema)
	{
		this->priSemaphore = sema.priSemaphore;

		dispatch_retain(this->priSemaphore);
	}

	semaphore::semaphore(semaphore &&sema)
	{
		this->priSemaphore = sema.priSemaphore;

		sema.priSemaphore = nullptr;
	}

	semaphore::~semaphore()
	{
		if (this->priSemaphore != nullptr) {
			dispatch_release(this->priSemaphore);
		}
	}

	long semaphore::signal()
	{
		return dispatch_semaphore_signal(this->priSemaphore);
	}

	long semaphore::wait(dispatch_time_t timeout)
	{
		return dispatch_semaphore_wait(this->priSemaphore, timeout);
	}
}


text:
ACCEPTED

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

#### Published in
Beih. Bot. Centralbl. , Abt. 2, 57(2):288. 1937 (Bull. Herb. Boissier sé 2, 5:969. 1905, nom. nud. )

#### Original name
null

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
module Rake
  module TableTask
    module PostGIS
      #
      # convenience methods
      %w{point linestring polygon}.each do |type|
        module_eval <<-DEFINE
          def add_#{type}_column(o={}); o[:geom_type]='#{type.upcase}';add_spatial_column(o);end
          def add_multi#{type}_column(o={}); o[:geom_type]='MULTI#{type.upcase}';add_spatial_column(o);end
        DEFINE
      end

      def add_spatial_column(options={})
        options[:column_name]||=:the_geom
        options[:geom_type]||='MULTIPOLYGON'
        options[:srid]||='4326'
        options[:dimensions]=2
        run %Q/SELECT AddGeometryColumn('#{table_name}',
                                             '#{options[:column_name]}',
                                             '#{options[:srid]}',
                                             '#{options[:geom_type]}',
                                             '#{options[:dimensions].to_s}')/
        add_spatial_index(options[:column_name])
      end

      def add_spatial_index(col = :the_geom, options={})
        db.alter_table(table_name) do
          add_spatial_index col, options
        end
      end

      # add a column containing the centroid of the original geometry
      # options:
      # :centroid_column (default 'the_geom_centroids)
      # :source_column (default 'the_geom')
      # :create_trigger (default true)
      # a spatial index is always created on the new column
      #
      def add_centroids(options={})
        options[:centroid_column]||= :the_geom_centroids
        options[:source_column]||= :the_geom
        options[:create_trigger] ||= true

        add_point_column(:column_name => options[:centroid_column])
        run %Q/UPDATE #{table_name} SET
                     #{options[:centroid_column]}=ST_PointOnSurface(#{options[:source_column]})
                     WHERE #{options[:centroid_column]} IS NULL
                   /
        add_latlong_from_centroid_trigger(options)
      end

      def add_latlong_from_centroid_trigger(options={})
        centroid_column = options[:centroid_column]||=:the_geom_centroids
        source_column = options[:source_column]||=:the_geom
        db.alter_table(table_name) do
          add_column :latitude, Float
          add_column :longitude, Float
        end

      run %Q/
       CREATE OR REPLACE FUNCTION add_centroid_#{table_name}() returns trigger as $$
         DECLARE
           geom_type text;
         BEGIN
           geom_type := geometrytype(NEW.#{@db.literal(source_column)});
           BEGIN
           -- we want to ignore rows that generate errors
           -- this is usually a bad geometry problem
             if geom_type = 'POINT' THEN
                 NEW.latitude := st_y(NEW.#{@db.literal(source_column)});
                 NEW.longitude := st_x(NEW.#{@db.literal(source_column)});
             elsif geom_type = 'MULTIPOLYGON' THEN
                 NEW.the_geom_centroids := ST_PointOnSurface(NEW.#{@db.literal(source_column)});
                 NEW.latitude := st_y(NEW.#{@db.literal(centroid_column)});
                 NEW.longitude := st_x(NEW.#{@db.literal(centroid_column)});
             end if;
           EXCEPTION
             WHEN internal_error THEN
             RETURN NULL;
           END;

           RETURN NEW;
         END;
       $$ language 'plpgsql';

       CREATE TRIGGER add_centroid
         BEFORE INSERT OR UPDATE ON #{table_name}
         FOR EACH ROW EXECUTE PROCEDURE add_centroid_#{table_name}();
       /
      end
    end
  end
end


text:
<?php
/*------------------------------------------------------------------------------
    File: www/index.php
 Project: MUN Computer Science Society Website
 Version: 0.1.0
      By: Tim Oram
 Website: http://society.cs.mun.ca
   Email: muncssociety@gmail.com
------------------------------------------------------------------------------*/
require 'init.php';

$tpl = TemplateEngine::templateFromFile('main');

$data = array(
	'page' => array(
		'title' => 'News and Updates'
	),
	'content' => TemplateEngine::get(TemplateEngine::templateFromFile('content/news'))
);
TemplateEngine::output($tpl, $data);


text:
<?php declare(strict_types=1);

return 'not an array';


text:
'use strict';

module.exports = function (app) {
  // User Routes
  var users = require('../controllers/users.server.controller');

  // Setting up the users profile api
  app.route('/api/users/me').get(users.me);

  // Finish by binding the user middleware
  app.param('userId', users.userByID);
};


text:
QUnit.module('validateEmailAddress_Default');

QUnit.test('validateEmailAddressFormat_EmptyAddress_ShouldReject', function (assert) {
    assert.expect(1);

    // Arrange
    var addr = '';

    // Act
    var result = validateEmailAddressFormat(addr);

    // Assert
    assert.notOk(result, 'Empty string should fail');
});

QUnit.test('validateEmailAddressFormat_NoAt_ShouldReject', function (assert) {
    assert.expect(1);

    // Arrange
    var addr = 'abcdefg.hijklmn.opqrs.com';

    // Act
    var result = validateEmailAddressFormat(addr);

    // Assert
    assert.notOk(result, 'Address without "@" should fail');
});

QUnit.test('validateEmailAddressFormat_EmptyLocal_ShouldReject', function (assert) {
    assert.expect(1);

    // Arrange
    var addr = '@example.com';

    // Act
    var result = validateEmailAddressFormat(addr);

    // Assert
    assert.notOk(result, 'Address without local part should fail');
});

QUnit.test('validateEmailAddressFormat_MinimalAddress_ShouldAccept', function (assert) {
    assert.expect(1);

    // Arrange
    var addr = 'a@b';

    // Act
    var result = validateEmailAddressFormat(addr);

    // Assert
    assert.ok(result, 'Valid address should pass');
});

QUnit.test('validateEmailAddressFormat_LongLegalAddress_ShouldAccept', function (assert) {
    assert.expect(1);

    // Arrange
    var addr = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkl@abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijk.abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijk.abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghi';

    // Act
    var result = validateEmailAddressFormat(addr);

    // Assert
    assert.ok(result, 'Valid long address should pass');
});

QUnit.test('validateEmailAddressFormat_TooLong_ShouldReject', function (assert) {
    assert.expect(1);

    // Arrange
    var addr = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkl@abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijk.abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijk.abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghij';

    // Act
    var result = validateEmailAddressFormat(addr);

    // Assert
    assert.notOk(result, 'Invalid long address should fail');
});

QUnit.test('validateEmailAddressFormat_LocalTooLong_ShouldReject', function (assert) {
    assert.expect(1);

    // Arrange
    var addr = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm@example.com';

    // Act
    var result = validateEmailAddressFormat(addr);

    // Assert
    assert.notOk(result, 'Address with over 64 characters in local part should fail');
});

QUnit.test('validateEmailAddressFormat_LocalPartHasValidSymbols_ShouldAccept', function (assert) {
    assert.expect(1);

    // Arrange
    var addr = "!#$%&'*+-/=?^_`{|}~@example.com";

    // Act
    var result = validateEmailAddressFormat(addr);

    // Assert
    assert.ok(result, 'Address with valid symbols in the local part should pass');
});

QUnit.test('validateEmailAddressFormat_LocalPartHasDots_ShouldAccept', function (assert) {
    assert.expect(1);

    // Arrange
    var addr = "abc.def.ghi.j.k@example.com";

    // Act
    var result = validateEmailAddressFormat(addr);

    // Assert
    assert.ok(result, 'Address with nonconsecutive . characters in the local part should pass');
});

QUnit.test('validateEmailAddressFormat_LocalPartHasConsecutiveDots_ShouldReject', function (assert) {
    assert.expect(1);

    // Arrange
    var addr = "abc..def@example.com";

    // Act
    var result = validateEmailAddressFormat(addr);

    // Assert
    assert.notOk(result, 'Address with consecutive . characters in the local part should fail');
});

QUnit.test('validateEmailAddressFormat_LocalPartStartsWithDot_ShouldReject', function (assert) {
    assert.expect(1);

    // Arrange
    var addr = ".abc@example.com";

    // Act
    var result = validateEmailAddressFormat(addr);

    // Assert
    assert.notOk(result, 'Address with local part starting with . character should fail');
});

QUnit.test('validateEmailAddressFormat_LocalPartEndsWithDot_ShouldReject', function (assert) {
    assert.expect(1);

    // Arrange
    var addr = "abc.@example.com";

    // Act
    var result = validateEmailAddressFormat(addr);

    // Assert
    assert.notOk(result, 'Address with local part ending with . character should fail');
});

QUnit.test('validateEmailAddressFormat_LocalHasInvalidSymbol_ShouldReject', function (assert) {

    // Arrange
    var addresses = [
        'abc@def@example.com',      // @ in middle of local part
        '@abc@example.com',         // @ at start of local part
        'abc@@example.com',         // @ at end of local part
        'ab"c"d@example.com',       // " in the wrong location
        '"abc@example.com',         // unbalanced "
        'abc"@example.com',         // unbalanced "
        'abc[@example.com',         // [
        'abc]@example.com',         // ]
        'abc[]def@example.com',     // [ and ]
        'abc[def]ghi@example.com',  // [ and ]
        'abc def@example.com',      // space
        'abc\ndef@example.com',     // newline
        'abc,def@example.com',      // comma
        'abc\x02def@example.com',   // control character
        ];
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.notOk(result.result, '"' + result.address + '" has invalid characters in the local part and should fail');
    })
});

QUnit.test('validateEmailAddressFormat_LocalHasBareEscapedSymbols_ShouldReject', function (assert) {

    // Arrange
    var addresses = [
        'abc\\@def@example.com',        // @ in middle of local part
        '\\@abc@example.com',           // @ at start of local part
        'abc\\@@example.com',           // @ at end of local part
        'ab\\"c\\"d@example.com',       // "
        '\\"abc@example.com',           // unbalanced "
        'abc\\"@example.com',           // unbalanced "
        'abc\\[@example.com',           // [
        'abc\\]@example.com',           // ]
        'abc\\[\\]def@example.com',     // [ and ]
        'abc\\[def\\]ghi@example.com',  // [ and ]
        'abc\\ def@example.com',        // space
        'abc\\\ndef@example.com',       // newline
        'abc\\,def@example.com',        // comma
        'abc\\\x02def@example.com',     // control character
        'abc.\\.def@example.com',       // consecutive dot
        'abc\\..def@example.com',       // consecutive dot
        '\\.abc@example.com',           // leading dot
        'abc\\.@example.com',           // trailing dot
        '\\a\\b\\c\\!#\\$%\\&\'*\\+-\\/=\\?^\\_`{\\|}~@example.com' // Unnecessarily escaped characters
        ];
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.notOk(result.result, '"' + result.address + '" has escaped symbols in the local part and should fail');
    })
});

QUnit.test('validateEmailAddressFormat_LocalHasQuotedSymbols_ShouldAccept', function (assert) {

    // Arrange
    var addresses = [
        '"abc"@example.com',
        '"abc@def"@example.com',
        '"@abc".def@example.com',
        'xyz."abc@"@example.com',
        '"abc["@example.com',
        'xyz."abc]".def@example.com',
        '"abc[]def"@example.com',
        '"abc[def]ghi"@example.com',
        '"abc def"@example.com',
        '"abc\n\tdef"@example.com',
        '"abc,def"@example.com',
        '"abc\x02def"@example.com',
        '"abc....def"@example.com',
        'abc."def@".ghi@example.com',
        '"abc".def."ghi"@example.com'
        ];
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.ok(result.result, '"' + result.address + '" has a quoted section in the local part and should pass');
    })
});

QUnit.test('validateEmailAddressFormat_LocalHasInvalidCharactersInQuotedString_ShouldReject', function (assert) {

    // Arrange
    var addresses = [
        '"a"bc"@example.com',
        '"abc"@"def"@example.com',
        '"@abc\\".def@example.com',
        '"abc\x03def@example.com'
        ];
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.notOk(result.result, '"' + result.address + '" has invalid characters within a quoted section in the local part and should fail');
    })
});

QUnit.test('validateEmailAddressFormat_LocalHasEscapedCharactersInQuotedString_ShouldAccept', function (assert) {

    // Arrange
    var addresses = [
        '"a\\"bc"@example.com',         // Escaped "
        '"abc\\"@\\"def"@example.com',  // Escaped pair of "
        '"@abc\\\\".def@example.com',   // Escaped backslash
        '"\\a\\b\\c"@example.com'       // Unnecessarily escaped characters
        ];
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.ok(result.result, '"' + result.address + '" has escaped characters within a quoted section in the local part and should pass');
    })
});

QUnit.test('validateEmailAddressFormat_EmptyDomain_ShouldReject', function (assert) {
    assert.expect(1);

    // Arrange
    var addr = 'example@';

    // Act
    var result = validateEmailAddressFormat(addr);

    // Assert
    assert.notOk(result, 'Address without domain part should fail');
});

QUnit.test('validateEmailAddressFormat_DomainTooLong_ShouldReject', function (assert) {
    assert.expect(1);

    // Arrange
    var addr = 'me@abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijk.abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijk.abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijk.abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijkl';

    // Act
    var result = validateEmailAddressFormat(addr);

    // Assert
    assert.notOk(result, 'Domain part longer than 255 characters should fail');
});

QUnit.test('validateEmailAddressFormat_DomainLiteralBadBrackets_ShouldReject', function (assert) {
    // Arrange
    var addresses = [
        'me@[127.0.0.1',
        'me@127.0.0.1]',
        'me@127[.0.0.1]',
        'me@[127.0.0].1',
        'me@[127.0.[0].1]',
        'me@[127.0.0.1\\]'
        ];
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.notOk(result.result, '"' + result.address + '" has an invalid domain literal and should fail');
    })
});

QUnit.test('validateEmailAddressFormat_DomainLiteralValid_ShouldAccept', function (assert) {
    assert.expect(1);

    // Arrange
    var addr = 'me@[This is a valid domain literal\x02. <Really>, it is! \n Trust me. (It isn\'t meaningful in any way\\], though.)\\\\]';

    // Act
    var result = validateEmailAddressFormat(addr);

    // Assert
    assert.ok(result, 'Valid address should pass');
});

QUnit.test('validateEmailAddressFormat_DomainLiteralEscapedCharacters_ShouldAccept', function (assert) {
    // Arrange
    var addresses = [
        'me@[127\\[.0.0.1]',
        'me@[127.0.0\\].1]',
        'me@[127.0.\\[0\\].1]',
        'me@[127.0.0.1\\\\]'
        ];
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.ok(result.result, '"' + result.address + '" has escaped characters in the domain literal and should pass');
    })
});

QUnit.test('validateEmailAddressFormat_DomainValidCharacters_ShouldAccept', function (assert) {
    assert.expect(1);

    // Arrange
    var addr = 'me@abcde-fghi-jklmno--pqrstuvw---xyz012-----345-6789';

    // Act
    var result = validateEmailAddressFormat(addr);

    // Assert
    assert.ok(result, 'Valid domain should pass');
});

QUnit.test('validateEmailAddressFormat_DomainValidCharacters_ShouldReject', function (assert) {
    // Arrange
    var addresses = [
        'me@abc,def',
        'me@abc..com',
        'me@abc>def',
        'me@abc"def',
        'me@abc`def',
        'me@abc:def',
        'me@abc\\"def'
        ];
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.notOk(result.result, '"' + result.address + '" has invalid characters in the domain and should fail');
    })
});

QUnit.test('validateEmailAddressFormat_DomainLabelStartsWithDash_ShouldReject', function (assert) {
    assert.expect(1);

    // Arrange
    var addr = 'me@abc.-def.com';

    // Act
    var result = validateEmailAddressFormat(addr);

    // Assert
    assert.notOk(result, 'Domain label starting with dash should fail');
});

QUnit.test('validateEmailAddressFormat_DomainLabelEndsWithDash_ShouldReject', function (assert) {
    assert.expect(1);

    // Arrange
    var addr = 'me@abc.def-.com';

    // Act
    var result = validateEmailAddressFormat(addr);

    // Assert
    assert.notOk(result, 'Domain label ending with dash should fail');
});

QUnit.test('validateEmailAddressFormat_DomainLongValidLabels_ShouldAccept', function (assert) {
    assert.expect(1);

    // Arrange
    var addr = 'me@abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijk.abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijk.abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijk.abcdefghijklmnopqrstuvwxyza';

    // Act
    var result = validateEmailAddressFormat(addr);

    // Assert
    assert.ok(result, 'Domain labels up to 63 characters long should pass');
});

QUnit.test('validateEmailAddressFormat_DomainLabelTooLong_ShouldReject', function (assert) {
    assert.expect(1);

    // Arrange
    var addr = 'me@abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijkl.com';

    // Act
    var result = validateEmailAddressFormat(addr);

    // Assert
    assert.notOk(result, 'Domain label longer than 63 characters should fail');
});

QUnit.test('validateEmailAddressFormat_CommentsValid_ShouldAccept', function (assert) {
    // Arrange
    var addresses = [
        '(comment)(comment)me(comment comment comment)@(comment)abc(comment)(comment)(comment).(comment)def(comment)',
        '(comment (nested comment ("third level"!) (another @third level)))me@abc.com',
        'me@abc(comment with a \n folding newline).def',
        'me(comment\twith spaces, tabs, \n\t\n and \n \n \n newlines)@example.com',
        '()me@abc().def',
        'me(comment with \x03 control character)@examle.com',
        ];
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.ok(result.result, '"' + result.address + '" has valid comments and should pass');
    })
});

QUnit.test('validateEmailAddressFormat_CommentsMisplaced_ShouldReject', function (assert) {
    // Arrange
    var addresses = [
        'before(comment cannot be inside a local label. Must be before or after the label)after@abc.def',
        'me@before(comment cannot be inside a domain label. Must be before or after the label)after',
        'me@unmatched.parentheses)',
        'me@unmatched.parentheses('
        ];
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.notOk(result.result, '"' + result.address + '" has invalid comments and should fail');
    })
});

QUnit.test('validateEmailAddressFormat_CommentsBadNesting_ShouldReject', function (assert) {
    // Arrange
    var addresses = [
        '(comment (inner comment)abc@abc.def',
        'me@(inner comment) comment)after',
        'me(comment.has(nested inner comment).and starts.before@and.has.another(nested inner).but.ends.after.the.at)def.com',
        ];
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.notOk(result.result, '"' + result.address + '" has invalid comments and should fail');
    })
});

QUnit.test('validateEmailAddressFormat_FWSValid_ShouldAccept', function (assert) {
    // Arrange
    var addresses = [
        'me \n\t@\tabc \n (comment) .def \n '
        ];
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.ok(result.result, '"' + result.address + '" has valid Folding Whitespace and should pass');
    })
});

QUnit.test('validateEmailAddressFormat_FWSInvalid_ShouldReject', function (assert) {
    // Arrange
    var addresses = [
        'me\n@abc.def'
        ];
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.notOk(result.result, '"' + result.address + '" has invalid Folding Whitespace and should fail');
    })
});

QUnit.test('validateEmailAddressFormat_CommentsInvalidFWS_ShouldReject', function (assert) {
    // Arrange
    var addresses = [
        '(comment with \nnewline not followed by space or tab)abc@abc.def',
        'me@(inner comment) comment)after',
        'me(comment.has(nested inner comment).and starts.before@and.has.another(nested inner).but.ends.after.the.at)def.com',
        ];
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.notOk(result.result, '"' + result.address + '" has invalid whitespace (does not conform to Folding Whitespace) in comments and should fail');
    })
});

QUnit.module('validateEmailAddress_WithOptions');

QUnit.test('validateEmailAddressFormat_LocalDisallowedEscapedSymbols_ShouldReject', function (assert) {

    // Arrange
    var addresses = [
        'abc\\@def@example.com',        // @ in middle of local part
        '\\@abc@example.com',           // @ at start of local part
        'abc\\@@example.com',           // @ at end of local part
        'ab\\"c\\"d@example.com',       // "
        '\\"abc@example.com',           // unbalanced "
        'abc\\"@example.com',           // unbalanced "
        'abc\\[@example.com',           // [
        'abc\\]@example.com',           // ]
        'abc\\[\\]def@example.com',     // [ and ]
        'abc\\[def\\]ghi@example.com',  // [ and ]
        'abc\\ def@example.com',        // space
        'abc\\\ndef@example.com',       // newline
        'abc\\,def@example.com',        // comma
        'abc.\\.def@example.com',       // consecutive dot
        'abc\\..def@example.com',       // consecutive dot
        '\\.abc@example.com',           // leading dot
        'abc\\.@example.com',           // trailing dot
        '\\a\\b\\c\\!#\\$%\\&\'*\\+-\\/=\\?^\\_`{\\|}~@example.com' // Unnecessarily escaped characters
        ];
    var options = { allowBareEscapes:false };
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr, options)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.notOk(result.result, '"' + result.address + '" has escaped symbols in the local part, but disallows bare escapes, and should fail');
    })
});

QUnit.test('validateEmailAddressFormat_LocalAllowedEscapedSymbols_ShouldAccept', function (assert) {

    // Arrange
    var addresses = [
        'abc\\@def@example.com',        // @ in middle of local part
        '\\@abc@example.com',           // @ at start of local part
        'abc\\@@example.com',           // @ at end of local part
        'ab\\"c\\"d@example.com',       // "
        '\\"abc@example.com',           // unbalanced "
        'abc\\"@example.com',           // unbalanced "
        'abc\\[@example.com',           // [
        'abc\\]@example.com',           // ]
        'abc\\[\\]def@example.com',     // [ and ]
        'abc\\[def\\]ghi@example.com',  // [ and ]
        'abc\\ def@example.com',        // space
        'abc\\\ndef@example.com',       // newline
        'abc\\,def@example.com',        // comma
        'abc\\\x02def@example.com',     // control character
        'abc.\\.def@example.com',       // consecutive dot
        'abc\\..def@example.com',       // consecutive dot
        '\\.abc@example.com',           // leading dot
        'abc\\.@example.com',           // trailing dot
        '\\a\\b\\c\\!#\\$%\\&\'*\\+-\\/=\\?^\\_`{\\|}~@example.com' // Unnecessarily escaped characters
        ];
    var options = { allowBareEscapes:true };
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr, options)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.ok(result.result, '"' + result.address + '" has escaped symbols in the local part, but explicitly allows bare escapes, and should pass');
    })
});

QUnit.test('validateEmailAddressFormat_LocalHasQuotedEscapesWhenBareEscapesDisallowed_ShouldAccept', function (assert) {

    // Arrange
    var addresses = [
        '"abc\\@def"@example.com',        // @ in middle of local part
        '"\\@abc"@example.com',           // @ at start of local part
        '"abc\\@"@example.com',           // @ at end of local part
        '"ab\\"c\\"d"@example.com',       // "
        '"\\"abc"@example.com',           // unbalanced "
        'def."abc\\""@example.com',       // unbalanced "
        '"abc\\[".def@example.com',       // [
        '"abc\\]"@example.com',           // ]
        '"abc\\[\\]def"@example.com',     // [ and ]
        '"abc\\[def\\]ghi"@example.com',  // [ and ]
        '"abc\\ def"@example.com',        // space
        '"abc\\\ndef"@example.com',       // newline
        '"abc\\,def"@example.com',        // comma
        '"abc\x02def"@example.com',       // control character
        '"abc.\\.def"@example.com',       // consecutive dot
        '"abc\\..def"@example.com',       // consecutive dot
        '"\\.abc"@example.com',           // leading dot
        '"abc\\."@example.com',           // trailing dot
        '"\\a\\b\\c\\!#\\$%\\&\'*\\+-\\/=\\?^\\_`{\\|}~"@example.com' // Unnecessarily escaped characters
        ];
    var options = { allowBareEscapes: false };
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr, options)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.ok(result.result, '"' + result.address + '" has escaped symbols within a quoted string and should pass');
    })
});

QUnit.test('validateEmailAddressFormat_DisallowCommentsAndDoesNotHaveComments_ShouldAccept', function (assert) {
    // Arrange
    var addresses = [
        'me@example.com',
        'me@[127.0.0.1]',
        '"quoted string"@example.com',
        ];
    var options = { allowComments: false };
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr, options)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.ok(result.result, '"' + result.address + '" is valid and should pass');
    })
});

QUnit.test('validateEmailAddressFormat_CommentsDisallowed_ShouldReject', function (assert) {
    // Arrange
    var addresses = [
        '(comment)(comment)me(comment comment comment)@(comment)abc(comment)(comment)(comment).(comment)def(comment)',
        '(comment (nested comment ("third level"!) (another @third level)))me@abc.com',
        'me@abc(comment with a \nnewline).def',
        '()me@abc().def'
        ];
    var options = { allowComments: false };
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr, options)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.notOk(result.result, '"' + result.address + '" has comments, but options disallow comments, and should fail');
    })
});

QUnit.test('validateEmailAddressFormat_FullAddressWithLocalExplicitlyDisallowed_ShouldAccept', function (assert) {
    // Arrange
    var addresses = [
        'abc@def.com'
        ];
    var options = { allowLocalAddresses: 0 };
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr, options)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.ok(result.result, '"' + result.address + '" is a non-local address with local addresses disallowed and should pass');
    })
});

QUnit.test('validateEmailAddressFormat_LocalAddressWithLocalExplicitlyDisallowed_ShouldReject', function (assert) {
    // Arrange
    var addresses = [
        'abc.def'
        ];
    var options = { allowLocalAddresses: 0 };
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr, options)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.notOk(result.result, '"' + result.address + '" is a local address with local addresses disallowed and should fail');
    })
});

QUnit.test('validateEmailAddressFormat_FullAddressWithLocalAllowed_ShouldAccept', function (assert) {
    // Arrange
    var addresses = [
        'abc@def.com'
        ];
    var options = { allowLocalAddresses: 1 };
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr, options)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.ok(result.result, '"' + result.address + '" is a non-local address with local addresses allowed and should pass');
    })
});

QUnit.test('validateEmailAddressFormat_LocalAddressWithLocalAllowed_ShouldAccept', function (assert) {
    // Arrange
    var addresses = [
        'abc.def'
        ];
    var options = { allowLocalAddresses: 1 };
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr, options)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.ok(result.result, '"' + result.address + '" is a local address with local addresses allowed and should pass');
    })
});

QUnit.test('validateEmailAddressFormat_FullAddressWithLocalRequired_ShouldReject', function (assert) {
    // Arrange
    var addresses = [
        'abc@def.com'
        ];
    var options = { allowLocalAddresses: -1 };
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr, options)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.notOk(result.result, '"' + result.address + '" is a non-local address with local addresses required and should fail');
    })
});

QUnit.test('validateEmailAddressFormat_LocalAddressWithLocalRequired_ShouldAccept', function (assert) {
    // Arrange
    var addresses = [
        'abc.def'
        ];
    var options = { allowLocalAddresses: -1 };
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr, options)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.ok(result.result, '"' + result.address + '" is a local address with local addresses required and should pass');
    })
});

QUnit.test('validateEmailAddressFormat_ReturnRegex_ShouldMatchValidAddresses', function (assert) {

    // Arrange
    var addresses = [
        'a@b',
        'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkl@abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijk.abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijk.abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghi',
        "!#$%&'*+-/=?^_`{|}~@example.com",
        '"abc\\"@\\"def"@example.com',
        'me@[This is a valid domain literal\x02. <Really>, it is! \n Trust me. (It isn\'t meaningful in any way\\], though.)\\\\]',
        '(comment (nested comment ("third level"!) (another @third level)))me@abc.com',
        'me@[127.0.0.1]'
        ];
    var options = { returnRegex: true };
    var resultRegex;
    var results = [];

    // Act
    resultRegex = validateEmailAddressFormat(null, options);
    addresses.forEach(function(addr) {
        results.push({address:addr, result:resultRegex.test(addr)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.ok(result.result, '"' + result.address + '" is valid and should pass');
    })
});

QUnit.test('validateEmailAddressFormat_ReturnRegexAndDisallowComments_ShouldNotMatchAddressesWithComments', function (assert) {

    // Arrange
    var addresses = [
        '(comment)me@example.com',
        'me(comment)@example.com',
        'abc(comment).def@example.com',
        'me@(comment)example.com',
        'me@[127.0.0.1](comment)'
        ];
    var options = {
        returnRegex: true,
        allowComments: false
    };
    var resultRegex;
    var results = [];

    // Act
    resultRegex = validateEmailAddressFormat(null, options);
    addresses.forEach(function(addr) {
        results.push({address:addr, result:resultRegex.test(addr)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.notOk(result.result, '"' + result.address + '" is has disallowed comments and should fail');
    })
});

QUnit.test('validateEmailAddressFormat_NoSeparateLocalLabelsValid_ShouldAllow', function (assert) {

    // Arrange
    var addresses = [
        'addresswithoutquotes@example.com',
        '"entirelocalpartisquoted"@example.com',
        '(commentbefore)abc.def@example.com',
        'abc.def(comment after)@example.com',
        '"quotedaddress"(with comments)@example.com',
        'me@example(domain comment).com',
        ];
    var options = {
        separateLocalLabels: false
    };
    var resultRegex;
    var results = [];

    // Act
    resultRegex = validateEmailAddressFormat(null, options);
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr, options)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.ok(result.result, '"' + result.address + '" is valid and should pass');
    })
});

QUnit.test('validateEmailAddressFormat_NoSeparateLocalLabelsWithQuotedLabels_ShouldReject', function (assert) {

    // Arrange
    var addresses = [
        '"abc".def@example.com',
        'abc."def"@example.com',
        'abc."def".ghi@example.com',
        '"abc".def."ghi"@example.com',
        ];
    var options = {
        separateLocalLabels: false
    };
    var resultRegex;
    var results = [];

    // Act
    resultRegex = validateEmailAddressFormat(null, options);
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr, options)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.notOk(result.result, '"' + result.address + '" has disallowed quoted individual labels and should fail');
    })
});

QUnit.test('validateEmailAddressFormat_NoSeparateLocalLabelsWithInternalComments_ShouldReject', function (assert) {

    // Arrange
    var addresses = [
        'abc(comment)def@example.com',
        ];
    var options = {
        separateLocalLabels: false
    };
    var resultRegex;
    var results = [];

    // Act
    resultRegex = validateEmailAddressFormat(null, options);
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr, options)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.notOk(result.result, '"' + result.address + '" has disallowed quoted individual labels and should fail');
    })
});

QUnit.test('validateEmailAddressFormat_NoSeparateDomainLabelsValid_ShouldAllow', function (assert) {

    // Arrange
    var addresses = [
        'addresswithoutquotes@example.com',
        'abc.def@(comment before)example.com',
        'abc.def@example.com(comment after)',
        'abc.(local comment)def@example.com',
        ];
    var options = {
        separateDomainLabels: false
    };
    var resultRegex;
    var results = [];

    // Act
    resultRegex = validateEmailAddressFormat(null, options);
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr, options)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.ok(result.result, '"' + result.address + '" is valid and should pass');
    })
});

QUnit.test('validateEmailAddressFormat_NoSeparateDomainLabelsWithInternalComments_ShouldReject', function (assert) {

    // Arrange
    var addresses = [
        'abc.def@example(comment).com',
        ];
    var options = {
        separateDomainLabels: false
    };
    var resultRegex;
    var results = [];

    // Act
    resultRegex = validateEmailAddressFormat(null, options);
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr, options)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.notOk(result.result, '"' + result.address + '" has disallowed CFWS between individual domain labels and should fail');
    })
});

QUnit.test('validateEmailAddressFormat_StrictFWSMultipleNewlines_ShouldReject', function (assert) {

    // Arrange
    var addresses = [
        'abc(comment \n with \n \n multiple newlines)def@example.com',
        ];
    var options = {
        allowObsoleteFoldingWhitespace: false
    };
    var resultRegex;
    var results = [];

    // Act
    resultRegex = validateEmailAddressFormat(null, options);
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr, options)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.notOk(result.result, '"' + result.address + '" has invalid whitespace and should fail');
    })
});

QUnit.test('validateEmailAddressFormat_NoDomainLiteralValid_ShouldAccept', function (assert) {

    // Arrange
    var addresses = [
        'me@[domain literal]',
        'me@[domain literal \n with control FWS that contains newline]',
        'me@(comment)[domain](comment)',
        ];
    var options = {
        allowDomainLiteralEscapes: false
    };
    var resultRegex;
    var results = [];

    // Act
    resultRegex = validateEmailAddressFormat(null, options);
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr, options)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.ok(result.result, '"' + result.address + '" is valid and should pass');
    })
});

QUnit.test('validateEmailAddressFormat_NoDomainLiteralEscapesHasEscapeOrControl_ShouldReject', function (assert) {

    // Arrange
    var addresses = [
        'me@[domain literal \\] with escape]',
        'me@[domain literal \x02 with control character]',
        ];
    var options = {
        allowDomainLiteralEscapes: false
    };
    var resultRegex;
    var results = [];

    // Act
    resultRegex = validateEmailAddressFormat(null, options);
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr, options)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.notOk(result.result, '"' + result.address + '" has a domain literal with escaped characters or control characters when those have been disallowed and should fail');
    })
});

QUnit.test('validateEmailAddressFormat_QuotedControlCharactersDisallowed_ShouldReject', function (assert) {

    // Arrange
    var addresses = [
        '"abc\x02def"@example.com',
        ];
    var options = { allowQuotedControlCharacters: false };
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr, options)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.notOk(result.result, '"' + result.address + '" has control characters in a quoted string but disallows this syntax and should fail');
    })
});

QUnit.test('validateEmailAddressFormat_EscapedControlCharactersDisallowed_ShouldReject', function (assert) {

    // Arrange
    var addresses = [
        'abc\\\x02def@example.com',
        ];
    var options = { allowEscapedControlCharacters: false, allowBareEscapes: true };
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr, options)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.notOk(result.result, '"' + result.address + '" has escaped control characters but disallows this syntax and should fail');
    })
});

QUnit.test('validateEmailAddressFormat_DisallowCommentControlChars_ShouldReject', function (assert) {

    // Arrange
    var addresses = [
        'me(comment with \x03 control character)@examle.com',
        ];
    var options = { allowControlCharactersInComments: false };
    var results = [];

    // Act
    addresses.forEach(function(addr) {
        results.push({address:addr, result:validateEmailAddressFormat(addr, options)});
    });

    // Assert
    assert.expect(addresses.length);
    results.forEach(function(result) {
        assert.notOk(result.result, '"' + result.address + '" has control characters in a comment but disallows this syntax and should fail');
    })
});


text:
import subprocess
import unittest
import shutil
import os

import lwp.lxclite as lxc

class TestLxcLite(unittest.TestCase):

    """
    Those tests are against the lxclite class
    """
    @classmethod
    def setUpClass(cls):
        shutil.rmtree('/tmp/lxc/', ignore_errors=True)

    def test_00_create(self):
        lxc.create('test00')
        assert os.path.exists('/tmp/lxc/test00')

    def test_01_clone(self):
        lxc.clone('test00', 'testclone')
        assert os.path.exists('/tmp/lxc/test00')
        assert os.path.exists('/tmp/lxc/testclone')

    def test_02_start(self):
        lxc.start('test00')

    def test_03_freeze(self):
        lxc.freeze('test00')

    def test_04_unfreeze(self):
        lxc.unfreeze('test00')

    def test_05_stop(self):
        lxc.stop('test00')

    def test_06_destroy(self):
        lxc.destroy('test00')
        assert not os.path.exists('/tmp/lxc/test00')

if __name__ == '__main__':
    unittest.main()


text:
namespace MassTransit.GrpcTransport
{
    using System.Threading;
    using System.Threading.Tasks;
    using Contracts;
    using Fabric;
    using Transports.Fabric;

    public class RemoteNodeMessageReceiver :
        IMessageReceiver<GrpcTransportMessage>
    {
        readonly IGrpcNode _node;
        readonly string _queueName;
        readonly long _receiverId;

        public RemoteNodeMessageReceiver(IGrpcNode node, string queueName, long receiverId)
        {
            _node = node;
            _queueName = queueName;
            _receiverId = receiverId;
        }

        public async Task Deliver(GrpcTransportMessage message, CancellationToken cancellationToken)
        {
            var transportMessage = new TransportMessage(message.Message)
            {
                Deliver =
                {
                    Receiver = new ReceiverDestination
                    {
                        QueueName = _queueName,
                        ReceiverId = _receiverId
                    }
                }
            };

            var grpcTransportMessage = new GrpcTransportMessage(transportMessage, message.Host);

            await _node.DeliverMessage(grpcTransportMessage).ConfigureAwait(false);
        }

        public void Probe(ProbeContext context)
        {
            var scope = context.CreateScope("remote");
            scope.Add("nodeAddress", _node.NodeAddress);
        }
    }
}


text:
package cassandra

import (
	"fmt"
	"strings"
	"sync"

	"github.com/gocql/gocql"
	"github.com/hashicorp/vault/logical"
	"github.com/hashicorp/vault/logical/framework"
)

// Factory creates a new backend
func Factory(conf *logical.BackendConfig) (logical.Backend, error) {
	return Backend().Setup(conf)
}

// Backend contains the base information for the backend's functionality
func Backend() *framework.Backend {
	var b backend
	b.Backend = &framework.Backend{
		Help: strings.TrimSpace(backendHelp),

		Paths: []*framework.Path{
			pathConfigConnection(&b),
			pathRoles(&b),
			pathCredsCreate(&b),
		},

		Secrets: []*framework.Secret{
			secretCreds(&b),
		},
	}

	return b.Backend
}

type backend struct {
	*framework.Backend

	// Session is goroutine safe, however, since we reinitialize
	// it when connection info changes, we want to make sure we
	// can close it and use a new connection; hence the lock
	session *gocql.Session
	lock    sync.Mutex
}

type sessionConfig struct {
	Hosts           string `json:"hosts" structs:"hosts"`
	Username        string `json:"username" structs:"username"`
	Password        string `json:"password" structs:"password"`
	TLS             bool   `json:"tls" structs:"tls"`
	InsecureTLS     bool   `json:"insecure_tls" structs:"insecure_tls"`
	Certificate     string `json:"certificate" structs:"certificate"`
	PrivateKey      string `json:"private_key" structs:"private_key"`
	IssuingCA       string `json:"issuing_ca" structs:"issuing_ca"`
	ProtocolVersion int    `json:"protocol_version" structs:"protocol_version"`
}

// DB returns the database connection.
func (b *backend) DB(s logical.Storage) (*gocql.Session, error) {
	b.lock.Lock()
	defer b.lock.Unlock()

	// If we already have a DB, we got it!
	if b.session != nil {
		return b.session, nil
	}

	entry, err := s.Get("config/connection")
	if err != nil {
		return nil, err
	}
	if entry == nil {
		return nil,
			fmt.Errorf("Configure the DB connection with config/connection first")
	}

	config := &sessionConfig{}
	if err := entry.DecodeJSON(config); err != nil {
		return nil, err
	}

	return createSession(config, s)
}

// ResetDB forces a connection next time DB() is called.
func (b *backend) ResetDB(newSession *gocql.Session) {
	b.lock.Lock()
	defer b.lock.Unlock()

	if b.session != nil {
		b.session.Close()
	}

	b.session = newSession
}

const backendHelp = `
The Cassandra backend dynamically generates database users.

After mounting this backend, configure it using the endpoints within
the "config/" path.
`


text:
'use strict';

/**
 * Create a range error with the message:
 *     'Dimension mismatch (<actual size> != <expected size>)'
 * @param {number | number[]} actual        The actual size
 * @param {number | number[]} expected      The expected size
 * @param {string} [relation='!=']          Optional relation between actual
 *                                          and expected size: '!=', '<', etc.
 * @extends RangeError
 */
function DimensionError(actual, expected, relation) {
  if (!(this instanceof DimensionError)) {
    throw new SyntaxError('Constructor must be called with the new operator');
  }

  this.actual   = actual;
  this.expected = expected;
  this.relation = relation;

  this.message = 'Dimension mismatch (' +
      (Array.isArray(actual) ? ('[' + actual.join(', ') + ']') : actual) +
      ' ' + (this.relation || '!=') + ' ' +
      (Array.isArray(expected) ? ('[' + expected.join(', ') + ']') : expected) +
      ')';

  this.stack = (new Error()).stack;
}

DimensionError.prototype = new RangeError();
DimensionError.prototype.constructor = RangeError;
DimensionError.prototype.name = 'DimensionError';

module.exports = DimensionError;


text:
'use strict';

/* deps: mocha */
var inquirer = require('inquirer');
var assert = require('assert');
var should = require('should');
var detect = require('./');

describe('file conflict', function () {
  it('should detect when an existing file is `identical`:', function (done) {
    var file = {path: 'fixtures/a.txt', contents: 'aaa'};
    detect(file, function (res) {
      res.should.equal('identical');
      done();
    });
  });

  it('should use the `content` property:', function (done) {
    var file = {path: 'fixtures/a.txt', content: 'aaa'};
    detect(file, function (res) {
      res.should.equal('identical');
      done();
    });
  });

  it('should throw an error when invalid args are passed:', function () {
    (function () {
      detect();
    }).should.throw('file should be an object');

    (function () {
      detect({});
    }).should.throw('file.path should be a string.');

    (function () {
      detect({path: 'foo'});
    }).should.throw('file.contents must be defined to do a comparison.');
  });
});


text:
from .transfer import (
    CreateAgentPoolRequest,
    CreateTransferJobRequest,
    DeleteAgentPoolRequest,
    DeleteTransferJobRequest,
    GetAgentPoolRequest,
    GetGoogleServiceAccountRequest,
    GetTransferJobRequest,
    ListAgentPoolsRequest,
    ListAgentPoolsResponse,
    ListTransferJobsRequest,
    ListTransferJobsResponse,
    PauseTransferOperationRequest,
    ResumeTransferOperationRequest,
    RunTransferJobRequest,
    UpdateAgentPoolRequest,
    UpdateTransferJobRequest,
)
from .transfer_types import (
    AgentPool,
    AwsAccessKey,
    AwsS3CompatibleData,
    AwsS3Data,
    AzureBlobStorageData,
    AzureCredentials,
    ErrorLogEntry,
    ErrorSummary,
    GcsData,
    GoogleServiceAccount,
    HttpData,
    LoggingConfig,
    MetadataOptions,
    NotificationConfig,
    ObjectConditions,
    PosixFilesystem,
    S3CompatibleMetadata,
    Schedule,
    TransferCounters,
    TransferJob,
    TransferManifest,
    TransferOperation,
    TransferOptions,
    TransferSpec,
)

__all__ = (
    "CreateAgentPoolRequest",
    "CreateTransferJobRequest",
    "DeleteAgentPoolRequest",
    "DeleteTransferJobRequest",
    "GetAgentPoolRequest",
    "GetGoogleServiceAccountRequest",
    "GetTransferJobRequest",
    "ListAgentPoolsRequest",
    "ListAgentPoolsResponse",
    "ListTransferJobsRequest",
    "ListTransferJobsResponse",
    "PauseTransferOperationRequest",
    "ResumeTransferOperationRequest",
    "RunTransferJobRequest",
    "UpdateAgentPoolRequest",
    "UpdateTransferJobRequest",
    "AgentPool",
    "AwsAccessKey",
    "AwsS3CompatibleData",
    "AwsS3Data",
    "AzureBlobStorageData",
    "AzureCredentials",
    "ErrorLogEntry",
    "ErrorSummary",
    "GcsData",
    "GoogleServiceAccount",
    "HttpData",
    "LoggingConfig",
    "MetadataOptions",
    "NotificationConfig",
    "ObjectConditions",
    "PosixFilesystem",
    "S3CompatibleMetadata",
    "Schedule",
    "TransferCounters",
    "TransferJob",
    "TransferManifest",
    "TransferOperation",
    "TransferOptions",
    "TransferSpec",
)


text:
const path = require('path');

const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin')

module.exports = {

    devtool: 'eval-source-map',

    entry: {
        polyfills: './src/demo/polyfills.ts',
        vender: './src/demo/vendor.ts',
        app: './src/demo/main.ts'
    },

    output: {
        path: path.resolve(__dirname, 'dist'),
        publicPath: 'http://localhost:3000/',
        filename: '[name].js'
    },

    resolve: {
        modules: [
            'node_modules',
            path.resolve(__dirname, "src")
        ],
        extensions: ['.ts', '.js']
    },

    module: {
        rules: [
            {
                test: /\.ts$/,
                use: [
                    {
                        loader: 'ts-loader',
                        options: {
                            configFileName: './src/demo/tsconfig.json'
                        }
                    },
                    'angular2-template-loader'
                ]
            },
            {
                test: /\.html$/,
                use: 'html-loader'
            },
            {
                test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
                use: 'file-loader?name=assets/[name].[hash].[ext]'
            },
            {
                test: /\.css$/,
                exclude: path.resolve(__dirname, "src", "demo", "app"),
                use: ExtractTextPlugin.extract({
                    fallbackLoader: "style-loader",
                    loader: "css-loader"
                })
            }
        ]
    },

    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            name: ['app', 'vendor', 'polyfills']
        }),

        new HtmlWebpackPlugin({
            template: 'src/demo/index.html'
        }),

        new ExtractTextPlugin('[name].css')
    ]
}


text:
package org.chebykin.webservices.lab1;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class PostgreSQLDAO {
    private final Connection connection;

    public PostgreSQLDAO(Connection connection) {
        this.connection = connection;
    }

    public List<Person> getPersons() {
        List<Person> persons = new ArrayList<>();
        try {
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("select * from persons");
            while (rs.next()) {
                String name = rs.getString("name");
                String surname = rs.getString("surname");
                String job = rs.getString("job");
                String city = rs.getString("city");
                int age = rs.getInt("age");
                Person person = new Person(name, surname, job, city, age);
                persons.add(person);
            }
        } catch (SQLException ex) {
            Logger.getLogger(PostgreSQLDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return persons;
    }

    public Connection getConnection() {
        return connection;
    }
}


text:
<!DOCTYPE html>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="../../media-resources/media-file.js"></script>
<video crossorigin></video>
<canvas></canvas>
<script>
async_test(function(t) {
    var video = document.querySelector("video");
    var mediaFile = findMediaFile("video", "../../media/resources/test");
    var type = mimeTypeForExtension(mediaFile.split('.').pop());

    video.onerror = t.unreached_func();
    video.onplaying = t.step_func_done(function() {
        var ctx = document.querySelector("canvas").getContext("2d");
        ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
        ctx.getImageData(0, 0, video.videoWidth, video.videoHeight);
    });

    video.src = "http://localhost:8080/security/resources/video-cross-origin-allow.php?name=" + mediaFile + "&type=" + type;
    video.play();
});
</script>


text:
package com.hearthsim.test.minion;

import com.hearthsim.card.Card;
import com.hearthsim.card.Deck;
import com.hearthsim.card.basic.minion.BoulderfistOgre;
import com.hearthsim.card.basic.minion.RaidLeader;
import com.hearthsim.card.basic.minion.StormwindChampion;
import com.hearthsim.card.basic.spell.TheCoin;
import com.hearthsim.card.classic.minion.common.FlesheatingGhoul;
import com.hearthsim.card.classic.minion.common.HarvestGolem;
import com.hearthsim.card.classic.minion.common.LootHoarder;
import com.hearthsim.card.classic.minion.rare.Abomination;
import com.hearthsim.card.minion.Minion;
import com.hearthsim.exception.HSException;
import com.hearthsim.model.BoardModel;
import com.hearthsim.model.PlayerModel;
import com.hearthsim.model.PlayerSide;
import com.hearthsim.util.tree.HearthTreeNode;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

public class TestFlesheatingGhoul {

    private HearthTreeNode board;
    private PlayerModel currentPlayer;
    private PlayerModel waitingPlayer;

    @Before
    public void setup() throws HSException {
        Card cards[] = new Card[10];
        for (int index = 0; index < 10; ++index) {
            cards[index] = new TheCoin();
        }

        Deck deck = new Deck(cards);

        board = new HearthTreeNode(new BoardModel(deck, deck));
        currentPlayer = board.data_.getCurrentPlayer();
        waitingPlayer = board.data_.getWaitingPlayer();

        board.data_.placeMinion(PlayerSide.CURRENT_PLAYER, new HarvestGolem());
        board.data_.placeMinion(PlayerSide.CURRENT_PLAYER, new RaidLeader());
        board.data_.placeMinion(PlayerSide.CURRENT_PLAYER, new StormwindChampion());

        board.data_.placeMinion(PlayerSide.WAITING_PLAYER, new LootHoarder());
        board.data_.placeMinion(PlayerSide.WAITING_PLAYER, new Abomination());
        board.data_.placeMinion(PlayerSide.WAITING_PLAYER, new RaidLeader());
        board.data_.placeMinion(PlayerSide.WAITING_PLAYER, new BoulderfistOgre());

        currentPlayer.setMana((byte) 10);
        waitingPlayer.setMana((byte) 10);

        Minion fb = new FlesheatingGhoul();
        currentPlayer.placeCardHand(fb);
    }

    @Test
    public void test0() throws HSException {
        Card theCard = currentPlayer.getHand().get(0);
        HearthTreeNode ret = theCard.useOn(PlayerSide.WAITING_PLAYER, 0, board);

        assertNull(ret);

        assertEquals(currentPlayer.getHand().size(), 1);
        assertEquals(currentPlayer.getNumMinions(), 3);
        assertEquals(waitingPlayer.getNumMinions(), 4);
        assertEquals(currentPlayer.getMana(), 10);
        assertEquals(waitingPlayer.getMana(), 10);
        assertEquals(currentPlayer.getHero().getHealth(), 30);
        assertEquals(waitingPlayer.getHero().getHealth(), 30);

        assertEquals(currentPlayer.getCharacter(1).getTotalHealth(), 4);
        assertEquals(currentPlayer.getCharacter(2).getTotalHealth(), 3);
        assertEquals(currentPlayer.getCharacter(3).getTotalHealth(), 6);
        assertEquals(waitingPlayer.getCharacter(1).getTotalHealth(), 1);
        assertEquals(waitingPlayer.getCharacter(2).getTotalHealth(), 4);
        assertEquals(waitingPlayer.getCharacter(3).getTotalHealth(), 2);
        assertEquals(waitingPlayer.getCharacter(4).getTotalHealth(), 7);

        assertEquals(currentPlayer.getCharacter(1).getTotalAttack(), 4);
        assertEquals(currentPlayer.getCharacter(2).getTotalAttack(), 3);
        assertEquals(currentPlayer.getCharacter(3).getTotalAttack(), 7);
        assertEquals(waitingPlayer.getCharacter(1).getTotalAttack(), 3);
        assertEquals(waitingPlayer.getCharacter(2).getTotalAttack(), 5);
        assertEquals(waitingPlayer.getCharacter(3).getTotalAttack(), 2);
        assertEquals(waitingPlayer.getCharacter(4).getTotalAttack(), 7);
    }

    @Test
    public void test1() throws HSException {
        Card theCard = currentPlayer.getHand().get(0);
        HearthTreeNode ret = theCard.useOn(PlayerSide.CURRENT_PLAYER, 3, board);

        assertFalse(ret == null);

        assertEquals(currentPlayer.getHand().size(), 0);
        assertEquals(currentPlayer.getNumMinions(), 4);
        assertEquals(waitingPlayer.getNumMinions(), 4);
        assertEquals(currentPlayer.getMana(), 7);
        assertEquals(waitingPlayer.getMana(), 10);
        assertEquals(currentPlayer.getHero().getHealth(), 30);
        assertEquals(waitingPlayer.getHero().getHealth(), 30);

        assertEquals(currentPlayer.getCharacter(1).getTotalHealth(), 4);
        assertEquals(currentPlayer.getCharacter(2).getTotalHealth(), 3);
        assertEquals(currentPlayer.getCharacter(3).getTotalHealth(), 6);
        assertEquals(currentPlayer.getCharacter(4).getTotalHealth(), 4);
        assertEquals(waitingPlayer.getCharacter(1).getTotalHealth(), 1);
        assertEquals(waitingPlayer.getCharacter(2).getTotalHealth(), 4);
        assertEquals(waitingPlayer.getCharacter(3).getTotalHealth(), 2);
        assertEquals(waitingPlayer.getCharacter(4).getTotalHealth(), 7);

        assertEquals(currentPlayer.getCharacter(1).getAuraHealth(), 1);
        assertEquals(currentPlayer.getCharacter(2).getAuraHealth(), 1);
        assertEquals(currentPlayer.getCharacter(3).getAuraHealth(), 0);
        assertEquals(currentPlayer.getCharacter(4).getAuraHealth(), 1);

        assertEquals(currentPlayer.getCharacter(1).getTotalAttack(), 4);
        assertEquals(currentPlayer.getCharacter(2).getTotalAttack(), 3);
        assertEquals(currentPlayer.getCharacter(3).getTotalAttack(), 7);
        assertEquals(currentPlayer.getCharacter(4).getTotalAttack(), 4);
        assertEquals(waitingPlayer.getCharacter(1).getTotalAttack(), 3);
        assertEquals(waitingPlayer.getCharacter(2).getTotalAttack(), 5);
        assertEquals(waitingPlayer.getCharacter(3).getTotalAttack(), 2);
        assertEquals(waitingPlayer.getCharacter(4).getTotalAttack(), 7);

        //---------------------------------------------------------------
        Minion attacker = currentPlayer.getCharacter(3);
        ret = attacker.attack(PlayerSide.WAITING_PLAYER, 2, board, false);

        assertFalse(ret == null);
        assertEquals(currentPlayer.getHand().size(), 0);
        assertEquals(currentPlayer.getNumMinions(), 3);
        assertEquals(waitingPlayer.getNumMinions(), 1);
        assertEquals(currentPlayer.getMana(), 7);
        assertEquals(waitingPlayer.getMana(), 10);
        assertEquals(currentPlayer.getHero().getHealth(), 28); //2 damage from Abomination's deathrattle
        assertEquals(waitingPlayer.getHero().getHealth(), 28); //2 damage from Abomination's deathrattle

        assertEquals(currentPlayer.getCharacter(1).getTotalHealth(), 2);
        assertEquals(currentPlayer.getCharacter(2).getTotalHealth(), 1);
        assertEquals(currentPlayer.getCharacter(3).getTotalHealth(), 2);
        assertEquals(waitingPlayer.getCharacter(1).getTotalHealth(), 5);

        assertEquals(currentPlayer.getCharacter(1).getAuraHealth(), 0);
        assertEquals(currentPlayer.getCharacter(2).getAuraHealth(), 0);
        assertEquals(currentPlayer.getCharacter(3).getAuraHealth(), 0);

        assertEquals(currentPlayer.getCharacter(1).getTotalAttack(), 3);
        assertEquals(currentPlayer.getCharacter(2).getTotalAttack(), 2);
        assertEquals(currentPlayer.getCharacter(3).getTotalAttack(), 3 + 4); //4 minions died, including the Stormwind Champion
        assertEquals(waitingPlayer.getCharacter(1).getTotalAttack(), 6);
    }
}


text:
layout: update
published: true
title: The easing editor
date: 2015-04-19
article:
  written_on: 2015-04-19
  updated_on: 2015-05-20
authors:
- umarhansa
collection: updates
type: tip
category: tools
product: chrome-devtools
description: Select an easing CSS property to get a visual animated preview for how
  it behaves.
featured-image: /web/updates/images/2015-05-19-select-an-easing-to-get-a-visual-animated-preview-for-how-it-behaves/easing-preview.gif
source_name: DevTips
source_url: https://umaar.com/dev-tips/27-easing-preview
permalink: /updates/2015/04/19/the-easing-editor.html
---

If you view a property value containing an easing (e.g. the 'ease-in' in transition: color .5s ease-in;) - click the easing icon to see a preview on what it looks like. You can also select other easings to preview and/or set them as the new easing for the inspected element.

Now in Chrome Canary


text:
using namespace gpdxl;

XERCES_CPP_NAMESPACE_USE

//---------------------------------------------------------------------------
//	@function:
//		CParseHandlerExternalScan::CParseHandlerExternalScan
//
//	@doc:
//		Ctor
//
//---------------------------------------------------------------------------
CParseHandlerExternalScan::CParseHandlerExternalScan
	(
	CMemoryPool *mp,
	CParseHandlerManager *parse_handler_mgr,
	CParseHandlerBase *parse_handler_root
	)
	:
	CParseHandlerTableScan(mp, parse_handler_mgr, parse_handler_root)
{}

//---------------------------------------------------------------------------
//	@function:
//		CParseHandlerExternalScan::StartElement
//
//	@doc:
//		Invoked by Xerces to process an opening tag
//
//---------------------------------------------------------------------------
void
CParseHandlerExternalScan::StartElement
	(
	const XMLCh* const, // element_uri,
	const XMLCh* const element_local_name,
	const XMLCh* const, // element_qname
	const Attributes& // attrs
	)
{
	CParseHandlerTableScan::StartElement(element_local_name, EdxltokenPhysicalExternalScan);
}

//---------------------------------------------------------------------------
//	@function:
//		CParseHandlerExternalScan::EndElement
//
//	@doc:
//		Invoked by Xerces to process a closing tag
//
//---------------------------------------------------------------------------
void
CParseHandlerExternalScan::EndElement
	(
	const XMLCh* const, // element_uri,
	const XMLCh* const element_local_name,
	const XMLCh* const // element_qname
	)
{
	CParseHandlerTableScan::EndElement(element_local_name, EdxltokenPhysicalExternalScan);
}

// EOF


text:
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class Client implements Runnable {
    private Socket mSocket;
    private MigratableProcess mp;

    private ThreadFinishListener mListener;

    public Client(Socket s) {
    	mSocket = s;
    }

    @Override
    public void run() {

    	try {
    	    ObjectOutputStream out = new ObjectOutputStream(mSocket.getOutputStream());

    	    if (mp != null) {
    	    	out.writeObject((Object)mp);
    	    	out.flush();
    	    	System.out.println("Finish transmission");

    	    	//wait for response from other nodes
    	    	ObjectInputStream in = new ObjectInputStream(mSocket.getInputStream());

    	    	while(true){
    	    		Object response = in.readObject();
    	    		if (response instanceof String && ((String)response).equals("Finished running")) {
    	    			mListener.onThreadFinish(mp);
    	    			break;
    	    		}
    	    	}
    	    }

    	} catch (Exception e) {
    	    e.printStackTrace();
    	}
    }

    public void setTransmitProcess(MigratableProcess m) {
    	mp = m;
    }

    public interface ThreadFinishListener {
    	void onThreadFinish(MigratableProcess mp);
    }

    public void setListener(ThreadFinishListener l) { mListener = l; }
}


text:
require 'httparty'
require 'omdbapi/version'
require 'omdbapi/default'
require 'omdbapi/client'

# Ruby wrapper for omdbapi.com API.
module OMDB

  class << self

    # API client for making calls to the omdbapi API.
    #
    # return [OMDB::Client] API Wrapper
    def client
      @client = Client.new unless @client
      @client
    end

    private

      def method_missing(name, *args, &block)
        client.send(name, *args, &block)
      end

  end
end


text:
package test

import (
	"io/ioutil"
	"path/filepath"
	"testing"
)

const (
	dir = "../internal/test/testdata"
)

// FixtureFile is a structure which contains the name
// input contents and expected output contents fixtures
type FixtureFile struct {
	Name    string
	Input   string
	Outputs map[string]string
}

// StageFixture writes the input contents of the fixture
// to "{{ name }}.go" in a temporary directory and returns
// the path to this directory
func StageFixture(t *testing.T, fi FixtureFile) string {
	dir, err := ioutil.TempDir("", fi.Name)
	if err != nil {
		t.Fatal(err)
	}

	if err := ioutil.WriteFile(filepath.Join(dir, fi.Name), []byte(fi.Input), 0644); err != nil {
		t.Fatal(err)
	}

	return dir
}

// Fixture loads the input and output files for a given
// fixture name
func Fixture(t *testing.T, input string, outputs ...string) FixtureFile {
	file := FixtureFile{
		Name:    input,
		Input:   mustRead(t, filepath.Join(dir, input)),
		Outputs: map[string]string{},
	}

	for _, outPath := range outputs {
		path := filepath.Join(dir, outPath)

		file.Outputs[outPath] = mustRead(t, path)
	}

	return file
}

func mustRead(t *testing.T, path string) string {
	data, err := ioutil.ReadFile(path)
	if err != nil {
		t.Fatal(err)
	}

	return string(data)
}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.ryansteckler.nlpunbounce.MaterialSettingsActivity"
    xmlns:app="http://schemas.android.com/apk/res-auto" >
    >

    <item android:id="@+id/action_search"
        android:title="@string/action_search"
        android:icon="@drawable/ic_action_search"
        android:showAsAction="ifRoom|collapseActionView"
        android:actionViewClass="android.widget.SearchView" />

    <item android:id="@+id/action_new_custom"
        android:title="@string/action_new_custom_item"
        android:icon="@drawable/ic_action_view_as_list"
        android:showAsAction="ifRoom|collapseActionView" />

    <item android:id="@+id/action_sort"
        android:icon="@drawable/ic_action_sort_by_size"
        android:title="@string/action_sort_by_count"
        android:showAsAction="always" />

</menu>


text:
package codeu.chat.common;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import codeu.chat.util.Uuid;

/**
 * This class saves user interests by saving the
 * conversations the user has created and added messages
 * to since the last update
 *
 */
public class UserInterest {

	private Uuid userID;
	private String name;
	private ArrayList<String> convosCreated;
	private ArrayList<String> convosAddedTo;

	public UserInterest(Uuid userID, String name) {
		this.userID = userID;
		this.name = name;
		this.convosCreated = new ArrayList<String>();
		this.convosAddedTo = new ArrayList<String>();
	}

	public void addConvoCreated(String convo){
		this.convosCreated.add(convo);
	}

	public void addConvoAddedTo(String convo){
		this.convosAddedTo.add(convo);
	}

	public Uuid getUserID() {
		return userID;
	}

	public String getname() {
		return name;
	}

	public ArrayList<String> getConvosCreated() {
		return convosCreated;
	}

	public ArrayList<String> getConvosAddedTo() {
		return convosAddedTo;
	}

}


text:
package org.elasticsearch.common.io;

import org.elasticsearch.common.bytes.BytesReference;

public interface BytesStream {

    BytesReference bytes();
}


text:
namespace wasm {

namespace decode {

PageCursor::PageCursor() : CurAddress(0) {}

PageCursor::PageCursor(Queue* Que)
    : CurPage(Que->FirstPage), CurAddress(Que->FirstPage->getMinAddress()) {
  assert(CurPage);
}

PageCursor::PageCursor(std::shared_ptr<Page> CurPage, AddressType CurAddress)
    : CurPage(CurPage), CurAddress(CurAddress) {
  assert(CurPage);
}

PageCursor::PageCursor(const PageCursor& PC)
    : CurPage(PC.CurPage), CurAddress(PC.CurAddress) {
  //    assert(CurPage);
}

PageCursor::~PageCursor() {}

void PageCursor::assign(const PageCursor& C) {
  CurPage = C.CurPage;
  CurAddress = C.CurAddress;
}

void PageCursor::swap(PageCursor& C) {
  std::swap(CurPage, C.CurPage);
  std::swap(CurAddress, C.CurAddress);
}

AddressType PageCursor::getMinAddress() const {
  return CurPage ? CurPage->getMinAddress() : 0;
}

AddressType PageCursor::getMaxAddress() const {
  return CurPage ? CurPage->getMaxAddress() : 0;
}

bool PageCursor::isValidPageAddress(AddressType Address) {
  return getMinAddress() <= Address && Address < getMaxAddress();
}

AddressType PageCursor::getRelativeAddress() const {
  return CurAddress - CurPage->getMinAddress();
}

void PageCursor::setMaxAddress(AddressType Address) {
  CurPage->setMaxAddress(Address);
}

bool PageCursor::isIndexAtEndOfPage() const {
  return getCurAddress() == getMaxAddress();
}

ByteType* PageCursor::getBufferPtr() {
  assert(CurPage);
  return CurPage->getByteAddress(getRelativeAddress());
}

Page* PageCursor::getCurPage() const {
  return CurPage.get();
}

FILE* PageCursor::describe(FILE* File, bool IncludePage) {
  AddressType Addr(CurAddress);
  describeAddress(File, Addr);
  if (IncludePage)
    describePage(File, CurPage.get());
  return File;
}

}  // end of namespace decode

}  // end of namespace wasm


text:
<?php

namespace Lunr\Spark\Twitter\Tests;

use Requests_Exception;
use Requests_Exception_HTTP_400;

/**
 * This class contains the tests for the Authentication.
 *
 * @covers Lunr\Spark\Twitter\Authentication
 */
class AuthenticationApiTest extends AuthenticationTest
{
    /**
     * A sample http options array
     * @var array
     */
    protected $options;

    /**
     * A sample http header array
     * @var array
     */
    protected $headers;

    /**
     * AuthenticationApiTest constructor.
     */
    public function setUp()
    {
        parent::setUp();

        $this->options = [
            'verify' => TRUE,
            'auth'   => [
                'Key',
                'Secret',
            ],
        ];

        $this->headers = [
            'Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8',
            'User-Agent'   => 'lunr.nl',
        ];
    }

    /**
     * Test that get_bearer_token() returns an empty string on request error.
     *
     * @covers Lunr\Spark\Twitter\Authentication::get_bearer_token
     */
    public function testGetBearerTokenReturnsErrorStringOnError()
    {
        $url    = 'https://api.twitter.com/oauth2/token';
        $params = [ 'grant_type' => 'client_credentials' ];

        $this->cas->expects($this->at(0))
                  ->method('get')
                  ->with($this->equalTo('twitter'), $this->equalTo('user_agent'))
                  ->will($this->returnValue('lunr.nl'));

        $this->cas->expects($this->at(1))
                  ->method('get')
                  ->with($this->equalTo('twitter'), $this->equalTo('consumer_key'))
                  ->will($this->returnValue('Key'));

        $this->cas->expects($this->at(2))
                  ->method('get')
                  ->with($this->equalTo('twitter'), $this->equalTo('consumer_secret'))
                  ->will($this->returnValue('Secret'));

        $this->http->expects($this->once())
                   ->method('request')
                   ->with($this->equalTo($url), $this->equalTo($this->headers), $this->equalTo($params), $this->equalTo('POST'), $this->equalTo($this->options))
                   ->will($this->returnValue($this->response));

        $this->response->status_code = 400;
        $this->response->body        = '{"errors":[{"message":"Test twitter error","code":34}]}';

        $this->response->expects($this->once())
                       ->method('throw_for_status')
                       ->will($this->throwException(new Requests_Exception_HTTP_400('Invalid Input!')));

        $this->assertSame('', $this->class->get_bearer_token());
    }

    /**
     * Test that get_bearer_token() returns an empty string on request failure.
     *
     * @covers Lunr\Spark\Twitter\Authentication::get_bearer_token
     */
    public function testGetBearerTokenReturnsErrorStringOnFailure()
    {
        $url    = 'https://api.twitter.com/oauth2/token';
        $params = [ 'grant_type' => 'client_credentials' ];

        $this->cas->expects($this->at(0))
                  ->method('get')
                  ->with($this->equalTo('twitter'), $this->equalTo('user_agent'))
                  ->will($this->returnValue('lunr.nl'));

        $this->cas->expects($this->at(1))
                  ->method('get')
                  ->with($this->equalTo('twitter'), $this->equalTo('consumer_key'))
                  ->will($this->returnValue('Key'));

        $this->cas->expects($this->at(2))
                  ->method('get')
                  ->with($this->equalTo('twitter'), $this->equalTo('consumer_secret'))
                  ->will($this->returnValue('Secret'));

        $this->http->expects($this->once())
                   ->method('request')
                   ->with($this->equalTo($url), $this->equalTo($this->headers), $this->equalTo($params), $this->equalTo('POST'), $this->equalTo($this->options))
                   ->will($this->throwException(new Requests_Exception('Network error!', 'curlerror', NULL)));

        $this->response->expects($this->never())
                       ->method('throw_for_status');

        $this->assertSame('', $this->class->get_bearer_token());
    }

    /**
     * Test that get_bearer_token() stores the bearer access token in the CAS.
     *
     * @covers Lunr\Spark\Twitter\Authentication::get_bearer_token
     */
    public function testGetBearerTokenStoresBearerTokenInCas()
    {
        $url    = 'https://api.twitter.com/oauth2/token';
        $params = [ 'grant_type' => 'client_credentials' ];

        $this->cas->expects($this->at(0))
                  ->method('get')
                  ->with($this->equalTo('twitter'), $this->equalTo('user_agent'))
                  ->will($this->returnValue('lunr.nl'));

        $this->cas->expects($this->at(1))
                  ->method('get')
                  ->with($this->equalTo('twitter'), $this->equalTo('consumer_key'))
                  ->will($this->returnValue('Key'));

        $this->cas->expects($this->at(2))
                  ->method('get')
                  ->with($this->equalTo('twitter'), $this->equalTo('consumer_secret'))
                  ->will($this->returnValue('Secret'));

        $this->http->expects($this->once())
                   ->method('request')
                   ->with($this->equalTo($url), $this->equalTo($this->headers), $this->equalTo($params), $this->equalTo('POST'), $this->equalTo($this->options))
                   ->will($this->returnValue($this->response));

        $this->response->status_code = 200;
        $this->response->body        = '{"token_type":"bearer","access_token":"TOKEN"}';

        $this->response->expects($this->once())
                       ->method('throw_for_status');

        $this->cas->expects($this->once())
                  ->method('add')
                  ->with($this->equalTo('twitter'), $this->equalTo('bearer_token'), $this->equalTo('TOKEN'));

        $this->assertEquals('TOKEN', $this->class->get_bearer_token());
    }

    /**
     * Test that get_bearer_token() returns the bearer access token.
     *
     * @covers Lunr\Spark\Twitter\Authentication::get_bearer_token
     */
    public function testGetBearerTokenReturnsBearerToken()
    {
        $url    = 'https://api.twitter.com/oauth2/token';
        $params = [ 'grant_type' => 'client_credentials' ];

        $this->cas->expects($this->at(0))
                  ->method('get')
                  ->with($this->equalTo('twitter'), $this->equalTo('user_agent'))
                  ->will($this->returnValue('lunr.nl'));

        $this->cas->expects($this->at(1))
                  ->method('get')
                  ->with($this->equalTo('twitter'), $this->equalTo('consumer_key'))
                  ->will($this->returnValue('Key'));

        $this->cas->expects($this->at(2))
                  ->method('get')
                  ->with($this->equalTo('twitter'), $this->equalTo('consumer_secret'))
                  ->will($this->returnValue('Secret'));

        $this->http->expects($this->once())
                   ->method('request')
                   ->with($this->equalTo($url), $this->equalTo($this->headers), $this->equalTo($params), $this->equalTo('POST'), $this->equalTo($this->options))
                   ->will($this->returnValue($this->response));

        $this->response->status_code = 200;
        $this->response->body        = '{"token_type":"bearer","access_token":"TOKEN"}';

        $this->response->expects($this->once())
                       ->method('throw_for_status');

        $this->cas->expects($this->once())
                  ->method('add')
                  ->with($this->equalTo('twitter'), $this->equalTo('bearer_token'), $this->equalTo('TOKEN'));

        $this->assertEquals('TOKEN', $this->class->get_bearer_token());
    }

}

?>


text:
const char* ToCString(const v8::String::Utf8Value& value) {
    return *value ? *value : "<string conversion failed>";
}

void ReportException(v8::Isolate* isolate, v8::TryCatch* try_catch, std::function<void(string)> error_cb) {
    v8::HandleScope handle_scope(isolate);
    v8::String::Utf8Value exception(try_catch->Exception());
    const char* exception_string = ToCString(exception);
    v8::Local<v8::Message> message = try_catch->Message();
    string res_string = "";
    if (message.IsEmpty()) {
        // V8 didn't provide any extra information about this error; just
        // print the exception.
        res_string += exception_string;
        res_string += "\n";
    } else {
        // Print (filename):(line number): (message).
        v8::String::Utf8Value filename(message->GetScriptOrigin().ResourceName());
        v8::Local<v8::Context> context(isolate->GetCurrentContext());
        const char* filename_string = ToCString(filename);
        int linenum = message->GetLineNumber(context).FromJust();
        res_string += filename_string;
        res_string += ":";
        res_string += std::to_string(linenum);
        res_string += ": ";
        res_string += exception_string;
        res_string += "\n";
        // Print line of source code.
        v8::String::Utf8Value sourceline(
                message->GetSourceLine(context).ToLocalChecked());
        const char* sourceline_string = ToCString(sourceline);
        res_string += sourceline_string;
        res_string += "\n";
        // Print wavy underline (GetUnderline is deprecated).
        int start = message->GetStartColumn(context).FromJust();
        for (int i = 0; i < start; i++) {
            res_string += " ";
        }
        int end = message->GetEndColumn(context).FromJust();
        for (int i = start; i < end; i++) {
            res_string += "^";
        }
        res_string += "\n";
        v8::Local<v8::Value> stack_trace_string;
        if (try_catch->StackTrace(context).ToLocal(&stack_trace_string) &&
            stack_trace_string->IsString() &&
            v8::Local<v8::String>::Cast(stack_trace_string)->Length() > 0) {
            v8::String::Utf8Value stack_trace(stack_trace_string);
            res_string += ToCString(stack_trace);
            res_string += "\n";
        }
    }
    error_cb(res_string);
}

// Executes a string within the current v8 context.
v8::Local<v8::Value> ExecuteString(v8::Isolate* isolate, v8::Local<v8::String> source,
                   v8::Local<v8::Value> name, bool report_exceptions, bool* failed, std::function<void(string)> error_cb) {
    v8::Isolate::Scope isolate_scope(isolate);
    v8::EscapableHandleScope handle_scope(isolate);
    v8::TryCatch try_catch(isolate);
    v8::ScriptOrigin origin(name);
    v8::Local<v8::Context> context(isolate->GetCurrentContext());
    v8::Local<v8::Script> script;
    if (!v8::Script::Compile(context, source, &origin).ToLocal(&script)) {
        v8::String::Utf8Value str(try_catch.Exception());
        // Print errors that happened during compilation.
        if (report_exceptions)
            ReportException(isolate, &try_catch, error_cb);
        *failed = true;
        return handle_scope.Escape(Null(isolate));
    } else {
        v8::Local<v8::Value> result;
        if (!script->Run(context).ToLocal(&result)) {
            assert(try_catch.HasCaught());
            // Print errors that happened during execution.
            if (report_exceptions)
                ReportException(isolate, &try_catch, error_cb);
            *failed = true;
            return handle_scope.Escape(Null(isolate));
        } else {
            assert(!try_catch.HasCaught());
            *failed = false;
            return handle_scope.Escape(result);
        }
    }
}

void split(const std::string &s, char delim, std::vector<std::string> &elems) {
    std::stringstream ss;
    ss.str(s);
    std::string item;
    while (std::getline(ss, item, delim)) {
        elems.push_back(item);
    }
}