text:
package org.apache.carbondata.processing.csvreaderstep;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.apache.carbondata.common.logging.LogService;
import org.apache.carbondata.common.logging.LogServiceFactory;
import org.apache.carbondata.common.logging.impl.StandardLogService;
import org.apache.carbondata.core.constants.CarbonCommonConstants;
import org.apache.carbondata.core.load.BlockDetails;
import org.apache.carbondata.core.util.CarbonProperties;
import org.apache.carbondata.core.util.CarbonTimeStatisticsFactory;
import org.apache.carbondata.processing.graphgenerator.GraphGenerator;

import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStep;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.di.trans.steps.textfileinput.EncodingType;

/**
 * Read a simple CSV file
 * Just output Strings found in the file...
 */
public class CsvInput extends BaseStep implements StepInterface {
  private static final Class<?> PKG = CsvInput.class;
  // for i18n purposes, needed by Translator2!!   $NON-NLS-1$
  private static final LogService LOGGER =
      LogServiceFactory.getLogService(CsvInput.class.getName());
  /**
   * NUM_CORES_DEFAULT_VAL
   */
  private static final int NUM_CORES_DEFAULT_VAL = 2;
  /**
   * ReentrantLock getFileBlockLock
   */
  private final Object getBlockListLock = new Object();
  /**
   * ReentrantLock putRowLock
   */
  private final Object putRowLock = new Object();
  private CsvInputMeta meta;
  private CsvInputData data;
  /**
   * resultArray
   */
  private Future[] resultArray;
  private boolean isTerminated;
  private List<List<BlockDetails>> threadBlockList = new ArrayList<>();

  private ExecutorService exec;

  public CsvInput(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr,
      TransMeta transMeta, Trans trans) {
    super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
    LOGGER.info("** Using csv file **");
  }

