text:
package runner

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/rsa"
	"crypto/subtle"
	"crypto/x509"
	"errors"
	"fmt"
	"io"
	"math/big"

	"./curve25519"
	"./newhope"
)

type keyType int

const (
	keyTypeRSA keyType = iota + 1
	keyTypeECDSA
)

var errClientKeyExchange = errors.New("tls: invalid ClientKeyExchange message")
var errServerKeyExchange = errors.New("tls: invalid ServerKeyExchange message")

// rsaKeyAgreement implements the standard TLS key agreement where the client
// encrypts the pre-master secret to the server's public key.
type rsaKeyAgreement struct {
	version       uint16
	clientVersion uint16
	exportKey     *rsa.PrivateKey
}

func (ka *rsaKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
	// Save the client version for comparison later.
	ka.clientVersion = clientHello.vers

	if !config.Bugs.RSAEphemeralKey {
		return nil, nil
	}

	// Generate an ephemeral RSA key to use instead of the real
	// one, as in RSA_EXPORT.
	key, err := rsa.GenerateKey(config.rand(), 512)
	if err != nil {
		return nil, err
	}
	ka.exportKey = key

	modulus := key.N.Bytes()
	exponent := big.NewInt(int64(key.E)).Bytes()
	serverRSAParams := make([]byte, 0, 2+len(modulus)+2+len(exponent))
	serverRSAParams = append(serverRSAParams, byte(len(modulus)>>8), byte(len(modulus)))
	serverRSAParams = append(serverRSAParams, modulus...)
	serverRSAParams = append(serverRSAParams, byte(len(exponent)>>8), byte(len(exponent)))
	serverRSAParams = append(serverRSAParams, exponent...)

	var sigAlg signatureAlgorithm
	if ka.version >= VersionTLS12 {
		sigAlg, err = selectSignatureAlgorithm(ka.version, cert.PrivateKey, config, clientHello.signatureAlgorithms)
		if err != nil {
			return nil, err
		}
	}

	sig, err := signMessage(ka.version, cert.PrivateKey, config, sigAlg, serverRSAParams)
	if err != nil {
		return nil, errors.New("failed to sign RSA parameters: " + err.Error())
	}

	skx := new(serverKeyExchangeMsg)
	sigAlgsLen := 0
	if ka.version >= VersionTLS12 {
		sigAlgsLen = 2
	}
	skx.key = make([]byte, len(serverRSAParams)+sigAlgsLen+2+len(sig))
	copy(skx.key, serverRSAParams)
	k := skx.key[len(serverRSAParams):]
	if ka.version >= VersionTLS12 {
		k[0] = byte(sigAlg >> 8)
		k[1] = byte(sigAlg)
		k = k[2:]
	}
	k[0] = byte(len(sig) >> 8)
	k[1] = byte(len(sig))
	copy(k[2:], sig)

	return skx, nil
}

func (ka *rsaKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
	preMasterSecret := make([]byte, 48)
	_, err := io.ReadFull(config.rand(), preMasterSecret[2:])
	if err != nil {
		return nil, err
	}

	if len(ckx.ciphertext) < 2 {
		return nil, errClientKeyExchange
	}

	ciphertext := ckx.ciphertext
	if version != VersionSSL30 {
		ciphertextLen := int(ckx.ciphertext[0])<<8 | int(ckx.ciphertext[1])
		if ciphertextLen != len(ckx.ciphertext)-2 {
			return nil, errClientKeyExchange
		}
		ciphertext = ckx.ciphertext[2:]
	}

	key := cert.PrivateKey.(*rsa.PrivateKey)
	if ka.exportKey != nil {
		key = ka.exportKey
	}
	err = rsa.DecryptPKCS1v15SessionKey(config.rand(), key, ciphertext, preMasterSecret)
	if err != nil {
		return nil, err
	}
	// This check should be done in constant-time, but this is a testing
	// implementation. See the discussion at the end of section 7.4.7.1 of
	// RFC 4346.
	vers := uint16(preMasterSecret[0])<<8 | uint16(preMasterSecret[1])
	if ka.clientVersion != vers {
		return nil, fmt.Errorf("tls: invalid version in RSA premaster (got %04x, wanted %04x)", vers, ka.clientVersion)
	}
	return preMasterSecret, nil
}

func (ka *rsaKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
	return errors.New("tls: unexpected ServerKeyExchange")
}

func (ka *rsaKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
	bad := config.Bugs.BadRSAClientKeyExchange
	preMasterSecret := make([]byte, 48)
	vers := clientHello.vers
	if bad == RSABadValueWrongVersion {
		vers ^= 1
	}
	preMasterSecret[0] = byte(vers >> 8)
	preMasterSecret[1] = byte(vers)
	_, err := io.ReadFull(config.rand(), preMasterSecret[2:])
	if err != nil {
		return nil, nil, err
	}

	sentPreMasterSecret := preMasterSecret
	if bad == RSABadValueTooLong {
		sentPreMasterSecret = make([]byte, len(sentPreMasterSecret)+1)
		copy(sentPreMasterSecret, preMasterSecret)
	} else if bad == RSABadValueTooShort {
		sentPreMasterSecret = sentPreMasterSecret[:len(sentPreMasterSecret)-1]
	}

	encrypted, err := rsa.EncryptPKCS1v15(config.rand(), cert.PublicKey.(*rsa.PublicKey), sentPreMasterSecret)
	if err != nil {
		return nil, nil, err
	}
	if bad == RSABadValueCorrupt {
		encrypted[len(encrypted)-1] ^= 1
		// Clear the high byte to ensure |encrypted| is still below the RSA modulus.
		encrypted[0] = 0
	}
	ckx := new(clientKeyExchangeMsg)
	if clientHello.vers != VersionSSL30 {
		ckx.ciphertext = make([]byte, len(encrypted)+2)
		ckx.ciphertext[0] = byte(len(encrypted) >> 8)
		ckx.ciphertext[1] = byte(len(encrypted))
		copy(ckx.ciphertext[2:], encrypted)
	} else {
		ckx.ciphertext = encrypted
	}
	return preMasterSecret, ckx, nil
}

func (ka *rsaKeyAgreement) peerSignatureAlgorithm() signatureAlgorithm {
	return 0
}

// A ecdhCurve is an instance of ECDH-style key agreement for TLS.
type ecdhCurve interface {
	// offer generates a keypair using rand. It returns the encoded |publicKey|.
	offer(rand io.Reader) (publicKey []byte, err error)

	// accept responds to the |peerKey| generated by |offer| with the acceptor's
	// |publicKey|, and returns agreed-upon |preMasterSecret| to the acceptor.
	accept(rand io.Reader, peerKey []byte) (publicKey []byte, preMasterSecret []byte, err error)

	// finish returns the computed |preMasterSecret|, given the |peerKey|
	// generated by |accept|.
	finish(peerKey []byte) (preMasterSecret []byte, err error)
}

// ellipticECDHCurve implements ecdhCurve with an elliptic.Curve.
type ellipticECDHCurve struct {
	curve      elliptic.Curve
	privateKey []byte
}

func (e *ellipticECDHCurve) offer(rand io.Reader) (publicKey []byte, err error) {
	var x, y *big.Int
	e.privateKey, x, y, err = elliptic.GenerateKey(e.curve, rand)
	if err != nil {
		return nil, err
	}
	return elliptic.Marshal(e.curve, x, y), nil
}

func (e *ellipticECDHCurve) accept(rand io.Reader, peerKey []byte) (publicKey []byte, preMasterSecret []byte, err error) {
	publicKey, err = e.offer(rand)
	if err != nil {
		return nil, nil, err
	}
	preMasterSecret, err = e.finish(peerKey)
	if err != nil {
		return nil, nil, err
	}
	return
}

func (e *ellipticECDHCurve) finish(peerKey []byte) (preMasterSecret []byte, err error) {
	x, y := elliptic.Unmarshal(e.curve, peerKey)
	if x == nil {
		return nil, errors.New("tls: invalid peer key")
	}
	x, _ = e.curve.ScalarMult(x, y, e.privateKey)
	preMasterSecret = make([]byte, (e.curve.Params().BitSize+7)>>3)
	xBytes := x.Bytes()
	copy(preMasterSecret[len(preMasterSecret)-len(xBytes):], xBytes)

	return preMasterSecret, nil
}

// x25519ECDHCurve implements ecdhCurve with X25519.
type x25519ECDHCurve struct {
	privateKey [32]byte
}

func (e *x25519ECDHCurve) offer(rand io.Reader) (publicKey []byte, err error) {
	_, err = io.ReadFull(rand, e.privateKey[:])
	if err != nil {
		return
	}
	var out [32]byte
	curve25519.ScalarBaseMult(&out, &e.privateKey)
	return out[:], nil
}

func (e *x25519ECDHCurve) accept(rand io.Reader, peerKey []byte) (publicKey []byte, preMasterSecret []byte, err error) {
	publicKey, err = e.offer(rand)
	if err != nil {
		return nil, nil, err
	}
	preMasterSecret, err = e.finish(peerKey)
	if err != nil {
		return nil, nil, err
	}
	return
}

func (e *x25519ECDHCurve) finish(peerKey []byte) (preMasterSecret []byte, err error) {
	if len(peerKey) != 32 {
		return nil, errors.New("tls: invalid peer key")
	}
	var out, peerKeyCopy [32]byte
	copy(peerKeyCopy[:], peerKey)
	curve25519.ScalarMult(&out, &e.privateKey, &peerKeyCopy)

	// Per RFC 7748, reject the all-zero value in constant time.
	var zeros [32]byte
	if subtle.ConstantTimeCompare(zeros[:], out[:]) == 1 {
		return nil, errors.New("tls: X25519 value with wrong order")
	}

	return out[:], nil
}

// cecpq1Curve is combined elliptic curve (X25519) and post-quantum (new hope) key
// agreement.
type cecpq1Curve struct {
	x25519  *x25519ECDHCurve
	newhope *newhope.Poly
}

func (e *cecpq1Curve) offer(rand io.Reader) (publicKey []byte, err error) {
	var x25519OfferMsg, newhopeOfferMsg []byte

	e.x25519 = new(x25519ECDHCurve)
	if x25519OfferMsg, err = e.x25519.offer(rand); err != nil {
		return nil, err
	}

	newhopeOfferMsg, e.newhope = newhope.Offer(rand)

	return append(x25519OfferMsg, newhopeOfferMsg[:]...), nil
}

func (e *cecpq1Curve) accept(rand io.Reader, peerKey []byte) (publicKey []byte, preMasterSecret []byte, err error) {
	if len(peerKey) != 32+newhope.OfferMsgLen {
		return nil, nil, errors.New("cecpq1: invalid offer message")
	}

	var x25519AcceptMsg, newhopeAcceptMsg []byte
	var x25519Secret []byte
	var newhopeSecret newhope.Key

	x25519 := new(x25519ECDHCurve)
	if x25519AcceptMsg, x25519Secret, err = x25519.accept(rand, peerKey[:32]); err != nil {
		return nil, nil, err
	}

	if newhopeSecret, newhopeAcceptMsg, err = newhope.Accept(rand, peerKey[32:]); err != nil {
		return nil, nil, err
	}

	return append(x25519AcceptMsg, newhopeAcceptMsg[:]...), append(x25519Secret, newhopeSecret[:]...), nil
}

