text:
/*****************************************************************************/
/*                                    XDMF                                   */
/*                       eXtensible Data Model and Format                    */
/*                                                                           */
/*  Id : XdmfFunction.cpp                                                    */
/*                                                                           */
/*  Author:                                                                  */
/*     Andrew Burns                                                          */
/*     andrew.j.burns2@us.army.mil                                           */
/*     US Army Research Laboratory                                           */
/*     Aberdeen Proving Ground, MD                                           */
/*                                                                           */
/*     Copyright @ 2013 US Army Research Laboratory                          */
/*     All Rights Reserved                                                   */
/*     See Copyright.txt for details                                         */
/*                                                                           */
/*     This software is distributed WITHOUT ANY WARRANTY; without            */
/*     even the implied warranty of MERCHANTABILITY or FITNESS               */
/*     FOR A PARTICULAR PURPOSE.  See the above copyright notice             */
/*     for more information.                                                 */
/*                                                                           */
/*****************************************************************************/

#include "XdmfArray.hpp"
#include "XdmfArrayType.hpp"
#include "XdmfFunction.hpp"
#include <stack>
#include <cmath>
#include <boost/assign.hpp>
#include "XdmfError.hpp"

class XdmfFunctionInternalImpl : public XdmfFunction::XdmfFunctionInternal {
  public:
    static shared_ptr<XdmfFunctionInternalImpl>
    New(shared_ptr<XdmfArray> (*newInternal)(std::vector<shared_ptr<XdmfArray> >))
    {
      shared_ptr<XdmfFunctionInternalImpl> p (new XdmfFunctionInternalImpl(newInternal));
      return p;
    }

    ~XdmfFunctionInternalImpl()
    {
    }

    virtual shared_ptr<XdmfArray> execute(std::vector<shared_ptr<XdmfArray> > valueVector)
    {
      return (*mInternalFunction)(valueVector);
    }
  private:
    XdmfFunctionInternalImpl(shared_ptr<XdmfArray> (*newInternal)(std::vector<shared_ptr<XdmfArray> >))
    {
      mInternalFunction = newInternal;
    }

    shared_ptr<XdmfArray> (*mInternalFunction)(std::vector<shared_ptr<XdmfArray> >);
};

class XdmfOperationInternalImpl : public XdmfFunction::XdmfOperationInternal {
  public:
    static shared_ptr<XdmfOperationInternalImpl>
    New(shared_ptr<XdmfArray> (*newInternal)(shared_ptr<XdmfArray>, shared_ptr<XdmfArray>))
    {
      shared_ptr<XdmfOperationInternalImpl> p (new XdmfOperationInternalImpl(newInternal));
      return p;
    }

    ~XdmfOperationInternalImpl()
    {
    }

    virtual shared_ptr<XdmfArray> execute(shared_ptr<XdmfArray> val1,
                                          shared_ptr<XdmfArray> val2)
    {
      return (*mInternalOperation)(val1, val2);
    }
  private:
    XdmfOperationInternalImpl(shared_ptr<XdmfArray> (*newInternal)(shared_ptr<XdmfArray>,
                                                                   shared_ptr<XdmfArray>))
    {
      mInternalOperation = newInternal;
    }

    shared_ptr<XdmfArray> (*mInternalOperation)(shared_ptr<XdmfArray>, shared_ptr<XdmfArray>);
};

std::string XdmfFunction::mSupportedOperations = "-+/*|#()";
const std::string XdmfFunction::mValidVariableChars =
  "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_:.";
const std::string XdmfFunction::mValidDigitChars = "1234567890.";
// List the priorities for the operations, based on the order of operations
// The index of the corresponding operation in validOperationChars
// is the same as the index of its priority in this array
std::map<char, int> XdmfFunction::mOperationPriority =
	boost::assign::map_list_of ('-', 4)
                                   ('+', 4)
                                   ('/', 3)
                                   ('*', 3)
                                   ('|', 2)
                                   ('#', 1)
                                   ('(', 0)
                                   (')', 0);
// The higher the value, the earlier the operation is
// evaluated in the order of operations
// With the exception of parenthesis which are evaluated
// as soon as the closing parenthesis is found

// Note, it doesn't handle overloaded functions well.
// Will generate errors unless overload methods are typecast.
std::map<std::string, shared_ptr<XdmfFunction::XdmfFunctionInternal> >
  XdmfFunction::arrayFunctions =
    boost::assign::map_list_of
      ("ABS", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
                                            XdmfFunction::abs))
      ("ABS_TOKEN", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
                                            XdmfFunction::abs))
      ("ACOS", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
                                            XdmfFunction::arccos))
      ("ASIN", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
                                            XdmfFunction::arcsin))
      ("ATAN", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
                                            XdmfFunction::arctan))
      ("AVE", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
                                            XdmfFunction::average))
      ("COS", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
                                            XdmfFunction::cos))
      ("EXP", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
                                            XdmfFunction::exponent))
      ("JOIN", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
                                            XdmfFunction::join))
      ("LOG", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
                                            XdmfFunction::log))
      ("SIN", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
                                            XdmfFunction::sin))
      ("SQRT", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
                                            XdmfFunction::sqrt))
      ("SUM", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
                                            XdmfFunction::sum))
      ("TAN", XdmfFunctionInternalImpl::New((shared_ptr<XdmfArray> (*)(std::vector<shared_ptr<XdmfArray> >))
                                            XdmfFunction::tan));

std::map<char, shared_ptr<XdmfFunction::XdmfOperationInternal> >
  XdmfFunction::operations =
    boost::assign::map_list_of
      ('-', XdmfOperationInternalImpl::New(XdmfFunction::subtraction))
      ('+', XdmfOperationInternalImpl::New(XdmfFunction::addition))
      ('*', XdmfOperationInternalImpl::New(XdmfFunction::multiplication))
      ('/', XdmfOperationInternalImpl::New(XdmfFunction::division))
      ('|', XdmfOperationInternalImpl::New(XdmfFunction::chunk))
      ('#', XdmfOperationInternalImpl::New(XdmfFunction::interlace));

shared_ptr<XdmfFunction>
XdmfFunction::New()
{
  shared_ptr<XdmfFunction> p(new XdmfFunction());
  return p;
}

shared_ptr<XdmfFunction>
XdmfFunction::New(std::string newExpression,
                  std::map<std::string, shared_ptr<XdmfArray> > newVariables)
{
  shared_ptr<XdmfFunction> p(new XdmfFunction(newExpression, newVariables));
  return p;
}

XdmfFunction::XdmfFunction():
  mExpression("")
{
}

XdmfFunction::XdmfFunction(std::string newExpression,
                           std::map<std::string, shared_ptr<XdmfArray> > newVariables):
  mVariableList(newVariables),
  mExpression(newExpression)
{
}

XdmfFunction::~XdmfFunction()
{
}

const std::string XdmfFunction::ItemTag = "Function";

shared_ptr<XdmfArray>
XdmfFunction::abs(std::vector<shared_ptr<XdmfArray> > values)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  // Only working with the first array provided
  if (values.size() < 1) {
    XdmfError::message(XdmfError::FATAL,
                       "Error: No Array Passed to Function abs");
  }
  bool release = false;
  if (!values[0]->isInitialized()) {
    values[0]->read();
    release = true;
  }
  for (unsigned int i = 0; i < values[0]->getSize(); ++i) {
    returnArray->pushBack(std::abs(values[0]->getValue<double>(i)));
  }
  if (release) {
    values[0]->release();
  }
  return returnArray;
}

int
XdmfFunction::addFunction(std::string name,
                          shared_ptr<XdmfArray>(*functionref)(std::vector<shared_ptr<XdmfArray> >))
{
  shared_ptr<XdmfFunctionInternalImpl> newFunction =
     XdmfFunctionInternalImpl::New(functionref);
  return XdmfFunction::addFunction(name, newFunction);
}

int
XdmfFunction::addFunction(std::string name,
                          shared_ptr<XdmfFunctionInternal> newFunction)
{
  // Check to ensure that the name has valid characters
  for (unsigned int i = 0; i < name.size(); ++i) {
    // If the character is not found in the list of valid characters
    if (mValidVariableChars.find(name[i]) == std::string::npos) {
      // Then throw an error
      XdmfError::message(XdmfError::FATAL,
                         "Error: Function Name Contains Invalid Character(s)");
    }
  }
  size_t origsize = arrayFunctions.size();
  arrayFunctions[name] = newFunction;
  // If no new functions were added
  if (origsize == arrayFunctions.size()) {
    // Toss a warning, it's nice to let people know that they're doing this
    XdmfError::message(XdmfError::WARNING,
                       "Warning: Function Overwritten");
  }
  return arrayFunctions.size();
}

int
XdmfFunction::addOperation(char newoperator,
                           shared_ptr<XdmfArray>(*operationref)(shared_ptr<XdmfArray>,
                                                                shared_ptr<XdmfArray>),
                           int priority)
{
  shared_ptr<XdmfOperationInternalImpl> newOperation =
     XdmfOperationInternalImpl::New(operationref);
  return XdmfFunction::addOperation(newoperator,
                                    newOperation,
                                    priority);
}

int
XdmfFunction::addOperation(char newoperator,
                           shared_ptr<XdmfOperationInternal> newOperation,
                           int priority)
{
  if (newoperator == '(' || newoperator == ')') {
    XdmfError::message(XdmfError::FATAL,
                       "Error: Parenthesis can not be redefined");
  }
  if (mValidVariableChars.find(newoperator) != std::string::npos
      || mValidDigitChars.find(newoperator) != std::string::npos) {
    XdmfError::message(XdmfError::FATAL,
                       "Error: Operation Overlaps with Variables");
  }
  // Give warning if the operation already exists
  size_t origsize = operations.size();
  // Place reference in the associated location
  operations[newoperator] = newOperation;
  if (origsize == operations.size()) {
    // It's nice to let people know they're doing this
    // So they don't get surprised about changes in behavior
    XdmfError::message(XdmfError::WARNING,
                       "Warning: Operation Overwritten");
    // Overwrite the existing info for that operation
    // Add the priority to the specified location in the priority array
    mOperationPriority[newoperator] = priority;
  }
  else {
    // Create new operation
    // Add operation to the supported character string
    mSupportedOperations.push_back(newoperator);
    mOperationPriority[newoperator] = priority;
  }
  return operations.size();
}

shared_ptr<XdmfArray>
XdmfFunction::addition(shared_ptr<XdmfArray> val1, shared_ptr<XdmfArray> val2)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  bool release1 = false;
  bool release2 = false;
  if (!val1->isInitialized()) {
    val1->read();
    release1 = true;
  }
  if (!val2->isInitialized()) {
    val2->read();
    release2 = true;
  }
  for (unsigned int i = 0; i < val1->getSize() || i < val2->getSize(); ++i) {
    if (val1->getSize() == val2->getSize()) {
      returnArray->pushBack(val1->getValue<double>(i) + val2->getValue<double>(i));
    }
    else if (val1->getSize() == 1) {
      returnArray->pushBack(val1->getValue<double>(0) + val2->getValue<double>(i));
    }
    else if (val2->getSize() == 1) {
      returnArray->pushBack(val1->getValue<double>(i) + val2->getValue<double>(0));
    }
    else {
      XdmfError::message(XdmfError::FATAL,
                         "Error: Array Size Mismatch in Function addition");
    }
  }
  if (release1) {
    val1->release();
  }
  if (release2) {
    val2->release();
  }
  return returnArray;
}

