text:
/**
 * @overview Describes an expression parser and evaluator over the complex
 * numbers
 * @author Colin Jeanne <colinjeanne@hotmail.com> (http://www.colinjeanne.net)
 */

import Complex from './complex.js';
import * as ComplexMath from './complex-math.js';

/**
 * Enumeration for known characters
 * @readonly
 * @enum string
 */
const KnownCharacters = {
   openParenthesis:           '(',
   closeParenthesis:          ')',
   openFloor:                 '\u230A',
   closeFloor:                '\u230B',
   openCeiling:               '\u2308',
   closeCeiling:              '\u2309',
   openBracket:               '[',
   closeBracket:              ']',
   blackLetterCapitalI:       '\u2111',
   blackLetterCapitalR:       '\u211C',
   comma:                     ',',
   invisibleSeparator:        '\u2063',
   plus:                      '+',
   invisiblePlus:             '\u2064',
   minus:                     '-',
   minusSign:                 '\u2212',
   times:                     '*',
   dotOperator:               '\u22C5',
   multiplicationSign:        '\u00D7',
   invisibleTimes:            '\u2062',
   divide:                    '/',
   divisionSign:              '\u00F7',
   fractionSlash:             '\u2044',
   divisionSlash:             '\u2215',
   greekCapitalLetterGamma:   '\u0393'
};

/**
 * Determines whether two types of parentheses match
 * @param  {string} openTerminal  The terminal of the opening parenthesis
 * @param  {string} closeTerminal The terminal of the closing parenthesis
 * @return {boolean}              Whether the closing terminal is a valid match
 * for the opening terminal
 */
const doParenthesesMatch = (openTerminal, closeTerminal) =>
   ((openTerminal === KnownCharacters.openParenthesis) &&
      (closeTerminal === KnownCharacters.closeParenthesis)) ||
   ((openTerminal === KnownCharacters.openFloor) &&
      (closeTerminal === KnownCharacters.closeFloor)) ||
   ((openTerminal === KnownCharacters.openCeiling) &&
      (closeTerminal === KnownCharacters.closeCeiling)) ||
   ((openTerminal === KnownCharacters.openBracket) &&
      (closeTerminal === KnownCharacters.closeBracket));

/**
 * Enumeration for token types
 * @readonly
 * @enum {Number}
 */
const TokenType = {
   space:             1,
   symbol:            2,
   number:            3,
   openParenthesis:   4,
   closeParenthesis:  5,
   comma:             6,
   plus:              7,
   minus:             8,
   times:             9,
   invisibleTimes:   10,
   divide:           11,
   unaryFunction:    12,
   binaryFunction:   13
};

/**
 * Determines if a given token is an operator
 * @param  {TokenType} tokenType The type of the token
 * @return {boolean}             Whether the token is an operator
 */
const isTokenOperator = tokenType =>
   (tokenType === TokenType.plus) ||
   (tokenType === TokenType.minus) ||
   (tokenType === TokenType.times) ||
   (tokenType === TokenType.invisibleTimes) ||
   (tokenType === TokenType.divide);

/**
 * Determines if a given token is a function
 * @param  {TokenType} tokenType The type of the token
 * @return {boolean}             Whether the token is a function
 */
const isTokenFunction = tokenType =>
   (tokenType === TokenType.unaryFunction) ||
   (tokenType === TokenType.binaryFunction);

/**
 * Determines if a given token is a value
 * @param  {TokenType} tokenType The type of the token
 * @return {boolean}             Whether the token is a value
 */
const isTokenValue = tokenType =>
   (tokenType === TokenType.symbol) ||
   (tokenType === TokenType.number);

/**
 * Determines if a given token ends the current scope
 * @param  {TokenType} tokenType The type of the token
 * @return {boolean}             Whether the token ends the current scope
 */
const isTokenScopeEnding = tokenType =>
   (tokenType === TokenType.closeParenthesis) ||
   (tokenType === TokenType.comma);

/**
 * Determines if a given token forces a subexpression to be an unary function
 * @param  {TokenType} tokenType The type of the token
 * @return {boolean}             Whether the token forces the subexpression to
 * be an unary function
 */
const isTokenUnaryForcing = tokenType =>
   (tokenType === TokenType.openParenthesis) ||
   (tokenType === TokenType.comma) ||

   // Plus and minus are unary operators at the start of a subexpression or
   // after an infix operator
   (tokenType === TokenType.plus) ||
   (tokenType === TokenType.minus) ||
   (tokenType === TokenType.times) ||
   (tokenType === TokenType.divide);

/**
 * Determines whether this token implies that a multiplication has taken place
 * @param  {TokenType} tokenType The type of the token
 * @return {boolean}             Whether the token implies that a multiplication
 * has taken place
 */
const tokenImpliesMultiplication = tokenType =>
   (tokenType === TokenType.openParenthesis) ||
   (tokenType === TokenType.number) ||
   (tokenType === TokenType.symbol) ||
   (tokenType === TokenType.unaryFunction) ||
   (tokenType === TokenType.binaryFunction);

/**
 * A token in an expression
 */
class Token {
   /**
    * Constructs a token given a token type and terminal
    * @param  {TokenType}  tokenType The type of the token
    * @param  {string}     terminal  The terminal string of the token
    * @return {Token}
    */
   constructor(tokenType, terminal) {
      this.tokenType = tokenType;
      this.terminal = terminal;
   }
}

/**
 * Determines if the left token is of lower or equal precedence to the right
 * token for the purpose of the Shunting-Yard Algorithm
 * @param  {TokenType} leftToken  The type of the left token
 * @param  {TokenType} rightToken The type of the right token
 * @return {boolean}              Whether the left token is of lower or equal
 * precedence to the right token
 */
const isLeftTokenLowerOrEqualPrecedence = (leftToken, rightToken) =>
   // Invisible Times has the highest precedence of the operators since it is
   // elided in order to imply a strong coupling between terms
   (rightToken === TokenType.invisibleTimes) ||

   // Non-operators all have the same precedence
   (!isTokenOperator(leftToken) && !isTokenOperator(rightToken)) ||

   // Operators, except for invisible times, have lower precedence than
   // non-operators
   (isTokenOperator(leftToken) && (leftToken !== TokenType.invisibleTimes) &&
      !isTokenOperator(rightToken)) ||

   // Times and divide have the second highest precedence amongst operators
   ((rightToken === TokenType.times) || (rightToken === TokenType.divide)) ||

   // The right token must be plus or minus so verify that the left token is
   // also plus or minus
   ((leftToken === TokenType.plus) || (leftToken === TokenType.minus));

/**
 * Converts an infix operator into a binary function
 * @param  {Token} token The operator token
 * @return {Token}       A binary function token
 */
const operatorToBinaryFunction = token => {
   if (!isTokenOperator(token.tokenType)) {
      throw new Error('Assertion failed: expected operator token');
   }

   return new Token(TokenType.binaryFunction, token.terminal);
};

/**
 * An exception thrown when a syntactically-malformed expression is encountered
 */
class ExpressionSyntaxError extends Error {
   /**
    * Constructs an ExpressionSyntaxError
    * @param  {string}                message The exception message
    * @return {ExpressionSyntaxError}
    */
   constructor(message) {
      super(message);
      this.message = message;
   }
}

/**
 * Coverts an expression from infix notation to reverse polish notation using
 * the Shunting-Yard Algorithm
 * @param  {Token[]} tokens An array of tokens in infix-notation
 * @return {Token[]}        An array of tokens in reverse polish notation
 */