func (e *cecpq1Curve) finish(peerKey []byte) (preMasterSecret []byte, err error) {
	if len(peerKey) != 32+newhope.AcceptMsgLen {
		return nil, errors.New("cecpq1: invalid accept message")
	}

	var x25519Secret []byte
	var newhopeSecret newhope.Key

	if x25519Secret, err = e.x25519.finish(peerKey[:32]); err != nil {
		return nil, err
	}

	if newhopeSecret, err = e.newhope.Finish(peerKey[32:]); err != nil {
		return nil, err
	}

	return append(x25519Secret, newhopeSecret[:]...), nil
}

func curveForCurveID(id CurveID) (ecdhCurve, bool) {
	switch id {
	case CurveP224:
		return &ellipticECDHCurve{curve: elliptic.P224()}, true
	case CurveP256:
		return &ellipticECDHCurve{curve: elliptic.P256()}, true
	case CurveP384:
		return &ellipticECDHCurve{curve: elliptic.P384()}, true
	case CurveP521:
		return &ellipticECDHCurve{curve: elliptic.P521()}, true
	case CurveX25519:
		return &x25519ECDHCurve{}, true
	default:
		return nil, false
	}

}

// keyAgreementAuthentication is a helper interface that specifies how
// to authenticate the ServerKeyExchange parameters.
type keyAgreementAuthentication interface {
	signParameters(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg, params []byte) (*serverKeyExchangeMsg, error)
	verifyParameters(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, params []byte, sig []byte) error
}

// nilKeyAgreementAuthentication does not authenticate the key
// agreement parameters.
type nilKeyAgreementAuthentication struct{}

func (ka *nilKeyAgreementAuthentication) signParameters(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg, params []byte) (*serverKeyExchangeMsg, error) {
	skx := new(serverKeyExchangeMsg)
	skx.key = params
	return skx, nil
}

func (ka *nilKeyAgreementAuthentication) verifyParameters(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, params []byte, sig []byte) error {
	return nil
}

// signedKeyAgreement signs the ServerKeyExchange parameters with the
// server's private key.
type signedKeyAgreement struct {
	keyType                keyType
	version                uint16
	peerSignatureAlgorithm signatureAlgorithm
}

func (ka *signedKeyAgreement) signParameters(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg, params []byte) (*serverKeyExchangeMsg, error) {
	// The message to be signed is prepended by the randoms.
	var msg []byte
	msg = append(msg, clientHello.random...)
	msg = append(msg, hello.random...)
	msg = append(msg, params...)

	var sigAlg signatureAlgorithm
	var err error
	if ka.version >= VersionTLS12 {
		sigAlg, err = selectSignatureAlgorithm(ka.version, cert.PrivateKey, config, clientHello.signatureAlgorithms)
		if err != nil {
			return nil, err
		}
	}

	sig, err := signMessage(ka.version, cert.PrivateKey, config, sigAlg, msg)
	if err != nil {
		return nil, err
	}
	if config.Bugs.SendSignatureAlgorithm != 0 {
		sigAlg = config.Bugs.SendSignatureAlgorithm
	}

	skx := new(serverKeyExchangeMsg)
	if config.Bugs.UnauthenticatedECDH {
		skx.key = params
	} else {
		sigAlgsLen := 0
		if ka.version >= VersionTLS12 {
			sigAlgsLen = 2
		}
		skx.key = make([]byte, len(params)+sigAlgsLen+2+len(sig))
		copy(skx.key, params)
		k := skx.key[len(params):]
		if ka.version >= VersionTLS12 {
			k[0] = byte(sigAlg >> 8)
			k[1] = byte(sigAlg)
			k = k[2:]
		}
		k[0] = byte(len(sig) >> 8)
		k[1] = byte(len(sig))
		copy(k[2:], sig)
	}

	return skx, nil
}

func (ka *signedKeyAgreement) verifyParameters(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, params []byte, sig []byte) error {
	// The peer's key must match the cipher type.
	switch ka.keyType {
	case keyTypeECDSA:
		_, ok := cert.PublicKey.(*ecdsa.PublicKey)
		if !ok {
			return errors.New("tls: ECDHE ECDSA requires a ECDSA server public key")
		}
	case keyTypeRSA:
		_, ok := cert.PublicKey.(*rsa.PublicKey)
		if !ok {
			return errors.New("tls: ECDHE RSA requires a RSA server public key")
		}
	default:
		return errors.New("tls: unknown key type")
	}

	// The message to be signed is prepended by the randoms.
	var msg []byte
	msg = append(msg, clientHello.random...)
	msg = append(msg, serverHello.random...)
	msg = append(msg, params...)

	var sigAlg signatureAlgorithm
	if ka.version >= VersionTLS12 {
		if len(sig) < 2 {
			return errServerKeyExchange
		}
		sigAlg = signatureAlgorithm(sig[0])<<8 | signatureAlgorithm(sig[1])
		sig = sig[2:]
		// Stash the signature algorithm to be extracted by the handshake.
		ka.peerSignatureAlgorithm = sigAlg
	}

	if len(sig) < 2 {
		return errServerKeyExchange
	}
	sigLen := int(sig[0])<<8 | int(sig[1])
	if sigLen+2 != len(sig) {
		return errServerKeyExchange
	}
	sig = sig[2:]

	return verifyMessage(ka.version, cert.PublicKey, config, sigAlg, msg, sig)
}

// ecdheKeyAgreement implements a TLS key agreement where the server
// generates a ephemeral EC public/private key pair and signs it. The
// pre-master secret is then calculated using ECDH. The signature may
// either be ECDSA or RSA.
type ecdheKeyAgreement struct {
	auth    keyAgreementAuthentication
	curve   ecdhCurve
	curveID CurveID
	peerKey []byte
}

func (ka *ecdheKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
	var curveid CurveID
	preferredCurves := config.curvePreferences()

NextCandidate:
	for _, candidate := range preferredCurves {
		for _, c := range clientHello.supportedCurves {
			if candidate == c {
				curveid = c
				break NextCandidate
			}
		}
	}

	if curveid == 0 {
		return nil, errors.New("tls: no supported elliptic curves offered")
	}

	var ok bool
	if ka.curve, ok = curveForCurveID(curveid); !ok {
		return nil, errors.New("tls: preferredCurves includes unsupported curve")
	}
	ka.curveID = curveid

	publicKey, err := ka.curve.offer(config.rand())
	if err != nil {
		return nil, err
	}

	// http://tools.ietf.org/html/rfc4492#section-5.4
	serverECDHParams := make([]byte, 1+2+1+len(publicKey))
	serverECDHParams[0] = 3 // named curve
	if config.Bugs.SendCurve != 0 {
		curveid = config.Bugs.SendCurve
	}
	serverECDHParams[1] = byte(curveid >> 8)
	serverECDHParams[2] = byte(curveid)
	serverECDHParams[3] = byte(len(publicKey))
	copy(serverECDHParams[4:], publicKey)
	if config.Bugs.InvalidECDHPoint {
		serverECDHParams[4] ^= 0xff
	}

	return ka.auth.signParameters(config, cert, clientHello, hello, serverECDHParams)
}

func (ka *ecdheKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
	if len(ckx.ciphertext) == 0 || int(ckx.ciphertext[0]) != len(ckx.ciphertext)-1 {
		return nil, errClientKeyExchange
	}
	return ka.curve.finish(ckx.ciphertext[1:])
}

func (ka *ecdheKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
	if len(skx.key) < 4 {
		return errServerKeyExchange
	}
	if skx.key[0] != 3 { // named curve
		return errors.New("tls: server selected unsupported curve")
	}
	curveid := CurveID(skx.key[1])<<8 | CurveID(skx.key[2])
	ka.curveID = curveid

	var ok bool
	if ka.curve, ok = curveForCurveID(curveid); !ok {
		return errors.New("tls: server selected unsupported curve")
	}

	publicLen := int(skx.key[3])
	if publicLen+4 > len(skx.key) {
		return errServerKeyExchange
	}
	// Save the peer key for later.
	ka.peerKey = skx.key[4 : 4+publicLen]

	// Check the signature.
	serverECDHParams := skx.key[:4+publicLen]
	sig := skx.key[4+publicLen:]
	return ka.auth.verifyParameters(config, clientHello, serverHello, cert, serverECDHParams, sig)
}

func (ka *ecdheKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
	if ka.curve == nil {
		return nil, nil, errors.New("missing ServerKeyExchange message")
	}

	publicKey, preMasterSecret, err := ka.curve.accept(config.rand(), ka.peerKey)
	if err != nil {
		return nil, nil, err
	}

	ckx := new(clientKeyExchangeMsg)
	ckx.ciphertext = make([]byte, 1+len(publicKey))
	ckx.ciphertext[0] = byte(len(publicKey))
	copy(ckx.ciphertext[1:], publicKey)
	if config.Bugs.InvalidECDHPoint {
		ckx.ciphertext[1] ^= 0xff
	}

	return preMasterSecret, ckx, nil
}

func (ka *ecdheKeyAgreement) peerSignatureAlgorithm() signatureAlgorithm {
	if auth, ok := ka.auth.(*signedKeyAgreement); ok {
		return auth.peerSignatureAlgorithm
	}
	return 0
}

// cecpq1RSAKeyAgreement is like an ecdheKeyAgreement, but using the cecpq1Curve
// pseudo-curve, and without any parameters (e.g. curve name) other than the
// keys being exchanged. The signature may either be ECDSA or RSA.
type cecpq1KeyAgreement struct {
	auth    keyAgreementAuthentication
	curve   ecdhCurve
	peerKey []byte
}

func (ka *cecpq1KeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
	ka.curve = &cecpq1Curve{}
	publicKey, err := ka.curve.offer(config.rand())
	if err != nil {
		return nil, err
	}

	if config.Bugs.CECPQ1BadX25519Part {
		publicKey[0] ^= 1
	}
	if config.Bugs.CECPQ1BadNewhopePart {
		publicKey[32] ^= 1
		publicKey[33] ^= 1
		publicKey[34] ^= 1
		publicKey[35] ^= 1
	}

	var params []byte
	params = append(params, byte(len(publicKey)>>8))
	params = append(params, byte(len(publicKey)&0xff))
	params = append(params, publicKey[:]...)

	return ka.auth.signParameters(config, cert, clientHello, hello, params)
}

func (ka *cecpq1KeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
	if len(ckx.ciphertext) < 2 {
		return nil, errClientKeyExchange
	}
	peerKeyLen := int(ckx.ciphertext[0])<<8 + int(ckx.ciphertext[1])
	peerKey := ckx.ciphertext[2:]
	if peerKeyLen != len(peerKey) {
		return nil, errClientKeyExchange
	}
	return ka.curve.finish(peerKey)
}

