text:
"""Tests for the `MapAndFilterFusion` optimization."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import functools

from absl.testing import parameterized

from tensorflow.python.data.experimental.ops import testing
from tensorflow.python.data.kernel_tests import test_base
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.data.ops import options as options_lib
from tensorflow.python.framework import combinations
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import math_ops
from tensorflow.python.platform import test

def _test_combinations():
  cases = []

  identity = lambda x: x
  increment = lambda x: x + 1
  minus_five = lambda x: x - 5

  def increment_and_square(x):
    y = x + 1
    return y * y

  functions = [identity, increment, minus_five, increment_and_square]

  take_all = lambda x: constant_op.constant(True)
  is_zero = lambda x: math_ops.equal(x, 0)
  is_odd = lambda x: math_ops.equal(x % 2, 0)
  greater = lambda x: math_ops.greater(x + 5, 0)
  predicates = [take_all, is_zero, is_odd, greater]

  for i, function in enumerate(functions):
    for j, predicate in enumerate(predicates):
      cases.append((function, "Scalar{}{}".format(i, j), predicate))

  replicate = lambda x: (x, x)
  with_two = lambda x: (x, 2)
  functions = [replicate, with_two]
  take_all = lambda x, y: constant_op.constant(True)
  is_zero = lambda x, y: math_ops.equal(x * math_ops.cast(y, dtypes.int64), 0)
  predicates = [take_all, is_zero]

  for i, function in enumerate(functions):
    for j, predicate in enumerate(predicates):
      cases.append((function, "Tuple{}{}".format(i, j), predicate))

  def reduce_fn(x, y):
    function, name, predicate = y
    return x + combinations.combine(
        function=function,
        predicate=combinations.NamedObject(name, predicate))

  return functools.reduce(reduce_fn, cases, [])

class MapAndFilterFusionTest(test_base.DatasetTestBase, parameterized.TestCase):

  def _testDataset(self, dataset, function, predicate):
    expected_output = []
    for x in range(10):
      r = function(x)
      if isinstance(r, tuple):
        b = predicate(*r)  # Pass tuple as multiple arguments.
      else:
        b = predicate(r)
      if self.evaluate(b):
        expected_output.append(r)
    self.assertDatasetProduces(dataset, expected_output=expected_output)

  @combinations.generate(
      combinations.times(test_base.default_test_combinations(),
                         _test_combinations()))
  def testMapAndFilterFusion(self, function, predicate):
    dataset = dataset_ops.Dataset.range(10).apply(
        testing.assert_next(["Map", "Filter",
                             "Map"])).map(function).filter(predicate)
    options = options_lib.Options()
    options.experimental_optimization.apply_default_optimizations = False
    options.experimental_optimization.map_and_filter_fusion = True
    dataset = dataset.with_options(options)
    self._testDataset(dataset, function, predicate)

  @combinations.generate(test_base.default_test_combinations())
  def testCapturedInputs(self):
    a = constant_op.constant(3, dtype=dtypes.int64)
    b = constant_op.constant(4, dtype=dtypes.int64)
    some_tensor = math_ops.mul(a, b)
    function = lambda x: x * x

    def predicate(y):
      return math_ops.less(math_ops.cast(y, dtypes.int64), some_tensor)

    # We currently do not support functions with captured inputs.
    dataset = dataset_ops.Dataset.range(10).apply(
        testing.assert_next(["Map", "Filter"])).map(function).filter(predicate)
    options = options_lib.Options()
    options.experimental_optimization.apply_default_optimizations = False
    options.experimental_optimization.map_and_filter_fusion = True
    dataset = dataset.with_options(options)
    self._testDataset(dataset, function, predicate)

if __name__ == "__main__":
  test.main()


text:
import Handsontable from './../browser';
import {getEditor, registerEditor, getEditorConstructor} from './../editors';
import {AutocompleteEditor} from './autocompleteEditor';

/**
 * @private
 * @editor DropdownEditor
 * @class DropdownEditor
 * @dependencies AutocompleteEditor
 */
class DropdownEditor extends AutocompleteEditor {
  prepare(row, col, prop, td, originalValue, cellProperties) {
    super.prepare(row, col, prop, td, originalValue, cellProperties);
    this.cellProperties.filter = false;
    this.cellProperties.strict = true;
  }
}

Handsontable.hooks.add('beforeValidate', function(value, row, col, source) {
  let cellMeta = this.getCellMeta(row, this.propToCol(col));

  if (cellMeta.editor === Handsontable.editors.DropdownEditor) {
    if (cellMeta.strict === void 0) {
      cellMeta.filter = false;
      cellMeta.strict = true;
    }
  }
});

export {DropdownEditor};

registerEditor('dropdown', DropdownEditor);

redpajama_set_name: RedPajamaGithub


text:
module ProjectsHelper
  def edit_profile_link(project)
    link_to 'Edit', edit_project_path(project) if policy(project).edit?
  end
end


text:
using Moq;
using Xunit;

namespace MAF.FeaturesFlipping.AspNetCore
{
    public partial class FeatureTagHelperTests
    {
        [Trait("Category", "UnitTest")]
        public class ShouldSuppressOutput
        {
            [Fact]
            public void Feature_Active_And_Inverse_Should_Suppress_Output()
            {
                // Arrange
                var featureServiceMock = new Mock<IFeatureService>();
                var tagHelper = new FeatureTagHelper(featureServiceMock.Object, Factory.NullLoggerFactory())
                {
                    Inverse = true
                };

                // Act
                var actual = tagHelper.ShouldSuppressOutput(true);

                // Assert
                Assert.True(actual);
            }

            [Fact]
            public void Feature_Active_And_Not_Inverse_Should_Not_Suppress_Output()
            {
                // Arrange
                var featureServiceMock = new Mock<IFeatureService>();
                var tagHelper = new FeatureTagHelper(featureServiceMock.Object, Factory.NullLoggerFactory())
                {
                    Inverse = false
                };

                // Act
                var actual = tagHelper.ShouldSuppressOutput(true);

                // Assert
                Assert.False(actual);
            }

            [Fact]
            public void Feature_Inactive_And_Inverse_Should_Not_Suppress_Output()
            {
                // Arrange
                var featureServiceMock = new Mock<IFeatureService>();
                var tagHelper = new FeatureTagHelper(featureServiceMock.Object, Factory.NullLoggerFactory())
                {
                    Inverse = true
                };

                // Act
                var actual = tagHelper.ShouldSuppressOutput(false);

                // Assert
                Assert.False(actual);
            }

            [Fact]
            public void Feature_Inactive_And_Not_Inverse_Should_Suppress_Output()
            {
                // Arrange
                var featureServiceMock = new Mock<IFeatureService>();
                var tagHelper = new FeatureTagHelper(featureServiceMock.Object, Factory.NullLoggerFactory())
                {
                    Inverse = false
                };

                // Act
                var actual = tagHelper.ShouldSuppressOutput(false);

                // Assert
                Assert.True(actual);
            }
        }
    }
}


text:
import requests
import grequests

r = requests.get("https://stepik.org/api/leaders")  # get the first page of leader list

leaders = ["https://stepik.org/api/users/" + str(leader["user"])
           for leader in r.json()["leaders"]]  # form urls for leaders

scores = {l["user"]: l["score"] for l in r.json()["leaders"]}  # remember all scores

rs = [grequests.get(l) for l in leaders]  # prepare all requests
result = grequests.map(rs)  # execute requests concurrently

print("Current leaders:\n")

for r in result:
    user = r.json()["users"][0]
    print(scores[user["profile"]], '\t', user['first_name'], user['last_name'])


text:
package com.molina.cvmfs.common.exceptions;

/**
 * @author Jose Molina Colmenero
 */
public class CvmfsNotInstalled extends Exception {

    public CvmfsNotInstalled() {
        super("It seems cvmfs is not installed on this machine");
    }
}


text:
package org.innovateuk.ifs.application.readonly.viewmodel;

import org.innovateuk.ifs.application.readonly.ApplicationReadOnlyData;
import org.innovateuk.ifs.form.resource.QuestionResource;
import org.innovateuk.ifs.user.resource.ProcessRoleResource;
import org.innovateuk.ifs.user.resource.Role;
import org.innovateuk.ifs.user.resource.UserResource;

import java.util.List;
import java.util.Optional;

/**
 * Holder of model attributes for the Application Team view.
 */
public class ApplicationTeamReadOnlyViewModel extends AbstractQuestionReadOnlyViewModel {
    private final List<ApplicationTeamOrganisationReadOnlyViewModel> organisations;
    private final Optional<ProcessRoleResource> ktaProcessRole;
    private final boolean internal;
    private final boolean shouldShowTeamMember;
    private final boolean ktpCompetition;
    private final String ktaPhoneNumber;
    private final boolean ediUpdateEnabled;

    public ApplicationTeamReadOnlyViewModel(ApplicationReadOnlyData data, QuestionResource question, List<ApplicationTeamOrganisationReadOnlyViewModel> organisations,
                                            Optional<ProcessRoleResource> ktaProcessRole, String ktaPhoneNumber, boolean internal, boolean shouldShowTeamMember, boolean ediUpdateEnabled) {
        super(data, question);
        this.organisations = organisations;
        this.ktpCompetition = data.getCompetition().isKtp();
        this.ktaProcessRole = ktaProcessRole;
        this.ktaPhoneNumber = ktaPhoneNumber;
        this.internal = internal;
        this.shouldShowTeamMember = shouldShowTeamMember;
        this.ediUpdateEnabled = ediUpdateEnabled;
    }

    public List<ApplicationTeamOrganisationReadOnlyViewModel> getOrganisations() {
        return organisations;
    }

    public boolean isInternal() {
        return internal;
    }

    public boolean isCollaborativeProject() { return organisations.size() != 1; }

    public boolean isKtpCompetition() {
        return ktpCompetition;
    }

    public String getKtaPhoneNumber() {
        return ktaPhoneNumber;
    }

    public Optional<ProcessRoleResource> getKtaProcessRole() {
        return ktaProcessRole;
    }

    @Override
    public String getFragment() {
        return "application-team";
    }

    public boolean isEdiUpdateEnabled() {
        return ediUpdateEnabled;
    }

    public boolean isShouldDisplayTeamMember() { return shouldShowTeamMember; }
}


text:
import sys
from pkg_resources import load_entry_point, DistributionNotFound

if __name__ == '__main__':
    try:
        sys.exit(
            load_entry_point('tyrian', 'console_scripts', 'tyrian')()
        )
    except DistributionNotFound:
        from tyrian import cli
        sys.exit(cli.main())


text:
        template <class T>
        struct ObjectCounter {
            static int count;
        };

        template<class T>
        int ObjectCounter<T>::count = 0;

        class Yices2 {
        public:
            typedef term_t result_type;
            typedef std::list<term_t> Exprs;

        private:
            Exprs assumptions_;
            Exprs assertions_;
            bool isPushed_;
            context_t *ctx;

            term_t throw_error(term_t value) {
                if (value == NULL_TERM) {
                    char *error = yices_error_string();
                    std::stringstream ss;
                    ss << "throw_error: ";
                    ss << error;
                    throw std::runtime_error(ss.str());
                }
                return value;
            }

        public:

            Yices2() : isPushed_(false) {
                if (ObjectCounter<Yices2>::count == 0) {
                    yices_init();
                }
                ctx_config_t *config = yices_new_config();
                yices_set_config(config, "mode", "interactive");
                ctx = yices_new_context(config);
                yices_free_config(config);
                ObjectCounter<Yices2>::count++;

            }

            ~Yices2() {
                yices_free_context(ctx);
                ObjectCounter<Yices2>::count--;
                if (ObjectCounter<Yices2>::count == 0) {
                    yices_exit();
                }
            }

            static void print_term(term_t term) {
                int32_t code;

                code = yices_pp_term(stdout, term, UINT32_MAX, 1, 0);
                if (code < 0) {
                    // An error occurred
                    fprintf(stderr, "Error in print_term: ");
                    yices_print_error(stderr);
                    exit(1);
                }
            }

            void assertion(result_type e) {
                assertions_.push_back(e);
            }

            void assumption(result_type e) {
                assumptions_.push_back(e);
            }

            void print_status(smt_status_t status) {
                switch (status) {
                    case STATUS_IDLE:
                        std::cerr << "STATUS_IDLE" << std::endl;
                        break;
                    case STATUS_SEARCHING:
                        std::cerr << "STATUS_SEARCHING" << std::endl;
                        break;
                    case STATUS_UNKNOWN:
                        std::cerr << "STATUS_UNKNOWN" << std::endl;
                        break;
                    case STATUS_SAT:
                        std::cerr << "STATUS_SAT" << std::endl;
                        break;
                    case STATUS_UNSAT:
                        std::cerr << "STATUS_UNSAT" << std::endl;
                        break;
                    case STATUS_INTERRUPTED:
                        std::cerr << "STATUS_INTERRUPTED" << std::endl;
                        break;
                    case STATUS_ERROR:
                        std::cerr << "STATUS_ERROR" << std::endl;
                        break;
                    default:
                        break;
                }
            }

            bool solve() {
                removeOldAssumptions();
                pushAssertions();
                pushAssumptions();
                smt_status_t status = yices_check_context(ctx, NULL);
                print_status(status);
                return (status == STATUS_SAT);
            }

        private:

            void removeOldAssumptions() {
                printf("removeOldAssumptions\n");
                if (isPushed_) {
                    if (yices_pop(ctx) == -1) {
                        char *error = yices_error_string();
                        std::stringstream ss;
                        ss << "removeOldAssumptions Error: ";
                        ss << error;
                        throw std::runtime_error(ss.str());
                    }
                    isPushed_ = false;
                }
            }

            void pushAssumptions() {
                printf("pushAssumptions\n");
				smt_status_t status = yices_context_status(ctx);
				if(status != STATUS_IDLE && status != STATUS_SAT && status != STATUS_UNKNOWN)
				{
					printf("invalid State Status: ");
					print_status(status);
					return;
				}
                if (yices_push(ctx) == -1) {
                    print_status(yices_context_status(ctx));
                    char *error = yices_error_string();
                    std::stringstream ss;
                    ss << "pushAssumptions Error: ";
                    ss << error;
                    throw std::runtime_error(ss.str());
                } else {
                    isPushed_ = true;
                    applyAssertions(assumptions_);
                    assumptions_.clear();
                }
            }

            void pushAssertions() {
                printf("pushAssertions\n");
                applyAssertions(assertions_);
                assertions_.clear();
            }

            void applyAssertions(Exprs const &expressions) {
                for (Exprs::const_iterator it = expressions.begin(), ie = expressions.end(); it != ie; ++it) {
                    print_term(*it);
                    if(yices_assert_formula(ctx, *it) != 0)
					{
						char *error = yices_error_string();
						std::string s;
						s += "applyAssertions0: ";
						s += error;
					}
                }
            }

        }; // class Yices2


text:
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;

/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model \common\models\LoginForm */

$this->title = 'Login';
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?php $form = ActiveForm::begin(['id' => 'login-form']); ?>

        <?= $form->field($model, 'username') ?>
        <?= $form->field($model, 'password')->passwordInput() ?>
        <?= $form->field($model, 'rememberMe')->checkbox(['class'=>'simple']) ?>

        <?= Html::submitButton(Yii::t('app', 'Sign me in'), ['class' => 'btn bg-olive btn-block', 'name' => 'login-button']) ?>

    <?php ActiveForm::end(); ?>


text:
'use strict';

/**
* High word mask for excluding the sign bit of a double-precision floating-point number.
*
* @module @stdlib/constants/float64/high-word-abs-mask
* @type {uinteger32}
*
* @example
* var FLOAT64_HIGH_WORD_ABS_MASK = require( '@stdlib/constants/float64/high-word-abs-mask' );
* // returns 2147483647
*/

// MAIN //

/**
* High word mask for excluding the sign bit of a double-precision floating-point number.
*
* ## Notes
*
* The high word mask for excluding the sign bit of a double-precision floating-point number is an unsigned 32-bit integer with the value \\( 2147483647 \\), which corresponds to the bit sequence
*
* ```binarystring
* 0 11111111111 11111111111111111111
* ```
*
* @constant
* @type {uinteger32}
* @default 0x7fffffff
* @see [IEEE 754]{@link https://en.wikipedia.org/wiki/IEEE_754-1985}
*/
var FLOAT64_HIGH_WORD_ABS_MASK = 0x7fffffff>>>0; // eslint-disable-line id-length

// EXPORTS //

module.exports = FLOAT64_HIGH_WORD_ABS_MASK;


text:
import traceback
import sys
import tornado
import httplib
import os
from tornado.web import RequestHandler
from tornado import template

class UncaughtExceptionMixin(object):
    def get_error_html(self, status_code, **kwargs):

        def get_snippet(fp, target_line, num_lines):
            if fp.endswith('.html'):
                fp = os.path.join(self.get_template_path(), fp)

            half_lines = (num_lines / 2)
            try:
                with open(fp) as f:
                    all_lines = [line for line in f]

                    return ''.join(all_lines[target_line - half_lines:target_line + half_lines])
            except Exception, ex:
                return ''

        if not self.application.settings.get('debug', False):
            if hasattr(self, 'exception_response'):
                # 如果handler存在此属性,将返回属性内容
                return self.exception_response
            full_message = kwargs.get('exception', None)
            if not full_message or unicode(full_message) == '':
                full_message = 'Server error.'

            return "<title>%(code)d: %(message)s</title>\

%(code)d: %(message)s
%(full_message)s" % {
                "code": status_code,
                "message": httplib.responses[status_code],
                "full_message": full_message,
            }

        else:
            exception = kwargs.get('exception', None)
            resource = os.path.split(os.path.dirname(__file__))[0]
            tmpl_file = '/resource/exception.html'

            def render_string(template_name, **kw):
                template_path = self.get_template_path()
                if not template_path:
                    frame = sys._getframe(0)
                    web_file = frame.f_code.co_filename
                    while frame.f_code.co_filename == web_file:
                        frame = frame.f_back
                    template_path = os.path.dirname(frame.f_code.co_filename)
                with RequestHandler._template_loader_lock:
                    settings = self.application.settings
                    kwarg = {}

                    if "autoescape" in settings:
                        kwarg["autoescape"] = settings["autoescape"]
                    loader = template.Loader(template_path, **kwarg)
                t = loader.load(template_name)
                namespace = self.get_template_namespace()
                namespace.update(kw)
                return t.generate(**namespace)

            return render_string("%s%s" % (resource, tmpl_file),
                                 get_snippet=get_snippet,
                                 exception=exception,
                                 traceback=traceback,
                                 sys=sys, tornado=tornado,
                                 status_code=status_code, os=os,
                                 kwargs=kwargs)

    def write_error(self, status_code, **kwargs):

        if 'exc_info' in kwargs:
            exc_info = kwargs.pop('exc_info')
            kwargs['exception'] = exc_info[1]

        return self.finish(self.get_error_html(status_code, **kwargs))


text:
var ask = typeof(prompt) === 'undefined' ? require('./ask.js') : prompt;

var name = ask('What\'s your name? ');

console.log("Hi, " + name);


text:
<?php

declare(strict_types=1);

namespace MsgPhp\User\Model;

use MsgPhp\Domain\DomainCollection;
use MsgPhp\Domain\GenericDomainCollection;
use MsgPhp\User\UserAttributeValue;

/**
 * @author Roland Franssen <franssen.roland@gmail.com>
 */
trait AttributeValuesField
{
    /** @var iterable<array-key, UserAttributeValue> */
    private $attributeValues = [];

    /**
     * @return DomainCollection<array-key, UserAttributeValue>
     */
    public function getAttributeValues(): DomainCollection
    {
        return new GenericDomainCollection($this->attributeValues);
    }
}


text:
html, body {
    display: flex;
    justify-content: center;
    flex-direction: column;
    height: 100%;
    width: 100%;
    background-color: #436177; }

#game-container {
    display: flex;
    justify-content: center;
    width: 100%; }
#game-container canvas {
    border: solid black 2px; }

#output-canvas {
    display: none; }


text:
namespace Polymeres.Compute.Utilities
{
    public static class Constants
    {
        public static readonly char[] Separators = new char[] {'-', '=', '≡'};
    }
}


text:
DROP DATABASE IF EXISTS marbletrader_dev;
CREATE DATABASE marbletrader_dev;

DROP DATABASE IF EXISTS marbletrader_test;
CREATE DATABASE marbletrader_test;

DROP DATABASE IF EXISTS marbletrader_prod;
CREATE DATABASE marbletrader_prod;


text:
// eccrypto.h - written and placed in the public domain by Wei Dai
//              deterministic signatures added by by Douglas Roark

//! \file eccrypto.h
//! \brief Classes and functions for Elliptic Curves over prime and binary fields

#ifndef CRYPTOPP_ECCRYPTO_H
#define CRYPTOPP_ECCRYPTO_H

#include "config.h"
#include "cryptlib.h"
#include "pubkey.h"
#include "integer.h"
#include "asn.h"
#include "hmac.h"
#include "sha.h"
#include "gfpcrypt.h"
#include "dh.h"
#include "mqv.h"
#include "hmqv.h"
#include "fhmqv.h"
#include "ecp.h"
#include "ec2n.h"

NAMESPACE_BEGIN(CryptoPP)

//! \brief Elliptic Curve Parameters
//! \tparam EC elliptic curve field
//! \details This class corresponds to the ASN.1 sequence of the same name
//!   in ANSI X9.62 and SEC 1. EC is currently defined for ECP and EC2N.
template <class EC>
class DL_GroupParameters_EC : public DL_GroupParametersImpl<EcPrecomputation<EC> >
{
	typedef DL_GroupParameters_EC<EC> ThisClass;

public:
	typedef EC EllipticCurve;
	typedef typename EllipticCurve::Point Point;
	typedef Point Element;
	typedef IncompatibleCofactorMultiplication DefaultCofactorOption;

	virtual ~DL_GroupParameters_EC() {}

	//! \brief Construct an EC GroupParameters
	DL_GroupParameters_EC() : m_compress(false), m_encodeAsOID(true) {}

	//! \brief Construct an EC GroupParameters
	//! \param oid the OID of a curve
	DL_GroupParameters_EC(const OID &oid)
		: m_compress(false), m_encodeAsOID(true) {Initialize(oid);}

	//! \brief Construct an EC GroupParameters
	//! \param ec the elliptic curve
	//! \param G the base point
	//! \param n the order of the base point
	//! \param k the cofactor
	DL_GroupParameters_EC(const EllipticCurve &ec, const Point &G, const Integer &n, const Integer &k = Integer::Zero())
		: m_compress(false), m_encodeAsOID(true) {Initialize(ec, G, n, k);}

	//! \brief Construct an EC GroupParameters
	//! \param bt BufferedTransformation with group parameters
	DL_GroupParameters_EC(BufferedTransformation &bt)
		: m_compress(false), m_encodeAsOID(true) {BERDecode(bt);}

	//! \brief Initialize an EC GroupParameters using {EC,G,n,k}
	//! \param ec the elliptic curve
	//! \param G the base point
	//! \param n the order of the base point
	//! \param k the cofactor
	//! \details This Initialize() function overload initializes group parameters from existing parameters.
	void Initialize(const EllipticCurve &ec, const Point &G, const Integer &n, const Integer &k = Integer::Zero())
	{
		this->m_groupPrecomputation.SetCurve(ec);
		this->SetSubgroupGenerator(G);
		m_n = n;
		m_k = k;
	}

	//! \brief Initialize a DL_GroupParameters_EC {EC,G,n,k}
	//! \param oid the OID of a curve
	//! \details This Initialize() function overload initializes group parameters from existing parameters.
	void Initialize(const OID &oid);

	// NameValuePairs
	bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const;
	void AssignFrom(const NameValuePairs &source);

	// GeneratibleCryptoMaterial interface
	//! this implementation doesn't actually generate a curve, it just initializes the parameters with existing values
	/*! parameters: (Curve, SubgroupGenerator, SubgroupOrder, Cofactor (optional)), or (GroupOID) */
	void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &alg);

	// DL_GroupParameters
	const DL_FixedBasePrecomputation<Element> & GetBasePrecomputation() const {return this->m_gpc;}
	DL_FixedBasePrecomputation<Element> & AccessBasePrecomputation() {return this->m_gpc;}
	const Integer & GetSubgroupOrder() const {return m_n;}
	Integer GetCofactor() const;
	bool ValidateGroup(RandomNumberGenerator &rng, unsigned int level) const;
	bool ValidateElement(unsigned int level, const Element &element, const DL_FixedBasePrecomputation<Element> *precomp) const;
	bool FastSubgroupCheckAvailable() const {return false;}
	void EncodeElement(bool reversible, const Element &element, byte *encoded) const
	{
		if (reversible)
			GetCurve().EncodePoint(encoded, element, m_compress);
		else
			element.x.Encode(encoded, GetEncodedElementSize(false));
	}
	virtual unsigned int GetEncodedElementSize(bool reversible) const
	{
		if (reversible)
			return GetCurve().EncodedPointSize(m_compress);
		else
			return GetCurve().GetField().MaxElementByteLength();
	}
	Element DecodeElement(const byte *encoded, bool checkForGroupMembership) const
	{
		Point result;
		if (!GetCurve().DecodePoint(result, encoded, GetEncodedElementSize(true)))
			throw DL_BadElement();
		if (checkForGroupMembership && !ValidateElement(1, result, NULL))
			throw DL_BadElement();
		return result;
	}
	Integer ConvertElementToInteger(const Element &element) const;
	Integer GetMaxExponent() const {return GetSubgroupOrder()-1;}
	bool IsIdentity(const Element &element) const {return element.identity;}
	void SimultaneousExponentiate(Element *results, const Element &base, const Integer *exponents, unsigned int exponentsCount) const;
	static std::string CRYPTOPP_API StaticAlgorithmNamePrefix() {return "EC";}

	// ASN1Key
	OID GetAlgorithmID() const;

	// used by MQV
	Element MultiplyElements(const Element &a, const Element &b) const;
	Element CascadeExponentiate(const Element &element1, const Integer &exponent1, const Element &element2, const Integer &exponent2) const;

	// non-inherited

	// enumerate OIDs for recommended parameters, use OID() to get first one
	static OID CRYPTOPP_API GetNextRecommendedParametersOID(const OID &oid);

	void BERDecode(BufferedTransformation &bt);
	void DEREncode(BufferedTransformation &bt) const;

	void SetPointCompression(bool compress) {m_compress = compress;}
	bool GetPointCompression() const {return m_compress;}

	void SetEncodeAsOID(bool encodeAsOID) {m_encodeAsOID = encodeAsOID;}
	bool GetEncodeAsOID() const {return m_encodeAsOID;}

	const EllipticCurve& GetCurve() const {return this->m_groupPrecomputation.GetCurve();}

	bool operator==(const ThisClass &rhs) const
		{return this->m_groupPrecomputation.GetCurve() == rhs.m_groupPrecomputation.GetCurve() && this->m_gpc.GetBase(this->m_groupPrecomputation) == rhs.m_gpc.GetBase(rhs.m_groupPrecomputation);}

	//#ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
	//const Point& GetBasePoint() const {return this->GetSubgroupGenerator();}
	//const Integer& GetBasePointOrder() const {return this->GetSubgroupOrder();}
	//void LoadRecommendedParameters(const OID &oid) {Initialize(oid);}
	//#endif

protected:
	unsigned int FieldElementLength() const {return GetCurve().GetField().MaxElementByteLength();}
	unsigned int ExponentLength() const {return m_n.ByteCount();}

	OID m_oid;			// set if parameters loaded from a recommended curve
	Integer m_n;		// order of base point
	mutable Integer m_k;		// cofactor
	mutable bool m_compress, m_encodeAsOID;		// presentation details
};

//! \class DL_PublicKey_EC
//! \brief Elliptic Curve Discrete Log (DL) public key
//! \tparam EC elliptic curve field
template <class EC>
class DL_PublicKey_EC : public DL_PublicKeyImpl<DL_GroupParameters_EC<EC> >
{
public:
	typedef typename EC::Point Element;

	virtual ~DL_PublicKey_EC() {}

	//! \brief Initialize an EC Public Key using {GP,Q}
	//! \param params group parameters
	//! \param Q the public point
	//! \details This Initialize() function overload initializes a public key from existing parameters.
	void Initialize(const DL_GroupParameters_EC<EC> &params, const Element &Q)
		{this->AccessGroupParameters() = params; this->SetPublicElement(Q);}

	//! \brief Initialize an EC Public Key using {EC,G,n,Q}
	//! \param ec the elliptic curve
	//! \param G the base point
	//! \param n the order of the base point
	//! \param Q the public point
	//! \details This Initialize() function overload initializes a public key from existing parameters.
	void Initialize(const EC &ec, const Element &G, const Integer &n, const Element &Q)
		{this->AccessGroupParameters().Initialize(ec, G, n); this->SetPublicElement(Q);}

	// X509PublicKey
	void BERDecodePublicKey(BufferedTransformation &bt, bool parametersPresent, size_t size);
	void DEREncodePublicKey(BufferedTransformation &bt) const;
};

//! \class DL_PrivateKey_EC
//! \brief Elliptic Curve Discrete Log (DL) private key
//! \tparam EC elliptic curve field
template <class EC>
class DL_PrivateKey_EC : public DL_PrivateKeyImpl<DL_GroupParameters_EC<EC> >
{
public:
	typedef typename EC::Point Element;

	virtual ~DL_PrivateKey_EC() {}

	//! \brief Initialize an EC Private Key using {GP,x}
	//! \param params group parameters
	//! \param x the private exponent
	//! \details This Initialize() function overload initializes a private key from existing parameters.
	void Initialize(const DL_GroupParameters_EC<EC> &params, const Integer &x)
		{this->AccessGroupParameters() = params; this->SetPrivateExponent(x);}

	//! \brief Initialize an EC Private Key using {EC,G,n,x}
	//! \param ec the elliptic curve
	//! \param G the base point
	//! \param n the order of the base point
	//! \param x the private exponent
	//! \details This Initialize() function overload initializes a private key from existing parameters.
	void Initialize(const EC &ec, const Element &G, const Integer &n, const Integer &x)
		{this->AccessGroupParameters().Initialize(ec, G, n); this->SetPrivateExponent(x);}

	//! \brief Create an EC private key
	//! \param rng a RandomNumberGenerator derived class
	//! \param params the EC group parameters
	//! \details This function overload of Initialize() creates a new private key because it
	//!   takes a RandomNumberGenerator() as a parameter. If you have an existing keypair,
	//!   then use one of the other Initialize() overloads.
	void Initialize(RandomNumberGenerator &rng, const DL_GroupParameters_EC<EC> &params)
		{this->GenerateRandom(rng, params);}

	//! \brief Create an EC private key
	//! \param rng a RandomNumberGenerator derived class
	//! \param ec the elliptic curve
	//! \param G the base point
	//! \param n the order of the base point
	//! \details This function overload of Initialize() creates a new private key because it
	//!   takes a RandomNumberGenerator() as a parameter. If you have an existing keypair,
	//!   then use one of the other Initialize() overloads.
	void Initialize(RandomNumberGenerator &rng, const EC &ec, const Element &G, const Integer &n)
		{this->GenerateRandom(rng, DL_GroupParameters_EC<EC>(ec, G, n));}

	// PKCS8PrivateKey
	void BERDecodePrivateKey(BufferedTransformation &bt, bool parametersPresent, size_t size);
	void DEREncodePrivateKey(BufferedTransformation &bt) const;
};

//! \class ECDH
//! \brief Elliptic Curve Diffie-Hellman
//! \tparam EC elliptic curve field
//! \tparam COFACTOR_OPTION \ref CofactorMultiplicationOption "cofactor multiplication option"
//! \sa Elliptic Curve Diffie-Hellman, AKA ECDH
template <class EC, class COFACTOR_OPTION = typename DL_GroupParameters_EC<EC>::DefaultCofactorOption>
struct ECDH
{
	typedef DH_Domain<DL_GroupParameters_EC<EC>, COFACTOR_OPTION> Domain;
};

//! \class ECMQV
//! \brief Elliptic Curve Menezes-Qu-Vanstone
//! \tparam EC elliptic curve field
//! \tparam COFACTOR_OPTION \ref CofactorMultiplicationOption "cofactor multiplication option"
/// \sa Elliptic Curve Menezes-Qu-Vanstone, AKA ECMQV
template <class EC, class COFACTOR_OPTION = typename DL_GroupParameters_EC<EC>::DefaultCofactorOption>
struct ECMQV
{
	typedef MQV_Domain<DL_GroupParameters_EC<EC>, COFACTOR_OPTION> Domain;
};

//! \class ECHMQV
//! \brief Hashed Elliptic Curve Menezes-Qu-Vanstone
//! \tparam EC elliptic curve field
//! \tparam COFACTOR_OPTION \ref CofactorMultiplicationOption "cofactor multiplication option"
//! \details This implementation follows Hugo Krawczyk's HMQV: A High-Performance
//!   Secure Diffie-Hellman Protocol. Note: this implements HMQV only. HMQV-C with Key Confirmation is not provided.
template <class EC, class COFACTOR_OPTION = typename DL_GroupParameters_EC<EC>::DefaultCofactorOption, class HASH = SHA256>
struct ECHMQV
{
	typedef HMQV_Domain<DL_GroupParameters_EC<EC>, COFACTOR_OPTION, HASH> Domain;
};

typedef ECHMQV< ECP, DL_GroupParameters_EC< ECP >::DefaultCofactorOption,   SHA1 >::Domain ECHMQV160;
typedef ECHMQV< ECP, DL_GroupParameters_EC< ECP >::DefaultCofactorOption, SHA256 >::Domain ECHMQV256;
typedef ECHMQV< ECP, DL_GroupParameters_EC< ECP >::DefaultCofactorOption, SHA384 >::Domain ECHMQV384;
typedef ECHMQV< ECP, DL_GroupParameters_EC< ECP >::DefaultCofactorOption, SHA512 >::Domain ECHMQV512;

//! \class ECFHMQV
//! \brief Fully Hashed Elliptic Curve Menezes-Qu-Vanstone
//! \tparam EC elliptic curve field
//! \tparam COFACTOR_OPTION \ref CofactorMultiplicationOption "cofactor multiplication option"
//! \details This implementation follows Augustin P. Sarr and Philippe Elbaz–Vincent, and Jean–Claude Bajard's
//!   A Secure and Efficient Authenticated Diffie-Hellman Protocol.
//!   Note: this is FHMQV, Protocol 5, from page 11; and not FHMQV-C.
template <class EC, class COFACTOR_OPTION = typename DL_GroupParameters_EC<EC>::DefaultCofactorOption, class HASH = SHA256>
struct ECFHMQV
{
	typedef FHMQV_Domain<DL_GroupParameters_EC<EC>, COFACTOR_OPTION, HASH> Domain;
};

typedef ECFHMQV< ECP, DL_GroupParameters_EC< ECP >::DefaultCofactorOption,   SHA1 >::Domain ECFHMQV160;
typedef ECFHMQV< ECP, DL_GroupParameters_EC< ECP >::DefaultCofactorOption, SHA256 >::Domain ECFHMQV256;
typedef ECFHMQV< ECP, DL_GroupParameters_EC< ECP >::DefaultCofactorOption, SHA384 >::Domain ECFHMQV384;
typedef ECFHMQV< ECP, DL_GroupParameters_EC< ECP >::DefaultCofactorOption, SHA512 >::Domain ECFHMQV512;

//! \class DL_Keys_EC
//! \brief Elliptic Curve Discrete Log (DL) keys
//! \tparam EC elliptic curve field
template <class EC>
struct DL_Keys_EC
{
	typedef DL_PublicKey_EC<EC> PublicKey;
	typedef DL_PrivateKey_EC<EC> PrivateKey;
};

// Forward declaration; documented below
template <class EC, class H>
struct ECDSA;

//! \class DL_Keys_ECDSA
//! \brief Elliptic Curve DSA keys
//! \tparam EC elliptic curve field
template <class EC>
struct DL_Keys_ECDSA
{
	typedef DL_PublicKey_EC<EC> PublicKey;
	typedef DL_PrivateKey_WithSignaturePairwiseConsistencyTest<DL_PrivateKey_EC<EC>, ECDSA<EC, SHA256> > PrivateKey;
};

//! \class DL_Algorithm_ECDSA
//! \brief Elliptic Curve DSA (ECDSA) signature algorithm
//! \tparam EC elliptic curve field
template <class EC>
class DL_Algorithm_ECDSA : public DL_Algorithm_GDSA<typename EC::Point>
{
public:
  CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "ECDSA";}
};

//! \class DL_Algorithm_ECDSA_RFC6979
//! \brief Elliptic Curve DSA (ECDSA) signature algorithm based on RFC 6979
//! \tparam EC elliptic curve field
//! \sa RFC 6979, Deterministic Usage of the
//!   Digital Signature Algorithm (DSA) and Elliptic Curve Digital Signature Algorithm (ECDSA)
//! \since Crypto++ 5.7
template <class EC, class H>
class DL_Algorithm_ECDSA_RFC6979 : public DL_Algorithm_DSA_RFC6979<typename EC::Point, H>
{
public:
  CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "ECDSA-RFC6979";}
};

//! \class DL_Algorithm_ECNR
//! \brief Elliptic Curve NR (ECNR) signature algorithm
//! \tparam EC elliptic curve field
template <class EC>
class DL_Algorithm_ECNR : public DL_Algorithm_NR<typename EC::Point>
{
public:
  CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "ECNR";}
};

//! \class ECDSA
//! \brief Elliptic Curve DSA (ECDSA) signature scheme
//! \tparam EC elliptic curve field
//! \tparam H HashTransformation derived class
//! \sa ECDSA
template <class EC, class H>
struct ECDSA : public DL_SS<DL_Keys_ECDSA<EC>, DL_Algorithm_ECDSA<EC>, DL_SignatureMessageEncodingMethod_DSA, H>
{
};

//! \class ECDSA_RFC6979
//! \brief Elliptic Curve DSA (ECDSA) deterministic signature scheme
//! \tparam EC elliptic curve field
//! \tparam H HashTransformation derived class
//! \sa Deterministic Usage of the
//!   Digital Signature Algorithm (DSA) and Elliptic Curve Digital Signature Algorithm (ECDSA)
template <class EC, class H>
struct ECDSA_RFC6979 : public DL_SS<
	DL_Keys_ECDSA<EC>,
	DL_Algorithm_ECDSA_RFC6979<EC, H>,
	DL_SignatureMessageEncodingMethod_DSA,
	H,
	ECDSA_RFC6979<EC,H> >
{
	static std::string CRYPTOPP_API StaticAlgorithmName() {return std::string("ECDSA-RFC6979/") + H::StaticAlgorithmName();}
};

//! \class ECNR
//! \brief Elliptic Curve NR (ECNR) signature scheme
//! \tparam EC elliptic curve field
//! \tparam H HashTransformation derived class
template <class EC, class H = SHA>
struct ECNR : public DL_SS<DL_Keys_EC<EC>, DL_Algorithm_ECNR<EC>, DL_SignatureMessageEncodingMethod_NR, H>
{
};

// ******************************************

template <class EC>
class DL_PublicKey_ECGDSA_ISO15946;
template <class EC>
class DL_PrivateKey_ECGDSA_ISO15946;

//! \class DL_PrivateKey_ECGDSA_ISO15946
//! \brief Elliptic Curve German DSA key for ISO/IEC 15946
//! \tparam EC elliptic curve field
//! \sa ECGDSA_ISO15946
//! \since Crypto++ 5.7
template <class EC>
class DL_PrivateKey_ECGDSA_ISO15946 : public DL_PrivateKeyImpl<DL_GroupParameters_EC<EC> >
{
public:
	typedef typename EC::Point Element;

	virtual ~DL_PrivateKey_ECGDSA_ISO15946() {}

	//! \brief Initialize an EC Private Key using {GP,x}
	//! \param params group parameters
	//! \param x the private exponent
	//! \details This Initialize() function overload initializes a private key from existing parameters.
	void Initialize(const DL_GroupParameters_EC<EC> &params, const Integer &x)
		{this->AccessGroupParameters() = params; this->SetPrivateExponent(x);}

	//! \brief Initialize an EC Private Key using {EC,G,n,x}
	//! \param ec the elliptic curve
	//! \param G the base point
	//! \param n the order of the base point
	//! \param x the private exponent
	//! \details This Initialize() function overload initializes a private key from existing parameters.
	void Initialize(const EC &ec, const Element &G, const Integer &n, const Integer &x)
		{this->AccessGroupParameters().Initialize(ec, G, n); this->SetPrivateExponent(x);}

	//! \brief Create an EC private key
	//! \param rng a RandomNumberGenerator derived class
	//! \param params the EC group parameters
	//! \details This function overload of Initialize() creates a new private key because it
	//!   takes a RandomNumberGenerator() as a parameter. If you have an existing keypair,
	//!   then use one of the other Initialize() overloads.
	void Initialize(RandomNumberGenerator &rng, const DL_GroupParameters_EC<EC> &params)
		{this->GenerateRandom(rng, params);}

	//! \brief Create an EC private key
	//! \param rng a RandomNumberGenerator derived class
	//! \param ec the elliptic curve
	//! \param G the base point
	//! \param n the order of the base point
	//! \details This function overload of Initialize() creates a new private key because it
	//!   takes a RandomNumberGenerator() as a parameter. If you have an existing keypair,
	//!   then use one of the other Initialize() overloads.
	void Initialize(RandomNumberGenerator &rng, const EC &ec, const Element &G, const Integer &n)
		{this->GenerateRandom(rng, DL_GroupParameters_EC<EC>(ec, G, n));}

	virtual void MakePublicKey(DL_PublicKey_ECGDSA_ISO15946<EC> &pub) const
	{
		const DL_GroupParameters<Element>& params = this->GetAbstractGroupParameters();
		pub.AccessAbstractGroupParameters().AssignFrom(params);
		const Integer &xInv = this->GetPrivateExponent().InverseMod(params.GetGroupOrder());
		pub.SetPublicElement(params.ExponentiateBase(xInv));
	}

	virtual bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
	{
		return GetValueHelper<DL_PrivateKey_ECGDSA_ISO15946<EC>,
			DL_PrivateKey_ECGDSA_ISO15946<EC> >(this, name, valueType, pValue).Assignable();
	}

	virtual void AssignFrom(const NameValuePairs &source)
	{
		AssignFromHelper<DL_PrivateKey_ECGDSA_ISO15946<EC>,
			DL_PrivateKey_ECGDSA_ISO15946<EC> >(this, source);
	}

	// PKCS8PrivateKey
	void BERDecodePrivateKey(BufferedTransformation &bt, bool parametersPresent, size_t size);
	void DEREncodePrivateKey(BufferedTransformation &bt) const;
};

//! \class DL_PublicKey_ECGDSA_ISO15946
//! \brief Elliptic Curve German DSA key for ISO/IEC 15946
//! \tparam EC elliptic curve field
//! \sa ECGDSA_ISO15946
//! \since Crypto++ 5.7
template <class EC>
class DL_PublicKey_ECGDSA_ISO15946 : public DL_PublicKeyImpl<DL_GroupParameters_EC<EC> >
{
	typedef DL_PublicKey_ECGDSA_ISO15946<EC> ThisClass;

public:
	typedef typename EC::Point Element;

	virtual ~DL_PublicKey_ECGDSA_ISO15946() {}

	//! \brief Initialize an EC Public Key using {GP,Q}
	//! \param params group parameters
	//! \param Q the public point
	//! \details This Initialize() function overload initializes a public key from existing parameters.
	void Initialize(const DL_GroupParameters_EC<EC> &params, const Element &Q)
		{this->AccessGroupParameters() = params; this->SetPublicElement(Q);}

	//! \brief Initialize an EC Public Key using {EC,G,n,Q}
	//! \param ec the elliptic curve
	//! \param G the base point
	//! \param n the order of the base point
	//! \param Q the public point
	//! \details This Initialize() function overload initializes a public key from existing parameters.
	void Initialize(const EC &ec, const Element &G, const Integer &n, const Element &Q)
		{this->AccessGroupParameters().Initialize(ec, G, n); this->SetPublicElement(Q);}

	virtual void AssignFrom(const NameValuePairs &source)
	{
		DL_PrivateKey_ECGDSA_ISO15946<EC> *pPrivateKey = NULL;
		if (source.GetThisPointer(pPrivateKey))
			pPrivateKey->MakePublicKey(*this);
		else
		{
			this->AccessAbstractGroupParameters().AssignFrom(source);
			AssignFromHelper(this, source)
				CRYPTOPP_SET_FUNCTION_ENTRY(PublicElement);
		}
	}

	// DL_PublicKey<T>
	virtual void SetPublicElement(const Element &y)
		{this->AccessPublicPrecomputation().SetBase(this->GetAbstractGroupParameters().GetGroupPrecomputation(), y);}

	// X509PublicKey
	void BERDecodePublicKey(BufferedTransformation &bt, bool parametersPresent, size_t size);
	void DEREncodePublicKey(BufferedTransformation &bt) const;
};

//! \class DL_Keys_ECGDSA_ISO15946
//! \brief Elliptic Curve German DSA keys for ISO/IEC 15946
//! \tparam EC elliptic curve field
//! \sa ECGDSA_ISO15946
//! \since Crypto++ 5.7
template <class EC>
struct DL_Keys_ECGDSA_ISO15946
{
	typedef DL_PublicKey_ECGDSA_ISO15946<EC> PublicKey;
	typedef DL_PrivateKey_ECGDSA_ISO15946<EC> PrivateKey;
};

//! \class DL_Algorithm_ECGDSA_ISO15946
//! \brief Elliptic Curve German DSA signature algorithm
//! \tparam EC elliptic curve field
//! \sa ECGDSA_ISO15946
//! \since Crypto++ 5.7
template <class EC>
class DL_Algorithm_ECGDSA_ISO15946 : public DL_Algorithm_GDSA_ISO15946<typename EC::Point>
{
public:
  CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "ECGDSA";}
};

//! \class ECGDSA
//! \brief Elliptic Curve German Digital Signature Algorithm signature scheme
//! \tparam EC elliptic curve field
//! \tparam H HashTransformation derived class
//! \sa Erwin Hess, Marcus Schafheutle, and Pascale Serf The
//!   Digital Signature Scheme ECGDSA (October 24, 2006)
//! \since Crypto++ 5.7
template <class EC, class H>
struct ECGDSA : public DL_SS<
	DL_Keys_ECGDSA_ISO15946<EC>,
	DL_Algorithm_ECGDSA_ISO15946<EC>,
	DL_SignatureMessageEncodingMethod_DSA,
	H>
{
	static std::string CRYPTOPP_API StaticAlgorithmName() {return std::string("ECGDSA-ISO15946/") + H::StaticAlgorithmName();}
};

// ******************************************

//! \class ECIES
//! \brief Elliptic Curve Integrated Encryption Scheme
//! \tparam COFACTOR_OPTION \ref CofactorMultiplicationOption "cofactor multiplication option"
//! \tparam HASH HashTransformation derived class used for key drivation and MAC computation
//! \tparam DHAES_MODE flag indicating if the MAC includes additional context parameters such as u·V, v·U and label
//! \tparam LABEL_OCTETS flag indicating if the label size is specified in octets or bits
//! \details ECIES is an Elliptic Curve based Integrated Encryption Scheme (IES). The scheme combines a Key Encapsulation
//!   Method (KEM) with a Data Encapsulation Method (DEM) and a MAC tag. The scheme is
//!   IND-CCA2, which is a strong notion of security.
//!   You should prefer an Integrated Encryption Scheme over homegrown schemes.
//! \details The library's original implementation is based on an early P1363 draft, which itself appears to be based on an early Certicom
//!   SEC-1 draft (or an early SEC-1 draft was based on a P1363 draft). Crypto++ 4.2 used the early draft in its Integrated Ecryption
//!   Schemes with <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=false</tt> and <tt>LABEL_OCTETS=true</tt>.
//! \details If you desire an Integrated Encryption Scheme with Crypto++ 4.2 compatibility, then use the ECIES template class with
//!   <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=false</tt> and <tt>LABEL_OCTETS=true</tt>.
//! \details If you desire an Integrated Encryption Scheme with Bouncy Castle 1.54 and Botan 1.11 compatibility, then use the ECIES
//!   template class with <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=true</tt> and <tt>LABEL_OCTETS=false</tt>.
//! \details The default template parameters ensure compatibility with Bouncy Castle 1.54 and Botan 1.11. The combination of
//!   <tt>IncompatibleCofactorMultiplication</tt> and <tt>DHAES_MODE=true</tt> is recommended for best efficiency and security.
//!   SHA1 is used for compatibility reasons, but it can be changed if desired. SHA-256 or another hash will likely improve the
//!   security provided by the MAC. The hash is also used in the key derivation function as a PRF.
//! \details Below is an example of constructing a Crypto++ 4.2 compatible ECIES encryptor and decryptor.
//!

//!     AutoSeededRandomPool prng;
//!     DL_PrivateKey_EC<ECP> key;
//!     key.Initialize(prng, ASN1::secp160r1());
//!
//!     ECIES<ECP,SHA1,NoCofactorMultiplication,true,true>::Decryptor decryptor(key);
//!     ECIES<ECP,SHA1,NoCofactorMultiplication,true,true>::Encryptor encryptor(decryptor);
//!

//! \sa DLIES, Elliptic Curve Integrated Encryption Scheme (ECIES),
//!   Martínez, Encinas, and Ávila's A Survey of the Elliptic
//!   Curve Integrated Encryption Schemes
//! \since Crypto++ 4.0, Crypto++ 5.7 for Bouncy Castle and Botan compatibility
template <class EC, class HASH = SHA1, class COFACTOR_OPTION = NoCofactorMultiplication, bool DHAES_MODE = true, bool LABEL_OCTETS = false>
struct ECIES
	: public DL_ES<
		DL_Keys_EC<EC>,
		DL_KeyAgreementAlgorithm_DH<typename EC::Point, COFACTOR_OPTION>,
		DL_KeyDerivationAlgorithm_P1363<typename EC::Point, DHAES_MODE, P1363_KDF2<HASH> >,
		DL_EncryptionAlgorithm_Xor<HMAC<HASH>, DHAES_MODE, LABEL_OCTETS>,
		ECIES<EC> >
{
	// TODO: fix this after name is standardized
	CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "ECIES";}
};

NAMESPACE_END

#ifdef CRYPTOPP_MANUALLY_INSTANTIATE_TEMPLATES
#include "eccrypto.cpp"
#endif

NAMESPACE_BEGIN(CryptoPP)

CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupParameters_EC<ECP>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupParameters_EC<EC2N>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKeyImpl<DL_GroupParameters_EC<ECP> >;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKeyImpl<DL_GroupParameters_EC<EC2N> >;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKey_EC<ECP>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKey_EC<EC2N>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKey_ECGDSA_ISO15946<ECP>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKey_ECGDSA_ISO15946<EC2N>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKeyImpl<DL_GroupParameters_EC<ECP> >;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKeyImpl<DL_GroupParameters_EC<EC2N> >;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_EC<ECP>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_EC<EC2N>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_ECGDSA_ISO15946<ECP>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_ECGDSA_ISO15946<EC2N>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_Algorithm_GDSA<ECP::Point>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_Algorithm_GDSA<EC2N::Point>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_WithSignaturePairwiseConsistencyTest<DL_PrivateKey_EC<ECP>, ECDSA<ECP, SHA256> >;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_WithSignaturePairwiseConsistencyTest<DL_PrivateKey_EC<EC2N>, ECDSA<EC2N, SHA256> >;

NAMESPACE_END

#endif


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

/**
 * DO NOT EDIT THIS FILE as it will be overwritten by the Pbj compiler.
 * @link https://github.com/gdbots/pbjc-php
 *
 * Returns an array of curies using mixin "triniti:dam:mixin:asset-patched:v1"
 * @link http://schemas.triniti.io/json-schema/triniti/dam/mixin/asset-patched/1-0-2.json#
 */

return [
];


text:
int main(int argc, char **argv) {
  return content::UnitTestTestSuite(new XWalkTestSuite(argc, argv)).Run();
}


text:
/*
 * reserved comment block
 * DO NOT REMOVE OR ALTER!
 */
/*
 * Copyright 2001-2004 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
 * $Id: ProcessingInstructionPattern.java,v 1.2.4.1 2005/09/12 11:04:08 pvedula Exp $
 */

package com.sun.org.apache.xalan.internal.xsltc.compiler;

import com.sun.org.apache.bcel.internal.generic.BranchHandle;
import com.sun.org.apache.bcel.internal.generic.ConstantPoolGen;
import com.sun.org.apache.bcel.internal.generic.GOTO;
import com.sun.org.apache.bcel.internal.generic.IFEQ;
import com.sun.org.apache.bcel.internal.generic.IF_ICMPEQ;
import com.sun.org.apache.bcel.internal.generic.INVOKEINTERFACE;
import com.sun.org.apache.bcel.internal.generic.INVOKEVIRTUAL;
import com.sun.org.apache.bcel.internal.generic.InstructionHandle;
import com.sun.org.apache.bcel.internal.generic.InstructionList;
import com.sun.org.apache.bcel.internal.generic.PUSH;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ClassGenerator;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.MethodGenerator;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.TypeCheckError;
import com.sun.org.apache.xml.internal.dtm.Axis;
import com.sun.org.apache.xml.internal.dtm.DTM;

/**
 * @author Morten Jorgensen
 */
final class ProcessingInstructionPattern extends StepPattern {

    private String _name = null;
    private boolean _typeChecked = false;

    /**
     * Handles calls with no parameter (current node is implicit parameter).
     */
    public ProcessingInstructionPattern(String name) {
        super(Axis.CHILD, DTM.PROCESSING_INSTRUCTION_NODE, null);
        _name = name;
        //if (_name.equals("*")) _typeChecked = true; no wildcard allowed!
    }

    /**
     *
     */
     public double getDefaultPriority() {
        return (_name != null) ? 0.0 : -0.5;
     }
    public String toString() {
        if (_predicates == null)
            return "processing-instruction("+_name+")";
        else
            return "processing-instruction("+_name+")"+_predicates;
    }

    public void reduceKernelPattern() {
        _typeChecked = true;
    }

    public boolean isWildcard() {
        return false;
    }

    public Type typeCheck(SymbolTable stable) throws TypeCheckError {
        if (hasPredicates()) {
            // Type check all the predicates (e -> position() = e)
            final int n = _predicates.size();
            for (int i = 0; i < n; i++) {
                final Predicate pred = (Predicate)_predicates.elementAt(i);
                pred.typeCheck(stable);
            }
        }
        return Type.NodeSet;
    }

    public void translate(ClassGenerator classGen, MethodGenerator methodGen) {
        final ConstantPoolGen cpg = classGen.getConstantPool();
        final InstructionList il = methodGen.getInstructionList();

        // context node is on the stack
        int gname = cpg.addInterfaceMethodref(DOM_INTF,
                                              "getNodeName",
                                              "(I)Ljava/lang/String;");
        int cmp = cpg.addMethodref(STRING_CLASS,
                                   "equals", "(Ljava/lang/Object;)Z");

        // Push current node on the stack
        il.append(methodGen.loadCurrentNode());
        il.append(SWAP);

        // Overwrite current node with matching node
        il.append(methodGen.storeCurrentNode());

        // If pattern not reduced then check kernel
        if (!_typeChecked) {
            il.append(methodGen.loadCurrentNode());
            final int getType = cpg.addInterfaceMethodref(DOM_INTF,
                                                          "getExpandedTypeID",
                                                          "(I)I");
            il.append(methodGen.loadDOM());
            il.append(methodGen.loadCurrentNode());
            il.append(new INVOKEINTERFACE(getType, 2));
            il.append(new PUSH(cpg, DTM.PROCESSING_INSTRUCTION_NODE));
            _falseList.add(il.append(new IF_ICMPEQ(null)));
        }

        // Load the requested processing instruction name
        il.append(new PUSH(cpg, _name));
        // Load the current processing instruction's name
        il.append(methodGen.loadDOM());
        il.append(methodGen.loadCurrentNode());
        il.append(new INVOKEINTERFACE(gname, 2));
        // Compare the two strings
        il.append(new INVOKEVIRTUAL(cmp));
        _falseList.add(il.append(new IFEQ(null)));

        // Compile the expressions within the predicates
        if (hasPredicates()) {
            final int n = _predicates.size();
            for (int i = 0; i < n; i++) {
                Predicate pred = (Predicate)_predicates.elementAt(i);
                Expression exp = pred.getExpr();
                exp.translateDesynthesized(classGen, methodGen);
                _trueList.append(exp._trueList);
                _falseList.append(exp._falseList);
            }
        }

        // Backpatch true list and restore current iterator/node
        InstructionHandle restore;
        restore = il.append(methodGen.storeCurrentNode());
        backPatchTrueList(restore);
        BranchHandle skipFalse = il.append(new GOTO(null));

        // Backpatch false list and restore current iterator/node
        restore = il.append(methodGen.storeCurrentNode());
        backPatchFalseList(restore);
        _falseList.add(il.append(new GOTO(null)));

        // True list falls through
        skipFalse.setTarget(il.append(NOP));
    }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="FlatRepresentationTests.cs" company="Hukano">
// Copyright (c) Hukano. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Sundew.Quantities.UnitTests.Representations.Flat;

using FluentAssertions;
using Xunit;

public class FlatRepresentationTests
{
    [Theory]
    [InlineData("kg", 2, "kg", 2, true)]
    [InlineData("kg", 2, "kg", 1, false)]
    [InlineData("kg", 2, "g", 2, false)]
    public void Equals_Then_ResultShouldBeExpected(
        string unit,
        double unitExponent,
        string other,
        double otherExponent,
        bool expected)
    {
        var testee = FlatUnit.CreateFlatRepresentation(new FlatUnit(unit, unitExponent));
        var rhs = FlatUnit.CreateFlatRepresentation(new FlatUnit(other, otherExponent));

        var result = testee.Equals(rhs);

        result.Should().Be(expected);
    }

    [Theory]
    [InlineData("kg", 2, "kg", 2, true)]
    [InlineData("kg", 2, "kg", 1, false)]
    [InlineData("kg", 2, "g", 2, false)]
    public void GetHashcode_Then_ResultShouldBeSameAsOtherResult(
        string unit,
        double unitExponent,
        string other,
        double otherExponent,
        bool expected)
    {
        var testee = FlatUnit.CreateFlatRepresentation(new FlatUnit(unit, unitExponent));
        var rhs = FlatUnit.CreateFlatRepresentation(new FlatUnit(other, otherExponent));

        var result = testee.GetHashCode();
        var otherResult = rhs.GetHashCode();

        result.Equals(otherResult).Should().Be(expected);
    }

    [Fact]
    public void ToString_Then_ResultShouldBeExpectedNotation()
    {
        const string ExpectedNotation = "m¹*h⁻¹*s⁻¹";
        var testee = FlatUnit.CreateFlatRepresentation(
            new FlatUnit("m"),
            new FlatUnit("h", -1),
            new FlatUnit("s", -1));

        var result = testee.ToString();

        result.Should().Be(ExpectedNotation);
    }
}


text:
namespace resource_coordinator {

TestLifecycleUnit::TestLifecycleUnit(base::TimeTicks last_focused_time,
                                     base::ProcessHandle process_handle,
                                     bool can_discard)
    : LifecycleUnitBase(nullptr, content::Visibility::VISIBLE, nullptr),
      last_focused_time_(last_focused_time),
      process_handle_(process_handle),
      sort_key_(last_focused_time),
      can_discard_(can_discard) {}

TestLifecycleUnit::TestLifecycleUnit(content::Visibility visibility,
                                     UsageClock* usage_clock)
    : LifecycleUnitBase(nullptr, visibility, usage_clock) {}

TestLifecycleUnit::TestLifecycleUnit(LifecycleUnitSourceBase* source)
    : LifecycleUnitBase(source, content::Visibility::VISIBLE, nullptr) {}

TestLifecycleUnit::~TestLifecycleUnit() {
  OnLifecycleUnitDestroyed();
}

TabLifecycleUnitExternal* TestLifecycleUnit::AsTabLifecycleUnitExternal() {
  return nullptr;
}

std::u16string TestLifecycleUnit::GetTitle() const {
  return title_;
}

base::TimeTicks TestLifecycleUnit::GetLastFocusedTime() const {
  return last_focused_time_;
}

base::ProcessHandle TestLifecycleUnit::GetProcessHandle() const {
  return process_handle_;
}

LifecycleUnit::SortKey TestLifecycleUnit::GetSortKey() const {
  return sort_key_;
}

content::Visibility TestLifecycleUnit::GetVisibility() const {
  return content::Visibility::VISIBLE;
}

mojom::LifecycleUnitLoadingState TestLifecycleUnit::GetLoadingState() const {
  return mojom::LifecycleUnitLoadingState::LOADED;
}

bool TestLifecycleUnit::Load() {
  return false;
}

int TestLifecycleUnit::GetEstimatedMemoryFreedOnDiscardKB() const {
  return 0;
}

bool TestLifecycleUnit::CanDiscard(mojom::LifecycleUnitDiscardReason reason,
                                   DecisionDetails* decision_details) const {
  return can_discard_;
}

bool TestLifecycleUnit::Discard(LifecycleUnitDiscardReason discard_reason) {
  return false;
}

LifecycleUnitDiscardReason TestLifecycleUnit::GetDiscardReason() const {
  return mojom::LifecycleUnitDiscardReason::EXTERNAL;
}

void ExpectCanDiscardTrue(const LifecycleUnit* lifecycle_unit,
                          LifecycleUnitDiscardReason discard_reason) {
  DecisionDetails decision_details;
  EXPECT_TRUE(lifecycle_unit->CanDiscard(discard_reason, &decision_details));
  EXPECT_TRUE(decision_details.IsPositive());
  EXPECT_EQ(1u, decision_details.reasons().size());
  EXPECT_EQ(DecisionSuccessReason::HEURISTIC_OBSERVED_TO_BE_SAFE,
            decision_details.SuccessReason());
}

void ExpectCanDiscardTrueAllReasons(const LifecycleUnit* lifecycle_unit) {
  ExpectCanDiscardTrue(lifecycle_unit, LifecycleUnitDiscardReason::EXTERNAL);
  ExpectCanDiscardTrue(lifecycle_unit, LifecycleUnitDiscardReason::URGENT);
}

void ExpectCanDiscardFalse(const LifecycleUnit* lifecycle_unit,
                           DecisionFailureReason failure_reason,
                           LifecycleUnitDiscardReason discard_reason) {
  DecisionDetails decision_details;
  EXPECT_FALSE(lifecycle_unit->CanDiscard(discard_reason, &decision_details));
  EXPECT_FALSE(decision_details.IsPositive());
  EXPECT_EQ(1u, decision_details.reasons().size());
  EXPECT_EQ(failure_reason, decision_details.FailureReason());
}

void ExpectCanDiscardFalseAllReasons(const LifecycleUnit* lifecycle_unit,
                                     DecisionFailureReason failure_reason) {
  ExpectCanDiscardFalse(lifecycle_unit, failure_reason,
                        LifecycleUnitDiscardReason::EXTERNAL);
  ExpectCanDiscardFalse(lifecycle_unit, failure_reason,
                        LifecycleUnitDiscardReason::URGENT);
}

void ExpectCanDiscardFalseTrivial(const LifecycleUnit* lifecycle_unit,
                                  LifecycleUnitDiscardReason discard_reason) {
  DecisionDetails decision_details;
  EXPECT_FALSE(lifecycle_unit->CanDiscard(discard_reason, &decision_details));
  EXPECT_FALSE(decision_details.IsPositive());
  // |reasons()| will either contain the status for the 4 local site features
  // heuristics or be empty if the database doesn't track this lifecycle unit.
  EXPECT_TRUE(decision_details.reasons().empty() ||
              (decision_details.reasons().size() == 4));
}

void ExpectCanDiscardFalseTrivialAllReasons(
    const LifecycleUnit* lifecycle_unit) {
  ExpectCanDiscardFalseTrivial(lifecycle_unit,
                               LifecycleUnitDiscardReason::EXTERNAL);
  ExpectCanDiscardFalseTrivial(lifecycle_unit,
                               LifecycleUnitDiscardReason::URGENT);
}

}  // namespace resource_coordinator


text:
using QIP.Public;
using QIP.Public.IServices;
using QIP.Public.ServicesExceptions;
using QIP.Authorization;
using QIP.Authorization.Extensions;
using QIP.Authorization.Resources;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using QIP.WebSockets.Extensions;
using QIP.WebSockets.Models;
using QIP.WebSockets.StringWebSockets;

namespace QIP.WebSockets.Operations {
    class FiguresOperations {
        private static readonly JsonSerializerSettings serializerSettings;

        private readonly IFiguresService _figuresService;
        private readonly IAuthorizationService _authorizationService;
        private readonly ILogger<FiguresOperations> _logger;

        static FiguresOperations() {
            serializerSettings = new JsonSerializerSettings() {
                Converters = { new StringEnumConverter() }
            };
        }

        public FiguresOperations(IFiguresService figuresService,IAuthorizationService authorizationService, ILogger<FiguresOperations> logger) {
            _figuresService = figuresService;
            _authorizationService = authorizationService;
            _logger = logger;
        }

        public async Task DeleteFigures(StringWebSocket stringWebSocket, IStringWebSocketSession session, JObject payload) {
            ClaimsPrincipal user = stringWebSocket.User;
            long boardId = session.Id;

            if(!await _authorizationService.AuthorizeAsync(user, new BoardRequest(boardId), Policies.WriteBoadPolicy)) {
                _logger.LogWarning(
                    LoggingEvents.DeleteWSFiguresNotAuthorized,
                    "DeleteFigures (Board {boardId}) NOT AUTHORIZED {userId}",
                    boardId,
                    user.GetNameIdentifier()
                );
                return;
            }

            DeleteWSFigures delFig = payload.ToObject<DeleteWSFigures>();

            var validationResults = new List<ValidationResult>();
            if(!Validator.TryValidateObject(delFig, new ValidationContext(delFig), validationResults, true)) {
                _logger.LogDebug(LoggingEvents.DeleteWSFiguresInvalidModel, "DeleteFigures (Board {boardId}) INVALID MODEL", boardId);
                return;
            }

            if(delFig.BoardId != boardId) {
                _logger.LogDebug(LoggingEvents.DeleteWSFiguresWrongBoardId, "DeleteFigures (Board {boardId}) WRONG BOARD ID {otherBoardId}", boardId, delFig.BoardId);
                return;
            }

            Task store = _figuresService.DeleteAsync(boardId, delFig.MaxFigureId);
            if(store.IsFaulted) {
                LogSynchronousFault(store, _logger, boardId, delFig.MaxFigureId);
                return;
            }

            Task messages = SendDeleteMessages(session, delFig);
            try {
                await store;
                _logger.LogInformation(
                    LoggingEvents.DeleteWSFigures,
                    "Figures up to {lastFigureToDelete} of Board {boardId} Deleted",
                    delFig.MaxFigureId,
                    boardId
                );

                await messages;
            }
            catch(Exception e) {
                _logger.LogError(
                    LoggingEvents.DeleteWSFiguresUnexpectedError,
                    e,
                    "DeleteFigures up to {lastFigureToDelete} (Board {boardId}) UNEXPECTED ERROR",
                    delFig.MaxFigureId,
                    boardId
                );
            }
        }

        private static void LogSynchronousFault(Task store, ILogger<FiguresOperations> logger, long boardId, long lastFigureToDelete) {
            ReadOnlyCollection<Exception> exceptions = store.Exception.InnerExceptions;
            Exception serviceException = exceptions.First();
            if(exceptions.Count == 1 && serviceException.GetType() == typeof(ServiceException)) {
                logger.LogError(
                    LoggingEvents.DeleteWSFiguresUnexpectedServiceError,
                    serviceException,
                    "DeleteFigures up to {lastFigureToDelete} (Board {boardId}) UNEXPECTED SERVICE ERROR",
                    lastFigureToDelete,
                    boardId
                );
            }
            else {
                logger.LogError(
                    LoggingEvents.DeleteWSFiguresUnexpectedError,
                    store.Exception,
                    "DeleteFigures up to {lastFigureToDelete} (Board {boardId}) UNEXPECTED ERROR",
                    lastFigureToDelete,
                    boardId
                );
            }
        }

        private static Task SendDeleteMessages(IStringWebSocketSession session, DeleteWSFigures delFig) {
            return session.BroadcastAsync(
                new {
                    type = OperationType.BOARD_CLEAN,
                    payload = delFig
                },
                serializerSettings
            );
        }
    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class MDashboard extends CI_Model {

	public function __construct()
	{
		parent::__construct();
		$this->load->database();
	}

	public function jumlahKaryawan()
	{
		$xSQL = ("
			SELECT DISTINCT fs_kode_lokasi as fs_lokasi, COUNT(fn_nik) as fn_jumlah
			FROM tm_karyawan
			WHERE fs_status = '1'
		");

		$xSQL = $xSQL.("
			GROUP BY fs_kode_lokasi
		");

		$sSQL = $this->db->query($xSQL);
		return $sSQL;
	}

}


text:
require 'spec_helper'

module DoorMat
  describe Actor do
    let(:user1) { {email: 'user1@example.com', password: 'password_user1'} }
    let(:user2) { {email: 'user2@example.com', password: 'password_user2'} }

    describe '#can_add_email?' do

      it 'can not add more emails than max_email_count_per_actor' do
        actor1, _ = DoorMat::TestHelper.create_signed_in_actor_with_confirmed_email_address(user1[:email], user1[:password])
        DoorMat::configuration.max_email_count_per_actor = 1
        email = DoorMat::Email.for('user@example.com')
        expect(actor1.can_add_email?(email)).to be false
        expect(email.errors.count).to eq(1)
        expect(email.errors.full_messages.join('')).to match(/maximum number of email per account was reached/)
        DoorMat::configuration.max_email_count_per_actor = 2
      end

      it 'can not add the same email twice' do
        actor1, _ = DoorMat::TestHelper.create_signed_in_actor_with_confirmed_email_address(user1[:email], user1[:password])
        DoorMat::configuration.max_email_count_per_actor = 2
        email = DoorMat::Email.for(user1[:email])

        expect(actor1.can_add_email?(email)).to be false
        expect(email.errors.count).to eq(1)
        expect(email.errors.full_messages.join('')).to match(/already associated/)
      end

      it 'can add a new email' do
        actor1, _ = DoorMat::TestHelper.create_signed_in_actor_with_confirmed_email_address(user1[:email], user1[:password])
        DoorMat::configuration.max_email_count_per_actor = 2
        email = DoorMat::Email.for('user@example.com')

        expect(actor1.can_add_email?(email)).to be true
      end
    end

    it "can share a secret with an other actor" do
      message = "some message"
      actor1, session1 = DoorMat::TestHelper.create_signed_in_actor_with_confirmed_email_address(user1[:email], user1[:password])
      actor2, session2 = DoorMat::TestHelper.create_signed_in_actor_with_confirmed_email_address(user2[:email], user2[:password])

      share = actor1.share_with(actor2, message)

      RequestStore.store[:current_session] = session1
      messages = DoorMat::Crypto.decrypt_shared(share[:secrets], actor1.decrypt_shared_key(share[:key], session1))
      expect(message).to eq(messages.first)

      messages = DoorMat::Crypto.decrypt_shared(share[:secrets], actor2.decrypt_shared_key(share[:other_key], session2))
      expect(message).to eq(messages.first)
    end

  end
end


text:
/**
 * @fileOverview Defines the {@link CKEDITOR.lang} object, for the
 * Galician language.
 */

/**#@+
   @type String
   @example
*/

/**
 * Contains the dictionary of language entries.
 * @namespace
 */
CKEDITOR.lang[ 'gl' ] = {
	// ARIA description.
	editor: 'Editor de texto mellorado',
	editorPanel: 'Panel do editor de texto mellorado',

	// Common messages and labels.
	common: {
		// Screenreader titles. Please note that screenreaders are not always capable
		// of reading non-English words. So be careful while translating it.
		editorHelp: 'Prema ALT 0 para obter axuda',

		browseServer: 'Examinar o servidor',
		url: 'URL',
		protocol: 'Protocolo',
		upload: 'Enviar',
		uploadSubmit: 'Enviar ao servidor',
		image: 'Imaxe',
		flash: 'Flash',
		form: 'Formulario',
		checkbox: 'Caixa de selección',
		radio: 'Botón de opción',
		textField: 'Campo de texto',
		textarea: 'Área de texto',
		hiddenField: 'Campo agochado',
		button: 'Botón',
		select: 'Campo de selección',
		imageButton: 'Botón de imaxe',
		notSet: '<sen estabelecer>',
		id: 'ID',
		name: 'Nome',
		langDir: 'Dirección de escritura do idioma',
		langDirLtr: 'Esquerda a dereita (LTR)',
		langDirRtl: 'Dereita a esquerda (RTL)',
		langCode: 'Código do idioma',
		longDescr: 'Descrición completa do URL',
		cssClass: 'Clases da folla de estilos',
		advisoryTitle: 'Título',
		cssStyle: 'Estilo',
		ok: 'Aceptar',
		cancel: 'Cancelar',
		close: 'Pechar',
		preview: 'Vista previa',
		resize: 'Redimensionar',
		generalTab: 'Xeral',
		advancedTab: 'Avanzado',
		validateNumberFailed: 'Este valor non é un número.',
		confirmNewPage: 'Calquera cambio que non gardara neste contido perderase.\r\nConfirma que quere cargar unha páxina nova?',
		confirmCancel: 'Algunhas das opcións foron cambiadas.\r\nConfirma que quere pechar o diálogo?',
		options: 'Opcións',
		target: 'Destino',
		targetNew: 'Nova xanela (_blank)',
		targetTop: 'Xanela principal (_top)',
		targetSelf: 'Mesma xanela (_self)',
		targetParent: 'Xanela superior (_parent)',
		langDirLTR: 'Esquerda a dereita (LTR)',
		langDirRTL: 'Dereita a esquerda (RTL)',
		styles: 'Estilo',
		cssClasses: 'Clases da folla de estilos',
		width: 'Largo',
		height: 'Alto',
		align: 'Aliñamento',
		alignLeft: 'Esquerda',
		alignRight: 'Dereita',
		alignCenter: 'Centro',
		alignTop: 'Arriba',
		alignMiddle: 'Centro',
		alignBottom: 'Abaixo',
		invalidValue	: 'Valor incorrecto.',
		invalidHeight: 'O alto debe ser un número.',
		invalidWidth: 'O largo debe ser un número.',
		invalidCssLength: 'O valor especificado para o campo «%1» debe ser un número positivo con ou sen unha unidade de medida CSS correcta (px, %, in, cm, mm, em, ex, pt, ou pc).',
		invalidHtmlLength: 'O valor especificado para o campo «%1» debe ser un número positivo con ou sen unha unidade de medida HTML correcta (px ou %).',
		invalidInlineStyle: 'O valor especificado no estilo en liña debe consistir nunha ou máis tuplas co formato «nome : valor», separadas por punto e coma.',
		cssLengthTooltip: 'Escriba un número para o valor en píxeles ou un número cunha unidade CSS correcta (px, %, in, cm, mm, em, ex, pt, ou pc).',

		// Put the voice-only part of the label in the span.
		unavailable: '%1, non dispoñíbel'
	}
};


text:
SCRIPT_NAME=tic4xcoff
OUTPUT_FORMAT="coff2-tic4x"
OUTPUT_ARCH="tic3x"
ARCH=tic3x
TEMPLATE_NAME=ticoff
OUTPUT_FORMAT_TEMPLATE=tic4x
ONCHIP=yes


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Trans. Am. microsc. Soc. 84: 507 (1965)

#### Original name
Evernia degasperi Sambo

### Remarks
null


text:
package io.quarkus.hibernate.orm.xml.orm;

import static org.assertj.core.api.Assertions.assertThat;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.Transactional;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.hibernate.orm.SchemaUtil;
import io.quarkus.hibernate.orm.SmokeTestUtils;
import io.quarkus.test.QuarkusUnitTest;

/**
 * Test that assigning an orm.xml mapping file explicitly works as expected
 * when configuring the persistence unit through Quarkus' application.properties.
 */
public class OrmXmlQuarkusConfigExplicitFileTest {

    @RegisterExtension
    static QuarkusUnitTest runner = new QuarkusUnitTest()
            .withApplicationRoot((jar) -> jar
                    .addClass(SmokeTestUtils.class)
                    .addClass(SchemaUtil.class)
                    .addClass(NonAnnotatedEntity.class)
                    .addAsResource("application-mapping-files-my-orm-xml.properties", "application.properties")
                    .addAsResource("META-INF/orm-simple.xml", "my-orm.xml"));

    @Inject
    EntityManagerFactory entityManagerFactory;

    @Inject
    EntityManager entityManager;

    @Test
    @Transactional
    public void ormXmlTakenIntoAccount() {
        assertThat(SchemaUtil.getColumnNames(entityManagerFactory, NonAnnotatedEntity.class))
                .contains("thename")
                .doesNotContain("name");
    }

    @Test
    @Transactional
    public void smokeTest() {
        SmokeTestUtils.testSimplePersistRetrieveUpdateDelete(entityManager,
                NonAnnotatedEntity.class, NonAnnotatedEntity::new,
                NonAnnotatedEntity::getId, NonAnnotatedEntity::setName, NonAnnotatedEntity::getName);
    }

}


text:
"""A setuptools based setup module.