const convertToReversePolishNotation = tokens => {
   // The current stack of operators. This uses shift/unshift so that the first
   // element is the top of the stack.
   let ops = [];

   // The tokens in reverse polish notation
   let rpn = [];

   tokens.forEach((token, index) => {
      if (isTokenValue(token.tokenType)) {
         rpn.push(token);
      } else if (token.tokenType === TokenType.openParenthesis) {
         ops.unshift(token);
      } else if (isTokenScopeEnding(token.tokenType)) {
         while ((ops.length !== 0) &&
            (ops[0].tokenType !== TokenType.openParenthesis)) {
            if (isTokenOperator(ops[0].tokenType)) {
               rpn.push(operatorToBinaryFunction(ops[0]));
            } else {
               rpn.push(ops[0]);
            }

            ops.shift();
         }

         if ((ops.length === 0) ||
            (ops[0].tokenType !== TokenType.openParenthesis)) {
            if (token.tokenType === TokenType.comma) {
               throw new ExpressionSyntaxError('Misplaced comma');
            } else if (token.terminal === KnownCharacters.closeParenthesis) {
               throw new ExpressionSyntaxError('Too many close parentheses');
            } else {
               throw new ExpressionSyntaxError('Mismatched circumfix operator');
            }
         }

         if ((ops.length !== 0) &&
            (token.tokenType === TokenType.closeParenthesis)) {
            if (!doParenthesesMatch(ops[0].terminal, token.terminal)) {
               throw new ExpressionSyntaxError('Mismatched circumfix operator');
            }

            // Pop open parenthesis
            ops.shift();

            if ((ops.length !== 0) && isTokenFunction(ops[0].tokenType)) {
               rpn.push(ops[0]);
               ops.shift();
            }
         }
      } else if (isTokenOperator(token.tokenType)) {
         // Check for a right hand operand. This is required because a syntax
         // error elsewhere in the expression may create an opporunity for an
         // operand to appear - for example "real(2, 3) +"
         const nextIndex = index + 1;
         if (nextIndex >= tokens.length) {
            throw new ExpressionSyntaxError('Missing right hand operand');
         }

         while ((ops.length !== 0) &&
            isLeftTokenLowerOrEqualPrecedence(
               token.tokenType,
               ops[0].tokenType)) {
            if (isTokenOperator(ops[0].tokenType)) {
               rpn.push(operatorToBinaryFunction(ops[0]));
            } else if (isTokenFunction(ops[0].tokenType)) {
               rpn.push(ops[0]);
            } else {
               break;
            }

            ops.shift();
         }

         ops.unshift(token);
      } else if (token.tokenType === TokenType.unaryFunction) {
         ops.unshift(token);
      } else if (token.tokenType === TokenType.binaryFunction) {
         const nextIndex = index + 1;
         if ((nextIndex >= tokens.length) ||
            (tokens[nextIndex].tokenType !== TokenType.openParenthesis)) {
            throw new ExpressionSyntaxError(
               'Binary functions must use parentheses');
         }

         ops.unshift(token);
      } else {
         throw new Error('Assertion failed: unknown token type');
      }
   });

   while (ops.length !== 0) {
      if (ops[0].tokenType === TokenType.openParenthesis) {
         if (ops[0].terminal === KnownCharacters.openParenthesis) {
            throw new ExpressionSyntaxError('Too many open parentheses');
         } else {
            throw new ExpressionSyntaxError('Mismatched circumfix operator');
         }
      }

      if (isTokenOperator(ops[0].tokenType)) {
         rpn.push(operatorToBinaryFunction(ops[0]));
      } else {
         rpn.push(ops[0]);
      }

      ops.shift();
   }

   if (rpn.length === 0) {
      throw new ExpressionSyntaxError('Empty expression');
   }

   return rpn;
};

/**
 * The set of known constants
 * @readonly
 * @enum {Complex}
 */
const KnownConstants = {
   e: ComplexMath.E,
   i: ComplexMath.I,
   pi: ComplexMath.PI
};

/**
 * Whether a terminal is a known constant
 * @param  {string} terminal The terminal
 * @return {boolean}         Whether the terminal is a known constant
 */
const isKnownConstant = terminal => KnownConstants.hasOwnProperty(terminal);

/**
 * Converts a terminal into either the value of a known constant or a complex
 * number
 * @param  {string} terminal The terminal
 * @return {Complex}         The complex value of the terminal
 */
const numberFromTerminal = terminal => {
   if (isKnownConstant(terminal)) {
      return KnownConstants[terminal];
   }

   return new Complex(Number.parseFloat(terminal));
};

/**
 * The known unary functions
 * @readonly
 * @enum {callback}
 */
const KnownUnaryFunctions = {
   abs:                                         ComplexMath.abs,
   arccos:                                      ComplexMath.acos,
   arccosh:                                     ComplexMath.acosh,
   arccot:                                      ComplexMath.acot,
   arccoth:                                     ComplexMath.acoth,
   arccsc:                                      ComplexMath.acsc,
   arccsch:                                     ComplexMath.acsch,
   arcsec:                                      ComplexMath.asec,
   arcsech:                                     ComplexMath.asech,
   arcsin:                                      ComplexMath.asin,
   arcsinh:                                     ComplexMath.asinh,
   arctan:                                      ComplexMath.atan,
   arctanh:                                     ComplexMath.atanh,
   arg:                                         ComplexMath.arg,
   ceil:                                        ComplexMath.ceil,
   conj:                                        ComplexMath.conj,
   cos:                                         ComplexMath.cos,
   cosh:                                        ComplexMath.cosh,
   cot:                                         ComplexMath.cot,
   coth:                                        ComplexMath.coth,
   csc:                                         ComplexMath.csc,
   csch:                                        ComplexMath.csch,
   exp:                                         ComplexMath.exp,
   floor:                                       ComplexMath.floor,
   frac:                                        ComplexMath.frac,
   gamma:                                       ComplexMath.gamma,
   [KnownConstants.greekCapitalLetterGamma]:    ComplexMath.gamma,
   imag:                                        ComplexMath.imag,
   [KnownConstants.blackLetterCapitalI]:        ComplexMath.imag,
   log10:                                       ComplexMath.log10,
   lg:                                          ComplexMath.log2,
   ln:                                          ComplexMath.ln,
   '-':                                         ComplexMath.negate,
   nint:                                        ComplexMath.nint,
   norm:                                        ComplexMath.norm,
   real:                                        ComplexMath.real,
   [KnownConstants.blackLetterCapitalR]:        ComplexMath.real,
   sec:                                         ComplexMath.sec,
   sech:                                        ComplexMath.sech,
   sin:                                         ComplexMath.sin,
   sinh:                                        ComplexMath.sinh,
   sqrt:                                        ComplexMath.sqrt,
   tan:                                         ComplexMath.tan,
   tanh:                                        ComplexMath.tanh
};

/**
 * Whether a terminal is a known unary function
 * @param  {string} terminal The terminal
 * @return {boolean}         Whether the terminal is a known unary function
 */
const isKnownUnaryFunction = terminal =>
   KnownUnaryFunctions.hasOwnProperty(terminal);

/**
 * Converts a terminal into an unary function
 * @param  {string}   terminal The terminal
 * @return {callback}          The function implementing the unary function
 */
const unaryFunctionFromTerminal = terminal => {
   if (isKnownUnaryFunction(terminal)) {
      return KnownUnaryFunctions[terminal];
   }

   throw new Error(
      'Assertion failed: attempting to create unknown unary function');
};

/**
 * The known binary functions
 * @readonly
 * @enum {callback}
 */
const KnownBinaryFunctions = {
   log: ComplexMath.log,
   mod: ComplexMath.mod,
   pow: ComplexMath.pow,
   '+': ComplexMath.add,
   '-': ComplexMath.subtract,
   '*': ComplexMath.multiply,
   '/': ComplexMath.divide
};

/**
 * Whether a terminal is a known binary function
 * @param  {string} terminal The terminal
 * @return {boolean}         Whether the terminal is a known binary function
 */
const isKnownBinaryFunction = terminal =>
   KnownBinaryFunctions.hasOwnProperty(terminal);

/**
 * Converts a terminal into an binary function
 * @param  {string}   terminal The terminal
 * @return {callback}          The function implementing the binary function
 */
const binaryFunctionFromTerminal = terminal => {
   if (isKnownBinaryFunction(terminal)) {
      return KnownBinaryFunctions[terminal];
   }

   throw new Error(
      'Assertion failed: attempting to create unknown binary function');
};

/**
 * Processes a set of tokens to add implied elements such as invisible times or
 * to differentiate between elements which are ambiguous at tokenization time
 * such as unary vs. binary plus and minus.
 * @param  {Token[]} tokens An array of tokens
 * @return {Token[]}        An array of tokens in which implied and ambiguous
 * elements are resolved
 */