func (ka *cecpq1KeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
	if len(skx.key) < 2 {
		return errServerKeyExchange
	}
	peerKeyLen := int(skx.key[0])<<8 + int(skx.key[1])
	// Save the peer key for later.
	if len(skx.key) < 2+peerKeyLen {
		return errServerKeyExchange
	}
	ka.peerKey = skx.key[2 : 2+peerKeyLen]
	if peerKeyLen != len(ka.peerKey) {
		return errServerKeyExchange
	}

	// Check the signature.
	params := skx.key[:2+peerKeyLen]
	sig := skx.key[2+peerKeyLen:]
	return ka.auth.verifyParameters(config, clientHello, serverHello, cert, params, sig)
}

func (ka *cecpq1KeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
	curve := &cecpq1Curve{}
	publicKey, preMasterSecret, err := curve.accept(config.rand(), ka.peerKey)
	if err != nil {
		return nil, nil, err
	}

	if config.Bugs.CECPQ1BadX25519Part {
		publicKey[0] ^= 1
	}
	if config.Bugs.CECPQ1BadNewhopePart {
		publicKey[32] ^= 1
		publicKey[33] ^= 1
		publicKey[34] ^= 1
		publicKey[35] ^= 1
	}

	ckx := new(clientKeyExchangeMsg)
	ckx.ciphertext = append(ckx.ciphertext, byte(len(publicKey)>>8))
	ckx.ciphertext = append(ckx.ciphertext, byte(len(publicKey)&0xff))
	ckx.ciphertext = append(ckx.ciphertext, publicKey[:]...)

	return preMasterSecret, ckx, nil
}

func (ka *cecpq1KeyAgreement) peerSignatureAlgorithm() signatureAlgorithm {
	if auth, ok := ka.auth.(*signedKeyAgreement); ok {
		return auth.peerSignatureAlgorithm
	}
	return 0
}

// dheRSAKeyAgreement implements a TLS key agreement where the server generates
// an ephemeral Diffie-Hellman public/private key pair and signs it. The
// pre-master secret is then calculated using Diffie-Hellman.
type dheKeyAgreement struct {
	auth    keyAgreementAuthentication
	p, g    *big.Int
	yTheirs *big.Int
	xOurs   *big.Int
}

func (ka *dheKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
	var q *big.Int
	if p := config.Bugs.DHGroupPrime; p != nil {
		ka.p = p
		ka.g = big.NewInt(2)
		q = p
	} else {
		// 2048-bit MODP Group with 256-bit Prime Order Subgroup (RFC
		// 5114, Section 2.3)
		ka.p, _ = new(big.Int).SetString("87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435E3B00E00DF8F1D61957D4FAF7DF4561B2AA3016C3D91134096FAA3BF4296D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B4758C022E0B1EF4275BF7B6C5BFC11D45F9088B941F54EB1E59BB8BC39A0BF12307F5C4FDB70C581B23F76B63ACAE1CAA6B7902D52526735488A0EF13C6D9A51BFA4AB3AD8347796524D8EF6A167B5A41825D967E144E5140564251CCACB83E6B486F6B3CA3F7971506026C0B857F689962856DED4010ABD0BE621C3A3960A54E710C375F26375D7014103A4B54330C198AF126116D2276E11715F693877FAD7EF09CADB094AE91E1A1597", 16)
		ka.g, _ = new(big.Int).SetString("3FB32C9B73134D0B2E77506660EDBD484CA7B18F21EF205407F4793A1A0BA12510DBC15077BE463FFF4FED4AAC0BB555BE3A6C1B0C6B47B1BC3773BF7E8C6F62901228F8C28CBB18A55AE31341000A650196F931C77A57F2DDF463E5E9EC144B777DE62AAAB8A8628AC376D282D6ED3864E67982428EBC831D14348F6F2F9193B5045AF2767164E1DFC967C1FB3F2E55A4BD1BFFE83B9C80D052B985D182EA0ADB2A3B7313D3FE14C8484B1E052588B9B7D2BBD2DF016199ECD06E1557CD0915B3353BBB64E0EC377FD028370DF92B52C7891428CDC67EB6184B523D1DB246C32F63078490F00EF8D647D148D47954515E2327CFEF98C582664B4C0F6CC41659", 16)
		q, _ = new(big.Int).SetString("8CF83642A709A097B447997640129DA299B1A47D1EB3750BA308B0FE64F5FBD3", 16)
	}

	var err error
	ka.xOurs, err = rand.Int(config.rand(), q)
	if err != nil {
		return nil, err
	}
	yOurs := new(big.Int).Exp(ka.g, ka.xOurs, ka.p)

	// http://tools.ietf.org/html/rfc5246#section-7.4.3
	pBytes := ka.p.Bytes()
	gBytes := ka.g.Bytes()
	yBytes := yOurs.Bytes()
	serverDHParams := make([]byte, 0, 2+len(pBytes)+2+len(gBytes)+2+len(yBytes))
	serverDHParams = append(serverDHParams, byte(len(pBytes)>>8), byte(len(pBytes)))
	serverDHParams = append(serverDHParams, pBytes...)
	serverDHParams = append(serverDHParams, byte(len(gBytes)>>8), byte(len(gBytes)))
	serverDHParams = append(serverDHParams, gBytes...)
	serverDHParams = append(serverDHParams, byte(len(yBytes)>>8), byte(len(yBytes)))
	serverDHParams = append(serverDHParams, yBytes...)

	return ka.auth.signParameters(config, cert, clientHello, hello, serverDHParams)
}

func (ka *dheKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
	if len(ckx.ciphertext) < 2 {
		return nil, errClientKeyExchange
	}
	yLen := (int(ckx.ciphertext[0]) << 8) | int(ckx.ciphertext[1])
	if yLen != len(ckx.ciphertext)-2 {
		return nil, errClientKeyExchange
	}
	yTheirs := new(big.Int).SetBytes(ckx.ciphertext[2:])
	if yTheirs.Sign() <= 0 || yTheirs.Cmp(ka.p) >= 0 {
		return nil, errClientKeyExchange
	}
	return new(big.Int).Exp(yTheirs, ka.xOurs, ka.p).Bytes(), nil
}

func (ka *dheKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
	// Read dh_p
	k := skx.key
	if len(k) < 2 {
		return errServerKeyExchange
	}
	pLen := (int(k[0]) << 8) | int(k[1])
	k = k[2:]
	if len(k) < pLen {
		return errServerKeyExchange
	}
	ka.p = new(big.Int).SetBytes(k[:pLen])
	k = k[pLen:]

	// Read dh_g
	if len(k) < 2 {
		return errServerKeyExchange
	}
	gLen := (int(k[0]) << 8) | int(k[1])
	k = k[2:]
	if len(k) < gLen {
		return errServerKeyExchange
	}
	ka.g = new(big.Int).SetBytes(k[:gLen])
	k = k[gLen:]

	// Read dh_Ys
	if len(k) < 2 {
		return errServerKeyExchange
	}
	yLen := (int(k[0]) << 8) | int(k[1])
	k = k[2:]
	if len(k) < yLen {
		return errServerKeyExchange
	}
	ka.yTheirs = new(big.Int).SetBytes(k[:yLen])
	k = k[yLen:]
	if ka.yTheirs.Sign() <= 0 || ka.yTheirs.Cmp(ka.p) >= 0 {
		return errServerKeyExchange
	}

	if l := config.Bugs.RequireDHPublicValueLen; l != 0 && l != yLen {
		return fmt.Errorf("RequireDHPublicValueLen set to %d, but server's public value was %d bytes on the wire and %d bytes if minimal", l, yLen, (ka.yTheirs.BitLen()+7)/8)
	}

	sig := k
	serverDHParams := skx.key[:len(skx.key)-len(sig)]

	return ka.auth.verifyParameters(config, clientHello, serverHello, cert, serverDHParams, sig)
}

func (ka *dheKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
	if ka.p == nil || ka.g == nil || ka.yTheirs == nil {
		return nil, nil, errors.New("missing ServerKeyExchange message")
	}

	xOurs, err := rand.Int(config.rand(), ka.p)
	if err != nil {
		return nil, nil, err
	}
	preMasterSecret := new(big.Int).Exp(ka.yTheirs, xOurs, ka.p).Bytes()

	yOurs := new(big.Int).Exp(ka.g, xOurs, ka.p)
	yBytes := yOurs.Bytes()
	ckx := new(clientKeyExchangeMsg)
	ckx.ciphertext = make([]byte, 2+len(yBytes))
	ckx.ciphertext[0] = byte(len(yBytes) >> 8)
	ckx.ciphertext[1] = byte(len(yBytes))
	copy(ckx.ciphertext[2:], yBytes)

	return preMasterSecret, ckx, nil
}

func (ka *dheKeyAgreement) peerSignatureAlgorithm() signatureAlgorithm {
	if auth, ok := ka.auth.(*signedKeyAgreement); ok {
		return auth.peerSignatureAlgorithm
	}
	return 0
}

// nilKeyAgreement is a fake key agreement used to implement the plain PSK key
// exchange.
type nilKeyAgreement struct{}

func (ka *nilKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
	return nil, nil
}

func (ka *nilKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
	if len(ckx.ciphertext) != 0 {
		return nil, errClientKeyExchange
	}

	// Although in plain PSK, otherSecret is all zeros, the base key
	// agreement does not access to the length of the pre-shared
	// key. pskKeyAgreement instead interprets nil to mean to use all zeros
	// of the appropriate length.
	return nil, nil
}

func (ka *nilKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
	if len(skx.key) != 0 {
		return errServerKeyExchange
	}
	return nil
}

func (ka *nilKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
	// Although in plain PSK, otherSecret is all zeros, the base key
	// agreement does not access to the length of the pre-shared
	// key. pskKeyAgreement instead interprets nil to mean to use all zeros
	// of the appropriate length.
	return nil, &clientKeyExchangeMsg{}, nil
}

func (ka *nilKeyAgreement) peerSignatureAlgorithm() signatureAlgorithm {
	return 0
}

// makePSKPremaster formats a PSK pre-master secret based on otherSecret from
// the base key exchange and psk.
func makePSKPremaster(otherSecret, psk []byte) []byte {
	out := make([]byte, 0, 2+len(otherSecret)+2+len(psk))
	out = append(out, byte(len(otherSecret)>>8), byte(len(otherSecret)))
	out = append(out, otherSecret...)
	out = append(out, byte(len(psk)>>8), byte(len(psk)))
	out = append(out, psk...)
	return out
}

// pskKeyAgreement implements the PSK key agreement.
type pskKeyAgreement struct {
	base         keyAgreement
	identityHint string
}

func (ka *pskKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
	// Assemble the identity hint.
	bytes := make([]byte, 2+len(config.PreSharedKeyIdentity))
	bytes[0] = byte(len(config.PreSharedKeyIdentity) >> 8)
	bytes[1] = byte(len(config.PreSharedKeyIdentity))
	copy(bytes[2:], []byte(config.PreSharedKeyIdentity))

	// If there is one, append the base key agreement's
	// ServerKeyExchange.
	baseSkx, err := ka.base.generateServerKeyExchange(config, cert, clientHello, hello)
	if err != nil {
		return nil, err
	}

	if baseSkx != nil {
		bytes = append(bytes, baseSkx.key...)
	} else if config.PreSharedKeyIdentity == "" && !config.Bugs.AlwaysSendPreSharedKeyIdentityHint {
		// ServerKeyExchange is optional if the identity hint is empty
		// and there would otherwise be no ServerKeyExchange.
		return nil, nil
	}

	skx := new(serverKeyExchangeMsg)
	skx.key = bytes
	return skx, nil
}