See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""

# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path

here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
    long_description = f.read()

setup(
    name='pyqimageview',
    version='1.0.0',
    description='A Qt5 based advanced image view widget',
    setup_requires=['setuptools-markdown'],
    long_description=long_description,
    url='https://github.com/nevion/pyqimageview',
    author='Jason Newton',
    author_email='nevion@gmail.com',
    license='MIT',
    zip_safe=False,
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'Topic :: Software Development :: User Interfaces',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
    ],

    keywords='Qt5 image viewer',
    packages=find_packages(exclude=['contrib', 'docs', 'tests*'])
)


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".PcmActivity" >

    <TextView
        android:id="@+id/mainText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Dan the Automator: Relaxation Spa Treatment"
        android:textSize="24sp" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/mainText"
        android:layout_below="@+id/mainText"
        android:text="CC Sampling Plus License" />

    <Button
        android:id="@+id/connectButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:text="Connect to speakers" />

</RelativeLayout>


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _Sidebar = require('../../../styled/Sidebar');

var _Sidebar2 = _interopRequireDefault(_Sidebar);

var _ScenarioNavLink = require('../../../styled/ScenarioNavLink');

var _ScenarioNavLink2 = _interopRequireDefault(_ScenarioNavLink);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/**
 * Footer of the sidebar. Shows demo mode page link.
 * @extends React.Component
 * @property {Object} props.selectedRoute - name of selected route, and if available, selected scenario and context
 */