const processHiddenElements = tokens => {
   let processedTokens = [];
   tokens.forEach((token, index) => {
      let nextIndex = index + 1;
      let isLastToken = nextIndex === tokens.length;

      switch (token.tokenType) {
         case TokenType.space:
            // Spaces are no longer needed for correct processing
            break;

         case TokenType.closeParenthesis:
         case TokenType.number:
         case TokenType.symbol:
            processedTokens.push(token);

            if (!isLastToken &&
               tokenImpliesMultiplication(tokens[nextIndex].tokenType)) {
               processedTokens.push(new Token(TokenType.invisibleTimes, '*'));
            }
            break;

         case TokenType.comma:
            if ((processedTokens.length === 0) ||
                (processedTokens[processedTokens.length - 1].tokenType === TokenType.openParenthesis) ||
                (!isLastToken && tokens[nextIndex].tokenType === TokenType.closeParenthesis)) {
               throw new ExpressionSyntaxError("Misplaced comma");
            }

            processedTokens.push(token);
            break;

         case TokenType.plus:
         case TokenType.minus:
            if ((processedTokens.length === 0) ||
                isTokenUnaryForcing(processedTokens[processedTokens.length - 1].tokenType)) {
               if (token.tokenType === TokenType.minus) {
                  // Unary plus is the identity function, so ignore it
                  // altogether
                  processedTokens.push(
                     new Token(TokenType.unaryFunction, token.terminal));
               }
            } else {
               processedTokens.push(token);
            }

            break;

         case TokenType.openParenthesis:
         case TokenType.times:
         case TokenType.invisibleTimes:
         case TokenType.divide:
         case TokenType.unaryFunction:
         case TokenType.binaryFunction:
            processedTokens.push(token);
            break;
      }
   });

   return processedTokens;
};

/**
 * Determines whether a character is alphabetic
 * @param  {string} c The character
 * @return {boolean}  Whether the character is alphabetic
 */
const isAlphabeticCharacter = c => /[A-Za-z]/.test(c);

/**
 * Determines whether a character is a digit
 * @param  {string} c The character
 * @return {boolean}  Whether the character is a digit
 */
const isDigitCharacter = c => /\d/.test(c);

/**
 * Determines whether a character is a numeric
 * @param  {string} c The character
 * @return {boolean}  Whether the character is a numeric
 */
const isNumericCharacter = c => /\d|\./.test(c);

/**
 * Determines whether a character is a space
 * @param  {string} c The character
 * @return {boolean}  Whether the character is a space
 */
const isSpaceCharacter = c => /\s/.test(c);

/**
 * Determines whether a character is a high surrogate
 * @param  {string} c The character
 * @return {boolean}  Whether the character is a high surrogate
 */
const isHighSurrogateCharacter = c =>
   (c.charCodeAt(0) >= 0xD800) && (c.charCodeAt(0) <= 0xDBFF);

/**
 * Determines whether a character is a loe surrogate
 * @param  {string} c The character
 * @return {boolean}  Whether the character is a low surrogate
 */
const isLowSurrogateCharacter = c =>
   (c.charCodeAt(0) >= 0xDC00) && (c.charCodeAt(0) <= 0xDFFF);

/**
 * Finds the ending index of a symbol
 * @param  {number}   startIndex The starting index of the symbol
 * @param  {string}   expression The expression
 * points
 * @return {number}              The ending index of the symbol
 */
const findSymbolEndIndex = (startIndex, expression) => {
   const startCharacter = expression[startIndex];

   let endIndex;
   if (isLowSurrogateCharacter(startCharacter)) {
      throw new ExpressionSyntaxError(
         'Encountered low surrogate without a corresponding high surrogate');
   } else if (isHighSurrogateCharacter(startCharacter)) {
      endIndex = startIndex + 2;
      if ((endIndex > expression.length) ||
         !isLowSurrogateCharacter(expression[startIndex + 1])) {
         throw new ExpressionSyntaxError(
            'Encountered high surrogate without a corresponding low surrogate');
      }
   } else if (isAlphabeticCharacter(startCharacter)) {
      let substring = expression.substring(startIndex);

      let relativeEndIndex = substring.search(/[^A-Za-z]|$/);
      if ((relativeEndIndex !== -1) &&
         isDigitCharacter(expression[relativeEndIndex])) {
         // Some symbols can have digits directly after, such as log10
         substring = substring.substring(relativeEndIndex);
         relativeEndIndex += substring.search(/\D/);
      }

      if (relativeEndIndex !== -1) {
         endIndex = relativeEndIndex + startIndex;
      } else {
         endIndex = startIndex + 1;
      }
   } else {
      // Single character Unicode symbol
      endIndex = startIndex + 1;
   }

   return endIndex;
};

/**
 * Tokenizes an expression
 * @param  {string} expression The expression to tokenize
 * @return {Token}             The set of tokens
 */
const tokenize = expression => {
   // This method explicitly does not support using | to mean absolute since
   // allowing this notation as well as invisible times leads to ambiguous
   // expressions such as |x|x|x|
   let tokens = [];
   let startIndex = 0;
   while (startIndex !== expression.length) {
      let character = expression[startIndex];

      if (character === '\u0000') {
         // Reached the end of the string, explicitly not supporting embedded
         // nulls
         break;
      } else if (isSpaceCharacter(character)) {
         tokens.push(new Token(TokenType.space, ' '));
         ++startIndex;
      } else if (character === KnownCharacters.openParenthesis) {
         tokens.push(new Token(TokenType.openParenthesis, '('));
         ++startIndex;
      } else if (character === KnownCharacters.openFloor) {
         tokens.push(new Token(TokenType.unaryFunction, 'floor'));
         tokens.push(new Token(TokenType.openParenthesis, KnownCharacters.openFloor));
         ++startIndex;
      } else if (character === KnownCharacters.openCeiling) {
         tokens.push(new Token(TokenType.unaryFunction, 'ceil'));
         tokens.push(new Token(TokenType.openParenthesis, KnownCharacters.openCeiling));
         ++startIndex;
      } else if (character === KnownCharacters.openBracket) {
         tokens.push(new Token(TokenType.unaryFunction, 'nint'));
         tokens.push(new Token(TokenType.openParenthesis, KnownCharacters.openBracket));
         ++startIndex;
      } else if ((character === KnownCharacters.closeParenthesis) ||
         (character === KnownCharacters.closeFloor) ||
         (character === KnownCharacters.closeCeiling) ||
         (character === KnownCharacters.closeBracket)) {
         tokens.push(new Token(TokenType.closeParenthesis, character));
         ++startIndex;
      } else if ((character === KnownCharacters.comma) ||
         (character === KnownCharacters.invisibleSeparator)) {
         tokens.push(new Token(TokenType.comma, ','));
         ++startIndex;
      } else if (isNumericCharacter(character)) {
         // Tokenize number
         const substring = expression.substring(startIndex);
         const terminal = substring.match(/^\d+(?:\.\d+)?/);
         tokens.push(new Token(TokenType.number, terminal[0]));

         startIndex += terminal[0].length;
      } else if ((character === KnownCharacters.plus) ||
         (character === KnownCharacters.invisiblePlus)) {
         tokens.push(new Token(TokenType.plus, '+'));
         ++startIndex;
      } else if ((character === KnownCharacters.minus) ||
         (character === KnownCharacters.minusSign)) {
         tokens.push(new Token(TokenType.minus, '-'));
         ++startIndex;
      } else if ((character === KnownCharacters.times) ||
         (character === KnownCharacters.dotOperator) ||
         (character === KnownCharacters.multiplicationSign)) {
         tokens.push(new Token(TokenType.times, '*'));
         ++startIndex;
      } else if (character === KnownCharacters.invisibleTimes) {
         tokens.push(new Token(TokenType.invisibleTimes, '*'));
         ++startIndex;
      } else if ((character === KnownCharacters.divide) ||
         (character === KnownCharacters.divisionSign) ||
         (character === KnownCharacters.fractionSlash) ||
         (character === KnownCharacters.divisionSlash)) {
         tokens.push(new Token(TokenType.divide, '/'));
         ++startIndex;
      } else {
         const endIndex = findSymbolEndIndex(startIndex, expression);
         const terminal = expression.substring(startIndex, endIndex);

         let tokenType;
         if (isKnownConstant(terminal)) {
            tokenType = TokenType.number;
         } else if (isKnownUnaryFunction(terminal)) {
            tokenType = TokenType.unaryFunction;
         } else if (isKnownBinaryFunction(terminal)) {
            tokenType = TokenType.binaryFunction;
         } else {
            tokenType = TokenType.symbol;
         }

         tokens.push(new Token(tokenType, terminal));
         startIndex = endIndex;
      }
   }

   return tokens;
};