func (ka *pskKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
	// First, process the PSK identity.
	if len(ckx.ciphertext) < 2 {
		return nil, errClientKeyExchange
	}
	identityLen := (int(ckx.ciphertext[0]) << 8) | int(ckx.ciphertext[1])
	if 2+identityLen > len(ckx.ciphertext) {
		return nil, errClientKeyExchange
	}
	identity := string(ckx.ciphertext[2 : 2+identityLen])

	if identity != config.PreSharedKeyIdentity {
		return nil, errors.New("tls: unexpected identity")
	}

	if config.PreSharedKey == nil {
		return nil, errors.New("tls: pre-shared key not configured")
	}

	// Process the remainder of the ClientKeyExchange to compute the base
	// pre-master secret.
	newCkx := new(clientKeyExchangeMsg)
	newCkx.ciphertext = ckx.ciphertext[2+identityLen:]
	otherSecret, err := ka.base.processClientKeyExchange(config, cert, newCkx, version)
	if err != nil {
		return nil, err
	}

	if otherSecret == nil {
		// Special-case for the plain PSK key exchanges.
		otherSecret = make([]byte, len(config.PreSharedKey))
	}
	return makePSKPremaster(otherSecret, config.PreSharedKey), nil
}

func (ka *pskKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
	if len(skx.key) < 2 {
		return errServerKeyExchange
	}
	identityLen := (int(skx.key[0]) << 8) | int(skx.key[1])
	if 2+identityLen > len(skx.key) {
		return errServerKeyExchange
	}
	ka.identityHint = string(skx.key[2 : 2+identityLen])

	// Process the remainder of the ServerKeyExchange.
	newSkx := new(serverKeyExchangeMsg)
	newSkx.key = skx.key[2+identityLen:]
	return ka.base.processServerKeyExchange(config, clientHello, serverHello, cert, newSkx)
}

func (ka *pskKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
	// The server only sends an identity hint but, for purposes of
	// test code, the server always sends the hint and it is
	// required to match.
	if ka.identityHint != config.PreSharedKeyIdentity {
		return nil, nil, errors.New("tls: unexpected identity")
	}

	// Serialize the identity.
	bytes := make([]byte, 2+len(config.PreSharedKeyIdentity))
	bytes[0] = byte(len(config.PreSharedKeyIdentity) >> 8)
	bytes[1] = byte(len(config.PreSharedKeyIdentity))
	copy(bytes[2:], []byte(config.PreSharedKeyIdentity))

	// Append the base key exchange's ClientKeyExchange.
	otherSecret, baseCkx, err := ka.base.generateClientKeyExchange(config, clientHello, cert)
	if err != nil {
		return nil, nil, err
	}
	ckx := new(clientKeyExchangeMsg)
	ckx.ciphertext = append(bytes, baseCkx.ciphertext...)

	if config.PreSharedKey == nil {
		return nil, nil, errors.New("tls: pre-shared key not configured")
	}
	if otherSecret == nil {
		otherSecret = make([]byte, len(config.PreSharedKey))
	}
	return makePSKPremaster(otherSecret, config.PreSharedKey), ckx, nil
}

func (ka *pskKeyAgreement) peerSignatureAlgorithm() signatureAlgorithm {
	return 0
}


text:
var child_process = require('child_process');

exports.teardown = function (cb) {
  child_process.exec('make clean', cb);
};

redpajama_set_name: RedPajamaGithub


text:
{% extends "base.html" %}
{% load static %}
{% load crispy_forms_tags %}
{% block content %}

Event Listing

<form method="post">
{% csrf_token %}
{{form|crispy}}
<button class="btn btn-primary" type="submit">Submit</button>
</form>
{% endblock %}


text:
<!DOCTYPE html>
<html>

<!-- Head: Containing all the meta data and import needed -->
<head >
    <meta charset="UTF-8">
    <title>fileupload</title>
</head>

<!-- Body: Containing all HTML of the page -->
<body>
<form method="post" enctype="multipart/form-data" action="/space?fileadd=101.200.167.44">
    <input type="file" name="file">
   <input type="submit" value="Upload">
  </form>
</body>
</html>


text:
var common = require('../common.js');
var crypto = require('crypto');

var bench = common.createBenchmark(main, {
  writes: [500],
  algo: ['sha1', 'sha256', 'sha512'],
  type: ['asc', 'utf', 'buf'],
  len: [2, 1024, 102400, 1024 * 1024],
  api: ['legacy', 'stream']
});

function main(conf) {
  var api = conf.api;
  if (api === 'stream' && process.version.match(/^v0\.[0-8]\./)) {
    console.error('Crypto streams not available until v0.10');
    // use the legacy, just so that we can compare them.
    api = 'legacy';
  }

  var crypto = require('crypto');
  var assert = require('assert');

  var message;
  var encoding;
  switch (conf.type) {
    case 'asc':
      message = new Array(conf.len + 1).join('a');
      encoding = 'ascii';
      break;
    case 'utf':
      message = new Array(conf.len / 2 + 1).join('ü');
      encoding = 'utf8';
      break;
    case 'buf':
      message = new Buffer(conf.len);
      message.fill('b');
      break;
    default:
      throw new Error('unknown message type: ' + conf.type);
  }

  var fn = api === 'stream' ? streamWrite : legacyWrite;

  bench.start();
  fn(conf.algo, message, encoding, conf.writes, conf.len);
}

function legacyWrite(algo, message, encoding, writes, len) {
  var written = writes * len;
  var bits = written * 8;
  var gbits = bits / (1024 * 1024 * 1024);
  var h = crypto.createHash(algo);

  while (writes-- > 0)
    h.update(message, encoding);

  h.digest();

  bench.end(gbits);
}

function streamWrite(algo, message, encoding, writes, len) {
  var written = writes * len;
  var bits = written * 8;
  var gbits = bits / (1024 * 1024 * 1024);
  var h = crypto.createHash(algo);

  while (writes-- > 0)
    h.write(message, encoding);

  h.end();
  h.read();

  bench.end(gbits);
}


text:
package unl.cse.queue;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class PCDemo {

	public static void main(String args[]) {
		BlockingQueue<String> q = new LinkedBlockingQueue<String>();
		Producer p1 = new Producer(q, "mlb");
		Consumer c1 = new Consumer(q, "consumer 01");
		Consumer c2 = new Consumer(q, "consumer 02");
		Consumer c3 = new Consumer(q, "consumer 03");
		new Thread(p1).start();
		new Thread(c1).start();
		new Thread(c2).start();
		new Thread(c3).start();
	}
}


text:
package org.apache.struts.config.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.config.ActionConfig;
import org.apache.struts.config.ActionConfigMatcher;
import org.apache.struts.config.BaseConfig;
import org.apache.struts.config.ControllerConfig;
import org.apache.struts.config.ExceptionConfig;
import org.apache.struts.config.FormBeanConfig;
import org.apache.struts.config.ForwardConfig;
import org.apache.struts.config.MessageResourcesConfig;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.config.PlugInConfig;

import java.io.Serializable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 *
The collection of static configuration information that describes a
 * Struts-based module.  Multiple modules are identified by a prefix
 * at the beginning of the context relative portion of the request URI.  If no
 * module prefix can be matched, the default configuration (with a prefix
 * equal to a zero-length string) is selected, which is elegantly backwards
 * compatible with the previous Struts behavior that only supported one
 * module.

 *
 * @version $Rev: 471754 $ $Date: 2005-12-31 03:57:16 -0500 (Sat, 31 Dec 2005)
 *          $
 * @since Struts 1.1
 */