shared_ptr<XdmfArray>
XdmfFunction::arcsin(std::vector<shared_ptr<XdmfArray> > values)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  // Only working with the first array provided
  if (values.size() < 1) {
    XdmfError::message(XdmfError::FATAL,
                       "Error: No Array Passed to Function arcsin");
  }
  bool release = false;
  if (!values[0]->isInitialized()) {
    values[0]->read();
    release = true;
  }
  for (unsigned int i = 0; i < values[0]->getSize(); ++i) {
    returnArray->pushBack(asin(values[0]->getValue<double>(i)));
  }
  if (release) {
    values[0]->release();
  }
  return returnArray;
}

shared_ptr<XdmfArray>
XdmfFunction::arccos(std::vector<shared_ptr<XdmfArray> > values)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  // Only working with the first array provided
  if (values.size() < 1) {
    XdmfError::message(XdmfError::FATAL,
                       "Error: No Array Passed to Function arccos");
  }
  bool release = false;
  if (!values[0]->isInitialized()) {
    values[0]->read();
    release = true;
  }
  for (unsigned int i = 0; i < values[0]->getSize(); ++i) {
    returnArray->pushBack(acos(values[0]->getValue<double>(i)));
  }
  if (release) {
    values[0]->release();
  }
  return returnArray;
}

shared_ptr<XdmfArray>
XdmfFunction::arctan(std::vector<shared_ptr<XdmfArray> > values)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  // Only working with the first array provided
  if (values.size() < 1) {
    XdmfError::message(XdmfError::FATAL,
                       "Error: No Array Passed to Function arctan");
  }
  bool release = false;
  if (!values[0]->isInitialized()) {
    values[0]->read();
    release = true;
  }
  for (unsigned int i = 0; i < values[0]->getSize(); ++i) {
    returnArray->pushBack(atan(values[0]->getValue<double>(i)));
  }
  if (release) {
    values[0]->release();
  }
  return returnArray;
}

shared_ptr<XdmfArray>
XdmfFunction::average(std::vector<shared_ptr<XdmfArray> > values)
{
  double total = sum(values)->getValue<double>(0);;
  int totalSize = 0;
  for (unsigned int i = 0; i < values.size(); ++i)
  {
    totalSize += values[i]->getSize();
  }
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  returnArray->insert(0, total/totalSize);
  return returnArray;
}

shared_ptr<XdmfArray>
XdmfFunction::cos(std::vector<shared_ptr<XdmfArray> > values)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  // Only working with the first array provided
  if (values.size() < 1) {
    XdmfError::message(XdmfError::FATAL,
                       "Error: No Array Passed to Function cos");
  }
  bool release = false;
  if (!values[0]->isInitialized()) {
    values[0]->read();
    release = true;
  }
  for (unsigned int i = 0; i < values[0]->getSize(); ++i) {
    returnArray->pushBack(std::cos(values[0]->getValue<double>(i)));
  }
  if (release) {
    values[0]->release();
  }
  return returnArray;
}

shared_ptr<XdmfArray>
XdmfFunction::chunk(shared_ptr<XdmfArray> val1, shared_ptr<XdmfArray> val2)
{
  // Join chunk (add the new array to the end of the first one)
  // Joins into new array and returns it
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  // Determining what type to class it as in order to not lose data
  // and to still have the smallest data type of the two
  shared_ptr<const XdmfArrayType> resultType =
    XdmfArrayType::comparePrecision(val1->getArrayType(),
                                    val2->getArrayType());
  bool release1 = false;
  bool release2 = false;
  if (!val1->isInitialized()) {
    val1->read();
    release1 = true;
  }
  if (!val2->isInitialized()) {
    val2->read();
    release2 = true;
  }
  if (resultType == XdmfArrayType::Int8()) {
    char sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::Int16()) {
    short sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::Int32()) {
    int sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::Int64()) {
    long sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::UInt8()) {
    unsigned char sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::UInt16()) {
    unsigned short sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::UInt32()) {
    unsigned int sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::Float32()) {
    float sampleValue = 0.0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::Float64()) {
    double sampleValue = 0.0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::String()) {
    std::string sampleValue = "";
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else {
    // error type not supported
    XdmfError::message(XdmfError::FATAL, "Invalid type during Chunk");
  }
  returnArray->insert(0, val1, 0, val1->getSize(),  1, 1);
  returnArray->insert(val1->getSize(), val2, 0, val2->getSize(), 1, 1);
  if (release1) {
    val1->release();
  }
  if (release2) {
    val2->release();
  }
  return returnArray;
}

shared_ptr<XdmfArray>
XdmfFunction::exponent(std::vector<shared_ptr<XdmfArray> > values)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  // Only working with the first array provided
  if (values.size() < 2) {
    XdmfError::message(XdmfError::FATAL,
                       "Error: Two Arrays Needed for Function exponent");
  }
  bool release1 = false;
  bool release2 = false;
  if (!values[0]->isInitialized()) {
    values[0]->read();
    release1 = true;
  }
  if (!values[1]->isInitialized()) {
    values[1]->read();
    release2 = true;
  }
  for (unsigned int i = 0; i < values[0]->getSize() || i < values[1]->getSize(); ++i) {
    if (values[0]->getSize() == values[1]->getSize()) {
      returnArray->pushBack(std::pow(values[0]->getValue<double>(i), values[1]->getValue<double>(i)));
    }
    else if (values[0]->getSize() == 1) {
      returnArray->pushBack(std::pow(values[0]->getValue<double>(0), values[1]->getValue<double>(i)));
    }
    else if (values[1]->getSize() == 1) {
      returnArray->pushBack(std::pow(values[0]->getValue<double>(i), values[1]->getValue<double>(0)));
    }
    else {
      XdmfError::message(XdmfError::FATAL,
                         "Error: Array Size Mismatch in Function exponent");
    }
  }
  if (release1) {
    values[0]->release();
  }
  if (release2) {
    values[1]->release();
  }
  return returnArray;
}

shared_ptr<XdmfArray>
XdmfFunction::division(shared_ptr<XdmfArray> val1, shared_ptr<XdmfArray> val2)
{
  bool release1 = false;
  bool release2 = false;
  if (!val1->isInitialized()) {
    val1->read();
    release1 = true;
  }
  if (!val2->isInitialized()) {
    val2->read();
    release2 = true;
  }
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  for (unsigned int i = 0; i < val1->getSize() || i < val2->getSize(); ++i) {
    if (val1->getSize() == val2->getSize()) {
      returnArray->pushBack(val1->getValue<double>(i) / val2->getValue<double>(i));
    }
    else if (val1->getSize() == 1) {
      returnArray->pushBack(val1->getValue<double>(0) / val2->getValue<double>(i));
    }
    else if (val2->getSize() == 1) {
      returnArray->pushBack(val1->getValue<double>(i) / val2->getValue<double>(0));
    }
    else {
      XdmfError::message(XdmfError::FATAL,
                         "Error: Array Size Mismatch in Function division");
    }
  }
  if (release1) {
    val1->release();
  }
  if (release2) {
    val2->release();
  }
  return returnArray;
}