var Footer = function (_React$Component) {
  _inherits(Footer, _React$Component);

  function Footer() {
    _classCallCheck(this, Footer);

    return _possibleConstructorReturn(this, (Footer.__proto__ || Object.getPrototypeOf(Footer)).apply(this, arguments));
  }

  _createClass(Footer, [{
    key: 'render',
    value: function render() {
      if (!window.__tessereactDemoMode) {
        return null;
      }

      return _react2.default.createElement(
        _Sidebar2.default.Footer,
        null,
        _react2.default.createElement(
          _Sidebar2.default.ListItem,
          null,
          _react2.default.createElement(
            _ScenarioNavLink2.default,
            {
              name: 'demo',
              active: this.props.selectedRoute.name === 'demo'
            },
            window.__tessereactDemoMode.link
          )
        )
      );
    }
  }]);

  return Footer;
}(_react2.default.Component);

exports.default = Footer;


text:
struct scalar_norm1_op {
  typedef RealScalar result_type;
  EIGEN_EMPTY_STRUCT_CTOR(scalar_norm1_op)
  inline RealScalar operator() (const Scalar& a) const { return internal::norm1(a); }
};
namespace Eigen {
  namespace internal {
    template<> struct functor_traits<scalar_norm1_op >
    {
      enum { Cost = 3 * NumTraits<Scalar>::AddCost, PacketAccess = 0 };
    };
  }
}