public class ModuleConfigImpl extends BaseConfig implements Serializable,
    ModuleConfig {
    /**
     *
Commons Logging instance.

     */
    protected static Log log = LogFactory.getLog(ModuleConfigImpl.class);

    // ----------------------------------------------------- Instance Variables
    // Instance Variables at end to make comparing Interface and implementation easier.

    /**
     *
The set of action configurations for this module, if any, keyed by
     * the path property.

     */
    protected HashMap actionConfigs = null;

    /**
     *
The set of action configuration for this module, if any, keyed by
     * the actionId property.

     */
    protected HashMap actionConfigIds = null;

    /**
     *
The set of action configurations for this module, if any, listed in
     * the order in which they are added.

     */
    protected List actionConfigList = null;

    /**
     *
The set of exception handling configurations for this module, if
     * any, keyed by the type property.

     */
    protected HashMap exceptions = null;

    /**
     *
The set of form bean configurations for this module, if any, keyed
     * by the name property.

     */
    protected HashMap formBeans = null;

    /**
     *
The set of global forward configurations for this module, if any,
     * keyed by the name property.

     */
    protected HashMap forwards = null;

    /**
     *
The set of message resources configurations for this module, if any,
     * keyed by the key property.

     */
    protected HashMap messageResources = null;

    /**
     *
The set of configured plug-in Actions for this module, if any, in
     * the order they were declared and configured.

     */
    protected ArrayList plugIns = null;

    /**
     *
The controller configuration object for this module.

     */
    protected ControllerConfig controllerConfig = null;

    /**
     *
The prefix of the context-relative portion of the request URI, used
     * to select this configuration versus others supported by the controller
     * servlet.  A configuration with a prefix of a zero-length String is the
     * default configuration for this web module.

     */
    protected String prefix = null;

    /**
     *
The default class name to be used when creating action form bean
     * instances.

     */
    protected String actionFormBeanClass =
        "org.apache.struts.action.ActionFormBean";

    /**
     * The default class name to be used when creating action mapping
     * instances.
     */
    protected String actionMappingClass =
        "org.apache.struts.action.ActionMapping";

    /**
     * The default class name to be used when creating action forward
     * instances.
     */
    protected String actionForwardClass =
        "org.apache.struts.action.ActionForward";

    /**
     *
Matches action config paths against compiled wildcard patterns

     */
    protected ActionConfigMatcher matcher = null;

    /**
     *
Constructor for ModuleConfigImpl.  Assumes default
     * configuration.

     *
     * @since Struts 1.2.8
     */
    public ModuleConfigImpl() {
        this("");
    }

    /**
     *
Construct an ModuleConfigImpl object according to the specified
     * parameter values.

     *
     * @param prefix Context-relative URI prefix for this module
     */
    public ModuleConfigImpl(String prefix) {
        super();
        this.prefix = prefix;
        this.actionConfigs = new HashMap();
        this.actionConfigIds = new HashMap();
        this.actionConfigList = new ArrayList();
        this.actionFormBeanClass = "org.apache.struts.action.ActionFormBean";
        this.actionMappingClass = "org.apache.struts.action.ActionMapping";
        this.actionForwardClass = "org.apache.struts.action.ActionForward";
        this.configured = false;
        this.controllerConfig = null;
        this.exceptions = new HashMap();
        this.formBeans = new HashMap();
        this.forwards = new HashMap();
        this.messageResources = new HashMap();
        this.plugIns = new ArrayList();
    }

    // --------------------------------------------------------- Public Methods

    /**
     *
 Has this module been completely configured yet.  Once this flag
     * has been set, any attempt to modify the configuration will return an
     * IllegalStateException.

     */
    public boolean getConfigured() {
        return (this.configured);
    }

    /**
     *
The controller configuration object for this module.

     */
    public ControllerConfig getControllerConfig() {
        if (this.controllerConfig == null) {
            this.controllerConfig = new ControllerConfig();
        }

        return (this.controllerConfig);
    }

    /**
     *
The controller configuration object for this module.

     *
     * @param cc The controller configuration object for this module.
     */
    public void setControllerConfig(ControllerConfig cc) {
        throwIfConfigured();
        this.controllerConfig = cc;
    }

    /**
     *
The prefix of the context-relative portion of the request URI, used
     * to select this configuration versus others supported by the controller
     * servlet.  A configuration with a prefix of a zero-length String is the
     * default configuration for this web module.

     */
    public String getPrefix() {
        return (this.prefix);
    }

    /**
     *
The prefix of the context-relative portion of the request URI, used
     * to select this configuration versus others supported by the controller
     * servlet.  A configuration with a prefix of a zero-length String is the
     * default configuration for this web module.

     */
    public void setPrefix(String prefix) {
        throwIfConfigured();
        this.prefix = prefix;
    }

    /**
     *
The default class name to be used when creating action form bean
     * instances.

     */
    public String getActionFormBeanClass() {
        return this.actionFormBeanClass;
    }

    /**
     *
The default class name to be used when creating action form bean
     * instances.

     *
     * @param actionFormBeanClass default class name to be used when creating
     *                            action form bean instances.
     */
    public void setActionFormBeanClass(String actionFormBeanClass) {
        this.actionFormBeanClass = actionFormBeanClass;
    }

    /**
     *
The default class name to be used when creating action mapping
     * instances.

     */
    public String getActionMappingClass() {
        return this.actionMappingClass;
    }

    /**
     *
 The default class name to be used when creating action mapping
     * instances.

     *
     * @param actionMappingClass default class name to be used when creating
     *                           action mapping instances.
     */
    public void setActionMappingClass(String actionMappingClass) {
        this.actionMappingClass = actionMappingClass;
    }

    /**
     *
 Ad   d a new ActionConfig instance to the set
     * associated with this module.

     *
     * @param config The new configuration instance to be added
     * @throws IllegalStateException if this module configuration has been
     *                               frozen
     */
    public void addActionConfig(ActionConfig config) {
        throwIfConfigured();
        config.setModuleConfig(this);

        String path = config.getPath();
        if (actionConfigs.containsKey(path)) {
            log.warn("Overriding ActionConfig of path " + path);
        }

        String actionId = config.getActionId();
        if ((actionId != null) && !actionId.equals("")) {
            if (actionConfigIds.containsKey(actionId)) {
                if (log.isWarnEnabled()) {
                    ActionConfig otherConfig = (ActionConfig) actionConfigIds.get(actionId);
                    StringBuffer msg = new StringBuffer("Overriding actionId[");
                    msg.append(actionId);
                    msg.append("] for path[");
                    msg.append(otherConfig.getPath());
                    msg.append("] with path[");
                    msg.append(path);
                    msg.append("]");
                    log.warn(msg);
                }
            }
            actionConfigIds.put(actionId, config);
        }

        actionConfigs.put(path, config);
        actionConfigList.add(config);
    }

    /**
     *
 Add a new ExceptionConfig instance to the set
     * associated with this module.

     *
     * @param config The new configuration instance to be added
     * @throws IllegalStateException if this module configuration has been
     *                               frozen
     */
    public void addExceptionConfig(ExceptionConfig config) {
        throwIfConfigured();

        String key = config.getType();

        if (exceptions.containsKey(key)) {
            log.warn("Overriding ExceptionConfig of type " + key);
        }

        exceptions.put(key, config);
    }

    /**
     *
 Add a new FormBeanConfig instance to the set
     * associated with this module.

     *
     * @param config The new configuration instance to be added
     * @throws IllegalStateException if this module configuration has been
     *                               frozen
     */
    public void addFormBeanConfig(FormBeanConfig config) {
        throwIfConfigured();

        String key = config.getName();

        if (formBeans.containsKey(key)) {
            log.warn("Overriding ActionForm of name " + key);
        }

        formBeans.put(key, config);
    }

    /**
     *
 The default class name to be used when creating action forward
     * instances.

     */
    public String getActionForwardClass() {
        return this.actionForwardClass;
    }

    /**
     *
 The default class name to be used when creating action forward
     * instances.

     *
     * @param actionForwardClass default class name to be used when creating
     *                           action forward instances.
     */
    public void setActionForwardClass(String actionForwardClass) {
        this.actionForwardClass = actionForwardClass;
    }

    /**
     *
 Add a new ForwardConfig instance to the set of global
     * forwards associated with this module.

     *
     * @param config The new configuration instance to be added
     * @throws IllegalStateException if this module configuration has been
     *                               frozen
     */
    public void addForwardConfig(ForwardConfig config) {
        throwIfConfigured();

        String key = config.getName();

        if (forwards.containsKey(key)) {
            log.warn("Overriding global ActionForward of name " + key);
        }

        forwards.put(key, config);
    }

    /**
     *
 Add a new MessageResourcesConfig instance to the set
     * associated with this module.

     *
     * @param config The new configuration instance to be added
     * @throws IllegalStateException if this module configuration has been
     *                               frozen
     */
    public void addMessageResourcesConfig(MessageResourcesConfig config) {
        throwIfConfigured();

        String key = config.getKey();

        if (messageResources.containsKey(key)) {
            log.warn("Overriding MessageResources bundle of key " + key);
        }

        messageResources.put(key, config);
    }

    /**
     *
 Add a newly configured {@link org.apache.struts.config.PlugInConfig}
     * instance to the set of plug-in Actions for this module.

     *
     * @param plugInConfig The new configuration instance to be added
     */
    public void addPlugInConfig(PlugInConfig plugInConfig) {
        throwIfConfigured();
        plugIns.add(plugInConfig);
    }

    /**
     *
 Return the action configuration for the specified path, first
     * looking a direct match, then if none found, a wildcard pattern match;
     * otherwise return null.

     *
     * @param path Path of the action configuration to return
     */
    public ActionConfig findActionConfig(String path) {
        ActionConfig config = (ActionConfig) actionConfigs.get(path);

        // If a direct match cannot be found, try to match action configs
        // containing wildcard patterns only if a matcher exists.
        if ((config == null) && (matcher != null)) {
            config = matcher.match(path);
        }

        return config;
    }

    /**
     *
Returns the action configuration for the specifed action
     * action identifier.

     *
     * @param actionId the action identifier
     * @return the action config if found; otherwise null
     * @see ActionConfig#getActionId()
     * @since Struts 1.3.6
     */
    public ActionConfig findActionConfigId(String actionId) {
        if (actionId != null) {
            return (ActionConfig) this.actionConfigIds.get(actionId);
        }
        return null;
    }

    /**
     *
 Return the action configurations for this module.  If there are
     * none, a zero-length array is returned.

     */
    public ActionConfig[] findActionConfigs() {
        ActionConfig[] results = new ActionConfig[actionConfigList.size()];

        return ((ActionConfig[]) actionConfigList.toArray(results));
    }

    /**
     *
 Return the exception configuration for the specified type, if any;
     * otherwise return null.

     *
     * @param type Exception class name to find a configuration for
     */
    public ExceptionConfig findExceptionConfig(String type) {
        return ((ExceptionConfig) exceptions.get(type));
    }

    /**
     *
Find and return the ExceptionConfig instance defining
     * how Exceptions of the specified type should be handled.
     *
     *
In original Struts usage, this was only available in
     * ActionConfig, but there are cases when an exception could
     * be thrown before an ActionConfig has been identified,
     * where global exception handlers may still be pertinent.

     *
     *
TODO: Look for a way to share this logic with
     * ActionConfig, although there are subtle differences, and
     * it certainly doesn't seem like it should be done with inheritance.

     *
     * @param type Exception class for which to find a handler
     * @since Struts 1.3.0
     */
    public ExceptionConfig findException(Class type) {
        // Check through the entire superclass hierarchy as needed
        ExceptionConfig config = null;

        while (true) {
            // Check for a locally defined handler
            String name = type.getName();

            log.debug("findException: look locally for " + name);
            config = findExceptionConfig(name);

            if (config != null) {
                return (config);
            }

            // Loop again for our superclass (if any)
            type = type.getSuperclass();

            if (type == null) {
                break;
            }
        }

        return (null); // No handler has been configured
    }

    /**
     *
 Return the exception configurations for this module.  If there are
     * none, a zero-length array is returned.

     */
    public ExceptionConfig[] findExceptionConfigs() {
        ExceptionConfig[] results = new ExceptionConfig[exceptions.size()];

        return ((ExceptionConfig[]) exceptions.values().toArray(results));
    }

    /**
     *
 Return the form bean configuration for the specified key, if any;
     * otherwise return null.

     *
     * @param name Name of the form bean configuration to return
     */
    public FormBeanConfig findFormBeanConfig(String name) {
        return ((FormBeanConfig) formBeans.get(name));
    }

    /**
     *
 Return the form bean configurations for this module.  If there are
     * none, a zero-length array is returned.

     */
    public FormBeanConfig[] findFormBeanConfigs() {
        FormBeanConfig[] results = new FormBeanConfig[formBeans.size()];

        return ((FormBeanConfig[]) formBeans.values().toArray(results));
    }

    /**
     *
 Return the forward configuration for the specified key, if any;
     * otherwise return null.

     *
     * @param name Name of the forward configuration to return
     */
    public ForwardConfig findForwardConfig(String name) {
        return ((ForwardConfig) forwards.get(name));
    }

    /**
     *
 Return the form bean configurations for this module.  If there are
     * none, a zero-length array is returned.

     */
    public ForwardConfig[] findForwardConfigs() {
        ForwardConfig[] results = new ForwardConfig[forwards.size()];

        return ((ForwardConfig[]) forwards.values().toArray(results));
    }

    /**
     *
 Return the message resources configuration for the specified key,
     * if any; otherwise return null.

     *
     * @param key Key of the data source configuration to return
     */
    public MessageResourcesConfig findMessageResourcesConfig(String key) {
        return ((MessageResourcesConfig) messageResources.get(key));
    }

    /**
     *
 Return the message resources configurations for this module. If
     * there are none, a zero-length array is returned.

     */
    public MessageResourcesConfig[] findMessageResourcesConfigs() {
        MessageResourcesConfig[] results =
            new MessageResourcesConfig[messageResources.size()];

        return ((MessageResourcesConfig[]) messageResources.values().toArray(results));
    }

    /**
     *
 Return the configured plug-in actions for this module.  If there
     * are none, a zero-length array is returned.

     */
    public PlugInConfig[] findPlugInConfigs() {
        PlugInConfig[] results = new PlugInConfig[plugIns.size()];

        return ((PlugInConfig[]) plugIns.toArray(results));
    }

    /**
     *
 Freeze the configuration of this module.  After this method
     * returns, any attempt to modify the configuration will return an
     * IllegalStateException.

     */
    public void freeze() {
        super.freeze();

        ActionConfig[] aconfigs = findActionConfigs();

        for (int i = 0; i < aconfigs.length; i++) {
            aconfigs[i].freeze();
        }

        matcher = new ActionConfigMatcher(aconfigs);

        getControllerConfig().freeze();

        ExceptionConfig[] econfigs = findExceptionConfigs();

        for (int i = 0; i < econfigs.length; i++) {
            econfigs[i].freeze();
        }

        FormBeanConfig[] fbconfigs = findFormBeanConfigs();

        for (int i = 0; i < fbconfigs.length; i++) {
            fbconfigs[i].freeze();
        }

        ForwardConfig[] fconfigs = findForwardConfigs();

        for (int i = 0; i < fconfigs.length; i++) {
            fconfigs[i].freeze();
        }

        MessageResourcesConfig[] mrconfigs = findMessageResourcesConfigs();

        for (int i = 0; i < mrconfigs.length; i++) {
            mrconfigs[i].freeze();
        }

        PlugInConfig[] piconfigs = findPlugInConfigs();

        for (int i = 0; i < piconfigs.length; i++) {
            piconfigs[i].freeze();
        }
    }

    /**
     *
 Remove the specified action configuration instance.

     *
     * @param config ActionConfig instance to be removed
     * @throws IllegalStateException if this module configuration has been
     *                               frozen
     */
    public void removeActionConfig(ActionConfig config) {
        throwIfConfigured();
        config.setModuleConfig(null);
        actionConfigs.remove(config.getPath());
        actionConfigList.remove(config);
    }

    /**
     *
 Remove the specified exception configuration instance.

     *
     * @param config ActionConfig instance to be removed
     * @throws IllegalStateException if this module configuration has been
     *                               frozen
     */
    public void removeExceptionConfig(ExceptionConfig config) {
        throwIfConfigured();
        exceptions.remove(config.getType());
    }

    /**
     *
 Remove the specified form bean configuration instance.

     *
     * @param config FormBeanConfig instance to be removed
     * @throws IllegalStateException if this module configuration has been
     *                               frozen
     */
    public void removeFormBeanConfig(FormBeanConfig config) {
        throwIfConfigured();
        formBeans.remove(config.getName());
    }

    /**
     *
 Remove the specified forward configuration instance.

     *
     * @param config ForwardConfig instance to be removed
     * @throws IllegalStateException if this module configuration has been
     *                               frozen
     */
    public void removeForwardConfig(ForwardConfig config) {
        throwIfConfigured();
        forwards.remove(config.getName());
    }

    /**
     *
 Remove the specified message resources configuration instance.
     *

     *
     * @param config MessageResourcesConfig instance to be removed
     * @throws IllegalStateException if this module configuration has been
     *                               frozen
     */
    public void removeMessageResourcesConfig(MessageResourcesConfig config) {
        throwIfConfigured();
        messageResources.remove(config.getKey());
    }
}