/**
 * A phrase representing a number
 */
class NumberPhrase {
   /**
    * Constructs a NumberPhrase from a number
    * @param  {number|Complex} value The value of the number phrase
    * @return {NumberPhrase}
    */
   constructor(value) {
      this.value = value;
   }

   /**
    * Evaluates the phrase
    * @return {number|Complex} The value of the phrase
    */
   evaluate() {
      return this.value;
   }
}

/**
 * An error raised when the expression is syntactically valid but cannot be
 * evaluated
 */
class ExpressionEvaluationError extends Error {
   /**
    * Constructs an ExpressionEvaluationError
    * @param  {string}                    message The exception message
    * @return {ExpressionEvaluationError}
    */
   constructor(message) {
      super(message);
      this.message = message;
   }
}

/**
 * A phrase representing a variable
 */
class VariablePhrase {
   /**
    * Constructs a VariablePhrase from a symbol
    * @param  {string}         symbol The symbol of the variable
    * @return {VariablePhrase}
    */
   constructor(symbol) {
      this.symbol = symbol;
   }

   /**
    * Evaluates the phrase
    * @param  {Object.<string, number|Complex>=} symbols A dictionary of
    * symbols and their values
    * @return {number|Complex} The value of the phrase
    */
   evaluate(symbols = {}) {
      if (!symbols.hasOwnProperty(this.symbol)) {
         throw new ExpressionEvaluationError(
            `Variable ${this.symbol} does not have a defined value`);
      }

      return symbols[this.symbol];
   }
}

/**
 * A phrase representing a function
 */
class FunctionPhrase {
   /**
    * Constructs a FunctionPhrase from a function
    * @param  {callback}                                         evalFunction The
    * function used to evaluate this phrase
    * @param  {NumberPhrase[]|VariablePhrase[]|FunctionPhrase[]} children The child
    * phrases of this phrase
    * @return {FunctionPhrase}
    */
   constructor(evalFunction, children) {
      if (children.length !== evalFunction.length) {
         throw new ExpressionSyntaxError('Improper number of arguments');
      }

      this.evalFunction = evalFunction;
      this.children = children;
   }

   /**
    * Evaluates the phrase
    * @param  {Object.<string, number|Complex>=} symbols A dictionary of
    * symbols and their values
    * @return {number|Complex} The value of the phrase
    */
   evaluate(symbols = {}) {
      return this.evalFunction.apply(
         null,
         this.children.map(phrase => phrase.evaluate(symbols)));
   }
}

/**
 * Builds a parse tree from a tokenized expression
 * @param  {Token[]} tokens A tokenized expression
 * @return {NumberPhrase|VariablePhrase|FunctionPhrase} The root of the parse
 * tree
 */
const buildParseTree = tokens => {
   let stack = [];

   tokens.forEach(token => {
      switch (token.tokenType) {
         case TokenType.number:
            stack.push(new NumberPhrase(numberFromTerminal(token.terminal)));
            break;

         case TokenType.symbol:
            stack.push(new VariablePhrase(token.terminal));
            break;

         case TokenType.unaryFunction:
            if (stack.length === 0) {
               throw new ExpressionSyntaxError(
                  `Too few arguments for function ${token.terminal}`);
            }

            stack.push(
               new FunctionPhrase(
                  unaryFunctionFromTerminal(token.terminal), [stack.pop()]));
            break;

         case TokenType.binaryFunction:
            if (stack.length < 2) {
               throw new ExpressionSyntaxError(
                  `Too few arguments for function ${token.terminal}`);
            }

            const children = [stack.pop(), stack.pop()].reverse();
            stack.push(
               new FunctionPhrase(
                  binaryFunctionFromTerminal(token.terminal),
                  children));
            break;

         default:
            throw new Error('Assertion failed: unexpected token type');
      }
   });

   if (stack.length === 0) {
      throw new ExpressionSyntaxError('Empty expression');
   } else if (stack.length !== 1) {
      throw new ExpressionSyntaxError('Unexpected expression');
   }

   return stack[0];
};

/**
 * An expression
 */
export default class {
   /**
    * Constructs an expression from a string
    * @param  {string} expression The expression string
    * @return {Expression}
    */
   constructor(expression) {
      this.phrase = buildParseTree(
         convertToReversePolishNotation(
            processHiddenElements(
               tokenize(
                  expression))));
   }

   /**
    * Evaluates the expression
    * @param  {Object.<string, number|Complex>=} symbols A dictionary of
    * symbols and their values
    * @return {number|Complex} The value of the expression
    */
   evaluate(symbols = {}) {
      return this.phrase.evaluate(symbols);
   }
}


text:
/************************************************************************/
/* À̹ÌÁö º¯È¯ ¹× ÀúÀå ¸ðµâ
/*		ÀúÀåÀº $(SolutionDir)/$(ConfigurationName) ¿¡ ÀúÀåµÇ±â ¶§¹®¿¡ ÀÌ°÷¿¡ ÀúÀåÇÏ¸é ¹Ù·Î ½ÇÇè ÇÁ·ÎÁ§Æ®¿¡¼ ÀÐÀ» ¼ö ÀÖÀ½
/************************************************************************/

#include <stdio.h>

#include <opencv2/legacy/legacy.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/gpu/gpu.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

#include "OpenCv2.4.5_libs.h"
#include "value.h"
#include "brisk/brisk.h"
using namespace cv;
using namespace std;

/************************************************************************/
/* À̹ÌÁö Rotate
/*
/* perspective matrix
/* [a b (1-a)*center.x-b*center.y ]
/* [-b a b*center.x+(1-a)*center.y]
/* a= scale*cos angle
/* b= scale*sin angle
/*
/************************************************************************/
IplImage *transform(FileStorage* fs, const IplImage *src, int angle, float centerX, float centerY,
	float scaleX, float scaleY,	float moveX, float moveY , double scale){
		IplImage *imageRotated = cvCreateImage(cvSize(src->width,src->height),src->depth,3);

		float sina = sin(-angle * DEG_TO_RAD);
		float cosa = cos(-angle * DEG_TO_RAD);
		CvMat*  transmat = cvCreateMat( 2,3, CV_32F );
		cvmSet( transmat, 0,0, scaleX*cosa );
		cvmSet( transmat, 0,1, scaleY*sina );
		cvmSet( transmat, 0,2, -centerX*scaleX*cosa - centerY*scaleY*sina + moveX + centerX );
		cvmSet( transmat, 1,0, -1.0*scaleX*sina );
		cvmSet( transmat, 1,1, scaleY*cosa );
		cvmSet( transmat, 1,2, -centerY*scaleY*cosa + centerX*scaleX*sina + moveY + centerY);

		cvWarpAffine( src, imageRotated, transmat);

		char name[100];
		sprintf(name, "P_%d_%d",(int)(scale*10),angle);
		write(*fs, name, transmat);

		cvReleaseMat( &transmat );
		return imageRotated;
}

/************************************************************************/
/* À̹ÌÁö »çÀÌÁî Á¶Á¤ ¹× Rotate
/************************************************************************/
IplImage *rotateImage(FileStorage* fs, const IplImage *src, int angleDegrees, double scale)
{
	//resize
	int w = src->width * scale;
	int h = src->height * scale;
	IplImage* temp= cvCreateImage( cvSize(w,h), IPL_DEPTH_8U, 3 );
	cvResize( src, temp );

	float width = sqrt((double)temp->width * (double)temp->width + temp->height * temp->height);

	IplImage* rotateImage = cvCreateImage( cvSize(width,width), IPL_DEPTH_8U, 3 );
	cvSet(rotateImage,cvScalar(0));

	CvPoint center;
	center.x = rotateImage->width / 2.0;
	center.y = rotateImage->height / 2.0;

	//º¹»çÇÏ°í ȸÀü
	cvSetImageROI(rotateImage, cvRect(center.x - temp->width / 2.0, center.y - temp->height / 2.0, temp->width, temp->height));
	cvCopy(temp,rotateImage);
	cvResetImageROI(rotateImage);

	IplImage *imageRotated;
	imageRotated = transform(fs, rotateImage, angleDegrees, rotateImage->width/2, rotateImage->height/2, 1,1, 0,0, scale);

	cvReleaseImage(&temp);
	cvReleaseImage(&rotateImage);

	return imageRotated;
}