// computes the sum of magnitudes of all vector elements or, for a complex vector x, the sum
// res = |Rex1| + |Imx1| + |Rex2| + |Imx2| + ... + |Rexn| + |Imxn|, where x is a vector of order n
RealScalar EIGEN_CAT(EIGEN_CAT(REAL_SCALAR_SUFFIX,SCALAR_SUFFIX),asum_)(int *n, RealScalar *px, int *incx)
{
//   std::cerr << "__asum " << *n << " " << *incx << "\n";
  Complex* x = reinterpret_cast<Complex*>(px);

  if(*n<=0) return 0;

  if(*incx==1)  return vector(x,*n).unaryExpr<scalar_norm1_op>().sum();
  else          return vector(x,*n,std::abs(*incx)).unaryExpr<scalar_norm1_op>().sum();
}

// computes a dot product of a conjugated vector with another vector.
int EIGEN_BLAS_FUNC(dotcw)(int *n, RealScalar *px, int *incx, RealScalar *py, int *incy, RealScalar* pres)
{
//   std::cerr << "_dotc " << *n << " " << *incx << " " << *incy << "\n";

  if(*n<=0) return 0;

  Scalar* x = reinterpret_cast<Scalar*>(px);
  Scalar* y = reinterpret_cast<Scalar*>(py);
  Scalar* res = reinterpret_cast<Scalar*>(pres);

  if(*incx==1 && *incy==1)    *res = (vector(x,*n).dot(vector(y,*n)));
  else if(*incx>0 && *incy>0) *res = (vector(x,*n,*incx).dot(vector(y,*n,*incy)));
  else if(*incx<0 && *incy>0) *res = (vector(x,*n,-*incx).reverse().dot(vector(y,*n,*incy)));
  else if(*incx>0 && *incy<0) *res = (vector(x,*n,*incx).dot(vector(y,*n,-*incy).reverse()));
  else if(*incx<0 && *incy<0) *res = (vector(x,*n,-*incx).reverse().dot(vector(y,*n,-*incy).reverse()));
  return 0;
}