shared_ptr<XdmfArray>
XdmfFunction::evaluateExpression(std::string expression,
                                 std::map<std::string,
                                   shared_ptr<XdmfArray> > variables)
{
  std::stack<shared_ptr<XdmfArray> > valueStack;
  std::stack<char> operationStack;

  // String is parsed left to right
  // Elements of the same priority are evaluated right to left
  for (unsigned int i = 0; i < expression.size(); ++i) {
    bool hyphenIsDigit = false;
    // hyphen is a special case since it can be used to annotate negative numbers
    if (expression[i] == '-') {
      if (i == 0) {
        //would have to be a digit, otherwise it would be a unpaired operation
        hyphenIsDigit = true;
      }
      else if (mValidDigitChars.find(expression[i+1]) != std::string::npos) {
        // If value after is a valid digit,
        // check value before
        // If a digit, it's an operation
        // If a variable, it's an operation
        // If an operation, it's a digit character
        if (mSupportedOperations.find(expression[i-1]) != std::string::npos) {
          hyphenIsDigit = true;
        }
        else if (expression[i-1] <= ' ') {
          // If whitespace is in front of the hyphen it is presumed to be a negative sign
          // This is to handle passing negative values to functions properly
          hyphenIsDigit = true;
        }
      }
    }
    // Found to be a digit
    if (mValidDigitChars.find(expression[i]) != std::string::npos ||
        (expression[i] == '-' && hyphenIsDigit)) {
      // Progress until a non-digit is found
      int valueStart = i;
      if (i + 1 < expression.size()) {
        while (mValidDigitChars.find(expression[i+1]) != std::string::npos) {
          i++;
        }
      }
      // Push back to the value stack
      shared_ptr<XdmfArray> valueArray = XdmfArray::New();
      // Use this to convert to double
      valueArray->insert(0, atof(expression.substr(valueStart, i + 1 - valueStart).c_str()));
      valueStack.push(valueArray);
    }
    else if (mValidVariableChars.find(expression[i]) != std::string::npos) {
      // Found to be a variable
      int valueStart = i;
      // Progress until a nonvariable value is found
      if (i+1 < expression.size()){
        while (mValidVariableChars.find(expression[i+1]) != std::string::npos) {
          i++;
        }
      }
      // Convert to equivalent
      if (variables.find(expression.substr(valueStart, i + 1 - valueStart))
          == variables.end()) {
        if (arrayFunctions.find(expression.substr(valueStart, i + 1 - valueStart))
            == arrayFunctions.end()) {
          XdmfError::message(XdmfError::FATAL,
                             "Error: Invalid Variable in evaluateExpression "
                             + expression.substr(valueStart, i + 1 - valueStart));
        }
        else {
          std::string currentFunction =
            expression.substr(valueStart, i + 1 - valueStart);
          // Check if next character is an open parenthesis
          if (i+1 >= expression.size()) {
            if (expression[i+1] != '(') {
              XdmfError::message(XdmfError::FATAL,
                                 "Error: No values supplied to function "
                                 + expression.substr(valueStart, i + 1 - valueStart));
            }
          }
          // If it is grab the string between paranthesis

          if (i + 2 >= expression.size()) {
            XdmfError::message(XdmfError::FATAL,
                               "Error: Missing closing parethesis to function "
                               + expression.substr(valueStart, i + 1 - valueStart));
          }
          i = i + 2;
          valueStart = i;
          int numOpenParenthesis = 0;
          while ((expression[i] != ')' || numOpenParenthesis) && i < expression.size()) {
            if (expression[i] == '(') {
              numOpenParenthesis++;
            }
            else if (expression[i] == ')') {
              numOpenParenthesis--;
            }
            i++;
          }
          std::string functionParameters = expression.substr(valueStart, i - valueStart);
          std::vector<shared_ptr<XdmfArray> > parameterVector;
          // Split that string at commas
          size_t parameterSplit = 0;
          while (parameterSplit != std::string::npos) {
            parameterSplit = 0;
            parameterSplit = functionParameters.find_first_of(",", parameterSplit);
            // Feed the substrings to the parse function
            if (parameterSplit == std::string::npos) {
              parameterVector.push_back(evaluateExpression(functionParameters, variables));
            }
            else {
              parameterVector.push_back(
                evaluateExpression(functionParameters.substr(0, parameterSplit),
                                   variables));
              functionParameters = functionParameters.substr(parameterSplit+1);
            }
          }
          valueStack.push(evaluateFunction(parameterVector, currentFunction));
        }
      }
      else {
        // Push equivalent to value stack
        valueStack.push(variables.find(expression.substr(valueStart, i + 1 - valueStart))->second);
      }
    }
    else if (mSupportedOperations.find(expression[i]) != std::string::npos) {
      // Found to be an operation
      // Pop operations off the stack until one of a lower or equal importance is found
      if (operationStack.size() > 0) {
        if (expression[i] == ')') {
          // To close a parenthesis pop off all operations until another parentheis is found
          while (operationStack.size() > 0 && operationStack.top() != '(') {
            // Must be at least two values for this loop to work properly
            if (valueStack.size() < 2) {
              XdmfError::message(XdmfError::FATAL,
                                 "Error: Not Enough Values in evaluateExpression");
            }
            else {
              shared_ptr<XdmfArray> val2 = valueStack.top();
              valueStack.pop();
              shared_ptr<XdmfArray> val1 = valueStack.top();
              valueStack.pop();
              valueStack.push(evaluateOperation(val1, val2, operationStack.top()));
              operationStack.pop();
            }
          }
          operationStack.pop();
        }
        else if (expression[i] == '(') {
          // Just add it if it's a start parenthesis
          // Nothing happens here in that case
          // Addition happens after the if statement
        }
        else {
          int operationLocation = getOperationPriority(expression[i]);
          int topOperationLocation = getOperationPriority(operationStack.top());
          // See order of operations to determine importance
          while (operationStack.size() > 0 && operationLocation < topOperationLocation) {
            // Must be at least two values for this loop to work properly
            if (valueStack.size() < 2) {
              XdmfError::message(XdmfError::FATAL,
                                 "Error: Not Enough Values in evaluateExpression");
            }
            else {
              shared_ptr<XdmfArray> val2 = valueStack.top();
              valueStack.pop();
              shared_ptr<XdmfArray> val1 = valueStack.top();
              valueStack.pop();
              valueStack.push(evaluateOperation(val1, val2, operationStack.top()));
              operationStack.pop();
              if (operationStack.size() == 0) {
                break;
              }
              topOperationLocation = getOperationPriority(operationStack.top());
            }
          }
        }
      }
      if (expression[i] != ')') {
        // Add the operation to the operation stack
        operationStack.push(expression[i]);
      }
    }
    // If not a value or operation the character is ignored
  }

  // Empty what's left in the stacks before finishing
  while (valueStack.size() > 1 && operationStack.size() > 0) {
    if (valueStack.size() < 2) {
      // Must be at least two values for this loop to work properly
      XdmfError::message(XdmfError::FATAL,
                         "Error: Not Enough Values in evaluateExpression");
    }
    else {
      if(operationStack.top() == '(') {
        XdmfError::message(XdmfError::WARNING,
                           "Warning: Unpaired Parenthesis");
      }
      else {
        shared_ptr<XdmfArray> val2 = valueStack.top();
        valueStack.pop();
        shared_ptr<XdmfArray> val1 = valueStack.top();
        valueStack.pop();
        if (operationStack.size() == 0) {
          XdmfError::message(XdmfError::FATAL,
                             "Error: Not Enough Operators in evaluateExpression");
        }
        else {
          valueStack.push(evaluateOperation(val1, val2, operationStack.top()));
          operationStack.pop();
        }
      }
    }
  }

  // Throw error if there's extra operations
  if (operationStack.size() > 0) {
    XdmfError::message(XdmfError::WARNING,
                       "Warning: Left Over Operators in evaluateExpression");
  }

  if (valueStack.size() > 1) {
    XdmfError::message(XdmfError::WARNING,
                       "Warning: Left Over Values in evaluateExpression");
  }

  // Ensure that an array is returned
  // Will error out if this is not done.
  if (valueStack.size() > 0) {
    return valueStack.top();
  }
  else {
    return XdmfArray::New();
  }
}

shared_ptr<XdmfArray>
XdmfFunction::evaluateOperation(shared_ptr<XdmfArray> val1,
                             shared_ptr<XdmfArray> val2,
                             char operation)
{
  if (operations.find(operation) != operations.end()) {
    return operations[operation]->execute(val1, val2);
  }
  else {
    return shared_ptr<XdmfArray>();
  }
}

shared_ptr<XdmfArray>
XdmfFunction::evaluateFunction(std::vector<shared_ptr<XdmfArray> > valueVector,
                            std::string functionName)
{
  if (arrayFunctions.find(functionName) != arrayFunctions.end()) {
    return arrayFunctions[functionName]->execute(valueVector);
  }
  else {
    return shared_ptr<XdmfArray>();
  }
}

std::string
XdmfFunction::getExpression() const
{
  return mExpression;
}

std::string
XdmfFunction::getItemTag() const
{
  return ItemTag;
}

std::map<std::string, std::string>
XdmfFunction::getItemProperties() const
{
  std::map<std::string, std::string> functionProperties;

  functionProperties["Expression"] = mExpression;
  functionProperties["ConstructedType"] = mConstructedType;

  for (std::map<std::string, std::string>::const_iterator constructedIt = mConstructedProperties.begin();
       constructedIt != mConstructedProperties.end();
       ++constructedIt) {
    functionProperties[constructedIt->first] = constructedIt->second;
  }

  std::stringstream variableStream;

  for (std::map<std::string, shared_ptr<XdmfArray> >::const_iterator variableIter = mVariableList.begin();
       variableIter != mVariableList.end();
       ++variableIter) {
    variableStream << "|" << variableIter->first;
  }

  functionProperties["VariableNames"] = variableStream.str();

  return functionProperties;
}

int
XdmfFunction::getOperationPriority(char operation)
{
  size_t operationLocation = mSupportedOperations.find(operation);
  if (operationLocation != std::string::npos) {
    return mOperationPriority[operation];
  }
  else {
    return -1;
  }
}

const std::string
XdmfFunction::getSupportedOperations()
{
        return mSupportedOperations;
}

const std::vector<std::string>
XdmfFunction::getSupportedFunctions()
{
  std::vector<std::string> returnVector;
  for (std::map<std::string, shared_ptr<XdmfFunctionInternal> >::iterator functionWalker
       = arrayFunctions.begin();
       functionWalker != arrayFunctions.end();
       ++functionWalker) {
    returnVector.push_back(functionWalker->first);
  }
  return returnVector;
}

const std::string
XdmfFunction::getValidDigitChars()
{
        return mValidDigitChars;
}

const std::string
XdmfFunction::getValidVariableChars()
{
        return mValidVariableChars;
}

shared_ptr<XdmfArray>
XdmfFunction::getVariable(std::string key)
{
  if (mVariableList.count(key) > 0) {
    return mVariableList[key];
  }
  else {
    return shared_ptr<XdmfArray>();
  }
}

std::vector<std::string>
XdmfFunction::getVariableList()
{
  std::vector<std::string> keyAccumulator;
  for (std::map<std::string, shared_ptr<XdmfArray> >::iterator it = mVariableList.begin();
       it != mVariableList.end();
       ++it) {
    keyAccumulator.push_back(it->first);
  }
  return keyAccumulator;
}

shared_ptr<XdmfArray>
XdmfFunction::interlace(shared_ptr<XdmfArray> val1, shared_ptr<XdmfArray> val2)
{
  // Join interlace (evenly space the second array within the first one)
  // Builds a new array
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  // Resize to the combined size of both arrays
  // Determining what type to class it as in order to not lose data
  // and to still have the smallest data type of the two
  shared_ptr<const XdmfArrayType> resultType =
    XdmfArrayType::comparePrecision(val1->getArrayType(), val2->getArrayType());
  bool release1 = false;
  bool release2 = false;
  if (!val1->isInitialized()) {
    val1->read();
    release1 = true;
  }
  if (!val2->isInitialized()) {
    val2->read();
    release2 = true;
  }
  if (resultType == XdmfArrayType::Int8()) {
    char sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::Int16()) {
    short sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::Int32()) {
    int sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::Int64()) {
    long sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::UInt8()) {
    unsigned char sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::UInt16()) {
    unsigned short sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::UInt32()) {
    unsigned int sampleValue = 0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::Float32()) {
    float sampleValue = 0.0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::Float64()) {
    double sampleValue = 0.0;
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else if (resultType == XdmfArrayType::String()) {
    std::string sampleValue = "";
    returnArray->resize(val1->getSize()+val2->getSize(), sampleValue);
  }
  else {
    // error type not supported
    XdmfError::message(XdmfError::FATAL, "Invalid type during Interlace");
  }

  // Determine ratio of array sizes
  int arrayRatio1 = (int)floor(static_cast<double>(val1->getSize())/val2->getSize());
  int arrayRatio2 = (int)floor(static_cast<double>(val2->getSize())/val1->getSize());
  if (arrayRatio1 < 1) {
    arrayRatio1 = 1;
  }
  if (arrayRatio2 < 1) {
    arrayRatio2 = 1;
  }
  // Stride is equal to the ratios rounded up and added together
  int stride = arrayRatio1+arrayRatio2;
  int arrayExcess1 = 0;
  int arrayExcess2 = 0;
  for (int i = 0; i < stride; ++i) {
    // Add the values of each array
    // using strides to interlace and starting index to offset
    // first array gets the first value of the new array
    if (i<arrayRatio1) {
      int amountWritten = val1->getSize()/arrayRatio1;
      if (((amountWritten * arrayRatio1) + i) < (int)val1->getSize()) {
        amountWritten++;
      }
      if (amountWritten > floor(static_cast<double>(val2->getSize())/arrayRatio2)) {
        arrayExcess1 += amountWritten - (int)floor(static_cast<double>(val2->getSize())/arrayRatio2);
        amountWritten = (int)floor(static_cast<double>(val2->getSize())/arrayRatio2);
      }
      returnArray->insert(i, val1, i, amountWritten, stride, arrayRatio1);
    }
    else {
      // Second array takes the rest
      int amountWritten = val2->getSize()/arrayRatio2;
      if (((amountWritten * arrayRatio2) + i) < (int)val2->getSize()) {
        amountWritten++;
      }
      if (amountWritten > floor(static_cast<double>(val1->getSize())/arrayRatio1)) {
        arrayExcess2 += amountWritten - (int)floor(static_cast<double>(val1->getSize())/arrayRatio1);
        amountWritten = (int)floor(static_cast<double>(val1->getSize())/arrayRatio1);
      }
      returnArray->insert(i, val2, i-arrayRatio1, amountWritten, stride, arrayRatio2);
    }
  }
  if (arrayExcess1 > 0) {
    returnArray->insert(val1->getSize()+val2->getSize()-arrayExcess1,
                        val1,
                        val1->getSize()-arrayExcess1,
                        arrayExcess1,
                        1,
                        1);
  }
  else if (arrayExcess2 > 0) {
    returnArray->insert(val1->getSize()+val2->getSize()-arrayExcess2,
                        val2,
                        val2->getSize()-arrayExcess2,
                        arrayExcess2,
                        1,
                        1);
  }
  // After all inserts are done, add the excess values to the end of the array
  if (release1) {
    val1->release();
  }
  if (release2) {
    val2->release();
  }
  return returnArray;
}

void
XdmfFunction::insertVariable(std::string key, shared_ptr<XdmfArray> value)
{
  mVariableList[key] = value;
}

shared_ptr<XdmfArray>
XdmfFunction::join(std::vector<shared_ptr<XdmfArray> > values)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  bool release = false;
  for (unsigned int i = 0; i < values.size(); ++i) {
    release = false;
    if (!values[i]->isInitialized()) {
      values[i]->read();
      release = true;
    }
    returnArray->insert(returnArray->getSize(),
                        values[i],
                        0,
                        values[i]->getSize(),
                        1,
                        1);
    if (release) {
      values[i]->release();
    }
  }
  return returnArray;
}