text:
<!-- Enter a short description here -->

## Steps to reproduce
<!-- List the steps to reproduce the issue -->

## Versions
<!-- List the version numbers -->

1. Browser: <!-- for example Chrome 65 -->
2. luminave: x.x.x


text:
package service

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestValidateSingleGenericResource(t *testing.T) {
	incorrect := []string{"foo", "fooo-bar"}
	correct := []string{"foo=bar", "bar=1", "foo=barbar"}

	for _, v := range incorrect {
		_, err := ValidateSingleGenericResource(v)
		assert.Error(t, err)
	}

	for _, v := range correct {
		_, err := ValidateSingleGenericResource(v)
		assert.NoError(t, err)
	}
}


text:
CKEDITOR.plugins.setLang( 'preview', 'sv', {
	preview: 'Förhandsgranska'
});


text:
<?php

namespace Google\Service\DisplayVideo;

class CreateAssetRequest extends \Google\Model
{
  /**
   * @var string
   */
  public $filename;

  /**
   * @param string
   */
  public function setFilename($filename)
  {
    $this->filename = $filename;
  }
  /**
   * @return string
   */
  public function getFilename()
  {
    return $this->filename;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(CreateAssetRequest::class, 'Google_Service_DisplayVideo_CreateAssetRequest');


text:
package com.frameworkset.orm.engine.transform;

/*

 *
 * 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.
 */

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.frameworkset.orm.engine.model.Column;
import com.frameworkset.orm.engine.model.Database;
import com.frameworkset.orm.engine.model.ForeignKey;
import com.frameworkset.orm.engine.model.IDMethod;
import com.frameworkset.orm.engine.model.Table;
import com.frameworkset.orm.sql.ParseException;
import com.frameworkset.orm.sql.SQLScanner;
import com.frameworkset.orm.sql.Token;

/**
 * A Class that converts an sql input file to a Database structure.
 * The class makes use of SQL Scanner to get
 * sql tokens and the parses these to create the Database
 * class. SQLToAppData is in effect a simplified sql parser.
 *
 * @author Leon Messerschmidt
 * @author Jon S. Stevens
 * @version $Id: SQLToAppData.java,v 1.7 2004/02/22 06:27:19 jmcnally Exp $
 */
public class SQLToAppData implements Serializable
{
    private String sqlFile;
    private List tokens;
    private Token token;
    private Database appDataDB;
    private int count;
    private String databaseType;

    /**
     * Create a new class with an input Reader
     *
     * @param sqlFile the sql file
     */
    public SQLToAppData(String sqlFile)
    {
        this.sqlFile = sqlFile;
    }

    /**
     * Create a new class with an input Reader.  This ctor is not used
     * but putting here in the event db.props properties are found to
     * be useful converting sql to xml, the infrastructure will exist
     *
     * @param sqlFile the sql file
     * @param databaseType
     */
    public SQLToAppData(String sqlFile, String databaseType)
    {
        this.sqlFile = sqlFile;
        this.databaseType = databaseType;
    }

    /**
     * Get the current input sql file
     *
     * @return the sql file
     */
    public String getSqlFile()
    {
        return sqlFile;
    }

    /**
     * Set the current input sql file
     *
     * @param sqlFile the sql file
     */
    public void setSqlFile(String sqlFile)
    {
        this.sqlFile = sqlFile;
    }

    /**
     * Move to the next token.
     *
     * @throws ParseException if there is no more tokens available.
     */
    private void next() throws ParseException
    {
        if (count < tokens.size())
        {
            token = (Token) tokens.get(count++);
        }
        else
        {
            throw new ParseException("No More Tokens");
        }
    }

    /**
     * Creates an error condition and adds the line and
     * column number of the current token to the error
     * message.
     *
     * @param name name of the error
     * @throws ParseException
     */
    private void err(String name) throws ParseException
    {
        throw new ParseException (name + " at [ line: " + token.getLine()
                + " col: " + token.getCol() + " ]");
    }

    /**
     * Check if there is more tokens available for parsing.
     *
     * @return true if there are more tokens available
     */
    private boolean hasTokens()
    {
        return count < tokens.size();
    }

    /**
     * Parses a CREATE TABLE FOO command.
     *
     * @throws ParseException
     */
    private void create() throws ParseException
    {
        next();
        if (token.getStr().toUpperCase().equals("TABLE"))
        {
            create_Table();
        }
    }

    /**
     * Parses a CREATE TABLE sql command
     *
     * @throws ParseException error parsing the input file
     */
    private void create_Table() throws ParseException
    {
        next();
        String tableName = token.getStr(); // name of the table
        next();
        if (!token.getStr().equals("("))
        {
            err("( expected");
        }
        next();

        Table tbl = new Table (tableName);
        //tbl.setIdMethod("none");
        while (!token.getStr().equals(";"))
        {
            create_Table_Column(tbl);
        }

        if (tbl.getPrimaryKey().size() == 1)
        {
            tbl.setIdMethod(IDMethod.ID_BROKER);
        }
        else
        {
            tbl.setIdMethod(IDMethod.NO_ID_METHOD);
        }
        appDataDB.addTable (tbl);
    }

    /**
     * Parses column information between the braces of a CREATE
     * TABLE () sql statement.
     *
     * @throws ParseException error parsing the input file
     */
    private void create_Table_Column(Table tbl) throws ParseException
    {
        // The token should be the first item
        // which is the name of the column or
        // PRIMARY/FOREIGN/UNIQUE
        if (token.getStr().equals(","))
        {
            next();
        }

        if (token.getStr().toUpperCase().equals("PRIMARY"))
        {
            create_Table_Column_Primary(tbl);
        }
        else if (token.getStr().toUpperCase().equals("FOREIGN"))
        {
            create_Table_Column_Foreign(tbl);
        }
        else if (token.getStr().toUpperCase().equals("UNIQUE"))
        {
            create_Table_Column_Unique(tbl);
        }
        else
        {
            create_Table_Column_Data(tbl);
        }
    }

    /**
     * Parses PRIMARY KEY (FOO,BAR) statement
     *
     * @throws ParseException error parsing the input file
     */
    private void create_Table_Column_Primary (Table tbl) throws ParseException
    {
        next();
        if (!token.getStr().toUpperCase().equals("KEY"))
        {
            err("KEY expected");
        }
        next();
        if (!token.getStr().toUpperCase().equals("("))
        {
            err("( expected");
        }
        next();

        String colName = token.getStr();
        Column c = tbl.getColumn(colName);
        if (c == null)
        {
            err("Invalid column name: " + colName);
        }
        c.setPrimaryKey(true);
        next();
        while (token.getStr().equals(","))
        {
            next();
            colName = token.getStr();
            c = tbl.getColumn(colName);
            if (c == null)
            {
                err("Invalid column name: " + colName);
            }
            c.setPrimaryKey(true);
            next();
        }

        if (!token.getStr().toUpperCase().equals(")"))
        {
            err(") expected");
        }
        next(); // skip the )
    }

    /**
     * Parses UNIQUE (NAME,FOO,BAR) statement
     *
     * @throws ParseException error parsing the input file
     */
    private void create_Table_Column_Unique(Table tbl) throws ParseException
    {
        next();
        if (!token.getStr().toUpperCase().equals("("))
        {
            err("( expected");
        }
        next();
        while (!token.getStr().equals(")"))
        {
            if (!token.getStr().equals(","))
            {
                String colName = token.getStr();
                Column c = tbl.getColumn(colName);
                if (c == null)
                {
                    err("Invalid column name: " + colName);
                }
                c.setUnique(true);
            }
            next();
        }
        if (!token.getStr().toUpperCase().equals(")"))
        {
            err(") expected got: " + token.getStr());
        }

        next(); // skip the )
    }

    /**
     * Parses FOREIGN KEY (BAR) REFERENCES TABLE (BAR) statement
     *
     * @throws ParseException error parsing the input file
     */
    private void create_Table_Column_Foreign(Table tbl) throws ParseException
    {
        next();
        if (!token.getStr().toUpperCase().equals("KEY"))
        {
            err("KEY expected");
        }
        next();
        if (!token.getStr().toUpperCase().equals("("))
        {
            err("( expected");
        }
        next();

        ForeignKey fk = new ForeignKey();
        List localColumns = new ArrayList();
        tbl.addForeignKey(fk);

        String colName = token.getStr();
        localColumns.add(colName);
        next();
        while (token.getStr().equals(","))
        {
            next();
            colName = token.getStr();
            localColumns.add(colName);
            next();
        }
        if (!token.getStr().toUpperCase().equals(")"))
        {
            err(") expected");
        }

        next();

        if (!token.getStr().toUpperCase().equals("REFERENCES"))
        {
            err("REFERENCES expected");
        }

        next();

        fk.setForeignTableName(token.getStr());

        next();

        if (token.getStr().toUpperCase().equals("("))
        {
            next();
            int i = 0;
            fk.addReference((String) localColumns.get(i++), token.getStr());
            next();
            while (token.getStr().equals(","))
            {
                next();
                fk.addReference((String) localColumns.get(i++), token.getStr());
                next();
            }
            if (!token.getStr().toUpperCase().equals(")"))
            {
                err(") expected");
            }
            next();
        }
    }

    /**
     * Parse the data definition of the column statement.
     *
     * @throws ParseException error parsing the input file
     */
    private void create_Table_Column_Data(Table tbl) throws ParseException
    {
        String columnSize = null;
        String columnPrecision = null;
        String columnDefault = null;
        boolean inEnum = false;

        String columnName = token.getStr();
        next();
        String columnType = token.getStr();

        if (columnName.equals(")") && columnType.equals(";"))
        {
            return;
        }

        next();

        // special case for MySQL ENUM's which are stupid anyway
        // and not properly handled by Torque.
        if (columnType.toUpperCase().equals("ENUM"))
        {
            inEnum = true;
            next(); // skip (
            while (!token.getStr().equals(")"))
            {
                // skip until )
                next();
            }
            while (!token.getStr().equals(","))
            {
                if (token.getStr().toUpperCase().equals("DEFAULT"))
                {
                    next();
                    if (token.getStr().equals("'"))
                    {
                        next();
                    }
                    columnDefault = token.getStr();
                    next();
                    if (token.getStr().equals("'"))
                    {
                        next();
                    }
                }
                // skip until ,
                next();
            }
            next(); // skip ,
            columnType = "VARCHAR";
        }
        else if (token.getStr().toUpperCase().equals("("))
        {
            next();
            columnSize = token.getStr();
            next();
            if (token.getStr().equals(","))
            {
                next();
                columnPrecision = token.getStr();
                next();
            }

            if (!token.getStr().equals(")"))
            {
                err(") expected");
            }
            next();
        }

        Column col = new Column(columnName);
        if (columnPrecision != null)
        {
            columnSize = columnSize + columnPrecision;
        }
        col.setTypeFromString(columnType, columnSize);
        tbl.addColumn(col);

        if (inEnum)
        {
            col.setNotNull(true);
            if (columnDefault != null)
            {
                col.setDefaultValue(columnDefault);
            }
        }
        else
        {
            while (!token.getStr().equals(",") && !token.getStr().equals(")"))
            {
                if (token.getStr().toUpperCase().equals("NOT"))
                {
                    next();
                    if (!token.getStr().toUpperCase().equals("NULL"))
                    {
                        err("NULL expected after NOT");
                    }
                    col.setNotNull(true);
                    next();
                }
                else if (token.getStr().toUpperCase().equals("PRIMARY"))
                {
                    next();
                    if (!token.getStr().toUpperCase().equals("KEY"))
                    {
                        err("KEY expected after PRIMARY");
                    }
                    col.setPrimaryKey(true);
                    next();
                }
                else if (token.getStr().toUpperCase().equals("UNIQUE"))
                {
                    col.setUnique(true);
                    next();
                }
                else if (token.getStr().toUpperCase().equals("NULL"))
                {
                    col.setNotNull(false);
                    next();
                }
                else if (token.getStr().toUpperCase().equals("AUTO_INCREMENT"))
                {
                    col.setAutoIncrement(true);
                    next();
                }
                else if (token.getStr().toUpperCase().equals("DEFAULT"))
                {
                    next();
                    if (token.getStr().equals("'"))
                    {
                        next();
                    }
                    col.setDefaultValue(token.getStr());
                    next();
                    if (token.getStr().equals("'"))
                    {
                        next();
                    }
                }
            }
            next(); // eat the ,
        }
    }

    /**
     * Execute the parser.
     *
     * @throws IOException If an I/O error occurs
     * @throws ParseException error parsing the input file
     */
    public Database execute() throws IOException, ParseException
    {
        count = 0;
        appDataDB = new Database(databaseType);

        FileReader fr = new FileReader(sqlFile);
        BufferedReader br = new BufferedReader(fr);
        SQLScanner scanner = new SQLScanner(br);

        tokens = scanner.scan();

        br.close();

        while (hasTokens())
        {
            if (token == null)
            {
                next();
            }

            if (token.getStr().toUpperCase().equals("CREATE"))
            {
                create();
            }
            if (hasTokens())
            {
                next();
            }
        }
        return appDataDB;
    }
}


text:
<?php
require_once 'functions.php';

$load_menu = 1;
$sub_page = 1;
$section = 6;
$page = 2;
$id = (int)$_GET['id'];

$info = $db->record("SELECT * FROM mfa_materials WHERE id = $id");

$list = $db->query("SELECT mfa_data.*, mfa_scales.name AS scalename, mfa_sources.name AS sourcename
FROM mfa_data
  LEFT JOIN mfa_scales ON mfa_data.scale = mfa_scales.id
  LEFT JOIN mfa_sources ON mfa_data.source_id = mfa_sources.id
WHERE mfa_data.material = $id
  ORDER BY mfa_data.year, mfa_data.scale");

if ($info->mfa_group) {
  $groupinfo = $db->record("SELECT * FROM mfa_groups WHERE id = {$info->mfa_group}");
  $project = $groupinfo->dataset;
  $projectinfo = $db->record("SELECT * FROM mfa_dataset WHERE id = $project");
}
require_once 'functions.omat.php';

if ($_GET['message'] ==  "delete-all") {
  $db->query("DELETE FROM mfa_data WHERE material = $id");
  header("Location: " . URL . "omat/data/$id/all-gone");
  exit();
}

if ($_GET['message'] == 'deleted') {
  $print = "Data point was deleted";
} elseif ($_GET['message'] == 'saved') {
  $print = "Information was saved";
} elseif ($_GET['message'] == "all-gone") {
  $print = "All data points have been deleted";
}

$notes = $db->record("SELECT COUNT(*) AS total FROM mfa_materials_notes WHERE material = $id");
?>
<!DOCTYPE html>

    <?php echo $header ?>
    <title><?php echo $info->name ?> | <?php echo SITENAME ?></title>

<?php require_once 'include.header.php'; ?>

  <a href="omat/material-comments/<?php echo $id ?>" class="btn btn-warning right">

  Comments
  <?php if ($notes->total) { ?> (<?php echo $notes->total ?>)<?php } ?>

<?php echo $info->name ?>

<a href="omat/<?php echo $project ?>/dashboard">Dashboard

<a href="omat/<?php echo $project ?>/manage">Data

<a href="omat/datagroup/<?php echo $groupinfo->id ?>"><?php echo $groupinfo->name ?>

<?php echo $info->name ?>

  <?php if ($print) { echo "
$print
"; } ?>

    A total of <?php echo count($list) ?> data <?php echo count($list) == 1 ? "point was" : "points were" ?> found.

  <?php if (count($list)) { ?>

        <?php if ($projectinfo->multiscale) { ?>
          Scale
        <?php } ?>
        Year
        Quantity
        Source
        Comments
        Actions

    <?php foreach ($list as $row) { ?>

        <?php if ($projectinfo->multiscale) { ?>
          <?php echo $row['scalename'] ?>
        <?php } ?>
        <?php echo $row['year'] ?>

          <?php echo number_format($row['data'],$projectinfo->decimal_precision) ?>
          <?php if ($row['multiplier'] != 1) { ?>
            x <?php echo $row['multiplier'] ?>
          <?php } ?>

        <?php if ($row['sourcename']) { ?>
          <a href="omat/<?php echo $project ?>/viewsource/<?php echo $row['source_id'] ?>"><?php echo $row['sourcename'] ?>
        <?php } elseif ($row['source_link']) { ?>
          <a href="<?php echo $row['source_link'] ?>"><?php echo $row['source'] ? $row['source'] : $row['source_link'] ?>
        <?php } else { ?>
          <?php echo $row['source'] ?>
        <?php } ?>

        <?php echo $row['comments'] ?>

          <a title="Edit" href="omat/data-edit/<?php echo $row['id'] ?>" class="btn btn-primary">
          <a title="Delete" href="omat/data-delete/<?php echo $row['id'] ?>" class="btn btn-danger" onclick="javascript:return confirm('Are you sure?')">

    <?php } ?>

  <?php } ?>

    <a href="omat/data-entry/<?php echo $id ?>" class="btn btn-success">Add single data point
    <a href="omat/multiple-data-entry/<?php echo $id ?>" class="btn btn-success">Add multiple points
    <a href="omat/data/<?php echo $id ?>/delete-all" class="btn pull-right btn-danger" onclick="javascript:return confirm('You are about to delete all these data points (<?php echo count($list) ?> in total). Are you sure?')">Delete all data points

<a href="omat/datagroup/<?php echo $info->mfa_group ?>" class="btn btn-primary">« Back to data group

<?php require_once 'include.footer.php'; ?>


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using LiteDB;

namespace Discord.Addons.SimplePermissions.LiteDbProvider
{
    /// <summary> </summary>
    /// <typeparam name="TChannel">The Channel configuration type.</typeparam>
    /// <typeparam name="TUser">The User configuration type.</typeparam>
    public class ConfigGuild<TChannel, TUser>
        where TChannel : ConfigChannel<TUser>
        where TUser : ConfigUser
    {
        /// <summary> </summary>
        [BsonId(true)]
        public int Id { get; set; }

        /// <summary> </summary>
        public ulong GuildId { get; set; }

        /// <summary> </summary>
        public ulong ModRole { get; set; }

        /// <summary> </summary>
        public ulong AdminRole { get; set; }

        /// <summary> </summary>
        public bool UseFancyHelp { get; set; }

        /// <summary> </summary>
        public bool HidePermCommands { get; set; }

        /// <summary> </summary>
        [BsonRef("channels")]
        public IList<TChannel> Channels { get; set; }

        /// <summary> </summary>
        [BsonRef("modules")]
        public IList<ConfigModule> WhiteListedModules { get; set; }
    }
}


text:
A method that unmounts the component. This can be used to simulate a component going through
an unmount/mount lifecycle.

#### Returns

`ReactWrapper`: Returns itself.

#### Example

```jsx
const willMount = sinon.spy();
const didMount = sinon.spy();
const willUnmount = sinon.spy();

class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.componentWillUnmount = willUnmount;
    this.componentWillMount = willMount;
    this.componentDidMount = didMount;
  }
  render() {
    return (
      <div className={this.props.id}>
        {this.props.id}
      </div>
    );
  }
}
const wrapper = mount(<Foo id="foo" />);
expect(willMount.callCount).to.equal(1);
expect(didMount.callCount).to.equal(1);
expect(willUnmount.callCount).to.equal(0);
wrapper.unmount();
expect(willMount.callCount).to.equal(1);
expect(didMount.callCount).to.equal(1);
expect(willUnmount.callCount).to.equal(1);
```

#### Related Methods

- [`.mount() => Self`](mount.md)


text:
using System;

namespace EasyApi.Metadata.Attributes
{
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
	public sealed class IgnoreAttribute : Attribute
	{
	}
}


text:
package org.apereo.cas.adaptors.authy.config.support.authentication;

import org.apereo.cas.authentication.DefaultChainingMultifactorAuthenticationBypassProvider;
import org.apereo.cas.authentication.bypass.AuthenticationMultifactorAuthenticationProviderBypass;
import org.apereo.cas.authentication.bypass.CredentialMultifactorAuthenticationProviderBypass;
import org.apereo.cas.authentication.bypass.GroovyMultifactorAuthenticationProviderBypass;
import org.apereo.cas.authentication.bypass.HttpRequestMultifactorAuthenticationProviderBypass;
import org.apereo.cas.authentication.bypass.MultifactorAuthenticationProviderBypass;
import org.apereo.cas.authentication.bypass.PrincipalMultifactorAuthenticationProviderBypass;
import org.apereo.cas.authentication.bypass.RegisteredServiceMultifactorAuthenticationProviderBypass;
import org.apereo.cas.authentication.bypass.RestMultifactorAuthenticationProviderBypass;
import org.apereo.cas.configuration.CasConfigurationProperties;

import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * This is {@link AuthyAuthenticationMultifactorProviderBypassConfiguration}.
 *
 * @author Misagh Moayyed
 * @since 6.1.0
 */
@Configuration("authyAuthenticationMultifactorProviderBypassConfiguration")
@EnableConfigurationProperties(CasConfigurationProperties.class)
public class AuthyAuthenticationMultifactorProviderBypassConfiguration {

    @Autowired
    private CasConfigurationProperties casProperties;

    @ConditionalOnMissingBean(name = "authyBypassEvaluator")
    @Bean
    @RefreshScope
    public MultifactorAuthenticationProviderBypass authyBypassEvaluator() {
        val bypass = new DefaultChainingMultifactorAuthenticationBypassProvider();
        val props = casProperties.getAuthn().getMfa().getAuthy().getBypass();

        if (StringUtils.isNotBlank(props.getPrincipalAttributeName())) {
            bypass.addMultifactorAuthenticationProviderBypass(authyPrincipalMultifactorAuthenticationProviderBypass());
        }
        bypass.addMultifactorAuthenticationProviderBypass(authyRegisteredServiceMultifactorAuthenticationProviderBypass());
        if (StringUtils.isNotBlank(props.getAuthenticationAttributeName())
            || StringUtils.isNotBlank(props.getAuthenticationHandlerName())
            || StringUtils.isNotBlank(props.getAuthenticationMethodName())) {
            bypass.addMultifactorAuthenticationProviderBypass(authyAuthenticationMultifactorAuthenticationProviderBypass());
        }

        if (StringUtils.isNotBlank(props.getCredentialClassType())) {
            bypass.addMultifactorAuthenticationProviderBypass(authyCredentialMultifactorAuthenticationProviderBypass());
        }
        if (StringUtils.isNotBlank(props.getHttpRequestHeaders()) || StringUtils.isNotBlank(props.getHttpRequestRemoteAddress())) {
            bypass.addMultifactorAuthenticationProviderBypass(authyHttpRequestMultifactorAuthenticationProviderBypass());
        }
        if (props.getGroovy().getLocation() != null) {
            bypass.addMultifactorAuthenticationProviderBypass(authyGroovyMultifactorAuthenticationProviderBypass());
        }
        if (StringUtils.isNotBlank(props.getRest().getUrl())) {
            bypass.addMultifactorAuthenticationProviderBypass(authyRestMultifactorAuthenticationProviderBypass());
        }
        return bypass;
    }

    @ConditionalOnMissingBean(name = "authyRestMultifactorAuthenticationProviderBypass")
    @Bean
    @RefreshScope
    public MultifactorAuthenticationProviderBypass authyRestMultifactorAuthenticationProviderBypass() {
        val authy = casProperties.getAuthn().getMfa().getAuthy();
        val props = authy.getBypass();
        return new RestMultifactorAuthenticationProviderBypass(props, authy.getId());
    }

    @ConditionalOnMissingBean(name = "authyGroovyMultifactorAuthenticationProviderBypass")
    @Bean
    @RefreshScope
    public MultifactorAuthenticationProviderBypass authyGroovyMultifactorAuthenticationProviderBypass() {
        val authy = casProperties.getAuthn().getMfa().getAuthy();
        val props = authy.getBypass();
        return new GroovyMultifactorAuthenticationProviderBypass(props, authy.getId());
    }

    @ConditionalOnMissingBean(name = "authyHttpRequestMultifactorAuthenticationProviderBypass")
    @Bean
    @RefreshScope
    public MultifactorAuthenticationProviderBypass authyHttpRequestMultifactorAuthenticationProviderBypass() {
        val authy = casProperties.getAuthn().getMfa().getAuthy();
        val props = authy.getBypass();
        return new HttpRequestMultifactorAuthenticationProviderBypass(props, authy.getId());
    }

    @Bean
    @RefreshScope
    @ConditionalOnMissingBean(name = "authyCredentialMultifactorAuthenticationProviderBypass")
    public MultifactorAuthenticationProviderBypass authyCredentialMultifactorAuthenticationProviderBypass() {
        val authy = casProperties.getAuthn().getMfa().getAuthy();
        val props = authy.getBypass();
        return new CredentialMultifactorAuthenticationProviderBypass(props, authy.getId());
    }

    @Bean
    @RefreshScope
    @ConditionalOnMissingBean(name = "authyRegisteredServiceMultifactorAuthenticationProviderBypass")
    public MultifactorAuthenticationProviderBypass authyRegisteredServiceMultifactorAuthenticationProviderBypass() {
        val authy = casProperties.getAuthn().getMfa().getAuthy();
        return new RegisteredServiceMultifactorAuthenticationProviderBypass(authy.getId());
    }

    @Bean
    @RefreshScope
    @ConditionalOnMissingBean(name = "authyPrincipalMultifactorAuthenticationProviderBypass")
    public MultifactorAuthenticationProviderBypass authyPrincipalMultifactorAuthenticationProviderBypass() {
        val authy = casProperties.getAuthn().getMfa().getAuthy();
        val props = authy.getBypass();
        return new PrincipalMultifactorAuthenticationProviderBypass(props, authy.getId());
    }

    @Bean
    @RefreshScope
    @ConditionalOnMissingBean(name = "authyAuthenticationMultifactorAuthenticationProviderBypass")
    public MultifactorAuthenticationProviderBypass authyAuthenticationMultifactorAuthenticationProviderBypass() {
        val authy = casProperties.getAuthn().getMfa().getAuthy();
        val props = authy.getBypass();
        return new AuthenticationMultifactorAuthenticationProviderBypass(props, authy.getId());
    }

}


text:
var DEFAULT_COMPILER = "fable-compiler"
// var DEFAULT_COMPILER = require("../fable-compiler"); // testing

var path = require("path");
var babel = require("@babel/core");
var babelPlugins = require("fable-babel-plugins");

function or(option, _default) {
    return option !== void 0 ? option : _default;
}

function ensureArray(obj) {
    return Array.isArray(obj) ? obj : (obj != null ? [obj] : []);
}

var customPlugins = [
    babelPlugins.getRemoveUnneededNulls(),
    babelPlugins.getTransformMacroExpressions(babel.template)
];

var compilerCache = null;

function log(opts, msg) {
    if (!opts.silent) {
        console.log(msg);
    }
}

function getTcpPort(opts) {
    if (opts.port != null) {
        return opts.port;
    } else if (process.env.FABLE_SERVER_PORT != null) {
        return parseInt(process.env.FABLE_SERVER_PORT, 10);
    } else {
        return null;
    }
}

function getCompiler(webpack, args, compiler) {
    if (compilerCache == null) {
        var fable = require(compiler);
        compilerCache = fable.default(args);
        if (!webpack.watchMode) {
            webpack.hooks.done.tap("fable-loader", function() {
                compilerCache.close();
            });
        }
    }
    return compilerCache;
}

function transformBabelAst(babelAst, babelOptions, sourceMapOptions, callback) {
    var fsCode = null;
    if (sourceMapOptions != null) {
        fsCode = sourceMapOptions.buffer.toString();
        babelOptions.sourceMaps = true;
        var fileName = sourceMapOptions.path.replace(/\\/g, '/');
        babelOptions.filename = fileName;
        babelOptions.sourceFileName = path.relative(process.cwd(), fileName);
    }
    babel.transformFromAst(babelAst, fsCode, babelOptions, callback);
}

var Loader = function(buffer) {
    var callback = this.async();

    var opts = this.loaders[0].options || {};
    opts.cli = opts.cli || {};
    opts.cli.silent = opts.silent;
    var babelOptions = opts.babel || {};
    babelOptions.plugins = customPlugins.concat(babelOptions.plugins || []);

    var define = ensureArray(or(opts.define, []));
    try {
        if (this._compiler.options.mode === "development" && define.indexOf("DEBUG") === -1) {
            define.push("DEBUG");
        }
    } catch (er) {}

    var msg = {
        path: this.resourcePath,
        rootDir: process.cwd(),
        define: define,
        typedArrays: or(opts.typedArrays, true),
        clampByteArrays: or(opts.clampByteArrays, false),
        extra: opts.extra || {}
    };

    var port = getTcpPort(opts);
    var command = port != null
        ? require("./net-client").send("127.0.0.1", port, JSON.stringify(msg)).then(json => JSON.parse(json))
        : getCompiler(this._compiler, opts.cli, opts.compiler || DEFAULT_COMPILER).send(msg);

    command.then(data => {
        if (data.error) {
            callback(new Error(data.error));
        }
        else {
            try {
                if (!msg.path.endsWith(".fsproj")) {
                    ensureArray(data.dependencies).forEach(p => {
                        // Fable normalizes path separator to '/' which causes issues in Windows
                        // Use `path.resolve` to restore the separator to the system default
                        this.addDependency(path.resolve(p));
                    });
                }
                if (typeof data.logs === "object") {
                    var isErrored = false;
                    Object.keys(data.logs).forEach(key => {
                        ensureArray(data.logs[key]).forEach(msg => {
                            switch (key)  {
                                case "error":
                                    isErrored = true;
                                    this.emitError(new Error(msg));
                                    break;
                                case "warning":
                                    this.emitWarning(new Error(msg));
                                    break;
                                default:
                                    log(opts, msg)
                            }
                        });
                      });
                      this.cacheable(!isErrored);
                }
                var sourceMapOpts = this.sourceMap ? {
                    path: data.fileName,
                    buffer: buffer
                } : null;
                transformBabelAst(data, babelOptions, sourceMapOpts, function (err, babelParsed) {
                    if (err) {
                        callback(err);
                    } else {
                        log(opts, "fable: Compiled " + path.relative(process.cwd(), msg.path));
                        callback(null, babelParsed.code, babelParsed.map);
                    }
                });
            }
            catch (err) {
                callback(err)
            }
        }
    })
    .catch(err => {
        callback(new Error(err.message))
    })
};

Loader.raw = true;
module.exports = Loader;