// computes a vector-vector dot product without complex conjugation.
int EIGEN_BLAS_FUNC(dotuw)(int *n, RealScalar *px, int *incx, RealScalar *py, int *incy, RealScalar* pres)
{
//   std::cerr << "_dotu " << *n << " " << *incx << " " << *incy << "\n";

  if(*n<=0) return 0;

  Scalar* x = reinterpret_cast<Scalar*>(px);
  Scalar* y = reinterpret_cast<Scalar*>(py);
  Scalar* res = reinterpret_cast<Scalar*>(pres);

  if(*incx==1 && *incy==1)    *res = (vector(x,*n).cwiseProduct(vector(y,*n))).sum();
  else if(*incx>0 && *incy>0) *res = (vector(x,*n,*incx).cwiseProduct(vector(y,*n,*incy))).sum();
  else if(*incx<0 && *incy>0) *res = (vector(x,*n,-*incx).reverse().cwiseProduct(vector(y,*n,*incy))).sum();
  else if(*incx>0 && *incy<0) *res = (vector(x,*n,*incx).cwiseProduct(vector(y,*n,-*incy).reverse())).sum();
  else if(*incx<0 && *incy<0) *res = (vector(x,*n,-*incx).reverse().cwiseProduct(vector(y,*n,-*incy).reverse())).sum();
  return 0;
}