shared_ptr<XdmfArray>
XdmfFunction::log(std::vector<shared_ptr<XdmfArray> > values)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  // Only working with the first array provided
  if (values.size() < 1) {
    XdmfError::message(XdmfError::FATAL,
                       "Error: No Array Passed to Function log");
  }
  bool release1 = false;
  bool release2 = false;
  if (!values[0]->isInitialized()) {
    values[0]->read();
    release1 = true;
  }
  if (values.size() > 1) {
    if (!values[1]->isInitialized()) {
      values[1]->read();
      release2 = true;
    }
  }
  for (unsigned int i = 0; i < values[0]->getSize(); ++i) {
    if (values.size() > 1) {
      if (values[0]->getSize() == values[1]->getSize()) {
        returnArray->pushBack(std::log(values[0]->getValue<double>(i))/std::log(values[1]->getValue<double>(i)));
      }
      else if (values[1]->getSize() == 1) {
        returnArray->pushBack(std::log(values[0]->getValue<double>(i))/std::log(values[1]->getValue<double>(0)));
      }
      else {
        XdmfError::message(XdmfError::FATAL,
                           "Error: Array Size Missmatch in Function Log");
      }
    }
    else {
      returnArray->pushBack(std::log(values[0]->getValue<double>(i)));
    }
  }
  if (release1) {
    values[0]->release();
  }
  if (release2) {
    values[1]->release();
  }
  return returnArray;
}

shared_ptr<XdmfArray>
XdmfFunction::multiplication(shared_ptr<XdmfArray> val1, shared_ptr<XdmfArray> val2)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  bool release1 = false;
  bool release2 = false;
  if (!val1->isInitialized()) {
    val1->read();
    release1 = true;
  }
  if (!val2->isInitialized()) {
    val2->read();
    release2 = true;
  }
  for (unsigned int i = 0; i < val1->getSize() || i < val2->getSize(); ++i) {
    if (val1->getSize() == val2->getSize()) {
      returnArray->pushBack(val1->getValue<double>(i) * val2->getValue<double>(i));
    }
    else if (val1->getSize() == 1) {
      returnArray->pushBack(val1->getValue<double>(0) * val2->getValue<double>(i));
    }
    else if (val2->getSize() == 1) {
      returnArray->pushBack(val1->getValue<double>(i) * val2->getValue<double>(0));
    }
    else {
      XdmfError::message(XdmfError::FATAL,
                         "Error: Array Size Mismatch in Function multiplication");
    }
  }
  if (release1) {
    val1->release();
  }
  if (release2) {
    val2->release();
  }
  return returnArray;
}

shared_ptr<XdmfArray>
XdmfFunction::read() const
{
  return evaluateExpression(mExpression, mVariableList);
}

void
XdmfFunction::removeVariable(std::string key)
{
  std::map<std::string, shared_ptr<XdmfArray> >::iterator removeWalker =
    mVariableList.find(key);
  if (removeWalker != mVariableList.end()) {
    mVariableList.erase(removeWalker);
  }
}

void
XdmfFunction::setExpression(std::string newExpression)
{
  mExpression = newExpression;
}

shared_ptr<XdmfArray>
XdmfFunction::sin(std::vector<shared_ptr<XdmfArray> > values)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  // Only working with the first array provided
  if (values.size() < 1) {
    XdmfError::message(XdmfError::FATAL,
                       "Error: No Array Passed to Function sin");
  }
  bool release = false;
  if (!values[0]->isInitialized()) {
    values[0]->read();
    release = true;
  }
  for (unsigned int i = 0; i < values[0]->getSize(); ++i) {
    returnArray->pushBack(std::sin(values[0]->getValue<double>(i)));
  }
  if (release) {
    values[0]->release();
  }
  return returnArray;
}

shared_ptr<XdmfArray>
XdmfFunction::sqrt(std::vector<shared_ptr<XdmfArray> > values)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  // Only working with the first array provided
  if (values.size() < 1) {
    XdmfError::message(XdmfError::FATAL,
                       "Error: No Array Passed to Function sqrt");
  }
  bool release = false;
  if (!values[0]->isInitialized()) {
    values[0]->read();
    release = true;
  }
  for (unsigned int i = 0; i < values[0]->getSize(); ++i) {
    returnArray->pushBack(std::sqrt(values[0]->getValue<double>(i)));
  }
  if (release) {
    values[0]->release();
  }
  return returnArray;
}

shared_ptr<XdmfArray>
XdmfFunction::subtraction(shared_ptr<XdmfArray> val1, shared_ptr<XdmfArray> val2)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  bool release1 = false;
  bool release2 = false;
  if (!val1->isInitialized()) {
    val1->read();
    release1 = true;
  }
  if (!val2->isInitialized()) {
    val2->read();
    release2 = true;
  }
  for (unsigned int i = 0; i < val1->getSize() || i < val2->getSize(); ++i) {
    if (val1->getSize() == val2->getSize()) {
      returnArray->pushBack(val1->getValue<double>(i) - val2->getValue<double>(i));
    }
    else if (val1->getSize() == 1) {
      returnArray->pushBack(val1->getValue<double>(0) - val2->getValue<double>(i));
    }
    else if (val2->getSize() == 1) {
      returnArray->pushBack(val1->getValue<double>(i) - val2->getValue<double>(0));
    }
    else {
      XdmfError::message(XdmfError::FATAL,
                         "Error: Array Size Mismatch in Function subtraction");
    }
  }
  if (release1) {
    val1->release();
  }
  if (release2) {
    val2->release();
  }
  return returnArray;
}

shared_ptr<XdmfArray>
XdmfFunction::sum(std::vector<shared_ptr<XdmfArray> > values)
{
  double total = 0.0;
  bool release = false;
  for (unsigned int i = 0; i < values.size(); ++i) {
    release = false;
    if (!values[i]->isInitialized()) {
      values[i]->read();
      release = true;
    }
    for (unsigned int j = 0; j < values[i]->getSize(); ++j) {
      total += values[i]->getValue<double>(j);
    }
    if (release) {
      values[i]->release();
    }
  }
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  returnArray->insert(0, total);
  return returnArray;
}

shared_ptr<XdmfArray>
XdmfFunction::tan(std::vector<shared_ptr<XdmfArray> > values)
{
  shared_ptr<XdmfArray> returnArray = XdmfArray::New();
  // Only working with the first array provided
  if (values.size() < 1) {
    XdmfError::message(XdmfError::FATAL,
                       "Error: No Array Passed to Function tan");
  }
  bool release = false;
  if (!values[0]->isInitialized()) {
    values[0]->read();
    release = true;
  }
  for (unsigned int i = 0; i < values[0]->getSize(); ++i) {
    returnArray->pushBack(std::tan(values[0]->getValue<double>(i)));
  }
  if (release) {
    values[0]->release();
  }
  return returnArray;
}

void
XdmfFunction::traverse(const shared_ptr<XdmfBaseVisitor> visitor)
{
  XdmfItem::traverse(visitor);

  shared_ptr<XdmfArray> spacerarray = XdmfArray::New();
  spacerarray->pushBack((int)0);
  spacerarray->accept(visitor);

  for (std::map<std::string, shared_ptr<XdmfArray> >::iterator it = mVariableList.begin();
       it != mVariableList.end();
       ++it) {
    it->second->accept(visitor);
  }
}


text:
<TITLE>Netica(TM) API Programmer's Reference Manual; API Funtion: DeleteSensvToFinding_bn</TITLE>
<LINK REL="stylesheet" TYPE="text/css" HREF="../css/rightFrame.css" TITLE="Style">
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<META NAME="COPYRIGHT" CONTENT="© 2012 Norsys Software Corp.">

  NORSYS SOFTWARE © 2012
      NETICA API
  C &nbsp VERSION &nbsp 5.04&nbsp

 void DeleteSensvToFinding_bn (	 sensv_bn*  sens )

Deletes the sensitivity measuring object sens, and frees the memory it uses.

You must not try to use sens after calling this.

It is okay if sens is a NULL pointer (then no action is taken).

Version:
Versions 2.03 and later have this function.<passageIndent2/>

See also:

NewSensvToFinding_bn	    	(reverse operation)  Create a new sensv_bn to do sensitivity analysis

Example:

See NewSensvToFinding_bn.

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services
        http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="Mcfedr\UuidExtraBundle\ParamConverter\UuidParamConverter">
            <tag name="request.param_converter" converter="uuid"/>
        </service>
        <service id="Mcfedr\UuidExtraBundle\Serializer\UuidNormalizer">
            <tag name="serializer.normalizer"/>
        </service>
        <service id="Mcfedr\UuidExtraBundle\Form\ValidatorTypeGuesser">
            <tag name="form.type_guesser" />
            <argument type="service" id="validator.mapping.class_metadata_factory" />
        </service>
    </services>
</container>


text:
namespace WLW2Git.Handlers.Model
{
	using System;

	[Serializable]
	public class MediaObjectInfo
	{
		public string url { get; set; }
	}
}


text:
package converters

import (
	"log"
	"testing"
	"time"

	fuzz "github.com/google/gofuzz"
	"github.com/stretchr/testify/assert"
)

func TestFuzzIntStringInt(t *testing.T) {
	seed := time.Now().UnixNano()
	f := fuzz.NewWithSeed(seed)
	var value int
	f.Fuzz(&value)
	log.Printf("Seed: %d\tValue: %d", seed, value)

	assert.Equal(t, value, String(Int(value).ToString()).MustInt())
}

func TestFuzzInt64StringInt64(t *testing.T) {
	seed := time.Now().UnixNano()
	f := fuzz.NewWithSeed(seed)
	var value int64
	f.Fuzz(&value)
	log.Printf("Seed: %d\tValue: %d", seed, value)

	assert.Equal(t, value, String(Int64(value).ToString()).MustInt64())
}


text:
<?php
namespace Application\Model;