void computeDescriptors(FileStorage* fs,IplImage* image,Ptr<FeatureDetector>& detector, cv::Ptr<cv::DescriptorExtractor>& descriptor, int imageNum,float scale, int angle, int gaussian)
{
	char name[100];
	vector<cv::KeyPoint> keyPoints;

	vector<cv::KeyPoint> keyPoints_brisk;
	Mat descriptors;

	Mat mat = Mat(image);
	Mat mat_gray(mat.size(),CV_8U);

	cv::cvtColor(mat, mat_gray, CV_BGR2GRAY);

	detector->detect(mat_gray, keyPoints);
	descriptor->compute(mat_gray, keyPoints, descriptors);

	if(scale == -1)
		cout<<keyPoints.size()<<endl;

	sprintf(name, "K_%d_%d_%d_%d",imageNum,(int)(scale*10),angle,gaussian);
	write(*fs, name, keyPoints);
	sprintf(name, "D_%d_%d_%d_%d",imageNum,(int)(scale*10),angle,gaussian);
	write(*fs, name, descriptors);

// 	for(int i=0 ; i < keyPoints.size();i++){
// 		circle(mat,keyPoints[i].pt,3,cvScalar(255,0,0),2);
// 	}
// 	imshow("msmsms",mat);
// 	cvWaitKey(0);
}

int main()
{
	char filename[100];
	char dbFilename[100]={0,};

	IplImage* rotImage = NULL;
	IplImage* gaussianImage = NULL;

	float maxScale = MAX_SCALE;
	int maxDBSize = MAX_DB_SIZE;

	FileStorage fs("Data.xml",FileStorage::WRITE);
	FileStorage ps("Perspective matrix.xml",FileStorage::WRITE);

	//brisk ¼³Á¤
	Ptr<FeatureDetector> detector;
	cv::Ptr<cv::DescriptorExtractor> descriptor;

	detector = new BriskFeatureDetector(130, 5);//Áöµµ : 130 //wall : 70  //ubc : 90
	descriptor = new cv::BriskDescriptorExtractor();
	memset(dbFilename, 0x00, sizeof(dbFilename));

	for(int i = 0 ; i < maxDBSize; i++ ){
		//sprintf(dbFilename,"dbImage/%d.jpg", 4);//i+1);
		sprintf(dbFilename,"dbImage/1.jpg");
		IplImage *dbImage = cvLoadImage(dbFilename);

		computeDescriptors( &fs, dbImage, detector,  descriptor, i+1, -1, -1, -1);

		for(float scale = MIN_SCALE; scale <= maxScale; scale += SCALE_INCREASE){			//scale º¯È
			for(int angle = 0; angle < 360; angle += ANGLE_INCREASE){						//angle º¯È
				//rotate
				rotImage = rotateImage(&ps, dbImage,angle,scale);

				//Save Image (¿øº»)
				sprintf(filename,"testset/%d_%.1f_%d_%d.png", i+1,scale,angle);
				//cvSaveImage(filename,rotImage);
				computeDescriptors( &fs, rotImage, detector,  descriptor, i+1, scale, angle, 0);

				cout<<filename << " is saved."<<endl;

				//Gaussian blur ÃÑ 3¹øÀ» ÇÑ´Ù.
				for(int g = 3 ; g < 8;g +=2){
					gaussianImage = cvCreateImage(cvSize(rotImage->width, rotImage->height), IPL_DEPTH_8U, 3);
					cvSmooth(rotImage,gaussianImage,CV_GAUSSIAN,g,g);

					//Save Image (Gaussian)
					sprintf(filename,"testset/%d_%.1f_%d_%d.png", 1,scale,angle,g);
					//cvSaveImage(filename,gaussianImage);
					computeDescriptors( &fs, gaussianImage, detector,  descriptor, i+1, scale, angle, g);

					cvReleaseImage(&gaussianImage);
				}
				cvReleaseImage(&rotImage);
			}
		}
	}
}

redpajama_set_name: RedPajamaGithub


text: Shim repository for Unveil


text:
// Copyright (c) André N. Klingsheim. See License.txt in the project root for license information.

using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace MvcAttributeWebsite.Controllers
{
    public class RedirectController : Controller
    {
        //
        // GET: /Redirect/

        public ActionResult Relative()
        {
            return Redirect("/");
        }

        public ActionResult SameSite()
        {

            var ub = new UriBuilder(Request.Scheme + "//" + Request.Host)
            {
                Path = Url.Action("Index", "Home"),
                Query = ""
            };
            var result = ub.Uri;
            if (!result.IsAbsoluteUri) throw new Exception("We didn't manage to create an absolute URI...");

            return Redirect(result.AbsoluteUri);
        }

        public ActionResult WhitelistedSite()
        {
            return Redirect("https://www.nwebsec.com/");
        }

        public ActionResult DangerousSite()
        {
            return Redirect("http://www.unexpectedsite.com/");
        }

        public ActionResult ValidationDisabledDangerousSite()
        {
            return Redirect("http://www.unexpectedsite.com/");
        }

    }
}


text:
<?php
namespace Dyon\Flatstrapper;

use Illuminate\Support\Facades\HTML;

/**
 * ButtonGroup for creating Twitter Bootstrap style Buttons groups.
 *
 * @category   HTML/UI
 * @package    Flatstrapper
 * @subpackage Twitter
 * @author     Daniel Hurtado - <hello@dyon.me>
 * @license    MIT License <http://www.opensource.org/licenses/mit>
 * @link       http://laravelbootstrapper.phpfogapp.com/
 *
 * @see        http://twitter.github.com/bootstrap/
 */
class ButtonGroup
{
    /**
     * Puts the ButtonGroup in a checkbox mode.
     *
     * @var string
     */
    const TOGGLE_CHECKBOX = 'checkbox';

    /**
     * Puts the ButtonGroup in a radio button mode. Allowing only
     * one button to be selected at a time.
     *
     * @var string
     */
    const TOGGLE_RADIO = 'radio';

    /**
     * Opens a vertical button group
     *
     * @param boolean $toggle     Whether the button group should be togglable
     * @param array   $attributes An array of attributes
     *
     * @return string An opening <div> tag
     */
    public static function vertical_open($toggle = null, $attributes = array())
    {
        $attributes = Helpers::add_class($attributes, 'btn-group-vertical');

        return static::open($toggle, $attributes);
    }

    /**
     * Alias for open so both horizontal_open and open can be used.
     *
     * @param boolean $toggle     Whether the button group should be togglable
     * @param array   $attributes An array of attributes
     *
     * @return string An opening <div> tag
     */
    public static function horizontal_open($toggle = null, $attributes = array())
    {
        return static::open($toggle, $attributes);
    }

    /**
     * Opens a new ButtonGroup section.
     *
     * @param string $toggle     Whether the button group should be togglable
     * @param array  $attributes An array of attributes
     *
     * @return string An opening <div> tag
     */
    public static function open($toggle = null, $attributes = array())
    {
        $validToggles = array(ButtonGroup::TOGGLE_CHECKBOX, ButtonGroup::TOGGLE_RADIO);
        if (isset($toggle) && in_array($toggle, $validToggles)) {
            $attributes['data-toggle'] = 'buttons-'.$toggle;
        }

        $attributes = Helpers::add_class($attributes, 'btn-group');

        return '<div'.Helpers::getContainer('html')->attributes($attributes).'>';
    }

    /**
     * Closes the ButtonGroup section.
     *
     * @return string
     */
    public static function close()
    {
        return '</div>';
    }
}


text: 存放SimpleMediaPlayer的素材图标,使用png格式;