RealScalar EIGEN_CAT(EIGEN_CAT(REAL_SCALAR_SUFFIX,SCALAR_SUFFIX),nrm2_)(int *n, RealScalar *px, int *incx)
{
//   std::cerr << "__nrm2 " << *n << " " << *incx << "\n";
  if(*n<=0) return 0;

  Scalar* x = reinterpret_cast<Scalar*>(px);

  if(*incx==1)
    return vector(x,*n).stableNorm();

  return vector(x,*n,*incx).stableNorm();
}

int EIGEN_CAT(EIGEN_CAT(SCALAR_SUFFIX,REAL_SCALAR_SUFFIX),rot_)(int *n, RealScalar *px, int *incx, RealScalar *py, int *incy, RealScalar *pc, RealScalar *ps)
{
  if(*n<=0) return 0;

  Scalar* x = reinterpret_cast<Scalar*>(px);
  Scalar* y = reinterpret_cast<Scalar*>(py);
  RealScalar c = *pc;
  RealScalar s = *ps;

  StridedVectorType vx(vector(x,*n,std::abs(*incx)));
  StridedVectorType vy(vector(y,*n,std::abs(*incy)));

  Reverse<StridedVectorType> rvx(vx);
  Reverse<StridedVectorType> rvy(vy);

  // TODO implement mixed real-scalar rotations
       if(*incx<0 && *incy>0) internal::apply_rotation_in_the_plane(rvx, vy, JacobiRotation<Scalar>(c,s));
  else if(*incx>0 && *incy<0) internal::apply_rotation_in_the_plane(vx, rvy, JacobiRotation<Scalar>(c,s));
  else                        internal::apply_rotation_in_the_plane(vx, vy,  JacobiRotation<Scalar>(c,s));

  return 0;
}