class Bildupload
{
	private $upload_folder    			= "public/img/";
	private $allowed_extensions			= array("png", "jpg", "jpeg", "gif");
	private $max_size					= 2*1024*1024;
	private $allowed_types				= array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
	private $img_folder					= "/img/";

	public function bildupload($uploadedfile) {

		//Pfadangabe
		$filename = pathinfo($_FILES["uploadedfile"]["name"], PATHINFO_FILENAME);
		$extension = strtolower(pathinfo($_FILES["uploadedfile"]["name"], PATHINFO_EXTENSION));

		if($_FILES['uploadedfile']['error'] !== UPLOAD_ERR_OK) {
			echo "Der Upload ist fehlgeschlagen! Wähl bitte ein anderes Bild aus.";
			$path = false;
			return $path;
		}

		//Dateiendung �berpr�fen
		if(!in_array($extension, $this->allowed_extensions))
		{
			echo "Ung&uumlltige Dateiendung! Nur png, jpg, jpeg und gif Dateien!";
			$path = false;
			return $path;
		}

		//Maximale Bildgr��e �berpr�fen
		if($_FILES["uploadedfile"]["size"] > $this->max_size)
		{
			echo "Bilder d&oumlfen nicht grouml;ßer als 2 MB sein!";
			$path = false;
			return $path;
		}

		//Erlaubte Dateiendung
		$detected_type = exif_imagetype($_FILES["uploadedfile"]["tmp_name"]);

		if(!in_array($detected_type, $this->allowed_types))
		{
			echo "Nur der Upload von Bildern ist erlaubt!";
			$path = false;
			return $path;
		}

		//L�nge des Filenamen bestimmen, falls der Name mehr als 12 Zeichen hat, werden diese gek�rzt
		//Es wird auf 12 Zeichen gek�rzt, damit im Falle von mehreren Dateien die Erweiterungen
		//nicht �ber 15 Zeichen hinausgehen kann
		$length = strlen($filename);

		if($length > 12) {
			$altfilename = substr($filename, 0, 12);
			$filename = $altfilename;
		}

		//Pfadangabe zum Ordner, in dem das Bild gespeichert wird
		$upload_folder = $this->upload_folder;

		//Pfad zusammensetzen
		$new_path = $this->upload_folder.$filename.'.'.$extension;
		$path = $this->img_folder.$filename.'.'.$extension;

		//Falls Dateiname bereits vorhanden, Erweiterung des Pfades um n�chsth�here Nummer
		if(file_exists($new_path))
		{
			$id = 1;
			do
			{
				$new_path = $this->upload_folder.$filename.'_'.$id.'.'.$extension;
				$path = $this->img_folder.$filename.'_'.$id.'.'.$extension;
				$id++;
			} while(file_exists($new_path));

		}

		//Das Bild wird in den Ordner Bilder mit absoluten Pfad verschoben, der relative Pfad wird zur�ckgegeben
		if (move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], $new_path))
		{
			//Maximale Aufl�sung �berpr�fen

			 $size = getimagesize($new_path);
			 $width = $size[0];
			 $height = $size[1];

			 if($width > 1024 OR $height > 1024)
			 {
			 echo "Die unterst&uumltzte Aufl&oumlsung von Bildern liegt bei 1024*1024";
			 unlink($new_path);
			 $path = false;
			 return $path;
			 }

			 return $path;
		}
		else
		{
			echo "Fehler beim Upload";
		}

	}
}


text:
package com.parse.starter;

import android.app.Application;

import com.parse.Parse;

public class StarterApplication extends Application {

  @Override
  public void onCreate() {
    super.onCreate();

    // Add your initialization code here
//    Parse.enableLocalDatastore(this);
    Parse.initialize(this, getString(R.string.parse_app_id), getString(R.string.parse_client_key));
  }

}


text:
/*
 * Created on Nov 18, 2005
 *
 */
package gov.va.med.imaging.dicom.test;

import gov.va.med.imaging.dicom.common.interfaces.IDicomDataSet;
import gov.va.med.imaging.dicom.dcftoolkit.utilities.reconstitution.LegacyTextFileParser;
import gov.va.med.imaging.dicom.dcftoolkit.utilities.reconstitution.OriginalPixelDataInfo;
import gov.va.med.imaging.exceptions.TextFileException;
import gov.va.med.imaging.exceptions.TextFileExtractionException;
import gov.va.med.imaging.exceptions.TextFileNotFoundException;
import gov.va.med.imaging.exchange.business.dicom.DicomServerConfiguration;

import java.util.ArrayList;
import java.util.Iterator;

import com.lbs.DCS.AttributeTag;
import com.lbs.DCS.DCM;
import com.lbs.DCS.DCSException;
import com.lbs.DCS.DicomAEElement;
import com.lbs.DCS.DicomASElement;
import com.lbs.DCS.DicomATElement;
import com.lbs.DCS.DicomCSElement;
import com.lbs.DCS.DicomDAElement;
import com.lbs.DCS.DicomDSElement;
import com.lbs.DCS.DicomDTElement;
import com.lbs.DCS.DicomDataSet;
import com.lbs.DCS.DicomElement;
import com.lbs.DCS.DicomFDElement;
import com.lbs.DCS.DicomFLElement;
import com.lbs.DCS.DicomFileOutput;
import com.lbs.DCS.DicomISElement;
import com.lbs.DCS.DicomLOElement;
import com.lbs.DCS.DicomLTElement;
import com.lbs.DCS.DicomOBElement;
import com.lbs.DCS.DicomOFElement;
import com.lbs.DCS.DicomOWElement;
import com.lbs.DCS.DicomPNElement;
import com.lbs.DCS.DicomSHElement;
import com.lbs.DCS.DicomSLElement;
import com.lbs.DCS.DicomSQElement;
import com.lbs.DCS.DicomSSElement;
import com.lbs.DCS.DicomSTElement;
import com.lbs.DCS.DicomTMElement;
import com.lbs.DCS.DicomUIElement;
import com.lbs.DCS.DicomULElement;
import com.lbs.DCS.DicomUNElement;
import com.lbs.DCS.DicomUSElement;
import com.lbs.DCS.DicomUTElement;
import com.lbs.DCS.UID;
import com.lbs.DCS.VRValidator;
import com.lbs.DCS.ValidationErrorList;

/**
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 *
 *
 * @author William Peterson
 *
 */
public class TextFileParserTest extends DicomDCFUtilitiesTestBase {

    /*
     * @see DicomDCFSCUTestBase#setUp()
     */
    protected void setUp() throws Exception {
        super.setUp();
    }

    /*
     * @see DicomDCFSCUTestBase#tearDown()
     */
    protected void tearDown() throws Exception {
        super.tearDown();
    }

    /**
     * Constructor for TextFileParserTest.
     * @param arg0
     */
    public TextFileParserTest(String arg0) {
        super(arg0);
   }

    public void testFileParserOne(){

        testLogger.info("Starting Test 1.");
        String textFilename = ".\\testdata\\Test1.txt";
        DicomDataSet dds;
        dds = this.parseToDDS(textFilename);
        this.writeToDisk("output1.dcm", dds);
       testLogger.info("Test 1 Completed Successfully...");

    }

    public void testFileParserTwo(){

        testLogger.info("Starting Test 2.");
        String textFilename = ".\\testdata\\Test2.txt";
        DicomDataSet dds;
        dds = this.parseToDDS(textFilename);
        this.writeToDisk("output2.dcm", dds);
        testLogger.info("Test 2 Completed Successfully...");
   }

    public void testFileParserThree(){

        testLogger.info("Starting Test 3.");
        String textFilename = ".\\testdata\\Test3.txt";
        DicomDataSet dds;
        dds = this.parseToDDS(textFilename);
        this.writeToDisk("output3.dcm", dds);
       testLogger.info("Test 3 Completed Successfully...");
    }

    public void testFileParserFour(){

        testLogger.info("Starting Test 4.");
        String textFilename = ".\\testdata\\Test4.txt";
        DicomDataSet dds;
        dds = this.parseToDDS(textFilename);
        this.writeToDisk("output4.dcm", dds);
        testLogger.info("Test 4 Completed Successfully...");
    }

    public void testFileParserFive(){

       testLogger.info("Starting Test 5.");
       String textFilename = ".\\testdata\\Test5.txt";
       DicomDataSet dds;
       dds = this.parseToDDS(textFilename);
       this.writeToDisk("output5.dcm", dds);
       testLogger.info("Test 5 Completed Successfully...");
     }

    public void testFileParserSix(){

        testLogger.info("Starting Test 6.");
        String textFilename = ".\\testdata\\Test6.txt";
        DicomDataSet dds;
        dds = this.parseToDDS(textFilename);
        this.writeToDisk("output6.dcm", dds);
        testLogger.info("Test 6 Completed Successfully...");
     }

    public void testFileParserSeven(){

        testLogger.info("Starting Test 7.");
        String textFilename = ".\\testdata\\Test7.txt";
        DicomDataSet dds;
        dds = this.parseToDDS(textFilename);
        this.writeToDisk("output7.dcm", dds);
        testLogger.info("Test 7 Completed Successfully...");
     }

    public void testFileParserEight(){

        testLogger.info("Starting Test 8.");
        String textFilename = ".\\testdata\\Test8.txt";
        DicomDataSet dds;
        dds = this.parseToDDS(textFilename);
        this.writeToDisk("output8.dcm", dds);
        testLogger.info("Test 8 Completed Successfully...");
     }

    public void testFileParserNine(){

        testLogger.info("Starting Test 9.");
        String textFilename = ".\\testdata\\Test9.txt";
        DicomDataSet dds;
        dds = this.parseToDDS(textFilename);
        this.writeToDisk("output9.dcm", dds);
        testLogger.info("Test 9 Completed Successfully...");
     }

    public void testFileParserTen(){

        testLogger.info("Starting Test 10.");
        String textFilename = ".\\testdata\\cha_cr.txt";
        DicomDataSet dds;
        dds = this.parseToDDS(textFilename);
        this.writeToDisk("output10.dcm", dds);
        testLogger.info("Test 10 Completed Successfully...");
     }

/*
    public void testFileParserEleven(){
        TESTLOGGER.info("Starting Test 11.  Empty DICOM Data Section.");
        String textFilename = ".\\testdata\\test11.txt";
        DicomDataSet dds;
        dds = this.parseToDDS(textFilename);
        TESTLOGGER.info("Test 11 Completed.  A thrown Exception is considered successful for this test.");
    }
*/

    public void testFileParserTwelve(){

        testLogger.info("Starting Test 12.");
        String textFilename = ".\\testdata\\test12.txt";
        DicomDataSet dds;
        dds = this.parseToDDS(textFilename);
        this.writeToDisk("output12.dcm", dds);
        testLogger.info("Test 12 Completed Successfully...");
     }

    public void testFileParserThirteen(){

        testLogger.info("Starting Test 13.");
        String textFilename = ".\\testdata\\test13.txt";
        DicomDataSet dds;
        dds = this.parseToDDS(textFilename);
        this.writeToDisk("output13.dcm", dds);
        testLogger.info("Test 13 Completed Successfully...");
     }