text:
<?php
class Kwf_View_Twig_Environment extends Twig_Environment
{
    public function __construct()
    {
        parent::__construct(new Kwf_View_Twig_FilesystemLoader('.'), array(
            'cache' => 'cache/twig',
            'auto_reload' => false
        ));

        $this->addFilter(new Twig_SimpleFilter('date',
            array('Kwf_Component_Renderer_Twig_Environment', 'date'),
            array('needs_context' => true)));
        $this->addFilter(new Twig_SimpleFilter('dateTime',
            array('Kwf_Component_Renderer_Twig_Environment', 'dateTime'),
            array('needs_context' => true)));
        $this->addFilter(new Twig_SimpleFilter('money',
            array('Kwf_Component_Renderer_Twig_Environment', 'money'),
            array('needs_context' => true)));
        $this->addFilter(new Twig_SimpleFilter('mailEncodeText',
            array('Kwf_Component_Renderer_Twig_Environment', 'mailEncodeText')));
        $this->addFilter(new Twig_SimpleFilter('mailLink',
            array('Kwf_Component_Renderer_Twig_Environment', 'mailLink')));
        $this->addFilter(new Twig_SimpleFilter('hiddenOptions',
            array('Kwf_Component_Renderer_Twig_Environment', 'hiddenOptions')));
    }

    public static function date($context, $date, $format = null)
    {
        $language = null;
        if (isset($context['data']) && $context['data'] instanceof Kwf_Component_Data) {
            if (!$format) $format = $context['data']->trlKwf('Y-m-d');
            $language = $context['data']->getLanguage();
        } else if (isset($context['item']) && $context['item'] instanceof Kwf_Component_Data) {
            if (!$format) $format = $context['item']->trlKwf('Y-m-d');
            $language = $context['item']->getLanguage();
        } else {
            if (!$format) $format = trlKwf('Y-m-d');
        }
        if (!$date || (is_string($date) && substr($date, 0, 10) == '0000-00-00')) return '';

        if (!$date instanceof Kwf_Date) {
            $date = new Kwf_Date($date);
        }
        return $date->format($format, $language);
    }

    public function dateTime($context, $date, $format = null)
    {
        if (isset($context['data']) && $context['data'] instanceof Kwf_Component_Data) {
            if (!$format) $format = $context['data']->trlKwf('Y-m-d H:i');
        } else if (isset($context['item']) && $context['item'] instanceof Kwf_Component_Data) {
            if (!$format) $format = $context['item']->trlKwf('Y-m-d H:i');
        } else {
            if (!$format) $format = trlKwf('Y-m-d H:i');
        }
        return self::date($context, $date, $format);
    }

    public static function money($context, $amount)
    {
        $data = null;

        if (isset($context['data']) && $context['data'] instanceof Kwf_Component_Data) {
            $data = $context['data'];
        } else if (isset($context['item']) && $context['item'] instanceof Kwf_Component_Data) {
            $data = $context['item'];
        }

        if ($data) {
            $format = $data->getBaseProperty('money.format');
            $decimals = $data->getBaseProperty('money.decimals');
            $decimalSeparator = $data->getBaseProperty('money.decimalSeparator');
            $thousandSeparator = $data->getBaseProperty('money.thousandSeparator');

            if (is_null($decimalSeparator)) $decimalSeparator = $data->trlcKwf('decimal separator', ".");
            if (is_null($thousandSeparator)) $thousandSeparator = $data->trlcKwf('thousands separator', ",");
        } else {
            $format = Kwf_Config::getValue('money.format');
            $decimals = Kwf_Config::getValue('money.decimals');
            $decimalSeparator = trlcKwf('decimal separator', ".");
            $thousandSeparator = trlcKwf('thousands separator', ",");
        }

        $number = number_format($amount, $decimals, $decimalSeparator, $thousandSeparator);
        return new Twig_Markup(str_replace('{0}', ''.$number.'', $format), 'utf-8');
    }

    public function mailEncodeText($text)
    {
        $helper = new Kwf_View_Helper_MailEncodeText();
        return $helper->mailEncodeText($text);
    }

    public function mailLink($mailAddress, $linkText = null, $cssClass = null)
    {
        $helper = new Kwf_View_Helper_MailLink();
        return new Twig_Markup($helper->mailLink($mailAddress, $linkText, $cssClass), 'utf-8');
    }