int EIGEN_CAT(EIGEN_CAT(SCALAR_SUFFIX,REAL_SCALAR_SUFFIX),scal_)(int *n, RealScalar *palpha, RealScalar *px, int *incx)
{
  if(*n<=0) return 0;

  Scalar* x = reinterpret_cast<Scalar*>(px);
  RealScalar alpha = *palpha;

//   std::cerr << "__scal " << *n << " " << alpha << " " << *incx << "\n";

  if(*incx==1)  vector(x,*n) *= alpha;
  else          vector(x,*n,std::abs(*incx)) *= alpha;

  return 0;
}


text:
require "spec_helper"

describe OpenXml::DrawingML::Properties::FillPattern do
  include PropertyTestMacros

  it_should_use tag: :pattFill, name: "fill_pattern"

  for_attribute(:pattern) do
    with_value(:solidDmnd) do # Not Exhaustive
      it_should_assign_successfully
      it_should_output_expected_xml
    end

    it_should_not_allow_invalid_value
  end
end


text:
package org.docksidestage.derby.dbflute.exentity;

import org.docksidestage.derby.dbflute.bsentity.BsMemberWithdrawal;

/**
 * The entity of MEMBER_WITHDRAWAL.
 * <p>
 * You can implement your original methods here.
 * This class remains when re-generating.
 * </p>
 * @author DBFlute(AutoGenerator)
 */
public class MemberWithdrawal extends BsMemberWithdrawal {

    /** Serial version UID. (Default) */
    private static final long serialVersionUID = 1L;
}


text:
ACCEPTED

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

#### Published in
Denisia 5, June: 220.

#### Original name
null

### Remarks
null


text:
static NSString * const TDJSONObjectKey = @"TDJSONObjectKey";

@interface TDJSONResponseSerializer : AFJSONResponseSerializer

@end


text:
import { DatabaseChanges } from 'sofa';

export default DatabaseChanges.extend({

  feed: 'long-polling'

});


text:
    <title>JQuery Cascading List</title>

    <link rel="stylesheet" href="https://cdn.rawgit.com/mikebski/jquery-cascade-list/master/src/cl.css">

Cascading List

The demo is automatically setup and will appear below below.  To destroy the demo click here.  To re-create the demo you can click here