    public void testFileParserFourteen(){

        testLogger.info("Starting Test 14.");
        String textFilename = ".\\testdata\\test14.txt";
        DicomDataSet dds;
        dds = this.parseToDDS(textFilename);
        this.writeToDisk("output14.dcm", dds);
        testLogger.info("Test 14 Completed Successfully...");
     }

    public void testFileParserFifteen(){

	    testLogger.info("Starting Test 15.");
	    String textFilename = ".\\testdata\\test15.txt";
	    DicomDataSet dds;
	    dds = this.parseToDDS(textFilename);
	    this.writeToDisk("output15.dcm", dds);
	    testLogger.info("Test 15 Completed Successfully...");
	 }

    public void testFileParserSixteen(){

	    testLogger.info("Starting Test 16.");
	    String textFilename = ".\\testdata\\test16.txt";
	    DicomDataSet dds;
	    dds = this.parseToDDS(textFilename);
	    this.writeToDisk("output16.dcm", dds);
	    testLogger.info("Test 16 Completed Successfully...");
	 }

    public void testFileParserSeventeen(){

	    testLogger.info("Starting Test 17.");
	    String textFilename = ".\\testdata\\test17.txt";
	    DicomDataSet dds;
	    dds = this.parseToDDS(textFilename);
	    this.writeToDisk("output17.dcm", dds);
	    testLogger.info("Test 17 Completed Successfully...");
	 }

    public void testFileParserEightteen(){

	    testLogger.info("Starting Test 18.");
	    String textFilename = ".\\testdata\\test18.txt";
	    DicomDataSet dds;
	    dds = this.parseToDDS(textFilename);
	    this.writeToDisk("output18.dcm", dds);
	    testLogger.info("Test 18 Completed Successfully...");
	 }

    public void testFileParserNineteen(){

	    testLogger.info("Starting Test 19.");
	    String textFilename = ".\\testdata\\test19.txt";
	    DicomDataSet dds;
	    dds = this.parseToDDS(textFilename);
	    this.writeToDisk("output19.dcm", dds);
	    testLogger.info("Test 19 Completed Successfully...");
	 }

    public void testFileParserVIXImage(){

        testLogger.info("Starting VIX Test.");
        String textFilename = ".\\testdata\\vix0001.txt";
        DicomDataSet dds;
        dds = this.parseToDDS(textFilename);
        this.writeToDisk("vix0001.dcm", dds);
        testLogger.info("VIX Test Completed Successfully...");
     }

    private DicomDataSet parseToDDS(String textFilename){

        //FUTURE Change to pass Exceptions to the various tests.  Do not pass/fail test inside
        //  of exceptions in this method.  Gives misleading results.
        try{
            LegacyTextFileParser textParser = new LegacyTextFileParser();
            IDicomDataSet dds;
            DicomDataSet dicomDataSet;
            OriginalPixelDataInfo pixelInfo = new OriginalPixelDataInfo();
            dds = textParser.createDicomDataSet(textFilename, pixelInfo);
            dicomDataSet = (DicomDataSet) dds.getDicomDataSet();
            //if(dicomDataSet){
            //    throw new TextFileExtractionException();
            //}
            //if(dds.getSeriesInstanceUID().length() < 2){
            //    throw new TextFileExtractionException();
            //}
            //if(dds.getSOPInstanceUID().length() < 2){
            //    throw new TextFileExtractionException();
            //}

            testLogger.info("Final DataSet:\n" + dicomDataSet.toString());
            this.removeSelectedBadVRElements(dicomDataSet);

            return dicomDataSet;
        }
        catch(TextFileNotFoundException noFile){
            testLogger.info("Did not find Text File " + textFilename);
            fail("Test failed.");
        }
        catch(TextFileException fileException){
            testLogger.info("General problem with " + textFilename);
            fail("Test failed.");
        }
        catch(TextFileExtractionException fileExtract){
            fileExtract.printStackTrace();
            testLogger.info("Did not extract data properly from " + textFilename);
            fail("Test failed.");
        }
        return null;
    }

    private void writeToDisk(String filename, DicomDataSet dds){
        try{
        	assertFalse(dds.containsElement(new AttributeTag(0x0002,0x0003)));
            DicomFileOutput out = new DicomFileOutput(filename, UID.TRANSFERLITTLEENDIANEXPLICIT, true, true);
            out.open();
            out.writeDataSet(dds);
            out.close();
        }
        catch (DCSException dcse){
            System.out.println("Failed to make DICOM file, "+filename);
        }
    }

	private void removeSelectedBadVRElements(DicomDataSet dds){
		ArrayList<String> removeList = DicomServerConfiguration.getConfiguration().getRemovedElements();
		if(removeList != null){
			Iterator<String> iter = removeList.iterator();
			while(iter.hasNext()){
				String tagNumber  = iter.next();
				try{
					AttributeTag tag = new AttributeTag(tagNumber);
					if(dds.containsElement(tag)){
						DicomElement element = dds.findElement(tag);
						short vr = element.vr();

						try{
							switch (vr){
								case DCM.VR_AE:
									VRValidator.instance().validateAE((DicomAEElement)element);
									break;
								case DCM.VR_AS:
									VRValidator.instance().validateAS((DicomASElement)element);
									break;
								case DCM.VR_AT:
									VRValidator.instance().validateAT((DicomATElement)element);
									break;
								case DCM.VR_CS:
									VRValidator.instance().validateCS((DicomCSElement)element);
									break;
								case DCM.VR_DA:
									VRValidator.instance().validateDA((DicomDAElement)element);
									break;
								case DCM.VR_DS:
									VRValidator.instance().validateDS((DicomDSElement)element);
									break;
								case DCM.VR_DT:
									VRValidator.instance().validateDT((DicomDTElement)element);
									break;
								case DCM.VR_FD:
									VRValidator.instance().validateFD((DicomFDElement)element);
									break;
								case DCM.VR_FL:
									VRValidator.instance().validateFL((DicomFLElement)element);
									break;
								case DCM.VR_IS:
									VRValidator.instance().validateIS((DicomISElement)element);
									break;
								case DCM.VR_LO:
									VRValidator.instance().validateLO((DicomLOElement)element);
									break;
								case DCM.VR_LT:
									VRValidator.instance().validateLT((DicomLTElement)element);
									break;
								case DCM.VR_PN:
									VRValidator.instance().validatePN((DicomPNElement)element);
									break;
								case DCM.VR_SH:
									VRValidator.instance().validateSH((DicomSHElement)element);
									break;
								case DCM.VR_SL:
									VRValidator.instance().validateSL((DicomSLElement)element);
									break;
								case DCM.VR_SQ:
									ValidationErrorList list = VRValidator.instance().validateSQ((DicomSQElement)element,"0");
									if(list.hasErrors()){
										throw new DCSException();
									}
									break;
								case DCM.VR_SS:
									VRValidator.instance().validateSS((DicomSSElement)element);
									break;
								case DCM.VR_ST:
									VRValidator.instance().validateST((DicomSTElement)element);
									break;
								case DCM.VR_TM:
									VRValidator.instance().validateTM((DicomTMElement)element);
									break;
								case DCM.VR_UI:
									VRValidator.instance().validateUI((DicomUIElement)element);
									break;
								case DCM.VR_UL:
									VRValidator.instance().validateUL((DicomULElement)element);
									break;
								case DCM.VR_UN:
									VRValidator.instance().validateUN((DicomUNElement)element);
									break;
								case DCM.VR_US:
									VRValidator.instance().validateUS((DicomUSElement)element);
									break;
								case DCM.VR_UT:
									VRValidator.instance().validateUT((DicomUTElement)element);
									break;
								case DCM.VR_OB:
									VRValidator.instance().validateOB((DicomOBElement)element);
									break;
								case DCM.VR_OW:
									VRValidator.instance().validateOW((DicomOWElement)element);
									break;
								case DCM.VR_OF:
									VRValidator.instance().validateOF((DicomOFElement)element);
									break;
							}
						}
						catch(DCSException dcsX){
							dds.insert(tag, "");
						}
					}
				}
				catch(DCSException dcsX){
					//Do nothing with exception.
				}
			}
		}
	}
}


text:
class <%= controller_class_name %>Controller < ApplicationController
  self.responder = Scaffold360::HtmlfResponder
  respond_to :html, :htmlf

  before_filter :set_dom_prefix
  #after_filter :dump_body

<% unless options[:singleton] -%>
  def index
    #@<%= table_name %> = <%= orm_class.all(class_name) %> # w/o will_paginate
    @<%= table_name %> = <%= class_name %>.paginate(:page => params[:page], :per_page => 2)  # will_paginate

    respond_with do |format|
      format.js     # "load more"
    end
  end
<% end -%>

  def show
    @<%= file_name %> = <%= orm_class.find(class_name, "params[:id]") %>
    respond_with @<%= file_name %>
  end

  def new
    @<%= file_name %> = <%= orm_class.build(class_name) %>
    respond_with @<%= file_name %>
  end

  def create
    @<%= file_name %> = <%= orm_class.build(class_name, "params[:#{file_name}]") %>
    @<%= orm_instance.save %>
    respond_with @<%= file_name %>
  end

  def edit
    @<%= file_name %> = <%= orm_class.find(class_name, "params[:id]") %>
    respond_with @<%= file_name %>
  end

  def update
    @<%= file_name %> = <%= orm_class.find(class_name, "params[:id]") %>
    @<%= orm_instance.update_attributes("params[:#{file_name}]") %>
    respond_with @<%= file_name %>
  end

  def destroy
    @<%= file_name %> = <%= orm_class.find(class_name, "params[:id]") %>
    @<%= orm_instance.destroy %>

    respond_to do |format|
      format.html { redirect_to(<%= table_name %>_url) }
      format.htmlf  { render :text=>'' }  # TODO
      #format.xml    { head :ok }
    end
  end

  protected

    def set_dom_prefix
      @_dom_prefix = params[:_dom_prefix]
    end

    def dump_body
      puts response.body
    end

end


text:
package com.hdcookbook.grin.animator;

import com.hdcookbook.grin.util.Debug;
import java.awt.Graphics2D;
import java.awt.Component;
import java.util.Hashtable;

/**
 * An AnimationClient is a client of an AnimationEngine.  When it's
 * set up, an AnimationEngine calls an AnimationClient to do some
 * amount of drawing, once per frame.  An AnimationEngine may have
 * multiple AnimationClient instances that it is managing.
 **/
public interface AnimationClient {

    /**
     * Initialize the animation client.  This is called from the
     * animation worker thread before starting the animation loop.
     *
     * @param  component The component this show will eventually be displayed
     *                   in.  It's used for things like
     *                   Component.prepareImage().
     **/
    public void initialize(Component component)
        throws InterruptedException;

    /**
     * Destroy this animatin client.  This is called from the animation
     * worker thread before ending the animation loop.
     **/
    public void destroy() throws InterruptedException;