  /**
   * This method is borrowed from TextFileInput
   *
   * @param log
   * @param line
   * @param delimiter
   * @param enclosure
   * @param escapeCharacter
   * @return
   * @throws KettleException
   */
  public static final String[] guessStringsFromLine(LogChannelInterface log, String line,
      String delimiter, String enclosure, String escapeCharacter) throws KettleException {
    List<String> strings = new ArrayList<String>(CarbonCommonConstants.CONSTANT_SIZE_TEN);

    String pol; // piece of line

    try {
      if (line == null) {
        return null;
      }

      // Split string in pieces, only for CSV!
      int pos = 0;
      int length = line.length();
      boolean dencl = false;

      int lenEncl = (enclosure == null ? 0 : enclosure.length());
      int lenEsc = (escapeCharacter == null ? 0 : escapeCharacter.length());

      while (pos < length) {
        int from = pos;
        int next;

        boolean enclFound;
        boolean containsEscapedEnclosures = false;
        boolean containsEscapedSeparators = false;

        // Is the field beginning with an enclosure?
        // "aa;aa";123;"aaa-aaa";000;...
        if (lenEncl > 0 && line.substring(from, from + lenEncl).equalsIgnoreCase(enclosure)) {
          if (log.isRowLevel()) {
            log.logRowlevel(BaseMessages.getString(PKG, "CsvInput.Log.ConvertLineToRowTitle"),
                BaseMessages.getString(PKG, "CsvInput.Log.ConvertLineToRow",
                    line.substring(from, from + lenEncl))); //$NON-NLS-1$ //$NON-NLS-2$
          }
          enclFound = true;
          int p = from + lenEncl;

          boolean isEnclosure =
              lenEncl > 0 && p + lenEncl < length && line.substring(p, p + lenEncl)
                  .equalsIgnoreCase(enclosure);
          boolean isEscape = lenEsc > 0 && p + lenEsc < length && line.substring(p, p + lenEsc)
              .equalsIgnoreCase(escapeCharacter);

          boolean enclosureAfter = false;

          // Is it really an enclosure? See if it's not repeated twice or escaped!
          if ((isEnclosure || isEscape) && p < length - 1) {
            String strnext = line.substring(p + lenEncl, p + 2 * lenEncl);
            if (strnext.equalsIgnoreCase(enclosure)) {
              p++;
              enclosureAfter = true;
              dencl = true;

              // Remember to replace them later on!
              if (isEscape) {
                containsEscapedEnclosures = true;
              }
            }
          }

          // Look for a closing enclosure!
          while ((!isEnclosure || enclosureAfter) && p < line.length()) {
            p++;
            enclosureAfter = false;
            isEnclosure = lenEncl > 0 && p + lenEncl < length && line.substring(p, p + lenEncl)
                .equals(enclosure);
            isEscape = lenEsc > 0 && p + lenEsc < length && line.substring(p, p + lenEsc)
                .equals(escapeCharacter);

            // Is it really an enclosure? See if it's not repeated twice or escaped!
            if ((isEnclosure || isEscape) && p < length - 1) // Is
            {
              String strnext = line.substring(p + lenEncl, p + 2 * lenEncl);
              if (strnext.equals(enclosure)) {
                p++;
                enclosureAfter = true;
                dencl = true;

                // Remember to replace them later on!
                if (isEscape) {
                  containsEscapedEnclosures = true; // remember
                }
              }
            }
          }

          if (p >= length) {
            next = p;
          } else {
            next = p + lenEncl;
          }

          if (log.isRowLevel()) {
            log.logRowlevel(BaseMessages.getString(PKG, "CsvInput.Log.ConvertLineToRowTitle"),
                BaseMessages.getString(PKG, "CsvInput.Log.EndOfEnclosure",
                    "" + p)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
          }
        } else {
          enclFound = false;
          boolean found = false;
          int startpoint = from;
          do {
            next = line.indexOf(delimiter, startpoint);

            // See if this position is preceded by an escape character.
            if (lenEsc > 0 && next - lenEsc > 0) {
              String before = line.substring(next - lenEsc, next);

              if (escapeCharacter != null && escapeCharacter.equals(before)) {
                // take the next separator, this one is escaped...
                startpoint = next + 1;
                containsEscapedSeparators = true;
              } else {
                found = true;
              }
            } else {
              found = true;
            }
          } while (!found && next >= 0);
        }
        if (next == -1) {
          next = length;
        }

        if (enclFound) {
          pol = line.substring(from + lenEncl, next - lenEncl);
          if (log.isRowLevel()) {
            log.logRowlevel(BaseMessages.getString(PKG, "CsvInput.Log.ConvertLineToRowTitle"),
                BaseMessages.getString(PKG, "CsvInput.Log.EnclosureFieldFound",
                    "" + pol)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
          }
        } else {
          pol = line.substring(from, next);
          if (log.isRowLevel()) {
            log.logRowlevel(BaseMessages.getString(PKG, "CsvInput.Log.ConvertLineToRowTitle"),
                BaseMessages.getString(PKG, "CsvInput.Log.NormalFieldFound",
                    "" + pol)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
          }
        }

        if (dencl) {
          StringBuilder sbpol = new StringBuilder(pol);
          int idx = sbpol.indexOf(enclosure + enclosure);
          while (idx >= 0) {
            sbpol.delete(idx, idx + (enclosure == null ? 0 : enclosure.length()));
            idx = sbpol.indexOf(enclosure + enclosure);
          }
          pol = sbpol.toString();
        }

        //  replace the escaped enclosures with enclosures...
        if (containsEscapedEnclosures) {
          String replace = escapeCharacter + enclosure;
          String replaceWith = enclosure;

          pol = Const.replace(pol, replace, replaceWith);
        }

        //replace the escaped separators with separators...
        if (containsEscapedSeparators) {
          String replace = escapeCharacter + delimiter;
          String replaceWith = delimiter;

          pol = Const.replace(pol, replace, replaceWith);
        }

        // Now add pol to the strings found!
        strings.add(pol);

        pos = next + delimiter.length();
      }
      if (pos == length) {
        if (log.isRowLevel()) {
          log.logRowlevel(BaseMessages.getString(PKG, "CsvInput.Log.ConvertLineToRowTitle"),
              BaseMessages.getString(PKG, "CsvInput.Log.EndOfEmptyLineFound"));
        }
        strings.add(""); //$NON-NLS-1$
      }
    } catch (Exception e) {
      throw new KettleException(
          BaseMessages.getString(PKG, "CsvInput.Log.Error.ErrorConvertingLine", e.toString()),
          e); //$NON-NLS-1$
    }

    return strings.toArray(new String[strings.size()]);
  }

  public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
    meta = (CsvInputMeta) smi;
    data = (CsvInputData) sdi;

    if (first) {
      CarbonTimeStatisticsFactory.getLoadStatisticsInstance().recordDictionaryValuesTotalTime(
          meta.getPartitionID(), System.currentTimeMillis());
      CarbonTimeStatisticsFactory.getLoadStatisticsInstance().recordCsvInputStepTime(
          meta.getPartitionID(), System.currentTimeMillis());
      first = false;
      data.outputRowMeta = new RowMeta();
      meta.getFields(data.outputRowMeta, getStepname(), null, null, this);

      // We only run in parallel if we have at least one file to process
      // AND if we have more than one step copy running...
      //
      data.parallel = meta.isRunningInParallel() && data.totalNumberOfSteps > 1;

      // The conversion logic for when the lazy conversion is turned of is simple:
      // Pretend it's a lazy conversion object anyway and get the native type during
      // conversion.
      //
      data.convertRowMeta = data.outputRowMeta.clone();

      for (ValueMetaInterface valueMeta : data.convertRowMeta.getValueMetaList()) {
        valueMeta.setStorageType(ValueMetaInterface.STORAGE_TYPE_BINARY_STRING);
      }

      // Calculate the indexes for the filename and row number fields
      //
      data.filenameFieldIndex = -1;
      if (!Const.isEmpty(meta.getFilenameField()) && meta.isIncludingFilename()) {
        data.filenameFieldIndex = meta.getInputFields().length;
      }

      data.rownumFieldIndex = -1;
      if (!Const.isEmpty(meta.getRowNumField())) {
        data.rownumFieldIndex = meta.getInputFields().length;
        if (data.filenameFieldIndex >= 0) {
          data.rownumFieldIndex++;
        }
      }
    }

    // start multi-thread to process
    int numberOfNodes;
    try {
      numberOfNodes = Integer.parseInt(CarbonProperties.getInstance()
          .getProperty(CarbonCommonConstants.NUM_CORES_LOADING,
              CarbonCommonConstants.NUM_CORES_DEFAULT_VAL));
    } catch (NumberFormatException exc) {
      numberOfNodes = NUM_CORES_DEFAULT_VAL;
    }

    BlockDetails[] blocksInfo = GraphGenerator.blockInfo.get(meta.getBlocksID());
    if (blocksInfo.length == 0) {
      //if isDirectLoad = true, and partition number > file num
      //then blocksInfo will get empty in some partition processing, so just return
      setOutputDone();
      return false;
    }

    if (numberOfNodes > blocksInfo.length) {
      numberOfNodes = blocksInfo.length;
    }

    //new the empty lists
    for (int pos = 0; pos < numberOfNodes; pos++) {
      threadBlockList.add(new ArrayList<BlockDetails>());
    }

    //block balance to every thread
    for (int pos = 0; pos < blocksInfo.length; ) {
      for (int threadNum = 0; threadNum < numberOfNodes; threadNum++) {
        if (pos < blocksInfo.length) {
          threadBlockList.get(threadNum).add(blocksInfo[pos++]);
        }
      }
    }
    LOGGER.info("*****************Started all csv reading***********");
    startProcess(numberOfNodes);
    LOGGER.info("*****************Completed all csv reading***********");
    CarbonTimeStatisticsFactory.getLoadStatisticsInstance().recordCsvInputStepTime(
        meta.getPartitionID(), System.currentTimeMillis());
    setOutputDone();
    return false;
  }

  private void startProcess(final int numberOfNodes) throws RuntimeException {
    exec = Executors.newFixedThreadPool(numberOfNodes);

    Callable<Void> callable = new Callable<Void>() {
      @Override public Void call() throws RuntimeException {
        StandardLogService.setThreadName(("PROCESS_BLOCKS"), Thread.currentThread().getName());
        try {
          LOGGER.info("*****************started csv reading by thread***********");
          doProcessUnivocity();
          LOGGER.info("*****************Completed csv reading by thread***********");
        } catch (Throwable e) {
          LOGGER.error(e, "Thread is terminated due to error");
          throw new RuntimeException("Thread is terminated due to error : " + e.getMessage());
        }
        return null;
      }
    };
    List<Future<Void>> results = new ArrayList<Future<Void>>(10);
    for (int i = 0; i < numberOfNodes; i++) {
      results.add(exec.submit(callable));
    }

    resultArray = results.toArray(new Future[results.size()]);
    try {
      for (int j = 0; j < resultArray.length; j++) {
        resultArray[j].get();
      }
    } catch (InterruptedException | ExecutionException e) {
      throw new RuntimeException("Thread InterruptedException", e);
    }
    finally {
      exec.shutdownNow();
    }
  }

  private void doProcessUnivocity() {
    List<BlockDetails> blocksListForProcess = null;
    synchronized (getBlockListLock) {
      //get the blocksList for this thread
      blocksListForProcess = threadBlockList.get(threadBlockList.size() - 1);
      threadBlockList.remove(threadBlockList.size() - 1);
    }
    long currentTimeMillis = System.currentTimeMillis();
    UnivocityCsvParser parser = new UnivocityCsvParser(getParserVo(blocksListForProcess));
    long numberOfRows = 0;
    int numberOfColumns = meta.getInputFields().length;
    try {
      parser.initialize();
      while (parser.hasMoreRecords()) {
        String[] next = parser.getNextRecord();
        if (next.length < numberOfColumns) {
          String[] temp = new String[numberOfColumns];
          System.arraycopy(next, 0, temp, 0, next.length);
          next = temp;
        }
        synchronized (putRowLock) {
          putRow(data.outputRowMeta, next);
          numberOfRows++;
        }
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    } catch (KettleException e) {
      throw new RuntimeException(e);
    }
    LOGGER.info("Total Number of records processed by this thread is: " + numberOfRows);
    LOGGER.info("Time taken to processed " + numberOfRows + " Number of records: " + (
        System.currentTimeMillis() - currentTimeMillis));
  }

  private UnivocityCsvParserVo getParserVo(List<BlockDetails> blocksListForProcess) {
    UnivocityCsvParserVo csvParserVo = new UnivocityCsvParserVo();
    csvParserVo.setBlockDetailsList(blocksListForProcess);
    csvParserVo.setDelimiter(meta.getDelimiter());
    csvParserVo.setNumberOfColumns(meta.getInputFields().length);
    csvParserVo.setEscapeCharacter(meta.getEscapeCharacter());
    csvParserVo.setHeaderPresent(meta.isHeaderPresent());
    csvParserVo.setQuoteCharacter(meta.getQuoteCharacter());
    csvParserVo.setCommentCharacter(meta.getCommentCharacter());
    String maxColumns = meta.getMaxColumns();
    if(null != maxColumns) {
      csvParserVo.setMaxColumns(Integer.parseInt(maxColumns));
    }
    return csvParserVo;
  }

  @Override public void dispose(StepMetaInterface smi, StepDataInterface sdi) {
    try {
      // Clean the block info in map
      if (GraphGenerator.blockInfo.get(meta.getBlocksID()) != null) {
        GraphGenerator.blockInfo.remove(meta.getBlocksID());
      }
    } catch (Exception e) {
      logError("Error closing file channel", e);
    }

    super.dispose(smi, sdi);
  }

  public boolean init(StepMetaInterface smi, StepDataInterface sdi) {
    meta = (CsvInputMeta) smi;
    data = (CsvInputData) sdi;

    if (super.init(smi, sdi)) {
      // If the step doesn't have any previous steps, we just get the filename.
      // Otherwise, we'll grab the list of filenames later...
      //
      if (getTransMeta().findNrPrevSteps(getStepMeta()) == 0) {
        String filename = environmentSubstitute(meta.getFilename());

        if (Const.isEmpty(filename)) {
          logError(BaseMessages.getString(PKG, "CsvInput.MissingFilename.Message")); //$NON-NLS-1$
          return false;
        }
      }

      data.encodingType = EncodingType.guessEncodingType(meta.getEncoding());

      // PDI-2489 - set the delimiter byte value to the code point of the
      // character as represented in the input file's encoding
      try {
        data.delimiter = data.encodingType
            .getBytes(environmentSubstitute(meta.getDelimiter()), meta.getEncoding());
        data.escapeCharacter = data.encodingType
            .getBytes(environmentSubstitute(meta.getEscapeCharacter()), meta.getEncoding());
        if (Const.isEmpty(meta.getEnclosure())) {
          data.enclosure = null;
        } else {
          data.enclosure = data.encodingType
              .getBytes(environmentSubstitute(meta.getEnclosure()), meta.getEncoding());
        }

      } catch (UnsupportedEncodingException e) {
        logError(BaseMessages.getString(PKG, "CsvInput.BadEncoding.Message"), e); //$NON-NLS-1$
        return false;
      }

      // Handle parallel reading capabilities...
      //

      if (meta.isRunningInParallel()) {
        data.totalNumberOfSteps = getUniqueStepCountAcrossSlaves();

        // We are not handling a single file, but possibly a list of files...
        // As such, the fair thing to do is calculate the total size of the files
        // Then read the required block.
        //

      }
      return true;
    }
    return false;
  }

}


text:
using namespace std::chrono_literals;

#ifdef RMW_IMPLEMENTATION
# define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX
# define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX)
#else
# define CLASSNAME(NAME, SUFFIX) NAME
#endif

class CLASSNAME (test_local_parameters, RMW_IMPLEMENTATION) : public ::testing::Test
{
public:
  static void SetUpTestCase()
  {
    rclcpp::init(0, nullptr);
  }

  static void TearDownTestCase()
  {
    rclcpp::shutdown();
  }
};

TEST_F(CLASSNAME(test_local_parameters, RMW_IMPLEMENTATION), to_string) {
  rclcpp::Parameter pv("foo", "bar");
  rclcpp::Parameter pv2("foo2", "bar2");
  std::string json_dict = std::to_string(pv);
  EXPECT_STREQ(
    "{\"name\": \"foo\", \"type\": \"string\", \"value\": \"bar\"}",
    json_dict.c_str());
  json_dict = rclcpp::_to_json_dict_entry(pv);
  EXPECT_STREQ(
    "\"foo\": {\"type\": \"string\", \"value\": \"bar\"}",
    json_dict.c_str());
  std::vector<rclcpp::Parameter> vpv;
  vpv.push_back(pv);
  vpv.push_back(pv2);
  json_dict = std::to_string(vpv);
  EXPECT_STREQ(
    "{\"foo\": {\"type\": \"string\", \"value\": \"bar\"}, "
    "\"foo2\": {\"type\": \"string\", \"value\": \"bar2\"}}",
    json_dict.c_str());

  pv = rclcpp::Parameter("foo", 2.1);
  // TODO(tfoote) convert the value to a float and use epsilon test.
  EXPECT_STREQ(
    "{\"name\": \"foo\", \"type\": \"double\", \"value\": \"2.100000\"}",
    std::to_string(pv).c_str());
  pv = rclcpp::Parameter("foo", 8);
  EXPECT_STREQ(
    "{\"name\": \"foo\", \"type\": \"integer\", \"value\": \"8\"}",
    std::to_string(pv).c_str());
}

TEST_F(CLASSNAME(test_local_parameters, RMW_IMPLEMENTATION), local_synchronous) {
  auto node = rclcpp::Node::make_shared("test_parameters_local_synchronous");
  declare_test_parameters(node);
  auto parameters_client = std::make_shared<rclcpp::SyncParametersClient>(node);
  if (!parameters_client->wait_for_service(20s)) {
    ASSERT_TRUE(false) << "service not available after waiting";
  }
  test_set_parameters_sync(parameters_client);
  test_get_parameters_sync(parameters_client);
}

TEST_F(CLASSNAME(test_local_parameters, RMW_IMPLEMENTATION), local_synchronous_repeated) {
  auto node = rclcpp::Node::make_shared("test_parameters_local_synchronous_repeated");
  declare_test_parameters(node);
  auto parameters_client = std::make_shared<rclcpp::SyncParametersClient>(node);
  if (!parameters_client->wait_for_service(20s)) {
    ASSERT_TRUE(false) << "service not available after waiting";
  }
  test_set_parameters_sync(parameters_client);
  for (int i = 0; i < 10; ++i) {
    printf("iteration: %d\n", i);
    test_get_parameters_sync(parameters_client);
  }
}

TEST_F(CLASSNAME(test_local_parameters, RMW_IMPLEMENTATION), local_asynchronous) {
  auto node = rclcpp::Node::make_shared(std::string("test_parameters_local_asynchronous"));
  declare_test_parameters(node);
  auto parameters_client = std::make_shared<rclcpp::AsyncParametersClient>(node);
  if (!parameters_client->wait_for_service(20s)) {
    ASSERT_TRUE(false) << "service not available after waiting";
  }
  test_set_parameters_async(node, parameters_client);
  test_get_parameters_async(node, parameters_client);
}

class ParametersAsyncNode : public rclcpp::Node
{
public:
  ParametersAsyncNode()
  : Node("test_local_parameters_async_with_callback")
  {
    this->declare_parameter("foo", 0);
    this->declare_parameter("bar", "");
    this->declare_parameter("barstr", "");
    this->declare_parameter("baz", 0.);
    this->declare_parameter("foobar", false);
    this->declare_parameter("barfoo", std::vector<uint8_t>{});

    parameters_client_ =
      std::make_shared<rclcpp::AsyncParametersClient>(this);
  }

  void queue_set_parameter_request(rclcpp::executors::SingleThreadedExecutor & executor)
  {
    using rclcpp::Parameter;
    using SetParametersResult =
      std::shared_future<std::vector<rcl_interfaces::msg::SetParametersResult>>;
    auto parameters = {
      Parameter("foo", 2),
      Parameter("bar", "hello"),
      Parameter("barstr", std::string("hello_str")),
      Parameter("baz", 1.45),
      Parameter("foobar", true),
      Parameter("barfoo", std::vector<uint8_t>{3, 4, 5}),
    };
    auto set_parameters_results = parameters_client_->set_parameters(
      parameters,
      [&executor](SetParametersResult future)
      {
        printf("Got set_parameters result\n");
        // Check to see if they were set.
        for (auto & result : future.get()) {
          ASSERT_TRUE(result.successful);
        }
        executor.cancel();
      }
    );
  }

  rclcpp::AsyncParametersClient::SharedPtr parameters_client_;
};

// Regression test for calling parameter client async services, but having the specified callback
// go out of scope before it gets called: see https://github.com/ros2/rclcpp/pull/414
TEST_F(CLASSNAME(test_local_parameters, RMW_IMPLEMENTATION), local_async_with_callback) {
  auto node = std::make_shared<ParametersAsyncNode>();
  if (!node->parameters_client_->wait_for_service(20s)) {
    ASSERT_TRUE(false) << "service not available after waiting";
  }
  rclcpp::executors::SingleThreadedExecutor executor;
  executor.add_node(node);
  node->queue_set_parameter_request(executor);
  // When the parameters client receives its response it will cancel the executor.
  executor.spin();
}

TEST_F(CLASSNAME(test_local_parameters, RMW_IMPLEMENTATION), helpers) {
  auto node = rclcpp::Node::make_shared("test_parameters_local_helpers");
  node->declare_parameter("foo", 0);
  node->declare_parameter("bar", "");
  node->declare_parameter("barstr", "");
  node->declare_parameter("baz", 0.);
  node->declare_parameter("foobar", false);
  node->declare_parameter("barfoo", std::vector<uint8_t>{});

  auto parameters_client = std::make_shared<rclcpp::SyncParametersClient>(node);
  if (!parameters_client->wait_for_service(20s)) {
    ASSERT_TRUE(false) << "service not available after waiting";
  }
  auto set_parameters_results = parameters_client->set_parameters(
  {
    rclcpp::Parameter("foo", 2),
    rclcpp::Parameter("bar", "hello"),
    rclcpp::Parameter("barstr", std::string("hello_str")),
    rclcpp::Parameter("baz", 1.45),
    rclcpp::Parameter("foobar", true),
    rclcpp::Parameter("barfoo", std::vector<uint8_t>{0, 1, 2}),
  }, 1s);
  printf("Got set_parameters result\n");

  // Check to see if they were set.
  for (auto & result : set_parameters_results) {
    ASSERT_TRUE(result.successful);
  }

  int foo = 0;
  std::string bar, barstr;
  double baz = 0.;
  bool foobar = false;
  std::vector<uint8_t> barfoo;

  // Test variables that are set, verifying that types are obeyed, and defaults not used.
  EXPECT_TRUE(parameters_client->has_parameter("foo"));
  EXPECT_THROW(
    baz = parameters_client->get_parameter<double>("foo"),
    rclcpp::exceptions::InvalidParameterTypeException);
  EXPECT_NO_THROW(foo = parameters_client->get_parameter<int>("foo"));
  EXPECT_EQ(foo, 2);
  EXPECT_NO_THROW(foo = parameters_client->get_parameter("foo", 42));
  EXPECT_EQ(foo, 2);

  EXPECT_TRUE(parameters_client->has_parameter("bar"));
  EXPECT_THROW(
    foo = parameters_client->get_parameter<int>("bar"),
    rclcpp::exceptions::InvalidParameterTypeException);
  EXPECT_NO_THROW(bar = parameters_client->get_parameter<std::string>("bar"));
  EXPECT_EQ(bar, "hello");
  EXPECT_NO_THROW(bar = parameters_client->get_parameter<std::string>("bar", "goodbye"));
  EXPECT_EQ(bar, "hello");

  EXPECT_TRUE(parameters_client->has_parameter("barstr"));
  EXPECT_THROW(
    foobar = parameters_client->get_parameter<bool>("barstr"),
    rclcpp::exceptions::InvalidParameterTypeException);
  EXPECT_NO_THROW(barstr = parameters_client->get_parameter<std::string>("barstr"));
  EXPECT_EQ(barstr, "hello_str");
  EXPECT_NO_THROW(barstr = parameters_client->get_parameter("barstr", std::string("heya")));
  EXPECT_EQ(barstr, "hello_str");

  EXPECT_TRUE(parameters_client->has_parameter("baz"));
  EXPECT_THROW(
    foobar = parameters_client->get_parameter<bool>("baz"),
    rclcpp::exceptions::InvalidParameterTypeException);
  EXPECT_NO_THROW(baz = parameters_client->get_parameter<double>("baz"));
  EXPECT_DOUBLE_EQ(baz, 1.45);
  EXPECT_NO_THROW(baz = parameters_client->get_parameter("baz", -4.2));
  EXPECT_DOUBLE_EQ(baz, 1.45);

  EXPECT_TRUE(parameters_client->has_parameter("foobar"));
  EXPECT_THROW(
    baz = parameters_client->get_parameter<double>("foobar"),
    rclcpp::exceptions::InvalidParameterTypeException);
  EXPECT_NO_THROW(foobar = parameters_client->get_parameter<bool>("foobar"));
  EXPECT_EQ(foobar, true);
  EXPECT_NO_THROW(foobar = parameters_client->get_parameter("foobar", false));
  EXPECT_EQ(foobar, true);

  EXPECT_TRUE(parameters_client->has_parameter("barfoo"));
  EXPECT_THROW(
    bar = parameters_client->get_parameter<std::string>("barfoo"),
    rclcpp::exceptions::InvalidParameterTypeException);
  EXPECT_NO_THROW(barfoo = parameters_client->get_parameter<std::vector<uint8_t>>("barfoo"));
  EXPECT_EQ(barfoo[0], 0);
  EXPECT_EQ(barfoo[1], 1);
  EXPECT_EQ(barfoo[2], 2);
  EXPECT_NO_THROW(
    barfoo = parameters_client->get_parameter("barfoo", std::vector<uint8_t>{3, 4, 5}));
  EXPECT_EQ(barfoo[0], 0);
  EXPECT_EQ(barfoo[1], 1);
  EXPECT_EQ(barfoo[2], 2);

  // Test a variable that's not set, checking that we throw when asking for its value without
  // specifying a default.
  EXPECT_FALSE(parameters_client->has_parameter("not_there"));
  EXPECT_THROW(parameters_client->get_parameter<int>("not_there"), std::runtime_error);
  EXPECT_THROW(parameters_client->get_parameter<std::string>("not_there"), std::runtime_error);
  EXPECT_THROW(parameters_client->get_parameter<double>("not_there"), std::runtime_error);
  EXPECT_THROW(parameters_client->get_parameter<bool>("not_there"), std::runtime_error);
  EXPECT_THROW(
    parameters_client->get_parameter<std::vector<uint8_t>>("not_there"), std::runtime_error);

  // Test a variable that's not set, checking that we correctly get the specified default.
  EXPECT_NO_THROW(foo = parameters_client->get_parameter("not_there", 42));
  EXPECT_EQ(foo, 42);
  EXPECT_NO_THROW(bar = parameters_client->get_parameter<std::string>("not_there", "goodbye"));
  EXPECT_EQ(bar, "goodbye");
  EXPECT_NO_THROW(barstr = parameters_client->get_parameter("not_there", std::string("heya")));
  EXPECT_EQ(barstr, "heya");
  EXPECT_NO_THROW(baz = parameters_client->get_parameter("not_there", -4.2));
  EXPECT_DOUBLE_EQ(baz, -4.2);
  EXPECT_NO_THROW(foobar = parameters_client->get_parameter("not_there", false));
  EXPECT_EQ(foobar, false);
  EXPECT_NO_THROW(
    barfoo = parameters_client->get_parameter("not_there", std::vector<uint8_t>{3, 4, 5}));
  EXPECT_EQ(barfoo[0], 3);
  EXPECT_EQ(barfoo[1], 4);
  EXPECT_EQ(barfoo[2], 5);
}

TEST_F(CLASSNAME(test_local_parameters, RMW_IMPLEMENTATION), get_from_node_primitive_type) {
  auto node = rclcpp::Node::make_shared("test_parameters_local_helpers");
  node->declare_parameter("foo", 0);
  node->declare_parameter("bar", "");
  node->declare_parameter("barstr", "");
  node->declare_parameter("baz", 0.);
  node->declare_parameter("foobar", false);
  node->declare_parameter("barfoo", std::vector<uint8_t>{});

  auto parameters_client = std::make_shared<rclcpp::SyncParametersClient>(node);
  if (!parameters_client->wait_for_service(20s)) {
    ASSERT_TRUE(false) << "service not available after waiting";
  }
  auto set_parameters_results = parameters_client->set_parameters(
  {
    rclcpp::Parameter("foo", 2),
    rclcpp::Parameter("bar", "hello"),
    rclcpp::Parameter("barstr", std::string("hello_str")),
    rclcpp::Parameter("baz", 1.45),
    rclcpp::Parameter("foobar", true),
    rclcpp::Parameter("barfoo", std::vector<uint8_t>{3, 4, 5}),
  }, 1s);
  printf("Got set_parameters result\n");

  // Check to see if they were set.
  for (auto & result : set_parameters_results) {
    ASSERT_TRUE(result.successful);
  }

  bool got_param = false;

  int64_t foo = 0;
  std::string foostr;

  std::string bar = "bar";
  double baz = 0.0;
  bool foobar = false;
  std::vector<uint8_t> barfoo(3);

  EXPECT_NO_THROW(got_param = node->get_parameter("foo", foo));
  EXPECT_EQ(true, got_param);
  EXPECT_EQ(2, foo);

  // Throw on type error
  EXPECT_THROW(
    got_param = node->get_parameter("foo", foostr),
    rclcpp::exceptions::InvalidParameterTypeException);

  // No throw on non-existent param, param shouldn't change
  foo = 1000;
  EXPECT_NO_THROW(got_param = node->get_parameter("no_such_param", foo));
  EXPECT_FALSE(got_param);
  EXPECT_EQ(1000, foo);

  EXPECT_NO_THROW(got_param = node->get_parameter("bar", bar));
  EXPECT_EQ(true, got_param);
  EXPECT_EQ("hello", bar);

  EXPECT_NO_THROW(got_param = node->get_parameter("baz", baz));
  EXPECT_EQ(true, got_param);
  EXPECT_DOUBLE_EQ(1.45, baz);

  EXPECT_NO_THROW(got_param = node->get_parameter("foobar", foobar));
  EXPECT_EQ(true, got_param);
  EXPECT_EQ(true, foobar);

  EXPECT_NO_THROW(got_param = node->get_parameter("barfoo", barfoo));
  EXPECT_EQ(true, got_param);
  EXPECT_EQ(barfoo[0], 3);
  EXPECT_EQ(barfoo[1], 4);
  EXPECT_EQ(barfoo[2], 5);
}

TEST_F(CLASSNAME(test_local_parameters, RMW_IMPLEMENTATION), get_from_node_variant_type) {
  using rclcpp::Parameter;

  auto node = rclcpp::Node::make_shared("test_parameters_local_helpers");
  node->declare_parameter("foo", 0);
  node->declare_parameter("bar", "");
  node->declare_parameter("barstr", "");
  node->declare_parameter("baz", 0.);
  node->declare_parameter("foobar", false);
  node->declare_parameter("barfoo", std::vector<uint8_t>{});

  auto parameters_client = std::make_shared<rclcpp::SyncParametersClient>(node);
  if (!parameters_client->wait_for_service(20s)) {
    ASSERT_TRUE(false) << "service not available after waiting";
  }
  auto set_parameters_results = parameters_client->set_parameters(
  {
    Parameter("foo", 2),
    Parameter("bar", "hello"),
    Parameter("barstr", std::string("hello_str")),
    Parameter("baz", 1.45),
    Parameter("foobar", true),
    Parameter("barfoo", std::vector<uint8_t>{3, 4, 5}),
  }, 1s);
  printf("Got set_parameters result\n");

  // Check to see if they were set.
  for (auto & result : set_parameters_results) {
    ASSERT_TRUE(result.successful);
  }

  bool got_param = false;

  Parameter foo;
  Parameter foostr;

  Parameter bar;
  Parameter baz;
  Parameter foobar;
  Parameter barfoo;

  EXPECT_NO_THROW(got_param = node->get_parameter("foo", foo));
  EXPECT_EQ(true, got_param);

  // No throw on non-existent param for reference passed version
  EXPECT_NO_THROW(got_param = node->get_parameter("no_such_param", foo));
  EXPECT_FALSE(got_param);

  // Throw on non-existent param for returning version
  EXPECT_THROW(
    node->get_parameter("no_such_param"),
    rclcpp::exceptions::ParameterNotDeclaredException);

  EXPECT_NO_THROW(got_param = node->get_parameter("bar", bar));
  EXPECT_EQ(true, got_param);

  EXPECT_NO_THROW(got_param = node->get_parameter("baz", baz));
  EXPECT_EQ(true, got_param);

  EXPECT_NO_THROW(got_param = node->get_parameter("foobar", foobar));
  EXPECT_EQ(true, got_param);

  EXPECT_NO_THROW(got_param = node->get_parameter("barfoo", barfoo));
  EXPECT_EQ(true, got_param);
}

int main(int argc, char ** argv)
{
  setvbuf(stdout, NULL, _IONBF, BUFSIZ);
  ::testing::InitGoogleTest(&argc, argv);
  int ret = RUN_ALL_TESTS();
  return ret;
}

redpajama_set_name: RedPajamaGithub


text:
package com.almasb.tutorial11;

import javafx.application.Application;
import javafx.scene.input.KeyCode;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class Main extends Application {

    private Text info = new Text();
    private Entity player, enemy;

    private Parent createContent() {
        Pane root = new Pane();
        root.setPrefSize(1280, 720);

        info.setTranslateX(50);
        info.setTranslateY(50);

        player = new Entity(400, 400, 30, 60, Color.GREEN);
        enemy = new Entity(300, 300, 40, 40, Color.RED);

        root.getChildren().addAll(info, player, enemy);
        return root;
    }

    private void checkCollisionAuto(Entity a, Entity b) {
        if (a.getBoundsInParent().intersects(b.getBoundsInParent())) {
            info.setText("Collision");
        }
        else {
            info.setText("");
        }
    }

    private void checkCollisionManual(Entity a, Entity b) {
        double minX = a.getTranslateX();
        double minY = a.getTranslateY();
        double maxX = minX + a.width;
        double maxY = minY + a.height;

        double minX2 = b.getTranslateX();
        double minY2 = b.getTranslateY();
        double maxX2 = minX2 + b.width;
        double maxY2 = minY2 + b.height;

        if (maxX >= minX2 && minX <= maxX2
                && maxY >= minY2 && minY <= maxY2) {
            info.setText("Collision");
        }
        else {
            info.setText("");
        }
    }

    private static class Entity extends Parent {
        double width, height;

        public Entity(double x, double y, double w, double h, Color c) {
            setTranslateX(x);
            setTranslateY(y);
            width = w;
            height = h;
            Rectangle rect = new Rectangle(w, h);
            rect.setFill(c);
            getChildren().add(rect);
        }
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        Scene scene = new Scene(createContent());
        scene.setOnKeyPressed(event -> {
            if (event.getCode() == KeyCode.W) {
                player.setTranslateY(player.getTranslateY() - 7);
            }
            else if (event.getCode() == KeyCode.S) {
                player.setTranslateY(player.getTranslateY() + 7);
            }
            else if (event.getCode() == KeyCode.A) {
                player.setTranslateX(player.getTranslateX() - 7);
            }
            else if (event.getCode() == KeyCode.D) {
                player.setTranslateX(player.getTranslateX() + 7);
            }

            //checkCollisionAuto(player, enemy);
            checkCollisionManual(player, enemy);
        });

        primaryStage.setTitle("Tutorial");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}


text:
package com.inteqrity.commands;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.InspectContainerResponse;

public class StartImage {

	public void startImage(DockerClient dockerClient,String imageName)  throws Exception{

		CreateContainerResponse container = dockerClient.createContainerCmd(imageName).exec();
	    dockerClient.startContainerCmd(container.getId()).exec();
	    InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(container.getId()).exec();

	    if (inspectContainerResponse.getState().isRunning()){
	    	System.out.println("Starting docker container : " + container.getId() + " from image " + imageName );
	    } else {
	    	System.out.println("Something wrong with starting of container");
	    }

	}
}


text:
package com.collective.celos;

import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.junit.Assert;
import org.junit.Test;

import java.sql.Timestamp;

public class UtilTest {

    @Test(expected=NullPointerException.class)
    public void requireNonNullWorks() {
        Util.requireNonNull(null);
    }

    @Test(expected=IllegalArgumentException.class)
    public void requireProperBucketIDorRegisterKeyThrowsOnSlash() {
        Util.requireProperBucketIDorRegisterKey("foo/bar");
    }

    @Test(expected=IllegalArgumentException.class)
    public void requireProperBucketIDorRegisterKeyThrowsOnDot() {
        Util.requireProperBucketIDorRegisterKey("foo.bar");
    }

    // DATETIME TESTS

    @Test
    public void toFullHourWorks() {
        Assert.assertEquals(new DateTime("2013-11-27T15:00:00.000Z"), Util.toFullHour(new DateTime("2013-11-27T15:36:23.475Z")));
    }

    @Test
    public void toFullMinuteWorks() {
        Assert.assertEquals(new DateTime("2013-11-27T15:36:00.000Z"), Util.toFullMinute(new DateTime("2013-11-27T15:36:23.475Z")));
    }

    @Test
    public void toFullSecondWorks() {
        Assert.assertEquals(new DateTime("2013-11-27T15:36:23.000Z"), Util.toFullSecond(new DateTime("2013-11-27T15:36:23.475Z")));
    }

    @Test
    public void isFullHourWorks() {
        Assert.assertTrue(Util.isFullHour(new DateTime("2013-11-27T15:00:00.000Z")));
        Assert.assertFalse(Util.isFullHour(new DateTime("2013-11-27T15:36:00.000Z")));
    }

    @Test
    public void isFullMinuteWorks() {
        Assert.assertTrue(Util.isFullMinute(new DateTime("2013-11-27T15:01:00.000Z")));
        Assert.assertFalse(Util.isFullMinute(new DateTime("2013-11-27T15:36:01.000Z")));
    }

    @Test
    public void isFullSecondWorks() {
        Assert.assertTrue(Util.isFullSecond(new DateTime("2013-11-27T15:01:00.000Z")));
        Assert.assertFalse(Util.isFullSecond(new DateTime("2013-11-27T15:36:01.001Z")));
    }

    // JSON TESTS

    @Test(expected=IllegalArgumentException.class)
    public void getStringPropertyDetectsUnsetProperty() {
        ObjectNode node = Util.newObjectNode();
        Util.getStringProperty(node, "foo");
    }

    @Test(expected=IllegalArgumentException.class)
    public void getStringPropertyDetectsNonStringProperty() {
        ObjectNode node = Util.newObjectNode();
        node.put("foo", 12);
        Util.getStringProperty(node, "foo");
    }

    @Test
    public void getStringPropertyWorks() {
        ObjectNode node = Util.newObjectNode();
        node.put("foo", "bar");
        Assert.assertEquals("bar", Util.getStringProperty(node, "foo"));
    }

    @Test(expected=IllegalArgumentException.class)
    public void getIntPropertyDetectsUnsetProperty() {
        ObjectNode node = Util.newObjectNode();
        Util.getIntProperty(node, "foo");
    }

    @Test(expected=IllegalArgumentException.class)
    public void getIntPropertyDetectsNonIntProperty() {
        ObjectNode node = Util.newObjectNode();
        node.put("foo", "foo");
        Util.getIntProperty(node, "foo");
    }

    @Test
    public void getIntPropertyWorks() {
        ObjectNode node = Util.newObjectNode();
        node.put("foo", 12);
        Assert.assertEquals(12, Util.getIntProperty(node, "foo"));
    }

    @Test(expected=IllegalArgumentException.class)
    public void getArrayPropertyDetectsUnsetProperty() {
        ObjectNode node = Util.newObjectNode();
        Util.getArrayProperty(node, "foo");
    }

    @Test(expected=IllegalArgumentException.class)
    public void getArrayPropertyDetectsNonArrayProperty() {
        ObjectNode node = Util.newObjectNode();
        node.put("foo", 12);
        Util.getArrayProperty(node, "foo");
    }

    @Test
    public void getArrayPropertyWorks() {
        ObjectNode node = Util.newObjectNode();
        ArrayNode array = Util.newArrayNode();
        array.add("bar");
        node.put("foo", array);
        Assert.assertEquals(array, Util.getArrayProperty(node, "foo"));
    }

    @Test(expected=IllegalArgumentException.class)
    public void getObjectPropertyDetectsUnsetProperty() {
        ObjectNode node = Util.newObjectNode();
        Util.getObjectProperty(node, "foo");
    }

    @Test(expected=IllegalArgumentException.class)
    public void getObjectPropertyDetectsNonObjectProperty() {
        ObjectNode node = Util.newObjectNode();
        node.put("foo", 12);
        Util.getObjectProperty(node, "foo");
    }

    @Test
    public void getObjectPropertyWorks() {
        ObjectNode node = Util.newObjectNode();
        ObjectNode nested = Util.newObjectNode();
        node.put("foo", nested);
        Assert.assertEquals(nested, Util.getObjectProperty(node, "foo"));
    }

    @Test
    public void toNominalTimeFormat() {
        String formatted = new DateTime(2013, 1, 3, 12, 10).toString(DateTimeFormat.forPattern("YYYY-MM-dd'T'HH:mm'Z"));
        Assert.assertEquals(formatted, "2013-01-03T12:10Z");
    }

    @Test
    public void toSQLTimestampAndBack() {
        ScheduledTime time = new ScheduledTime("2014-02-03T12:13Z");
        Timestamp timestamp = Util.toTimestamp(time);
        Assert.assertEquals(Util.fromTimestamp(timestamp), time);
    }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Coverage Report :: DatabaseChangeRegistration</title>

    [ all classes ]
    [ oracle.jdbc.dcn ]

Coverage Summary for Class: DatabaseChangeRegistration (oracle.jdbc.dcn)

  Class

  Class, %

  Method, %

  Line, %

  DatabaseChangeRegistration

    0%

    (0/ 1)

    0%

    (0/ 2)

    0%

    (0/ 2)

1 package oracle.jdbc.dcn;
2
3 /**
4  * A mocking class used as a placeholder for the real Oracle JDBC drivers to prevent build errors.
5  */
6 public class DatabaseChangeRegistration {
7
8     public void addListener(@SuppressWarnings("unused") DatabaseChangeListener listener) {
9         // do nothing
10     }
11 }

generated on 2017-07-15 00:44


text:
description = '''\
txretry provides a Twisted class, RetryingCall, that calls a function
until it succeeds. A back-off iterator (a generator function that yields
intervals) can be specified to customize the interval between retried
calls.  When/if the back-off iterator raises StopIteration the attempt to
call the function is aborted. An instance of the RetryingCall class
provides a start method that returns a Deferred that will fire with the
function result or errback with the first failure encountered.

Usage of the class is described in the following blog post:
http://blogs.fluidinfo.com/terry/2009/11/12/twisted-code-for-retrying-function-calls/
'''

d = dict(name='txretry',
         version='1.0.0',
         provides=['txretry'],
         maintainer='Fluidinfo Inc.',
         maintainer_email='terry@jon.es',
         url='https://github.com/fluidinfo/txretry',
         download_url='https://github.com/fluidinfo/txretry',
         packages=['txretry', 'txretry.test'],
         keywords=['twisted function retry'],
         classifiers=[
             'Programming Language :: Python',
             'Framework :: Twisted',
             'Development Status :: 4 - Beta',
             'Intended Audience :: Developers',
             'License :: OSI Approved :: Apache Software License',
             'Operating System :: OS Independent',
             'Topic :: Software Development :: Libraries :: Python Modules',
             ],
         description=('A Twisted class for retrying failing calls '
                      'with a customizable back-off schedule.'),
         long_description=description,
         )

try:
    from setuptools import setup
    _ = setup  # Keeps pyflakes from complaining.
except ImportError:
    from distutils.core import setup
else:
    d['install_requires'] = ['Twisted', 'six']

setup(**d)


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:weightSum="1">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_weight="0.26">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="match_parent">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/info_session" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Shimmer IMU: "
                tools:ignore="HardcodedText" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="BioHarness: "
                tools:ignore="HardcodedText" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="GPS: "
                tools:ignore="HardcodedText" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Version: "
                tools:ignore="HardcodedText" />
        </LinearLayout>

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="match_parent">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/info_not_started"
                android:id="@+id/textViewInfoSessionStatus" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/info_not_connected"
                android:id="@+id/textViewInfoShimmerImoConnectionStatus" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/info_not_connected"
                android:id="@+id/textViewInfoBioHarnessConnectionStatus" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/info_not_connected"
                android:id="@+id/textViewInfoGpsConnectionStatus" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="1.0"
                android:id="@+id/textViewInfoVersionName" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>


text:
import React from 'react'
import ReactDOM from 'react-dom'
import './Styles/index.css'
import App from './Components/App'
import registerServiceWorker from './registerServiceWorker'

ReactDOM.render(<App />, document.getElementById('app'))
registerServiceWorker()


text:
package com.huawei.esdk.fusionmanager.local.impl.autogen.net;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for VfwInfo complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="VfwInfo">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="ipGwID" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="isAspfEnable" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
 *         <element name="maxRxThroughput" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
 *         <element name="maxSessionNum" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
 *         <element name="maxTxThroughput" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
 *         <element name="status" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "VfwInfo", namespace = "http://response.model.v2.firewall.soap.business.net.north.galaxmanager.com/xsd", propOrder = {
    "ipGwID",
    "isAspfEnable",
    "maxRxThroughput",
    "maxSessionNum",
    "maxTxThroughput",
    "status"
})
public class VfwInfo {

    protected String ipGwID;
    protected Integer isAspfEnable;
    protected Integer maxRxThroughput;
    protected Integer maxSessionNum;
    protected Integer maxTxThroughput;
    protected Integer status;

    /**
     * Gets the value of the ipGwID property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getIpGwID() {
        return ipGwID;
    }

    /**
     * Sets the value of the ipGwID property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setIpGwID(String value) {
        this.ipGwID = value;
    }

    /**
     * Gets the value of the isAspfEnable property.
     *
     * @return
     *     possible object is
     *     {@link Integer }
     *
     */
    public Integer getIsAspfEnable() {
        return isAspfEnable;
    }

    /**
     * Sets the value of the isAspfEnable property.
     *
     * @param value
     *     allowed object is
     *     {@link Integer }
     *
     */
    public void setIsAspfEnable(Integer value) {
        this.isAspfEnable = value;
    }

    /**
     * Gets the value of the maxRxThroughput property.
     *
     * @return
     *     possible object is
     *     {@link Integer }
     *
     */
    public Integer getMaxRxThroughput() {
        return maxRxThroughput;
    }

    /**
     * Sets the value of the maxRxThroughput property.
     *
     * @param value
     *     allowed object is
     *     {@link Integer }
     *
     */
    public void setMaxRxThroughput(Integer value) {
        this.maxRxThroughput = value;
    }

    /**
     * Gets the value of the maxSessionNum property.
     *
     * @return
     *     possible object is
     *     {@link Integer }
     *
     */
    public Integer getMaxSessionNum() {
        return maxSessionNum;
    }

    /**
     * Sets the value of the maxSessionNum property.
     *
     * @param value
     *     allowed object is
     *     {@link Integer }
     *
     */
    public void setMaxSessionNum(Integer value) {
        this.maxSessionNum = value;
    }

    /**
     * Gets the value of the maxTxThroughput property.
     *
     * @return
     *     possible object is
     *     {@link Integer }
     *
     */
    public Integer getMaxTxThroughput() {
        return maxTxThroughput;
    }

    /**
     * Sets the value of the maxTxThroughput property.
     *
     * @param value
     *     allowed object is
     *     {@link Integer }
     *
     */
    public void setMaxTxThroughput(Integer value) {
        this.maxTxThroughput = value;
    }

    /**
     * Gets the value of the status property.
     *
     * @return
     *     possible object is
     *     {@link Integer }
     *
     */
    public Integer getStatus() {
        return status;
    }

    /**
     * Sets the value of the status property.
     *
     * @param value
     *     allowed object is
     *     {@link Integer }
     *
     */
    public void setStatus(Integer value) {
        this.status = value;
    }

}


text:
<?php

use Behat\Behat\Tester\Exception\PendingException;
use Behat\Behat\Context\Context;
use Behat\Gherkin\Node\PyStringNode;
use Behat\Gherkin\Node\TableNode;
use Matcher\FileExistsMatcher;
use Matcher\FileHasContentsMatcher;
use PhpSpec\Matcher\MatchersProviderInterface;
use Symfony\Component\Filesystem\Filesystem;

/**
 * Defines application features from the specific context.
 */
class FilesystemContext implements Context, MatchersProviderInterface
{
    /**
     * @var string
     */
    private $workingDirectory;

    /**
     * @var Filesystem
     */
    private $filesystem;

    public function __construct()
    {
        $this->filesystem = new Filesystem();
    }

    /**
     * @beforeScenario
     */
    public function prepWorkingDirectory()
    {
        $this->workingDirectory = tempnam(sys_get_temp_dir(), 'phpspec-behat');
        $this->filesystem->remove($this->workingDirectory);
        $this->filesystem->mkdir($this->workingDirectory);
        chdir($this->workingDirectory);
    }

    /**
     * @afterScenario
     */
    public function removeWorkingDirectory()
    {
        $this->filesystem->remove($this->workingDirectory);
    }

    /**
     * @Given the bootstrap file :file contains:
     */
    public function theFileContains($file, PyStringNode $contents)
    {
        $this->filesystem->dumpFile($file, (string)$contents);
    }

    /**
     * @Given the class file :file contains:
     * @Given the spec file :file contains:
     * @Given the trait file :file contains:
     */
    public function theClassOrTraitOrSpecFileContains($file, PyStringNode $contents)
    {
        $this->theFileContains($file, $contents);
        require_once($file);
    }

    /**
     * @Given the config file contains:
     */
    public function theConfigFileContains(PyStringNode $contents)
    {
        $this->theFileContains('phpspec.yml', $contents);
    }

    /**
     * @Given there is no file :file
     */
    public function thereIsNoFile($file)
    {
        expect($file)->toNotExist();
        expect(file_exists($file))->toBe(false);
    }

    /**
     * @Then the class in :file should contain:
     * @Then a new class/spec should be generated in the :file:
     */
    public function theFileShouldContain($file, PyStringNode $contents)
    {
        expect($file)->toExist();
        expect($file)->toHaveContents($contents);
    }

    /**
     * @Given the config file located in :folder contains:
     */
    public function theConfigFileInFolderContains($folder, PyStringNode $contents)
    {
        $this->theFileContains($folder.DIRECTORY_SEPARATOR.'phpspec.yml', $contents);
    }

    /**
     * @return array
     */
    public function getMatchers()
    {
        return array(
            new FileExistsMatcher(),
            new FileHasContentsMatcher()
        );
    }
}


text:
/**
 * A function that compares 2 dates. The comparison also includes the time portion.
 *
 * @param candidate - The candidate date.
 * @param expected - The expected date.
 * @returns - A Boolean value indicating whether the values are equal.
 *
 * @example
 * ```ts-no-run
 * isEqual(new Date(2016, 0, 1), new Date(2016, 0, 1)); // true
 * isEqual(new Date(2016, 0, 1), new Date(2016, 0, 2)); // false
 * isEqual(new Date(2016, 0, 1, 10), new Date(2016, 0, 1, 20)); // false
 * ```
 */
export declare const isEqual: (candidate: Date, expected: Date) => boolean;


text:
if [[ ! -f wiremock-standalone-2.19.0.jar ]] ; then
    echo wiremock-standalone-2.19.0.jar does not exist!
    exit
fi

java -jar wiremock-standalone-2.19.0.jar --proxy-all="https://api.fyyd.de/0.2/" --record-mappings --verbose &

sleep 5

curl "http://localhost:8080/search/podcast?title=wrint"
curl "http://localhost:8080/search/podcast?title=wrint&count=5"

kill $!

rm -rf src/test/resources/__files
rm -rf src/test/resources/mappings

mv __files src/test/resources/
mv mappings src/test/resources/


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdysTech.InfluxDB.Client.Net
{
    public static class EpochHelper
    {
        private static readonly DateTime Origin = new DateTime (1970, 1, 1);

        public static long ToEpoch(this DateTime time, TimePrecision precision)
        {
            TimeSpan t = time - Origin;
            switch ( precision )
            {
                case TimePrecision.Hours: return (long) t.TotalHours;
                case TimePrecision.Minutes: return (long) t.TotalMinutes;
                case TimePrecision.Seconds: return (long) t.TotalSeconds;
                case TimePrecision.Milliseconds: return (long) t.TotalMilliseconds;
                case TimePrecision.Microseconds: return (long) t.TotalMilliseconds * 1000;
                case TimePrecision.Nanoseconds: return (long) t.TotalMilliseconds * 1000 * 1000;
            }
            return 0;
        }
    }
}


text: Rails.application.config.session_store :cookie_store, key: '_sign-seeing-NYC_session'


text:
package com.googlecode.eyesfree.brailleback;

import android.accessibilityservice.AccessibilityService;
import android.content.Context;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.util.Log;
import android.view.accessibility.AccessibilityNodeInfo;
import com.googlecode.eyesfree.utils.AccessibilityNodeInfoUtils;
import com.googlecode.eyesfree.utils.LogUtils;
import com.googlecode.eyesfree.utils.NodeFocusFinder;
import java.util.HashSet;

/**
 * Functions to find focus.
 *
 * NOTE: To give a consistent behaviour, this code should be kept in sync
 * with the relevant subset of code in the {@code CursorController}
 * class in TalkBack.
 */
public class FocusFinder {

    public static final int SEARCH_FORWARD = NodeFocusFinder.SEARCH_FORWARD;
    public static final int SEARCH_BACKWARD = NodeFocusFinder.SEARCH_BACKWARD;

    private Context mContext;

    private final HashSet<AccessibilityNodeInfoCompat> mTmpNodeHash =
            new HashSet<AccessibilityNodeInfoCompat>();

    public FocusFinder(Context context) {
        mContext = context;
    }

    public AccessibilityNodeInfoCompat linear(
        AccessibilityNodeInfoCompat source,
        int direction) {
        if (source == null) {
            return null;
        }
        AccessibilityNodeInfoCompat next =
                NodeFocusFinder.focusSearch(source, direction);

        HashSet<AccessibilityNodeInfoCompat> seenNodes = mTmpNodeHash;
        seenNodes.clear();

        while ((next != null)
                && !AccessibilityNodeInfoUtils.shouldFocusNode(
                    mContext, next)) {
            if (seenNodes.contains(next)) {
                LogUtils.log(this, Log.ERROR,
                        "Found duplicate node during traversal: %s", next);
                break;
            }

            LogUtils.log(this, Log.VERBOSE,
                    "Search strategy rejected node: %s", next.getInfo());
            seenNodes.add(next);
            next = NodeFocusFinder.focusSearch(next, direction);
        }

        // Clear the list of seen nodes.
        AccessibilityNodeInfoUtils.recycleNodes(seenNodes);

        if (next == null) {
            LogUtils.log(this, Log.VERBOSE, "Failed to find the next node");
        }
        return next;
    }

    public static AccessibilityNodeInfoCompat findFirstFocusableDescendant(
            AccessibilityNodeInfoCompat root, Context context) {
        // null guard and shortcut for leaf nodes.
        if (root == null || root.getChildCount() <= 0) {
            return null;
        }
        HashSet<AccessibilityNodeInfoCompat> seenNodes =
                new HashSet<AccessibilityNodeInfoCompat>();
        seenNodes.add(root);
        try {
            return findFirstFocusableDescendantInternal(
                    root, context, seenNodes);
        } finally {
            seenNodes.remove(root);  // Not owned by us.
            AccessibilityNodeInfoUtils.recycleNodes(seenNodes);
        }
    }

    private static AccessibilityNodeInfoCompat
          findFirstFocusableDescendantInternal(
                  AccessibilityNodeInfoCompat root, Context context,
                  HashSet<AccessibilityNodeInfoCompat> seenNodes) {
        for (int i = 0, end = root.getChildCount(); i < end; ++i) {
            AccessibilityNodeInfoCompat child = root.getChild(i);
            if (child == null) {
                continue;
            }
            if (AccessibilityNodeInfoUtils.shouldFocusNode(
                            context, child)) {
                return child;
            }
            if (!seenNodes.add(child)) {
                LogUtils.log(FocusFinder.class, Log.ERROR,
                        "Cycle in node tree");
                child.recycle();
                return null;
            }
            AccessibilityNodeInfoCompat n =
                    findFirstFocusableDescendantInternal(
                            child, context, seenNodes);
            if (n != null) {
                return n;
            }
        }
        return null;
    }

    public static AccessibilityNodeInfoCompat findLastFocusableDescendant(
            AccessibilityNodeInfoCompat root, Context context) {
        // null guard and shortcut for leaf nodes.
        if (root == null || root.getChildCount() <= 0) {
            return null;
        }
        HashSet<AccessibilityNodeInfoCompat> seenNodes =
                new HashSet<AccessibilityNodeInfoCompat>();
        seenNodes.add(root);
        try {
            return findLastFocusableDescendantInternal(
                    root, context, seenNodes);
        } finally {
            seenNodes.remove(root);  // Not owned by us.
            AccessibilityNodeInfoUtils.recycleNodes(seenNodes);
        }
    }

    private static AccessibilityNodeInfoCompat
          findLastFocusableDescendantInternal(
                  AccessibilityNodeInfoCompat root, Context context,
                  HashSet<AccessibilityNodeInfoCompat> seenNodes) {
        for (int end = root.getChildCount(), i = end - 1; i >= 0; --i) {
            AccessibilityNodeInfoCompat child = root.getChild(i);
            if (child == null) {
                continue;
            }

            AccessibilityNodeInfoCompat n =
                    findLastFocusableDescendantInternal(
                            child, context, seenNodes);
            if (n != null) {
                return n;
            }

            if (AccessibilityNodeInfoUtils.shouldFocusNode(context, child)) {
                return child;
            }
            if (!seenNodes.add(child)) {
                LogUtils.log(FocusFinder.class, Log.ERROR,
                        "Cycle in node tree");
                child.recycle();
                return null;
            }
        }
        return null;
    }

    public static AccessibilityNodeInfoCompat getFocusedNode(
        AccessibilityService service, boolean fallbackOnRoot) {
        AccessibilityNodeInfo root =
                service.getRootInActiveWindow();
        AccessibilityNodeInfo focused = null;
        try {
            AccessibilityNodeInfo ret = null;
            if (root != null) {
                focused = root.findFocus(
                    AccessibilityNodeInfo.FOCUS_ACCESSIBILITY);
                if (focused != null && focused.isVisibleToUser()) {
                    ret = focused;
                    focused = null;
                } else if (fallbackOnRoot) {
                    ret = root;
                    root = null;
                }
            } else {
                LogUtils.log(service, Log.ERROR, "No current window root");
            }
            if (ret != null) {
                return new AccessibilityNodeInfoCompat(ret);
            }
        } finally {
            if (root != null) {
                root.recycle();
            }
            if (focused != null) {
                focused.recycle();
            }
        }
        return null;
    }
}


text:
from addons.base.apps import BaseAddonAppConfig

from addons.figshare.views import figshare_root_folder

class FigshareAddonAppConfig(BaseAddonAppConfig):

    name = 'addons.figshare'
    label = 'addons_figshare'
    full_name = 'figshare'
    short_name = 'figshare'
    owners = ['user', 'node']
    configs = ['accounts', 'node']
    categories = ['storage']
    has_hgrid_files = True
    max_file_size = 50  # MB

    @property
    def get_hgrid_data(self):
        return figshare_root_folder

    FIGSHARE_FOLDER_CREATED = 'figshare_folder_created'
    FIGSHARE_FOLDER_SELECTED = 'figshare_folder_selected'
    FIGSHARE_CONTENT = 'figshare_content_unlinked'
    FIGSHARE_FILE_ADDED = 'figshare_file_added'
    FIGSHARE_FILE_REMOVED = 'figshare_file_removed'
    FIGSHARE_NODE_AUTHORIZED = 'figshare_node_authorized'
    FIGSHARE_NODE_DEAUTHORIZED = 'figshare_node_deauthorized'
    FIGSHARE_NODE_DEAUTHORIZED_NO_USER = 'figshare_node_deauthorized_no_user'

    actions = (
        FIGSHARE_FOLDER_CREATED,
        FIGSHARE_FOLDER_SELECTED,
        FIGSHARE_CONTENT,
        FIGSHARE_FILE_ADDED,
        FIGSHARE_FILE_REMOVED,
        FIGSHARE_NODE_AUTHORIZED,
        FIGSHARE_NODE_DEAUTHORIZED,
        FIGSHARE_NODE_DEAUTHORIZED_NO_USER)

    @property
    def routes(self):
        from . import routes
        return [routes.api_routes]

    @property
    def user_settings(self):
        return self.get_model('UserSettings')

    @property
    def node_settings(self):
        return self.get_model('NodeSettings')


text:
from django.http import Http404
from django_filters.rest_framework import DjangoFilterBackend

from rest_framework import mixins
from rest_framework import filters

from rest_framework_mongoengine.viewsets import GenericViewSet

from emgapi import mixins as emg_mixins
from emgapi import serializers as emg_serializers
from emgapi import models as emg_models
from emgapi import filters as emg_filters

from mongoengine import DoesNotExist

class ReadOnlyModelViewSet(mixins.RetrieveModelMixin,
                           emg_mixins.ListModelMixin,
                           GenericViewSet):
    """ Adaptation of DRF ReadOnlyModelViewSet """
    pass

class MultipleFieldLookupModelViewSet(emg_mixins.MultipleFieldLookupMixin,
                                      emg_mixins.ListModelMixin,
                                      GenericViewSet):
    """ Adaptation of DRF ReadOnlyModelViewSet """
    pass

class ListReadOnlyModelViewSet(emg_mixins.ListModelMixin,
                               GenericViewSet):
    """ Adaptation of DRF ReadOnlyModelViewSet """
    pass

class AnalysisRelationshipViewSet(ListReadOnlyModelViewSet):
    """Get the the Analysis that have a particular Model

    This mixin provides abstracts the common code to get the Analysis that have a
    particular annotation.

    For example: get all the analysis that have the Pfam entry X.

    Usage:
        `annotation_model`: annotation mongo model
        `get_job_ids`: method to get all the jobs that have a particular annotation
    """
    serializer_class = emg_serializers.AnalysisSerializer

    filter_class = emg_filters.AnalysisJobFilter

    filter_backends = (
        DjangoFilterBackend,
        filters.SearchFilter,
        filters.OrderingFilter,
    )

    ordering_fields = (
        'accession',
    )

    ordering = ('-accession',)

    search_fields = (
        'sample__metadata__var_val_ucv',
    )

    lookup_field = 'accession'

    annotation_model = None

    def get_job_ids(self):
        pass

    def get_queryset(self):
        accession = self.kwargs[self.lookup_field]
        try:
            annotation = self.annotation_model.objects.get(accession=accession)
        except KeyError:
            raise Http404(("Attribute error '%s'." % self.lookup_field))
        except DoesNotExist:
            raise Http404(('No %s matches the given query.' %
                           self.annotation_model.__class__.__name__))

        job_ids = self.get_job_ids(annotation)

        return emg_models.AnalysisJob.objects \
            .filter(job_id__in=job_ids) \
            .available(self.request)

    def get_serializer_class(self):
        return emg_serializers.AnalysisSerializer


text:
using System;

using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Math;

namespace Org.BouncyCastle.Asn1.Cms
{
    public class IssuerAndSerialNumber
        : Asn1Encodable
    {
        private X509Name	name;
        private DerInteger	serialNumber;

        public static IssuerAndSerialNumber GetInstance(object obj)
        {
            if (obj == null)
                return null;
            IssuerAndSerialNumber existing = obj as IssuerAndSerialNumber;
            if (existing != null)
                return existing;
            return new IssuerAndSerialNumber(Asn1Sequence.GetInstance(obj));
        }

        [Obsolete("Use GetInstance() instead")]
        public IssuerAndSerialNumber(
            Asn1Sequence seq)
        {
            this.name = X509Name.GetInstance(seq[0]);
            this.serialNumber = (DerInteger) seq[1];
        }

        public IssuerAndSerialNumber(
            X509Name	name,
            BigInteger	serialNumber)
        {
            this.name = name;
            this.serialNumber = new DerInteger(serialNumber);
        }

        public IssuerAndSerialNumber(
            X509Name	name,
            DerInteger	serialNumber)
        {
            this.name = name;
            this.serialNumber = serialNumber;
        }

        public X509Name Name
        {
            get { return name; }
        }

        public DerInteger SerialNumber
        {
            get { return serialNumber; }
        }

        public override Asn1Object ToAsn1Object()
        {
            return new DerSequence(name, serialNumber);
        }
    }
}


text:
package org.apache.hadoop.hive.llap.io.decode;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.llap.counters.QueryFragmentCounters;
import org.apache.hadoop.hive.llap.io.api.impl.ColumnVectorBatch;
import org.apache.hadoop.hive.ql.io.orc.encoded.Consumer;
import org.apache.hadoop.hive.ql.io.sarg.SearchArgument;
import org.apache.hadoop.hive.ql.plan.PartitionDesc;
import org.apache.hadoop.hive.serde2.Deserializer;
import org.apache.hadoop.mapred.FileSplit;
import org.apache.hadoop.mapred.InputFormat;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.Reporter;
import org.apache.orc.TypeDescription;

/**
 * Entry point used by LlapInputFormat to create read pipeline to get data.
 */
public interface ColumnVectorProducer {
  ReadPipeline createReadPipeline(Consumer<ColumnVectorBatch> consumer, FileSplit split,
      List<Integer> columnIds, SearchArgument sarg, String[] columnNames,
      QueryFragmentCounters counters, TypeDescription readerSchema,
      InputFormat<?, ?> sourceInputFormat, Deserializer sourceSerDe, Reporter reporter,
      JobConf job, Map<Path, PartitionDesc> parts) throws IOException;
}


text:
/*

    This file is part of VIPS.

    VIPS is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

 */

/*

    These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk

 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif /*HAVE_CONFIG_H*/
#include <vips/intl.h>

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <assert.h>

#include <vips/vips.h>

#ifdef WITH_DMALLOC
#include <dmalloc.h>
#endif /*WITH_DMALLOC*/

int
im_compass( IMAGE *in, IMAGE *out, INTMASK *mask )
{
	IMAGE *filtered[8];
	IMAGE *absed[8];
	int i;

	if( im_open_local_array( out, filtered, 8, "im_compass:1", "p" ) ||
		im_open_local_array( out, absed, 8, "im_compass:2", "p" ) )
		return( -1 );

	for( i = 0; i < 8; i++ ) {
		if( im_conv( in, filtered[i], mask ) ||
		    !(mask = (INTMASK *) im_local( out,
			(im_construct_fn) im_rotate_imask45,
			(im_callback_fn) im_free_imask,
			mask, mask->filename, NULL )) )
			return( -1 );
	}

	for( i = 0; i < 8; i++ )
		if( im_abs( filtered[i], absed[i] ) )
			return( -1 );

	return( im_maxvalue( absed, out, 8 ) );
}

int
im_lindetect( IMAGE *in, IMAGE *out, INTMASK *mask )
{
	IMAGE *filtered[4];
	IMAGE *absed[4];
	int i;

	if( im_open_local_array( out, filtered, 4, "im_lindetect:1", "p" ) ||
		im_open_local_array( out, absed, 4, "im_lindetect:2", "p" ) )
		return( -1 );

	for( i = 0; i < 4; i++ ) {
		if( im_conv( in, filtered[i], mask ) ||
		    !(mask = (INTMASK *) im_local( out,
			(im_construct_fn) im_rotate_imask45,
			(im_callback_fn) im_free_imask,
			mask, mask->filename, NULL )) )
			return( -1 );
	}

	for( i = 0; i < 4; i++ )
		if( im_abs( filtered[i], absed[i] ) )
			return( -1 );

	return( im_maxvalue( absed, out, 4 ) );
}

#define GTEMPS (4)

int
im_gradient( IMAGE *in, IMAGE *out, INTMASK *mask )
{
	IMAGE *t[GTEMPS];
	INTMASK *rmask;

	if( im_open_local_array( out, t, GTEMPS, "im_gradient", "p" ) )
		return( -1 );

	if( !(rmask = (INTMASK *) im_local( out,
		(im_construct_fn) im_rotate_imask90,
		(im_callback_fn) im_free_imask, mask, mask->filename, NULL )) )
		return( -1 );

	if( im_conv( in, t[0], mask ) ||
		im_conv( in, t[1], rmask ) ||
		im_abs( t[0], t[2] ) ||
		im_abs( t[1], t[3] ) ||
		im_add( t[2], t[3], out ) )
		return( -1 );

	return( 0 );
}


text:
require 'setup/base'

module Setup

  # As of v0.5.1 Setup.rb no longer support the document phase at all. The
  # document phase would generate *ri* documentation for a project, adding in
  # with the rest of ri documentation. After careful consideration, it has
  # become clear that it is better for documentation to be left up to dedicated
  # tools. For example, you could easily document your Ruby install site
  # location yourself with
  #
  #   $ rdoc --ri-site /usr/local/lib/site_ruby
  #
  # Using of course, whichever path is appropriate to your system.
  #
  # This descision also allows setup.rb to be less Ruby-specific, and useful
  # as a more general install tool.
  #
  # @deprecated Setup.rb no longer generates ri documentation, ever.
  #
  class Documentor < Base

    #
    def document
      return if config.no_doc

      exec_ri
      exec_yri
    end

    # Generate ri documentation.
    #
    # @todo Should we run rdoc programmatically instead of shelling out?
    #
    def exec_ri
      case config.type #installdirs
      when 'home'
        output = "--ri"
      when 'site'
        output = "--ri-site"
      when 'std', 'ruby'
        output  = "--ri-site"
      else
        abort "bad config: should not be possible -- type=#{config.type}"
      end

      opt = []
      opt << "-U"
      opt << "-q" #if quiet?
      #opt << "-D" #if $DEBUG
      opt << output

      unless project.document
        files = []
        files << 'lib' if project.find('lib')
        files << 'ext' if project.find('ext')
      else
        files = []
        #files = File.read('.document').split("\n")
        #files.reject!{ |l| l =~ /^\s*[#]/ || l !~ /\S/ }
        #files.collect!{ |f| f.strip }
      end

      opt.concat(files)

      opt.flatten!

      cmd = "rdoc " + opt.join(' ')

      if trial?
        puts cmd
      else
        begin
          success = system(cmd)
          raise unless success
          #require 'rdoc/rdoc'
          #::RDoc::RDoc.new.document(opt)
          io.puts "Ok ri." #unless quiet?
        rescue Exception
          $stderr.puts "ri generation failed"
          $stderr.puts "command was: '#{cmd}'"
          #$stderr.puts "proceeding with install..."
        end
      end
    end

    #
    # Generate YARD Ruby Index documention.
    #
    def exec_yri

    end

    # Generate rdocs. Needs project <tt>name</tt>.
    #
    # @deprecated This is not being used. It's here in case we decide
    #   to add the feature back in the future.
    #
    def exec_rdoc
      main = Dir.glob("README{,.*}", File::FNM_CASEFOLD).first

      if File.exist?('.document')
        files = File.read('.document').split("\n")
        files.reject!{ |l| l =~ /^\s*[#]/ || l !~ /\S/ }
        files.collect!{ |f| f.strip }
      else
        files = []
        files << main  if main
        files << 'lib' if File.directory?('lib')
        files << 'ext' if File.directory?('ext')
      end

      checkfiles = (files + files.map{ |f| Dir[File.join(f,'*','**')] }).flatten.uniq
      if FileUtils.uptodate?('doc/rdoc', checkfiles)
        puts "RDocs look current."
        return
      end

      output    = 'doc/rdoc'
      title     = (PACKAGE.capitalize + " API").strip if PACKAGE
      template  = config.doctemplate || 'html'

      opt = []
      opt << "-U"
      opt << "-q" #if quiet?
      opt << "--op=#{output}"
      #opt << "--template=#{template}"
      opt << "--title=#{title}"
      opt << "--main=#{main}"     if main
      #opt << "--debug"
      opt << files

      opt = opt.flatten

      cmd = "rdoc " + opt.join(' ')

      if trial?
        puts cmd
      else
        begin
          system(cmd)
          #require 'rdoc/rdoc'
          #::RDoc::RDoc.new.document(opt)
          puts "Ok rdoc." unless quiet?
        rescue Exception
          puts "Fail rdoc."
          puts "Command was: '#{cmd}'"
          puts "Proceeding with install anyway."
        end
      end
    end

  end

end


text:
<?php include('header.php'); ?>

You can put this button almost anywhere – including Facebook posts, YouTube and emails.

Try it with a £0.50 donation to the DEC Nepal Appeal now.

<?php include('footer.php'); ?>


text:
#ifndef PANGOLIN_GLFORMATTRAITS_H
#define PANGOLIN_GLFORMATTRAITS_H

#include <pangolin/gl/glplatform.h>

namespace pangolin
{

template<typename T>
struct GlFormatTraits;
//{
//    static const GLint glinternalformat = 0;
//    static const GLenum glformat = 0;
//    static const GLenum gltype = 0;
//    static const T glmin = 0;
//    static const T glmax = 0;
//};

//////////////////////////////////////////////////////////////////

template<>
struct GlFormatTraits<float>
{
    static const GLint glinternalformat = GL_LUMINANCE32F_ARB;
    static const GLenum glformat = GL_LUMINANCE;
    static const GLenum gltype = GL_FLOAT;
};

//////////////////////////////////////////////////////////////////

template<>
struct GlFormatTraits<unsigned char>
{
    static const GLint glinternalformat = GL_LUMINANCE;
    static const GLenum glformat = GL_LUMINANCE;
    static const GLenum gltype = GL_UNSIGNED_BYTE;
};

//////////////////////////////////////////////////////////////////

template<>
struct GlFormatTraits<unsigned short>
{
    static const GLint glinternalformat = GL_LUMINANCE;
    static const GLenum glformat = GL_LUMINANCE;
    static const GLenum gltype = GL_UNSIGNED_SHORT;
};

template<>
struct GlFormatTraits<unsigned int>
{
    static const GLint glinternalformat = GL_LUMINANCE;
    static const GLenum glformat = GL_LUMINANCE;
    static const GLenum gltype = GL_UNSIGNED_INT;
};

template<>
struct GlFormatTraits<int>
{
    static const GLint glinternalformat = GL_LUMINANCE;
    static const GLenum glformat = GL_LUMINANCE;
    static const GLenum gltype = GL_INT;
};

}

#endif // PANGOLIN_GLFORMATTRAITS_H


text:
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(TypeName="bar-style")]
public enum BarStyle {

    /// <remarks/>
    regular,

    /// <remarks/>
    dotted,

    /// <remarks/>
    dashed,

    /// <remarks/>
    heavy,

    /// <remarks/>
    [System.Xml.Serialization.XmlEnumAttribute("light-light")]
    lightlight,

    /// <remarks/>
    [System.Xml.Serialization.XmlEnumAttribute("light-heavy")]
    lightheavy,

    /// <remarks/>
    [System.Xml.Serialization.XmlEnumAttribute("heavy-light")]
    heavylight,

    /// <remarks/>
    [System.Xml.Serialization.XmlEnumAttribute("heavy-heavy")]
    heavyheavy,

    /// <remarks/>
    tick,

    /// <remarks/>
    @short,

    /// <remarks/>
    none,
}


text:
package unicode

import common.CommonTest
import unicode.api.SkillState
import java.io.File
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class SimpleTest  extends CommonTest {
  import SkillState._

  test("create unicode example") {
    val path = tmpFile("unicode.writetest")

    val σ = create
    σ.Unicode("1", "ö", "☢")
    σ.write(path)

    assert(sha256(path) === sha256(new File("src/test/resources/unicode-reference.sf").toPath))
  }

  test("check unicode example") {
    val path = new File("src/test/resources/unicode-reference.sf").toPath()

    val σ = read(path)
    val u = σ.Unicode.all.next
    assert(σ.Unicode.size === 1)
    assert(u.one.length === 1, u.one)
    assert(u.one.getBytes.length === 1, u.one)
    assert(u.two.length === 1, u.two)
    assert(u.two.getBytes.length === 2, u.two)
    assert(u.three.length === 1, u.three)
    assert(u.three.getBytes.length === 3, u.three)
  }
}


text:
DarkRP.PLAYER.isInRoom = DarkRP.stub{
	name = "isInRoom",
	description = "Whether the player is in the same room as the LocalPlayer.",
	parameters = {},
	returns = {
		{
			name = "inRoom",
			description = "Whether the player is in the same room.",
			type = "boolean"
		}
	},
	metatable = DarkRP.PLAYER
}

DarkRP.deLocalise = DarkRP.stub{
	name = "deLocalise",
	description = "Makes sure the string will not be localised when drawn or printed.",
	parameters = {
		{
			name = "text",
			description = "The text to delocalise.",
			type = "string",
			optional = false
		}
	},
	returns = {
		{
			name = "text",
			description = "The delocalised text.",
			type = "string"
		}
	},
	metatable = DarkRP
}

DarkRP.textWrap = DarkRP.stub{
	name = "textWrap",
	description = "Wrap a text around when reaching a certain width.",
	parameters = {},
	returns = {
		{
			name = "text",
			description = "The text to wrap.",
			type = "string"
		},
		{
			name = "font",
			description = "The font of the text.",
			type = "string"
		},
		{
			name = "width",
			description = "The maximum width in pixels.",
			type = "number"
		}
	},
	metatable = DarkRP
}

DarkRP.setPreferredJobModel = DarkRP.stub{
	name = "setPreferredJobModel",
	description = "Set the model preferred by the player (if the job allows multiple models).",
	parameters = {
		{
			name = "teamNr",
			description = "The team number of the job.",
			type = "number",
			optional = false
		},
		{
			name = "model",
			description = "The preferred model for the job.",
			type = "string",
			optional = false
		}
	},
	returns = {
	},
	metatable = DarkRP
}

DarkRP.getPreferredJobModel = DarkRP.stub{
	name = "getPreferredJobModel",
	description = "Get the model preferred by the player (if the job allows multiple models).",
	parameters = {
		{
			name = "teamNr",
			description = "The team number of the job.",
			type = "number",
			optional = false
		}
	},
	returns = {
		{
			name = "model",
			description = "The preferred model for the job.",
			type = "string"
		}
	},
	metatable = DarkRP
}

DarkRP.hookStub{
	name = "teamChanged",
	description = "When your team is changed.",
	parameters = {
		{
			name = "before",
			description = "The team before the change.",
			type = "number"
		},
		{
			name = "after",
			description = "The team after the change.",
			type = "number"
		}
	},
	returns = {

	}
}


text:
package bzh.caerwent.coquille.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by vincent on 13/01/2015.
 */
public class AppUtils {
    private static final String TAG = AppUtils.class.getName();

    private static MessageDigest sDigest;

    public synchronized static String encodeMD5(String stringToEncode) {
        if (sDigest == null) {
            try {
                sDigest = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException e) {
                Log.e(TAG, "Error : No md5 digest", e);
                return null;
            }
        }

        byte messageDigest[] = sDigest.digest(stringToEncode.getBytes());
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < messageDigest.length; i++) {
            hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
        }
        return hexString.toString();
    }

    // =============================================================================
    // Application infos
    // =============================================================================

    private static String mAppVersion;
    private static String mAppRevision;

    /**
     * Get application version code
     *
     * @param aContext
     */
    public static String getApplicationVersion(final Context aContext) {
        if (mAppVersion == null) {
            try {
                PackageInfo pi = aContext.getPackageManager().getPackageInfo(aContext.getPackageName(), 0);
                mAppVersion = pi.versionName;
            } catch (PackageManager.NameNotFoundException e) {
                Log.v(TAG, "Error : No version name in manifest");
            }
        }
        return mAppVersion;
    }

    public static String getApplicationRevision(final Context aContext) {
        if (mAppRevision == null) {
            try {
                PackageInfo pi = aContext.getPackageManager().getPackageInfo(aContext.getPackageName(), 0);
                int codeVersion = pi.versionCode;
                mAppRevision = String.valueOf(codeVersion);
            } catch (PackageManager.NameNotFoundException e) {
                Log.v(TAG, "Error : No version name in manifest");
            }
        }
        return mAppRevision;
    }
}


text:
<?php

class DeviceTypeController
{
    /**
     * Returns all device types with fields
     *
     * @throws Exception
     *
     * @return array with DeviceType objects
     */
    public static function getAllTypes()
    {
        $returnArr = [];

        global $database;

        $typeQuery = $database->query('SELECT * FROM device_type ORDER BY name ASC');

        while ($typeResult = $typeQuery->fetch(PDO::FETCH_ASSOC))
        {
            // Get all the fields
            $fieldQuery = $database->prepare('SELECT * FROM type_field WHERE type_id = :id');
            $fieldQuery->bindValue(':id', $typeResult['id']);

            if (!$fieldQuery->execute())
                throw new Exception('Query $fieldQuery failed');

            $fields = [];

            while ($fieldResult = $fieldQuery->fetch(PDO::FETCH_ASSOC))
            {
                $fields[] = ['id' => $fieldResult['id'],
                             'fieldid' => $fieldResult['fieldid'],
                             'name' => $fieldResult['fieldname'],
                             'type' => $fieldResult['type']];
            }

            $returnArr[] = new DeviceType($typeResult['id'], $typeResult['name'], $fields);
        }

        return $returnArr;
    }

    /**
     * Gets a DeviceType by it's ID
     *
     * @throws Exception
     *
     * @param int $id => The id of the device type
     *
     * @return DeviceType object
     */
    public static function getDeviceType($id)
    {
        global $database;

        $typeQuery = $database->prepare('SELECT * FROM device_type WHERE id = :id');
        $typeQuery->bindValue(':id', $id);

        if (!$typeQuery->execute())
            throw new Exception('Query $typeQuery failed');

        if ($typeQuery->rowCount() == 0)
            throw new NotFoundException;

        $typeResult = $typeQuery->fetch(PDO::FETCH_ASSOC);

        $fields = self::getTypeFields($typeResult['id']);

        return (new DeviceType($typeResult['id'], $typeResult['name'], $fields));
    }

    /**
     * Gets the fields for a DeviceType
     *
     * @param int $id => THe id of the device type
     *
     * @return array
     */
    public static function getTypeFields($id)
    {
        global $database;

        // Get all the fields
        $fieldQuery = $database->prepare('SELECT * FROM type_field WHERE type_id = :id');
        $fieldQuery->bindValue(':id', $id);

        if (!$fieldQuery->execute())
            throw new Exception('Query $fieldQuery failed');

        $fields = [];

        while ($fieldResult = $fieldQuery->fetch(PDO::FETCH_ASSOC))
        {
            $fields[] = ['id' => $fieldResult['id'],
                         'fieldid' => $fieldResult['fieldid'],
                         'name' => $fieldResult['fieldname'],
                         'type' => $fieldResult['type']];
        }

        return $fields;
    }
}


text:
(function($) {

	var hash, iframe, links, inited;

	$.tools = $.tools || {version: '@VERSION'};

	$.tools.history = {

		init: function(els) {

			if (inited) { return; }

			// IE
			if ($.browser.msie && $.browser.version < '8') {

				// create iframe that is constantly checked for hash changes
				if (!iframe) {
					iframe = $("<iframe/>").attr("src", "javascript:false;").hide().get(0);
					$("body").append(iframe);

					setInterval(function() {
						var idoc = iframe.contentWindow.document,
							 h = idoc.location.hash;

						if (hash !== h) {
							$(window).trigger("hash", h);
						}
					}, 100);

					setIframeLocation(location.hash || '#');
				}

			// other browsers scans for location.hash changes directly without iframe hack
			} else {
				setInterval(function() {
					var h = location.hash;
					if (h !== hash) {
						$(window).trigger("hash", h);
					}
				}, 100);
			}

			links = !links ? els : links.add(els);

			els.click(function(e) {
				var href = $(this).attr("href");
				if (iframe) { setIframeLocation(href); }

				// handle non-anchor links
				if (href.slice(0, 1) != "#") {
					location.href = "#" + href;
					return e.preventDefault();
				}

			});

			inited = true;
		}
	};

	function setIframeLocation(h) {
		if (h) {
			var doc = iframe.contentWindow.document;
			doc.open().close();
			doc.location.hash = h;
		}
	}

	// global histroy change listener
	$(window).on("hash", function(e, h)  {
		if (h) {
			links.filter(function() {
			  var href = $(this).attr("href");
			  return href == h || href == h.replace("#", "");
			}).trigger("history", [h]);
		} else {
			links.eq(0).trigger("history", [h]);
		}

		hash = h;

	});

	// jQuery plugin implementation
	$.fn.history = function(fn) {

		$.tools.history.init(this);

		// return jQuery
		return this.on("history", fn);
	};

})(jQuery);


text:
package com.mmnaseri.couteau.reflection.beans.impl;

import com.mmnaseri.couteau.reflection.beans.BeanInitializer;
import com.mmnaseri.couteau.reflection.error.BeanInstantiationException;
import com.mmnaseri.couteau.reflection.util.ReflectionUtils;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.HashSet;
import java.util.Set;

/**
 * This implementation of {@link BeanInitializer} will allow for easy bean construction through
 * declared constructors.
 *
 * @author Milad Naseri (mmnaseri@programmer.net)
 * @since 1.0 (7/4/13, 6:55 PM)
 */
public class ConstructorBeanInitializer implements BeanInitializer {

    private final boolean allowAccessible;

    public ConstructorBeanInitializer() {
        this(false);
    }

    public ConstructorBeanInitializer(boolean allowAccessible) {
        this.allowAccessible = allowAccessible;
    }

    /**
     *
This method will initialize a bean of the given type using the specified initialization
     * arguments.

     *
     *
Any errors occurring during this process will be reflected as a BeanInstantiationException
     * to simplify handing exceptions for bean initialization.

     * @param type             the type of the bean
     * @param argumentTypes    the types of the arguments being passed
     * @param arguments        the arguments used for initialization of the bean
     * @param <E>              the type of the bean
     * @return an instance of the bean in question
     * @throws BeanInstantiationException
     */
    @Override
    public <E> E initialize(Class<E> type, Class[] argumentTypes, Object... arguments) throws BeanInstantiationException {
        if (argumentTypes == null) {
            throw new BeanInstantiationException("Argument types cannot be null");
        }
        if (arguments == null) {
            throw new BeanInstantiationException("Arguments cannot be null");
        }
        if (argumentTypes.length != arguments.length) {
            throw new BeanInstantiationException("Argument types must match arguments");
        }
        for (int i = 0; i < argumentTypes.length; i++) {
            final Class argumentType = ReflectionUtils.mapType(argumentTypes[i]);
            final Object argument = arguments[i];
            if (!argumentType.isInstance(argument) && ((argumentType.isPrimitive() || argument != null))) {
                throw new BeanInstantiationException("Arguments do not match the provided types");
            }
        }
        if (Modifier.isAbstract(type.getModifiers())) {
            throw new BeanInstantiationException("Cannot instantiate abstract class: " + type.getCanonicalName());
        }
        if (type.isInterface()) {
            throw new BeanInstantiationException("Cannot instantiate interface: " + type.getCanonicalName());
        }
        if (!Modifier.isPublic(type.getModifiers())) {
            if (!allowAccessible) {
                throw new BeanInstantiationException("Cannot instantiate a class unless it is public: " + type.getCanonicalName());
            }
        }
        final Constructor<?>[] constructors = type.getDeclaredConstructors();
        final Set<Constructor<?>> candidates = new HashSet<Constructor<?>>();
        for (Constructor<?> constructor : constructors) {
            if ((allowAccessible || Modifier.isPublic(constructor.getModifiers())) && constructor.getParameterTypes().length == arguments.length) {
                boolean matches = true;
                for (int i = 0; i < arguments.length; i ++) {
                    if (!constructor.getParameterTypes()[i].isAssignableFrom(argumentTypes[i])) {
                        matches = false;
                        break;
                    }
                }
                if (matches) {
                    candidates.add(constructor);
                }
            }
        }
        if (candidates.isEmpty()) {
            throw new BeanInstantiationException("No matching constructor found for specified arguments: " + type.getCanonicalName());
        }
        if (candidates.size() > 1) {
            throw new BeanInstantiationException("Ambiguous call to constructors for " + type.getCanonicalName());
        }
        final Constructor<?> constructor = candidates.iterator().next();
        constructor.setAccessible(true);
        final Object instance;
        try {
            instance = constructor.newInstance(arguments);
        } catch (IllegalArgumentException e) {
            throw new BeanInstantiationException("Invalid arguments passed to constructor", e);
        } catch (InstantiationException e) {
            throw new BeanInstantiationException("Failed to instantiate bean of type " + type.getCanonicalName(), e);
        } catch (IllegalAccessException e) {
            throw new BeanInstantiationException("Access denied to constructor: " + type.getCanonicalName(), e);
        } catch (InvocationTargetException e) {
            throw new BeanInstantiationException("Construction failed due to errors inside the constructor for type " + type.getCanonicalName(), e);
        }
        return type.cast(instance);
    }

}