    public function hiddenOptions($options, $class = 'options')
    {
        $helper = new Kwf_View_Helper_HiddenOptions();
        return new Twig_Markup($helper->hiddenOptions($options, $class), 'utf-8');
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.karan.android"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.READ_CONTACTS" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/Kontacts"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.karan.android.activity.MainActivity"
            android:label="@string/Kontacts" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.karan.android.activity.DetailActivity"
            android:label="@string/title_activity_detail" >
        </activity>
    </application>

</manifest>


text:
@import url("sphinxdoc.css");

@import url("custom.css");


text:
package se.kfm.xml.converters;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;

import org.joda.time.LocalDate;

public class XSDDateToJodaLocalDateMarshaller {

public static LocalDate unmarshal(String xmlGregorianCalendar) {
    return new LocalDate(xmlGregorianCalendar);
}

public static String marshal(LocalDate localDate)  {
   String result = "MARSHALLING_ERROR";
    try {
        result = DatatypeFactory.newInstance().newXMLGregorianCalendar(localDate.toDateTimeAtStartOfDay().toGregorianCalendar()).toXMLFormat();
    } catch (DatatypeConfigurationException e) {
    	throw new RuntimeException(e);
    }
    return result;
}
}


text:
namespace rambler { namespace timestamp {

    String now();

}}


text:
package com.heliosphere.athena.base.command.internal.protocol;

/**
 * Provides a basic behavior for command category type enumerations.
 *

 * @author Christophe Resse
 * @version 1.0.0
 */
public interface ICommandCategoryType
{
	/**
	 * Creates a command category type based on its string representation.
	 *

	 * @param value String representation.
	 * @return Command category type.
	 */
	Enum<? extends ICommandCategoryType> fromString(String value);

	/**
	 * Returns the prefix for the command category.
	 *

	 * @return Command category prefix.
	 */
	String getPrefix();
}


text:
package com.google.dataflow.sample.timeseriesflow.test;

import com.google.dataflow.sample.timeseriesflow.TimeSeriesData.TSAccumSequence;
import com.google.dataflow.sample.timeseriesflow.TimeSeriesData.TSKey;
import com.google.dataflow.sample.timeseriesflow.test.SnapShotUtils.IterableTSAccumSequenceTSKeyDoFn;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.testing.PAssert;
import org.apache.beam.sdk.testing.TestPipeline;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.Reify;
import org.apache.beam.sdk.transforms.windowing.IntervalWindow;
import org.apache.beam.sdk.values.PCollection;
import org.joda.time.Duration;
import org.joda.time.Instant;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class SnapShotScalabilityUtilsTest {

  static ScaleTestingOptions OPTIONS = PipelineOptionsFactory.as(ScaleTestingOptions.class);

  {
    OPTIONS.setAppName("SimpleDataStreamTSDataPoints");
    OPTIONS.setTypeOneComputationsLengthInSecs(1);
    OPTIONS.setTypeTwoComputationsLengthInSecs(3);
    OPTIONS.setOutputTimestepLengthInSecs(3);
    OPTIONS.setNumKeys(1);
    OPTIONS.setNumSecs(3);
    OPTIONS.setNumFeatures(1);
  }

  @Rule public final transient TestPipeline p = TestPipeline.fromOptions(OPTIONS);

  @Test
  public void testSnapShotScalabilityOneKey() {

    PCollection<Iterable<TSAccumSequence>> result = SnapShotUtils.testSnapShotScalability(p);

    PCollection<TSKey> windowKeys = result.apply(ParDo.of(new IterableTSAccumSequenceTSKeyDoFn()));

    windowKeys.apply(Reify.windows()).apply(new Print<>());

    TSKey key =
        TSDataTestUtils.KEY_A_A
            .toBuilder()
            .setMajorKey(TSDataTestUtils.KEY_A_A.getMajorKey().concat("0"))
            .build();

    PAssert.that(windowKeys)
        .inWindow(
            new IntervalWindow(
                Instant.ofEpochMilli(TSDataTestUtils.START - 2000), Duration.standardSeconds(3)))
        .containsInAnyOrder(key)
        .inWindow(
            new IntervalWindow(
                Instant.ofEpochMilli(TSDataTestUtils.START - 1000), Duration.standardSeconds(3)))
        .containsInAnyOrder(key)
        .inWindow(
            new IntervalWindow(
                Instant.ofEpochMilli(TSDataTestUtils.START), Duration.standardSeconds(3)))
        .containsInAnyOrder(key)
        .inWindow(
            new IntervalWindow(
                Instant.ofEpochMilli(TSDataTestUtils.START + 1000), Duration.standardSeconds(3)))
        .containsInAnyOrder(key)
        .inWindow(
            new IntervalWindow(
                Instant.ofEpochMilli(TSDataTestUtils.START + 2000), Duration.standardSeconds(3)))
        .containsInAnyOrder(key);

    p.run();
  }

  @Test
  public void testSnapShotScalabilityThreeKey() {

    p.getOptions().as(ScaleTestingOptions.class).setNumKeys(3);

    PCollection<Iterable<TSAccumSequence>> result = SnapShotUtils.testSnapShotScalability(p);

    PCollection<TSKey> windowKeys = result.apply(ParDo.of(new IterableTSAccumSequenceTSKeyDoFn()));

    TSKey key1 =
        TSDataTestUtils.KEY_A_A
            .toBuilder()
            .setMajorKey(TSDataTestUtils.KEY_A_A.getMajorKey().concat("0"))
            .build();

    TSKey key2 =
        TSDataTestUtils.KEY_A_A
            .toBuilder()
            .setMajorKey(TSDataTestUtils.KEY_A_A.getMajorKey().concat("1"))
            .build();

    TSKey key3 =
        TSDataTestUtils.KEY_A_A
            .toBuilder()
            .setMajorKey(TSDataTestUtils.KEY_A_A.getMajorKey().concat("2"))
            .build();

    PAssert.that(windowKeys)
        .inWindow(
            new IntervalWindow(
                Instant.ofEpochMilli(TSDataTestUtils.START - 2000), Duration.standardSeconds(3)))
        .containsInAnyOrder(key1, key2, key3)
        .inWindow(
            new IntervalWindow(
                Instant.ofEpochMilli(TSDataTestUtils.START - 1000), Duration.standardSeconds(3)))
        .containsInAnyOrder(key1, key2, key3)
        .inWindow(
            new IntervalWindow(
                Instant.ofEpochMilli(TSDataTestUtils.START), Duration.standardSeconds(3)))
        .containsInAnyOrder(key1, key2, key3)
        .inWindow(
            new IntervalWindow(
                Instant.ofEpochMilli(TSDataTestUtils.START + 1000), Duration.standardSeconds(3)))
        .containsInAnyOrder(key1, key2, key3)
        .inWindow(
            new IntervalWindow(
                Instant.ofEpochMilli(TSDataTestUtils.START + 2000), Duration.standardSeconds(3)))
        .containsInAnyOrder(key1, key2, key3);

    p.run();
  }
}


text:
/********************************************************************************/
/*                                                                              */
/*                              TPM Types                                       */
/*                           Written by Ken Goldman                             */
/*                     IBM Thomas J. Watson Research Center                     */
/*            $Id: tpm_types.h 4702 2013-01-03 21:26:29Z kgoldman $             */
/*                                                                              */
/* (c) Copyright IBM Corporation 2006, 2010.					*/
/*										*/
/* All rights reserved.								*/
/* 										*/
/* Redistribution and use in source and binary forms, with or without		*/
/* modification, are permitted provided that the following conditions are	*/
/* met:										*/
/* 										*/
/* Redistributions of source code must retain the above copyright notice,	*/
/* this list of conditions and the following disclaimer.			*/
/* 										*/
/* Redistributions in binary form must reproduce the above copyright		*/
/* notice, this list of conditions and the following disclaimer in the		*/
/* documentation and/or other materials provided with the distribution.		*/
/* 										*/
/* Neither the names of the IBM Corporation nor the names of its		*/
/* contributors may be used to endorse or promote products derived from		*/
/* this software without specific prior written permission.			*/
/* 										*/
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS		*/
/* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT		*/
/* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR	*/
/* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT		*/
/* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,	*/
/* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT		*/
/* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,	*/
/* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY	*/
/* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT		*/
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE	*/
/* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.		*/
/********************************************************************************/

#ifndef TPM_TYPES_H
#define TPM_TYPES_H

#include <stdint.h>

#ifdef TPM_WINDOWS
#include <windows.h>
#endif
#if defined (TPM_POSIX) || defined (TPM_SYSTEM_P)
#include <netinet/in.h>         /* for byte order conversions */
#endif

/* 2.2.1 Basic data types rev 87 */
typedef unsigned char  BYTE;            /* Basic byte used to transmit all character fields.  */
typedef unsigned char  TPM_BOOL;        /* TRUE/FALSE field. TRUE = 0x01, FALSE = 0x00 Use TPM_BOOL
                                           because MS VC++ defines BOOL on Windows */

/* 2.2.2 Boolean types rev 107 */

#undef TRUE
#define TRUE   0x01  /* Assertion   */
#undef FALSE
#define FALSE  0x00  /* Contradiction   */

/* 2.2.3 Helper redefinitions rev 101

   The following definitions are to make the definitions more explicit and easier to read.

   NOTE: They cannot be changed without breaking the serialization.
*/

typedef BYTE  TPM_AUTH_DATA_USAGE;      /* Indicates the conditions where it is required that
                                           authorization be presented.  */
typedef BYTE  TPM_PAYLOAD_TYPE;         /* The information as to what the payload is in an encrypted
                                           structure */
typedef BYTE  TPM_VERSION_BYTE;         /* The version info breakdown */
typedef BYTE  TPM_DA_STATE;             /* The state of the dictionary attack mitigation logic */

/* added kgold */
typedef BYTE  TPM_ENT_TYPE;             /* LSB of TPM_ENTITY_TYPE */
typedef BYTE  TPM_ADIP_ENC_SCHEME;      /* MSB of TPM_ENTITY_TYPE */

typedef uint16_t  TPM_PROTOCOL_ID;	/* The protocol in use.  */
typedef uint16_t  TPM_STARTUP_TYPE;	/* Indicates the start state.  */
typedef uint16_t  TPM_ENC_SCHEME;	/* The definition of the encryption scheme. */
typedef uint16_t  TPM_SIG_SCHEME;	/* The definition of the signature scheme. */
typedef uint16_t  TPM_MIGRATE_SCHEME;	/* The definition of the migration scheme */
typedef uint16_t  TPM_PHYSICAL_PRESENCE; /* Sets the state of the physical presence mechanism. */
typedef uint16_t  TPM_ENTITY_TYPE;	/* Indicates the types of entity that are supported by the
                                           TPM. */
typedef uint16_t  TPM_KEY_USAGE;	/* Indicates the permitted usage of the key.  */
typedef uint16_t  TPM_EK_TYPE;		/* The type of asymmetric encrypted structure in use by the
                                           endorsement key  */
typedef uint16_t  TPM_STRUCTURE_TAG;	/* The tag for the structure */
typedef uint16_t  TPM_PLATFORM_SPECIFIC; /* The platform specific spec to which the information
                                           relates to */
typedef uint32_t  TPM_COMMAND_CODE;	/* The command ordinal. */
typedef uint32_t  TPM_CAPABILITY_AREA;	/* Identifies a TPM capability area. */
typedef uint32_t  TPM_KEY_FLAGS;	/* Indicates information regarding a key. */
typedef uint32_t  TPM_ALGORITHM_ID;	/* Indicates the type of algorithm.  */
typedef uint32_t  TPM_MODIFIER_INDICATOR; /* The locality modifier  */
typedef uint32_t  TPM_ACTUAL_COUNT;	/* The actual number of a counter.  */
typedef uint32_t  TPM_TRANSPORT_ATTRIBUTES;	/* Attributes that define what options are in use
                                                   for a transport session */
typedef uint32_t  TPM_AUTHHANDLE;	/* Handle to an authorization session  */
typedef uint32_t  TPM_DIRINDEX;		/* Index to a DIR register  */
typedef uint32_t  TPM_KEY_HANDLE;	/* The area where a key is held assigned by the TPM.  */
typedef uint32_t  TPM_PCRINDEX;		/* Index to a PCR register  */
typedef uint32_t  TPM_RESULT;		/* The return code from a function  */
typedef uint32_t  TPM_RESOURCE_TYPE;	/* The types of resources that a TPM may have using internal
                                           resources */
typedef uint32_t  TPM_KEY_CONTROL;	/* Allows for controlling of the key when loaded and how to
                                           handle TPM_Startup issues  */
typedef uint32_t  TPM_NV_INDEX;		/* The index into the NV storage area  */
typedef uint32_t  TPM_FAMILY_ID;	/* The family ID. Families ID's are automatically assigned a
                                           sequence number by the TPM. A trusted process can set the
                                           FamilyID value in an individual row to zero, which
                                           invalidates that row. The family ID resets to zero on
                                           each change of TPM Owner.  */
typedef uint32_t  TPM_FAMILY_VERIFICATION;	/* A value used as a label for the most recent
						   verification of this family. Set to zero when not
						   in use.  */
typedef uint32_t  TPM_STARTUP_EFFECTS;	/* How the TPM handles var  */
typedef uint32_t  TPM_SYM_MODE;		/* The mode of a symmetric encryption  */
typedef uint32_t  TPM_FAMILY_FLAGS;	/* The family flags  */
typedef uint32_t  TPM_DELEGATE_INDEX;	/* The index value for the delegate NV table  */
typedef uint32_t  TPM_CMK_DELEGATE;	/* The restrictions placed on delegation of CMK
                                           commands */
typedef uint32_t  TPM_COUNT_ID;		/* The ID value of a monotonic counter  */
typedef uint32_t  TPM_REDIT_COMMAND;	/* A command to execute  */
typedef uint32_t  TPM_TRANSHANDLE;	/* A transport session handle  */
typedef uint32_t  TPM_HANDLE;		/* A generic handle could be key, transport etc.  */
typedef uint32_t  TPM_FAMILY_OPERATION;	/* What operation is happening  */

/* Not in specification */

typedef uint16_t  TPM_TAG;		/* The command and response tags */

typedef unsigned char *	TPM_SYMMETRIC_KEY_TOKEN;	/* abstract symmetric key token */
typedef unsigned char *	TPM_BIGNUM;			/* abstract bignum */

#endif


text:
using System;
using System.Collections.Generic;
using System.Reflection;

namespace Swank.Description
{
    public interface IApiParameterDescription
    {
        string Name { get; }
        string Documentation { get; }
        object DefaultValue { get; }
        Type Type { get; }
        bool IsOptional { get; }
        bool IsUrlParameter { get; }
        bool IsQuerystring { get; }
        MethodInfo ActionMethod { get; }

        T GetAttribute<T>() where T : Attribute;
        IEnumerable<T> GetAttributes<T>() where T : Attribute;
        bool HasAttribute<T>() where T : Attribute;
    }
}


text:
package com.pointr.tensorflow.api;

public class PcieDMAClient extends DMAClientBase implements TensorFlowIf.DMAClient {

  public PcieDMAClient() {
    String parentDir = System.getenv("GITDIR") + "/tfdma";
    String ext = System.getProperty("os.name").equals("Mac OS X") ? ".dylib" : ".so";
    String libpath = String.format("%s/%s%s",parentDir,"src/main/cpp/dmaclient",ext);
    Logger.info("Loading DMA native library " + libpath + " ..");
    try {
      System.load(libpath);
    } catch(Exception e) {
      Logger.error("Unable to load native library %s: %s".format( libpath, e.getMessage()),e);
    }

  }

  @Override
  public String setupChannel(String setupJson) {
    super.setupChannel(setupJson);
    return setupChannelN(setupJson);
  }

  @Override
  public String prepareWrite(String configJson) {

    super.prepareWrite(configJson);
    return prepareWriteN(configJson);
  }

  @Override
  public DMAStructures.WriteResultStruct write(String configJson, byte[] data, byte[] md5) {

    super.write(configJson, data, md5);
    return writeN(configJson, data, md5);
  }

  @Override
  public DMAStructures.WriteResultStruct completeWrite(String configJson) {

    super.completeWrite(configJson);
    return completeWriteN(configJson);
  }

  @Override
  public String prepareRead(String configJson) {

    super.prepareRead(configJson);
    return prepareReadN(configJson);
  }

  @Override
  public DMAStructures.ReadResultStruct read(String configJson) {
    super.read(configJson);
    return readN(configJson);
  }

  @Override
  public String completeRead(String configJson) {
    super.completeRead(configJson);
    return completeReadN(configJson);
  }

  @Override
  public String shutdownChannel(String shutdownJson) {
    super.shutdownChannel(shutdownJson);
    return shutdownChannelN(shutdownJson);
  }

  @Override
  public byte[] readLocal(byte[] dataptr) {
    super.readLocal(dataptr);
    return readLocalN(dataptr);
  }

  native String setupChannelN(String setupJson);
  native String prepareWriteN(String configJson);
  native DMAStructures.WriteResultStruct writeN(String configJson, byte[] data, byte[] md5);
  native DMAStructures.WriteResultStruct completeWriteN(String configJson);
  native String prepareReadN(String configJson);
  native DMAStructures.ReadResultStruct readN(String configJson);
  native String completeReadN(String setupJson);
  native String shutdownChannelN(String shutdownJson);
  native byte[] readLocalN(byte[] dataptr);
}


text:
using System;
using System.Runtime.InteropServices;

namespace SharpVk.NVidia
{
    /// <summary>
    ///
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    public partial struct CoarseSampleOrderCustom
    {
        /// <summary>
        ///
        /// </summary>
        public SharpVk.NVidia.ShadingRatePaletteEntry ShadingRate
        {
            get;
            set;
        }

        /// <summary>
        ///
        /// </summary>
        public uint SampleCount
        {
            get;
            set;
        }

        /// <summary>
        ///
        /// </summary>
        public SharpVk.NVidia.CoarseSampleLocation[] SampleLocations
        {
            get;
            set;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="pointer">
        /// </param>
        internal unsafe void MarshalTo(SharpVk.Interop.NVidia.CoarseSampleOrderCustom* pointer)
        {
            pointer->ShadingRate = this.ShadingRate;
            pointer->SampleCount = this.SampleCount;
            pointer->SampleLocationCount = (uint)(Interop.HeapUtil.GetLength(this.SampleLocations));
            if (this.SampleLocations != null)
            {
                var fieldPointer = (SharpVk.NVidia.CoarseSampleLocation*)(Interop.HeapUtil.AllocateAndClear<SharpVk.NVidia.CoarseSampleLocation>(this.SampleLocations.Length).ToPointer());
                for(int index = 0; index < (uint)(this.SampleLocations.Length); index++)
                {
                    fieldPointer[index] = this.SampleLocations[index];
                }
                pointer->SampleLocations = fieldPointer;
            }
            else
            {
                pointer->SampleLocations = null;
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="pointer">
        /// </param>
        internal static unsafe CoarseSampleOrderCustom MarshalFrom(SharpVk.Interop.NVidia.CoarseSampleOrderCustom* pointer)
        {
            CoarseSampleOrderCustom result = default(CoarseSampleOrderCustom);
            result.ShadingRate = pointer->ShadingRate;
            result.SampleCount = pointer->SampleCount;
            if (pointer->SampleLocations != null)
            {
                var fieldPointer = new SharpVk.NVidia.CoarseSampleLocation[(uint)(pointer->SampleLocationCount)];
                for(int index = 0; index < (uint)(pointer->SampleLocationCount); index++)
                {
                    fieldPointer[index] = pointer->SampleLocations[index];
                }
                result.SampleLocations = fieldPointer;
            }
            else
            {
                result.SampleLocations = null;
            }
            return result;
        }
    }
}


text:
declare module "mdns-js" {
  import { EventEmitter } from "events";

  export interface Browser extends EventEmitter {
    start: () => void;
    stop: () => void;
    discover: () => void;
  }

  export function createBrowser(Item: string): Browser;
  export function tcp(name: string): string;
}