    /**
     * Advance the state of the show to the next frame.  This is
     * called once per frame; the first time it is called can be
     * considered "frame 0", and can monotonically increase from there.
     *

     * This method can be called multiple times before any attempt is
     * made to display the UI state.  This happens when animation falls
     * behind; the engine catches up by skipping frames.  Animation
     * clients should perform only quick updates in this method; any
     * more time-consuming calculations should be deferred until
     * an object is first painted for a given frame.
     *
     * @see AnimationEngine#getModelTimeSkipped()
     *
     * @throws  InterruptedException    if the thread has been interrupted
     *                                  (e.g. because the xlet is being killed)
     **/
    public void nextFrame() throws InterruptedException;

    /**
     * Indicate to the animation client that we're not behind in the
     * animation, so that the current frame will actually be displayed.
     * Clients shouldn't make any changes to the model in this call; all
     * such changes need to happen in nextFrame()
     *
     * @throws  InterruptedException    if the thread has been interrupted
     *                                  (e.g. because the xlet is being killed)
     *
     * @see #nextFrame()
     **/
    public void setCaughtUp() throws InterruptedException;

    /**
     * Tell the animation manager what areas need to be drawn to for the
     * next frame.  This is called just after setCaughtUp(), and just
     * before paintFrame().
     *

     * In this call, the client must indicate where it intends to draw
     * by calling methods on RenderContext.  Internally, a RenderContext
     * keeps a number of rendering area "targets".  Each target will
     * keep track of a bounding rectangle of all of drawing
     * operations that are considered within that target.  When the
     * call to addDisplayAreas is complete, the animation manager may
     * merge some of these rendering areas targets,
     * or may leave them seperate; it will then call paintFrame() as
     * many times as it needs to, with a different clip rect each time.  These
     * clip rects will never overlap, so you don't need to worry about
     * a Src mode drawing to the same pixel twice in the same frame.
     *

     * The purpose of these targets is to try to minimize the number of
     * pixels that will be updated on the screen in each frame of animation.
     * Consider, for example, the case where most of the screen isn't changing,
     * but where there's a small animation in the upper-left hand corner,
     * and another small animation in the lower-right hand corner.  If those
     * two animations used the same target, the overall bounding rectangle
     * would cover the whole screen.  By using two different targets, the
     * screen update can be confined to two small rectangles, one at each
     * corner.
     *

     * The number of render area targets is set up when an AnimationEngine
     * is created, by calling mapDrawTargets() on each client.  During
     * animation, each AnimationClient is passed the same set of targets.
     * If there are multiple AnimationClient instances attached to an
     * AnimationEngine, it is up to the programmer to decide which render area
     * targets should be shared between clients so as to optimize drawing
     * performance.  This can be done with appropriate naming of the
     * targets in the mapDrawTargets() call.
     *

     * Often, an AnimationClient only needs to erase or draw objects
     * that have changed.  However, under certain circumstances, the
     * AnimationClient will be asked to redraw everything.  This will
     * happen on the first frame drawn, and possibly on others.  For
     * example, with repaint draw and platform double-buffering, the
     * platform erases the buffer for each frame, so a full redraw is
     * required.  When this happens, the animation enginer automatically
     * adds the full extent of the component to one of the targets.
     * In this case, it still calls this method, so that items we draw
     * have the opportunity to erase themselves if needed.
     *

     * This method will be called exactly once for each frame displayed.
     * Because paintFrame can be called multiple times per frame, any state
     * maintained by the animation client to optimize display areas should
     * be updated in this method, and not in paintFrame().
     *
     * @param targets           The RenderContext that manages  the set of
     *                          targets the client can draw to.
     *
     * @throws  InterruptedException    if the thread has been interrupted
     *                                  (e.g. because the xlet is being killed)
     *
     * @see RenderContext#setTarget(int)
     * @see #mapDrawTargets(Hashtable)
     **/
    public void addDisplayAreas(RenderContext targets)
        throws InterruptedException;

    /**
     * Paint the current frame of the animation.  This is called after
     * addDisplayAreas(), as the last step in a cycle through the animation
     * loop.  This might be called multiple times for a given frame
     * of animation, with a different clip rect set each time.  It also
     * might be called zero times, if no display areas were added.  The callee
     * should leave the graphics context in the same state as it was found in
     * initially, notably:
     *

     *
 Src drawing mode
     *
 clip rect set to the full extent of this drawing operation
     *

     *

     * The animation client shouldn't erase screen areas in this call.  That
     * can be handled more efficiently (for some drawing styles) via
     * RenderArea.clearAndAddArea()
     *
     * @param gr        The graphics context to draw to, set to Src drawing mode
     *
     * @throws  InterruptedException    if the thread has been interrupted
     *                                  (e.g. because the xlet is being killed)
     *
     * @see RenderContext#addArea(DrawRecord)
     **/
    public void paintFrame(Graphics2D gr)
        throws InterruptedException ;

    /**
     * Called when the animation framework is done painting the current
     * frame.  In each frame, the animation framework calls addDisplayAreas
     * once, paintFrame zero or more times, and it is guaranteed to
     * call paintDone() exactly once, even if the thread is interrupted.
     * Note that if the thread is interrupted, it's possible paintDone()
     * might be called without addDisplayAreas() having been called first.
     **/
    public void paintDone();

    /**
     * Get the names of the draw targets used by this animation client.
     *

     * Note that GRIN uses the name "T:Default" as the name of the
     * draw target if the GRIN show doesn't specify any.
     **/
    public String[] getDrawTargets();

    /**
     * Map draw target names into the numeric values that are required by the
     * animation engine.  This is called during initialization.  By calling
     * this on all AnimationClient instances, clients can share draw targets
     * by giving them the same name.
     *

     * The total number of different draw targets in an animation should
     * be small, because the algorithm for combining draw targets is
     * of cubic time complexity.  One or two different draw targets might
     * be a typical number, and more than four is questionable.
     *

     * See addDisplayAreas() for a discussion of what a render area target
     * is for.
     *
     * @param targets   A hashtable mapping String names to Integer values
     *
     * @see RenderContext#setTarget(int)
     * @see #addDisplayAreas(RenderContext)
     **/
    public void mapDrawTargets(Hashtable targets);
}


text:
#include <mpi.h>
#include "md_zinc.h"
#include "mpi_commid.h"
#include "mpi_zlib.h"
#include "grid.h"

static int dyncommid = _NUM_RESERVED_IDS;
static int maxcommid = 32767;

void _InitCommID() {
  int *tagub;
  int flag;

  MPI_Attr_get(_GRID_WORLD(_DefaultGrid),MPI_TAG_UB,&tagub,&flag);
  if (flag) {
    maxcommid = *tagub;
  }
}

int _GetDynamicCommID(void) {
  dyncommid++;
  if (dyncommid >= maxcommid) {
    dyncommid = _NUM_RESERVED_IDS;
  }
  return dyncommid;
}

/* FUNCTION: _SetDynamicCommID - set dynamic comm ID to dcid and return
 *           old value
 */

int _SetDynamicCommID(int dcid) {
  int tmp = dyncommid;

  dyncommid = dcid;

  return (tmp);
}


text:
warn "Jdbc-JTDS is only for use with JRuby" if (JRUBY_VERSION.nil? rescue true)
require 'jdbc/jtds/version'

module Jdbc
  module JTDS

    def self.driver_jar
      "jtds-#{DRIVER_VERSION}.jar"
    end

    def self.load_driver(method = :load)
      vers = Java::java.lang.System::get_property( "java.specification.version" )
      if ( ( vers.split( '.' ).map(&:to_i) <=> [ 1, 7 ] ) >= 0 )
        send method, driver_jar
      else
        raise LoadError, "Version #{VERSION} of Jdbc-JTDS requires Java 1.7 " +
                         "or later (try using gem 'jdbc-jtds', '~> 1.2.8'). "
      end
    end

    def self.driver_name
      'net.sourceforge.jtds.jdbc.Driver'
    end

    if defined?(JRUBY_VERSION) && # enable backwards-compat behavior :
      ( Java::JavaLang::Boolean.get_boolean("jdbc.driver.autoload") ||
        Java::JavaLang::Boolean.get_boolean("jdbc.jtds.autoload") )
      warn "autoloading JDBC driver on require 'jdbc/jtds'" if $VERBOSE
      load_driver :require
    end
  end
end


text:
namespace blink {
class WebFileWriterClient;
class WebURL;
}

namespace content {

class CONTENT_EXPORT WebFileWriterBase
    : public NON_EXPORTED_BASE(blink::WebFileWriter) {
 public:
  WebFileWriterBase(const GURL& path, blink::WebFileWriterClient* client);
  virtual ~WebFileWriterBase();

  // WebFileWriter implementation
  virtual void truncate(long long length);
  virtual void write(long long position, const blink::WebString& id);
  virtual void cancel();

 protected:
  // This calls DidSucceed() or DidFail() based on the value of |error_code|.
  void DidFinish(base::PlatformFileError error_code);

  void DidWrite(int64 bytes, bool complete);
  void DidSucceed();
  void DidFail(base::PlatformFileError error_code);

  // Derived classes must provide these methods to asynchronously perform
  // the requested operation, and they must call the appropiate DidSomething
  // method upon completion and as progress is made in the Write case.
  virtual void DoTruncate(const GURL& path, int64 offset) = 0;
  virtual void DoWrite(const GURL& path,
                       const std::string& blob_id,
                       int64 offset) = 0;
  virtual void DoCancel() = 0;

 private:
  enum OperationType {
    kOperationNone,
    kOperationWrite,
    kOperationTruncate
  };

  enum CancelState {
    kCancelNotInProgress,
    kCancelSent,
    kCancelReceivedWriteResponse,
  };

  void FinishCancel();

  GURL path_;
  blink::WebFileWriterClient* client_;
  OperationType operation_;
  CancelState cancel_state_;
};

}  // namespace content

#endif  // CONTENT_CHILD_FILEAPI_WEBFILEWRITER_BASE_H_


text:
package example.herding.cats

import cats._
import cats.data._
import cats.implicits._

/**
  * A monoid is a semigroup with an identity. A monoid is a specialization of a
  * semigroup, so its operation must be associative. Additionally,
  * `combine(x, empty) == combine(empty, x) == x`. For example, if we have `Monoid[String]`,
  * with `combine` as string concatenation, then `empty = ""`.
  *
  * In addition to the semigroup law, monoid must satify two more laws:
  *
  * - associativity (x |+| y) |+| z = x |+| (y |+| z)
  * - left identity Monoid[A].empty |+| x = x
  * - right identity x |+| Monoid[A].empty = x
  */
class Disjunction(val unwrap: Boolean) extends AnyVal
object Disjunction {
  @inline def apply(b: Boolean): Disjunction = new Disjunction(b)
  implicit val disjunctionMonoid: Monoid[Disjunction] = new Monoid[Disjunction] {
    def combine(a1: Disjunction, a2: Disjunction): Disjunction =
      Disjunction(a1.unwrap || a2.unwrap)
    def empty: Disjunction = Disjunction(false)
  }
  implicit val disjunctionEq: Eq[Disjunction] = new Eq[Disjunction] {
    def eqv(a1: Disjunction, a2: Disjunction): Boolean =
      a1.unwrap == a2.unwrap
  }
}

class Conjunction(val unwrap: Boolean) extends AnyVal
object Conjunction {
  @inline def apply(b: Boolean): Conjunction = new Conjunction(b)
  implicit val conjunctionMonoid: Monoid[Conjunction] = new Monoid[Conjunction] {
    def combine(a1: Conjunction, a2: Conjunction): Conjunction =
      Conjunction(a1.unwrap && a2.unwrap)
    def empty: Conjunction = Conjunction(true)
  }
  implicit val conjunctionEq: Eq[Conjunction] = new Eq[Conjunction] {
    def eqv(a1: Conjunction, a2: Conjunction): Boolean =
      a1.unwrap == a2.unwrap
  }
}

object MonoidExample extends App {
  val x1 = Disjunction(true) |+| Disjunction(false)
  println(s"x1.unwrap=${x1.unwrap}")

  val x2 = Monoid[Disjunction].empty |+| Disjunction(true)
  println(s"x2.unwrap=${x2.unwrap}")

  val x3 = Conjunction(true) |+| Conjunction(false)
  println(s"x3.unwrap=${x3.unwrap}")

  val x4 = Monoid[Conjunction].empty |+| Conjunction(true)
  println(s"x4.unwrap=${x4.unwrap}")

  // One way is to treat `Maybe` a as a `monoid` only if its type parameter a is a monoid as well and
  // then implement mappend in such a way that it uses the mappend operation of the values that are
  // wrapped with Just.
  //
  implicit def optionMonoid[A](implicit ev: Semigroup[A]): Monoid[Option[A]] =
    new Monoid[Option[A]] {
      def empty: Option[A] = None
      def combine(x: Option[A], y: Option[A]): Option[A] =
        x match {
          case None ⇒ y
          case Some(xx) ⇒
            y match {
              case None ⇒ x
              case Some(yy) ⇒ Some(ev.combine(xx, yy))
            }
        }
    }
  //val x5: Option[String] = none[String] |+| "andy".some
  //println(s"x5=${x5}") // expect `Some("andy")`

  // But if we don't know if the contents are monoids, we can't use mappend between them, so what
  // are we to do? Well, one thing we can do is to just discard the second value and keep the first
  // one. For this, the First a type exists.
  case class First[A: Eq](val unwrap: Option[A])
  object First {
    implicit def firstMonoid[A: Eq]: Monoid[First[A]] = new Monoid[First[A]] {
      def combine(a1: First[A], a2: First[A]): First[A] =
        First((a1.unwrap, a2.unwrap) match {
          case (Some(x), _) ⇒ Some(x)
          case (None, y) ⇒ y

        })
      def empty: First[A] = First(None: Option[A])

    }
    implicit def firstEq[A: Eq]: Eq[First[A]] = new Eq[First[A]] {
      def eqv(a1: First[A], a2: First[A]): Boolean =
        Eq[Option[A]].eqv(a1.unwrap, a2.unwrap)
    }
  }
  val x6 = First('a'.some) |+| First('b'.some)
  println(s"x6=$x6")
  val x7 = First(none[Char]) |+| First('b'.some)
  println(s"x7=$x7")

  // f we want a monoid on Maybe a such that the second parameter is kept if both parameters of
  // mappend are Just values, Data.Monoid provides a the Last a type.
  case class Last[A: Eq](val unwrap: Option[A])
  object Last {
    implicit def lastMonoid[A: Eq]: Monoid[Last[A]] = new Monoid[Last[A]] {
      def combine(a1: Last[A], a2: Last[A]): Last[A] =
        Last((a1.unwrap, a2.unwrap) match {
          case (_, Some(y)) ⇒ Some(y)
          case (x, None) ⇒ x

        })
      def empty: Last[A] = Last(None: Option[A])

    }
    implicit def lastEq[A: Eq]: Eq[Last[A]] = new Eq[Last[A]] {
      def eqv(a1: Last[A], a2: Last[A]): Boolean =
        Eq[Option[A]].eqv(a1.unwrap, a2.unwrap)
    }
  }
  val x8 = Last('a'.some) |+| Last('b'.some)
  println(s"x8=$x8")

  val x9 = Last('a'.some) |+| Last(none[Char])
  println(s"x9=$x9")
}


text:
package ethanjones.cubes.graphics.menu;

import ethanjones.cubes.block.Block;
import ethanjones.cubes.core.id.IDManager;
import ethanjones.cubes.core.util.BlockFace;
import ethanjones.cubes.graphics.world.BlockTextureHandler;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.Array;

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

import static ethanjones.cubes.graphics.Graphics.*;

/**
 * MenuManager
 */
public class MenuManager {

	private static Menu menu;
	private static Array<Menu> menus = new Array<Menu>();
	private static final TextureRegion texture;
	private static final boolean disableBackground = false;

	public static void setMenu(Menu menu) {
		int i = menus.indexOf(menu, true);
		if (i == -1) {
			menus.add(menu);
		} else if (i + 1 < menus.size) {
			for (int j = i + 1; j < menus.size; j++) {
				menus.get(j).save();
			}
			menus.removeRange(i + 1, menus.size - 1);
		}
		MenuManager.menu = menu;
	}

	public static Menu getPrevious(Menu aMenu) {
		int index = menus.indexOf(aMenu, true);
		if (index == -1 || index == 0)
			return null;
		return menus.get(index - 1);
	}

	private static void reanderBackgroundWhile1(List<Block> blocks) {
		int size = blocks.size();
		try {
			while (texture == null && size > 0) {
				int index = MathUtils.random(0, blocks.size() - 1);
				Block block = blocks.get(index);
				if (block.canBeTransparent()) {
					blocks.remove(index);
					continue;
				}
				BlockTextureHandler textureHandler;

				textureHandler = block.getTextureHandler(0);
				if (textureHandler == null)
					throw new Error();
				;
			}
			texture = textureHandler.getSide(BlockFace.posX);
			size = blocks.size();
		} catch (Exception e) {
			blocks.remove(index);
			continue;
		}
	}

	public static void renderBackground() {
		if (disableBackground)
			return;
		if (texture == null) {
			List<Block> blocks = new ArrayList<Block>();
			blocks.addAll(IDManager.getBlocks());

			reanderBackgroundWhile1(blocks);

			if (texture == null) {
				disableBackground = true;
				return;
			}
		}
		spriteBatch.begin();
		spriteBatch.setColor(Color.WHITE);
		float width = texture.getRegionWidth();
		float height = texture.getRegionHeight();
		int xTimes = (int) Math.floor(GUI_WIDTH / width);
		int yTimes = (int) Math.floor(GUI_HEIGHT / height);
		for (int x = 0; x <= xTimes; x++) {
			for (int y = 0; y <= yTimes; y++) {
				spriteBatch.draw(texture, x * width, y * height, width, height);
			}
		}
		spriteBatch.end();
	}
}


text:
#pragma once
#include <aws/gamelift/GameLift_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace GameLift
{
namespace Model
{
  /**
   *
Represents the returned data in response to a request
   * operation.

See Also:
   AWS
   * API Reference

   */
  class AWS_GAMELIFT_API ListFleetsResult
  {
  public:
    ListFleetsResult();
    ListFleetsResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    ListFleetsResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
Set of fleet IDs matching the list request. You can retrieve additional
     * information about all returned fleets by passing this result set to a call to
     * DescribeFleetAttributes, DescribeFleetCapacity, or
     * DescribeFleetUtilization.

     */
    inline const Aws::Vector<Aws::String>& GetFleetIds() const{ return m_fleetIds; }

    /**
     *
Set of fleet IDs matching the list request. You can retrieve additional
     * information about all returned fleets by passing this result set to a call to
     * DescribeFleetAttributes, DescribeFleetCapacity, or
     * DescribeFleetUtilization.

     */
    inline void SetFleetIds(const Aws::Vector<Aws::String>& value) { m_fleetIds = value; }

    /**
     *
Set of fleet IDs matching the list request. You can retrieve additional
     * information about all returned fleets by passing this result set to a call to
     * DescribeFleetAttributes, DescribeFleetCapacity, or
     * DescribeFleetUtilization.

     */
    inline void SetFleetIds(Aws::Vector<Aws::String>&& value) { m_fleetIds = std::move(value); }

    /**
     *
Set of fleet IDs matching the list request. You can retrieve additional
     * information about all returned fleets by passing this result set to a call to
     * DescribeFleetAttributes, DescribeFleetCapacity, or
     * DescribeFleetUtilization.

     */
    inline ListFleetsResult& WithFleetIds(const Aws::Vector<Aws::String>& value) { SetFleetIds(value); return *this;}

    /**
     *
Set of fleet IDs matching the list request. You can retrieve additional
     * information about all returned fleets by passing this result set to a call to
     * DescribeFleetAttributes, DescribeFleetCapacity, or
     * DescribeFleetUtilization.

     */
    inline ListFleetsResult& WithFleetIds(Aws::Vector<Aws::String>&& value) { SetFleetIds(std::move(value)); return *this;}

    /**
     *
Set of fleet IDs matching the list request. You can retrieve additional
     * information about all returned fleets by passing this result set to a call to
     * DescribeFleetAttributes, DescribeFleetCapacity, or
     * DescribeFleetUtilization.

     */
    inline ListFleetsResult& AddFleetIds(const Aws::String& value) { m_fleetIds.push_back(value); return *this; }

    /**
     *
Set of fleet IDs matching the list request. You can retrieve additional
     * information about all returned fleets by passing this result set to a call to
     * DescribeFleetAttributes, DescribeFleetCapacity, or
     * DescribeFleetUtilization.

     */
    inline ListFleetsResult& AddFleetIds(Aws::String&& value) { m_fleetIds.push_back(std::move(value)); return *this; }

    /**
     *
Set of fleet IDs matching the list request. You can retrieve additional
     * information about all returned fleets by passing this result set to a call to
     * DescribeFleetAttributes, DescribeFleetCapacity, or
     * DescribeFleetUtilization.

     */
    inline ListFleetsResult& AddFleetIds(const char* value) { m_fleetIds.push_back(value); return *this; }

    /**
     *
Token that indicates where to resume retrieving results on the next call to
     * this operation. If no token is returned, these results represent the end of the
     * list.

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

    /**
     *
Token that indicates where to resume retrieving results on the next call to
     * this operation. If no token is returned, these results represent the end of the
     * list.

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

    /**
     *
Token that indicates where to resume retrieving results on the next call to
     * this operation. If no token is returned, these results represent the end of the
     * list.

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

    /**
     *
Token that indicates where to resume retrieving results on the next call to
     * this operation. If no token is returned, these results represent the end of the
     * list.

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

    /**
     *
Token that indicates where to resume retrieving results on the next call to
     * this operation. If no token is returned, these results represent the end of the
     * list.

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

    /**
     *
Token that indicates where to resume retrieving results on the next call to
     * this operation. If no token is returned, these results represent the end of the
     * list.

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

    /**
     *
Token that indicates where to resume retrieving results on the next call to
     * this operation. If no token is returned, these results represent the end of the
     * list.

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

  private:

    Aws::Vector<Aws::String> m_fleetIds;

    Aws::String m_nextToken;
  };

} // namespace Model
} // namespace GameLift
} // namespace Aws