text:
If you have suggestions on different syntax, please create
an issue: [here](https://github.com/AdamBrodzinski/RedScript/issues).

## Variables

RedScript has one kind of variable and does not need to be declared.
However they have the same scoping rules as JavaScript's `let`.

```elixir
result = 10 + 5
result = result + 5
# IO.inspect(result)
# 15
```

Compiled JavaScript:
```javascript
let result = 10 + 5
result = result + 5
// IO.inspect(result)
// 15
```

## Comments

RedScript has one kind of comment, a single line. All text is ignored to the right of the `#`.

```coffeescript
# this is a single line comment
# commented_out_func()
```

## String

RedScript has one kind of string, a double quote. Single quotes will not compile.

Strings can be interpolated with the `#{}` construct.

```elixir
name = "Jane"
"Hello #{name}"
```

Compiles to JavaScript:

```javascript
let name = "Jane"
`Hello ${name}`
```

## Number

Number is the same as the JavaScript implementation.

```javascript
typeof 1 == "number"
typeof 1.4 == "number"
```

## Symbol

Symbol is the same as the ES6 JavaScript implementation with a syntax similar to Elixir/Ruby.

```elixir
env = :prod

typeof :prod == "symbol"
# >> true
typeof env == "symbol"
# >> true

# use a symbol with a map (string keys are standard)
res = {foo: 1, [:bar]: 2}
```

Compiles to JavaScript:

```javascript
let env = Symbol.for(":prod")

typeof Symbol.for(":prod") == "symbol"
typeof env == "symbol"

// use a symbol with a map (string keys are standard)
let res = {foo: 1, [Symbol.for(":bar")]: 2}
```

## Boolean

Booleans are the same as JavaScript and many other languages.

```javascript
true
false
```

## Null

Null is the same as the JavaScript implementation.

```javascript
null
```

## Undefined

Undefined is the same as the JavaScript implementation.

```javascript
undefined
```

## Basic Arithmetic

Arithmetic is the same as the JavaScript implementation.

```elixir
1 + 2
# 3
5 * 5
# 25
10 / 2
# 5
```

## Anonymous functions

Anonymous functions have the same scoping rules as JavaScript but the syntax has a skinny arrow instead of a fat arrow.

```elixir
double_num = (x) -> x * 2
```

```javascript
let double_num = (x) => x * 2
```

## Maps

RedScript does not not have an "Object" type like JavaScript. It has
a "Map" type that acts like an immutable JavaScript literal. To make a change
you must copy the object and merge in the new key/values.

You can copy maps in several ways. However `Map.put` and the literal notation are
the most frequently used. `Map.put` is ideal for changing a map inside a pipeline.
Both of these are similar to using ES6 spread syntax in JavaScript.

If you *have* to mutate a map for performance reasons you have to explicitly
call `Map.mutate`

#### trying to mutate JS style will throw an error
```text
map.bar = 4
# or
map["bar"] = 4

Error: you can't mutate Maps
Perhaps you want to try using:
  map_copy = {old_map <- bar: 4}
or
  map_copy = Map.put(old_map, "bar", 4)
```

In order to change a value of a map you must use Map.put or the shorthand notation.

```elixir
map = {foo: 1, bar: 2}
map = Map.put(map, "bar", 4)
IO.inspect(map)
#log {foo: 1, bar: 4}

# or literal notation
map = {map <- foo: 2}
IO.inspect(map)
#log {foo: 2, bar: 4}
```

Compiled JavaScript

```javascript
map = {foo: 1, bar: 2}
map = Map.put(map, "bar", 4)
IO.inspect(map)
//log {foo: 1, bar: 4}

// or literal notation
map = {...map, foo: 2}
IO.inspect(map)
//log {foo: 2, bar: 4}
```

## If Else Uness

RedScript borrows the same sytax from Elixir for if, else, and unless

```elixir

if foo > 2 do
  # do work
end

if foo > 2 do
  # do work
else if foo > 2
  # do work
else
  # do work
end

unless foo > 2 do
  # do work
end
```

Compiled JavaScript

```javascript

if (foo > 2) {
  // do work
}

if (foo > 2) {
  // do work
} else if (foo > 2) {
  // do work
} else {
  // do work
}

if (!(foo > 2)) {
 // do work
}
```

redpajama_set_name: RedPajamaGithub


text:
#ifndef CFRLOGGER_HPP
#define CFRLOGGER_HPP

#include "cppmicroservices/BundleContext.h"
#include "cppmicroservices/ServiceTracker.h"
#include "cppmicroservices/logservice/LogService.hpp"

namespace cppmicroservices {
namespace cfrimpl {
/**
 * This class is used to track the availability of LogService in the
 * framework. If a LogService is available the calls to Log methods
 * are forwarded to the LogService. Otherwise, the calls to Log methods
 * are no-op calls. This class implements the LogService interface so that
 * other classes within the runtime can easily use a mock log service for
 * testing purposes.
 *
 * Note: This is directly copied from CMLogger.hpp. The only difference
 * is that the name of the class has been changed.
 *
 * TODO(achristoforides): Provide unified "utility" library for the core framework,
 *   DS, CA, and future services containing an implementation of this class, the one
 *   for the AsyncWorkService, and any others that may be needed.
 */
class CFRLogger final
  : public cppmicroservices::logservice::LogService
  , public detail::MultiThreaded<>
  , public cppmicroservices::ServiceTrackerCustomizer<
      cppmicroservices::logservice::LogService>
{
public:
  CFRLogger();
  CFRLogger(const CFRLogger&) = delete;
  CFRLogger(CFRLogger&&) = delete;
  CFRLogger& operator=(const CFRLogger&) = delete;
  CFRLogger& operator=(CFRLogger&&) = delete;
  ~CFRLogger() override;

  // methods from the cppmicroservices::logservice::LogService interface
  void Log(logservice::SeverityLevel level,
           const std::string& message) override;
  void Log(logservice::SeverityLevel level,
           const std::string& message,
           const std::exception_ptr ex) override;
  void Log(const ServiceReferenceBase& sr,
           logservice::SeverityLevel level,
           const std::string& message) override;
  void Log(const ServiceReferenceBase& sr,
           logservice::SeverityLevel level,
           const std::string& message,
           const std::exception_ptr ex) override;

  // methods from the cppmicroservices::ServiceTrackerCustomizer interface
  std::shared_ptr<TrackedParamType> AddingService(
    const ServiceReference<cppmicroservices::logservice::LogService>& reference)
    override;
  void ModifiedService(
    const ServiceReference<cppmicroservices::logservice::LogService>& reference,
    const std::shared_ptr<cppmicroservices::logservice::LogService>& service)
    override;
  void RemovedService(
    const ServiceReference<cppmicroservices::logservice::LogService>& reference,
    const std::shared_ptr<cppmicroservices::logservice::LogService>& service)
    override;

  // methods for the CFRLogger class
  void Open();
  void Close();

private:
  cppmicroservices::BundleContext cfrContext;
  std::unique_ptr<
    cppmicroservices::ServiceTracker<cppmicroservices::logservice::LogService>>
    serviceTracker;
  std::shared_ptr<cppmicroservices::logservice::LogService> logService;
};
} // cfrimpl
} // cppmicroservices

#endif // CFRLOGGER_HPP


text:
package com.intellij.application.options.colors;

import com.intellij.openapi.editor.colors.FontPreferences;
import org.jetbrains.annotations.NotNull;

/**
 * User: anna
 */
public class ConsoleFontOptions extends FontOptions {
  public ConsoleFontOptions(ColorAndFontOptions options) {
    super(options, "Console Font");
  }

  @NotNull
  @Override
  protected FontPreferences getFontPreferences() {
    return getCurrentScheme().getConsoleFontPreferences();
  }

  @Override
  protected void setFontSize(int fontSize) {
    getCurrentScheme().setConsoleFontSize(fontSize);
  }

  @Override
  protected float getLineSpacing() {
    return getCurrentScheme().getConsoleLineSpacing();
  }

  @Override
  protected void setCurrentLineSpacing(float lineSpacing) {
    getCurrentScheme().setConsoleLineSpacing(lineSpacing);
  }
}


text:
/*
 * GET home page.
 */

exports.index = function(req, res){
  res.render('index', { title: 'FestKids' });
};

exports.teste = function(req,res){
	res.render('teste');
};


text:
package std.other.session;

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

import javax.persistence.Query;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;

import std.commons.session.FakeEntityQuery;
import std.other.entity.ArticleCategory;
import std.util.InvokeFeatures;

@Name("articleCategoryList")
@Scope(value = ScopeType.CONVERSATION)
public class ArticleCategoryList extends FakeEntityQuery implements InvokeFeatures {

	private static final long serialVersionUID = 1L;
	private static final String EJBQL = "select articleCategory from ArticleCategory articleCategory where 0 = 0";
	private ArticleCategory articleCategory = new ArticleCategory();
	private List<Object[]> theParentList;// 上级菜单
	private String gainDisplayOrder2param;
	private JSONObject gainDisplayOrder2result;
	private String updateDisplayOrder2param;
	private JSONObject updateDisplayOrder2result;

	@SuppressWarnings("unchecked")
	public void init() {
		if (theParentList != null) {
			theParentList.clear();
		} else {
			theParentList = new ArrayList<Object[]>();
		}
		theParentList.add(new Object[] { "", "无" });
		Map<Object, List<Object>> nexusMap = new HashMap<Object, List<Object>>();// 上下级关系集合
		Map<Object, Object> valueMap = new HashMap<Object, Object>();// 值集合
		String dataSql = "select the_id, the_pid, the_value from article_category order by display_order";// 注意:这个排序至关重要,避免使用Collections.sort降低效率。
		List<Object[]> dataList = getEntityManager().createNativeQuery(dataSql).getResultList();
		if (dataList != null && dataList.size() > 0) {
			for (Object[] data : dataList) {
				valueMap.put(data[0], data[2]);
				List<Object> leafList = nexusMap.get(data[1]);
				if (leafList != null) {
					leafList.add(data[0]);
				} else {
					leafList = new ArrayList<Object>();
					leafList.add(data[0]);
					nexusMap.put(data[1], leafList);
				}
			}
		}
		List<Object> rootList = nexusMap.get(null);
		if (rootList != null && rootList.size() > 0) {
			for (Object root : rootList) {
				theParentList.add(new Object[] { root, valueMap.get(root) });
				disposeLeaf(theParentList, nexusMap, valueMap, 1, nexusMap.get(root));
			}
		}
	}

	/** 递归处理子节点 */
	public void disposeLeaf(List<Object[]> targetList, Map<Object, List<Object>> nexusMap, Map<Object, Object> valueMap, int indentWidth, List<Object> leafList) {
		if (leafList != null && leafList.size() > 0) {
			for (Object leaf : leafList) {
				String indentStr = "";
				for (int i = 0; i < indentWidth; i++) {
					indentStr += " ";
				}
				targetList.add(new Object[] { leaf, indentStr + valueMap.get(leaf) });
				disposeLeaf(targetList, nexusMap, valueMap, indentWidth + 1, nexusMap.get(leaf));
			}
		}
	}

	@SuppressWarnings("unchecked")
	public void gainDisplayOrder2action() {
		if (gainDisplayOrder2result != null) {
			gainDisplayOrder2result.clear();
		} else {
			gainDisplayOrder2result = new JSONObject();
		}
		gainDisplayOrder2result.accumulate(INVOKE_RESULT, INVOKE_SUCCESS);
		JSONArray dataArr = new JSONArray();
		List<ArticleCategory> sourceList = getEntityManager().createQuery(EJBQL + (gainDisplayOrder2param != null && !"".equals(gainDisplayOrder2param) ? " and articleCategory.articleCategory.theId = " + gainDisplayOrder2param : " and articleCategory.articleCategory is null") + " order by articleCategory.displayOrder").getResultList();
		if (sourceList != null && sourceList.size() > 0) {
			for (ArticleCategory source : sourceList) {
				JSONObject data = new JSONObject();
				data.accumulate("value", source.getTheId());
				data.accumulate("label", source.getTheValue());
				dataArr.add(data);
			}
		}
		gainDisplayOrder2result.accumulate("data", dataArr);
	}

	public void updateDisplayOrder2action() {
		if (updateDisplayOrder2result != null) {
			updateDisplayOrder2result.clear();
		} else {
			updateDisplayOrder2result = new JSONObject();
		}
		updateDisplayOrder2result.accumulate(INVOKE_RESULT, INVOKE_SUCCESS);
		updateDisplayOrder2result.accumulate(INVOKE_MESSAGE, "排序成功!");
		try {
			if (updateDisplayOrder2param != null && !"".equals(updateDisplayOrder2param)) {
				String[] args = updateDisplayOrder2param.split(",");
				if (args != null && args.length > 0) {
					for (int i = 0; i < args.length; i++) {
						ArticleCategory source = getEntityManager().find(ArticleCategory.class, Integer.valueOf(args[i]));
						source.setDisplayOrder(i + 1);
					}
					getEntityManager().flush();
				}
			}
		} catch (Exception e) {
			updateDisplayOrder2result.element(INVOKE_RESULT, INVOKE_FAILURE);
			updateDisplayOrder2result.element(INVOKE_MESSAGE, "排序失败!");
		}
	}

	@Override
	protected Query createQuery() {
		setFakeEntityColumns("the_id", "the_value", "the_parent_value");
		StringBuffer sql = new StringBuffer("select t1.the_id, t1.the_value, t2.the_value the_parent_value from article_category t1");
		sql.append(" left join article_category t2 on t1.the_pid = t2.the_id");
		sql.append(" where 0 = 0");
		if (keyword != null && !"".equals(keyword)) {
			sql.append(" and (0 <> 0");
			sql.append(" or t1.the_value like '%" + keyword + "%'");
			sql.append(" or t2.the_value like '%" + keyword + "%'");
			sql.append(" )");
		}
		sql.append(" order by t1.the_pid, t1.display_order");
		sql.insert(0, "select * from (").append(") as recordset");
		setEjbql(sql.toString());
		return super.createQuery();
	}

	public ArticleCategoryList() {
		setEjbql("");
		setAttribute("");
	}

	public ArticleCategory getArticleCategory() {
		return articleCategory;
	}

	public List<Object[]> getTheParentList() {
		return theParentList;
	}

	public JSONObject getGainDisplayOrder2result() {
		return gainDisplayOrder2result;
	}

	public void setGainDisplayOrder2param(String gainDisplayOrder2param) {
		this.gainDisplayOrder2param = gainDisplayOrder2param;
	}

	public JSONObject getUpdateDisplayOrder2result() {
		return updateDisplayOrder2result;
	}

	public void setUpdateDisplayOrder2param(String updateDisplayOrder2param) {
		this.updateDisplayOrder2param = updateDisplayOrder2param;
	}

}


text:
import ensembles as en
import pandas as pd
import numpy as np
import xgboost as xgb
import category_encoders as ce
from sklearn import datasets, linear_model, preprocessing, grid_search
from sklearn.preprocessing import Imputer, PolynomialFeatures, StandardScaler
from sklearn.tree import DecisionTreeClassifier
from sklearn.cross_validation import KFold
from sklearn.ensemble import RandomForestClassifier
from sklearn.cross_validation import StratifiedKFold, KFold
from sklearn.preprocessing import OneHotEncoder
from sklearn.externals import joblib
from keras.layers import Dense, Activation, Dropout
from keras.models import Sequential
from keras.regularizers import l2, activity_l2
from sklearn.metrics import roc_auc_score, average_precision_score, f1_score, log_loss, accuracy_score, mean_absolute_error, mean_squared_error, r2_score
from sklearn.cross_validation import train_test_split
from joblib import Parallel, delayed
from sklearn.pipeline import Pipeline
from hyperopt import hp, fmin, tpe, STATUS_OK, Trials
from hyperas import optim
from hyperas.distributions import choice, uniform, conditional
from functools import partial
np.random.seed(1338)

# In[ ]:

#Setting the parameters for the Random Forest Model

# # Example 1

# In[ ]:

#Default Values
param_rf = en.parameter_set_random_forest()
print(param_rf)

# # Example 2

# In[ ]:

#Setting n_estimators, rest are deafult values
param_rf = en.parameter_set_random_forest(n_estimators = [15])
print(param_rf)

# # Example 3

# In[ ]:

#Setting n_estimators, criterion, rest are default values
#Hyper parameter optimisation - n_estimators
param_rf = en.parameter_set_random_forest(n_estimators = [6, 10, 12], criterion = ['entropy'])
print(param_rf)

# # Example 4

# In[ ]:

#Setting max_depth, n_estimators, rest are default values
#Hyper parameter optimisation - max_depth
#Hyper parameter optimisation - n_estimators
param_rf = en.parameter_set_random_forest(max_depth = [6, 10, 12], n_estimators = [6, 10])
print(param_rf)

# # Example 5

# In[ ]:

#Setting max_depth, n_estimators, max_features, rest are default values
#Hyper parameter optimisation - max_depth
#Hyper parameter optimisation - n_estimators
param_rf = en.parameter_set_random_forest(max_depth = [6, 10, 12, 15], n_estimators = [10, 20, 30],                                           max_features = 'log2')
print(param_rf)


text:
.. mpy-dev-tools documentation master file, created by
   sphinx-quickstart on Sun Sep 17 16:58:03 2017.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to mpy-dev-tools's documentation!
=========================================

.. toctree::
    :maxdepth: 2

    cli
    _api/modules

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
INCLUDE(CMakeParseArguments)
# NOTE: For CMake versions 3.5.0 and above, this module is empty so the
# natively implemented function CMAKE_PARSE_ARGUMENTS() will get used!

MACRO(PARSE_ARGUMENTS_DEPRECATED_WARNING)
  MESSAGE(WARNING "PARSE_ARGUMENTS() is deprecated and should not be used."
     " Instead use CMAKE_PARSE_ARGUMENTS()")
ENDMACRO()

PARSE_ARGUMENTS_DEPRECATED_WARNING()

# Set PARSE_ARGUMENTS_DUMP_OUTPUT_ENABLED to TRUE to see output from parsing.

FUNCTION(PARSE_ARGUMENTS_DUMP_OUTPUT  OUTPUT_STR)
  IF (PARSE_ARGUMENTS_DUMP_OUTPUT_ENABLED)
    MESSAGE("${OUTPUT_STR}")
  ENDIF()
ENDFUNCTION()

#
# @MACRO: PARSE_ARGUMENTS()
#
# Parse a set of macro/function input arguments into different lists.  This
# allows the easy implementation of keyword-based user-defined macros and
# functions.
#
# Usage::
#
#   PARSE_ARGUMENTS(
#     <prefix>  <argNamesList>  <optionNamesList>
#     <inputArgsList>
#     )
#
# Arguments to this macro are:
#
#   ``<prefix>``
#
#     Prefix ``<prefix>_`` added the list and option variables created listed
#     in ``<argNamesList>`` and ``<optionNamesList>``.
#
#   ``<argNamesList>``
#
#     Quoted array of list arguments (e.g. ``"<argName0>;<argName1>;..."``).
#     For each variable name ``<argNamei>``, a local variable will be created
#     in the current scope with the name ``<prefix>_<argNamei>`` which gives
#     the list of variables parsed out of ``<inputArgsList>``.
#
#   ``<optionNamesList>``
#
#     Quoted array of list options (e.g. ``"<optName0>;<optName1>;..."``)
#     typically pass in as ``${ARGN}`` in the outer function/macro.  For each
#     variable name ``<optNamei>``, a local variable will be created in the
#     current scope with the name ``<prefix>_<optNamei>`` that is either set
#     to ``TRUE`` or ``FALSE`` depending if ``<optNamei>`` appears in
#     ``<inputArgsList>`` or not.
#
#   ``<inputArgsList>``
#
#     List of arguments keyword-based arguments passed in through the outer
#     macro or function to be parsed out into the different argument and
#     option lists.
#
# What this macro does is very simple yet very useful.  What it does is to
# allow one to create one's own user-defined keyword-based macros and
# functions like is used by some built-in CMake commands.
#
# For example, consider the following user-defined macro that uses both
# positional and keyword-based arguments using ``PARSE_ARGUMENTS()``::
#
#   MACRO(PARSE_SPECIAL_VARS  BASE_NAME)
#
#     PARSE_ARGUMENTS(
#       #prefix
#       ${BASE_NAME}
#       #lists
#       "ARG0;ARG1;ARG2"
#       #options
#       "OPT0;OPT1"
#       ${ARGN}
#       )
#
#   ENDMACRO()
#
# Calling this macro as::
#
#   PARSE_SPECIAL_VARS(MyVar ARG0 a b ARG2 c OPT1)
#
# sets the following variables in the current scope::
#
#   MyVar_ARG0="a;b"
#   MyVar_ARG1=""
#   MyVar_ARG2="c"
#   MyVar_OPT0="FALSE"
#   MyVar_OPT1="TRUE"
#
# This allows one to define user-defined macros and functions that have a
# mixture of positional arguments and keyword-based arguments like one can do
# in other languages.  The keyword-based arguments can be passed in any order
# and those that are missing are empty (or false for options) by default.
#
# Any initial arguments that are not recognized as ``<argNamesList>`` or
# ``<optionNamesList>`` keyword arguments will be put into the local variable
# ``<prefix>_DEFAULT_ARGS``.  If no arguments in ``<inputArgsList>``
# (typically ``${ARGN}``) match any in ``<argNamesList>``, then all non-option
# arguments are put into ``<prefix>_DEFAULT_ARGS``.  For example, if one
# passes in::
#
#   PARSE_SPECIAL_VARS(MyVar ARG5 a b c)
#
# you will get::
#
#   MyVar_DEFAULT_ARGS="ARG5;a;b;c"
#   MyVar_ARG0=""
#   MyVar_ARG1=""
#   MyVar_ARG2=""
#   MyVar_OPT0="FALSE"
#   MyVar_OPT1="FALSE"
#
# Multiple occurrences of keyword arguments in ``<inputArgsList>`` is allowed
# but only the last one listed will be recorded.  For example, if one calls::
#
#   PARSE_SPECIAL_VARS(MyVar ARG1 a b ARG1 c)
#
# then this will set::
#
#   MyVar_ARG0=""
#   MyVar_ARG1="c"
#   MyVar_ARG2=""
#   MyVar_OPT0="FALSE"
#   MyVar_OPT1="FALSE"
#
# This is actually consistent with the way that most argument list parsers
# behave with respect to multiple instances of the same argument so hopefully
# this will not be a surprise to anyone.
#
# If one puts an option keyword in the middle of a keyword argument list, the
# option keyword will get pulled out of the list.  For example, if one calls::
#
#   PARSE_SPECIAL_VARS(MyVar ARG0 a OPT0 c)
#
# then this will set::
#
#   MyVar_ARG0="a;c"
#   MyVar_ARG1=""
#   MyVar_ARG2=""
#   MyVar_OPT0="TRUE"
#   MyVar_OPT1="FALSE"
#
# This is confusing behavior so users would be smart not to mix option
# arguments inside of list arguments.
#
# If ``PARSE_ARGUMENTS_DUMP_OUTPUT_ENABLED`` is set to ``TRUE``, then a bunch
# of detailed debug info will be printed.  This should only be used in the
# most desperate of debug situations because it will print a *lot* of output!
#
# **PERFORMANCE:** This function will scale as::
#
#   O( (len(<argNamesList>) * len(<optionNamesList>)) * len(<inputArgsList>) )
#
# Therefore, this could scale very badly for large sets of argument and option
# names and input argument list names.
#
MACRO(PARSE_ARGUMENTS prefix arg_names option_names)

  PARSE_ARGUMENTS_DEPRECATED_WARNING()

  PARSE_ARGUMENTS_DUMP_OUTPUT("PARSE_ARGUMENTS: prefix='${prefix}'")
  PARSE_ARGUMENTS_DUMP_OUTPUT("PARSE_ARGUMENTS: arg_names='${arg_names}'")
  PARSE_ARGUMENTS_DUMP_OUTPUT("PARSE_ARGUMENTS: option_names='${option_names}'")
  PARSE_ARGUMENTS_DUMP_OUTPUT("PARSE_ARGUMENTS: ARGN='${ARGN}'")

  FOREACH(arg_name ${arg_names})
    SET(${prefix}_${arg_name})
  ENDFOREACH()

  FOREACH(option ${option_names})
    SET(${prefix}_${option} FALSE)
  ENDFOREACH()

  SET(DEFAULT_ARGS)
  SET(current_arg_name DEFAULT_ARGS)
  SET(current_arg_list)

  FOREACH(arg ${ARGN})
    SET(larg_names ${arg_names})
    LIST(FIND larg_names "${arg}" is_arg_name)
    IF (is_arg_name GREATER -1)
      SET(${prefix}_${current_arg_name} "${current_arg_list}")
      PARSE_ARGUMENTS_DUMP_OUTPUT("PARSE_ARGUMENTS: ${prefix}_${current_arg_name} = '${${prefix}_${current_arg_name}}'" )
      SET(current_arg_name "${arg}")
      SET(current_arg_list)
    ELSE()
      SET(loption_names "${option_names}")
      LIST(FIND loption_names "${arg}" is_option)
      IF (is_option GREATER -1)
        SET(${prefix}_${arg} TRUE)
        PARSE_ARGUMENTS_DUMP_OUTPUT( "PARSE_ARGUMENTS: ${prefix}_${arg} = '${${prefix}_${arg}}'" )
      ELSE()
        LIST(APPEND current_arg_list "${arg}")
      ENDIF()
    ENDIF()
  ENDFOREACH()

  SET(${prefix}_${current_arg_name} "${current_arg_list}")
  PARSE_ARGUMENTS_DUMP_OUTPUT( "PARSE_ARGUMENTS: ${prefix}_${current_arg_name} = '${${prefix}_${current_arg_name}}'" )

ENDMACRO()

# NOTE: If the above function turns out to be a performance bottle neck, there
# are a few things that could be done to improve performance.  One thing you
# could do is repalce the O(len(arg_names)) and O(len(option_names)) lookups
# with O(1) lookups by creating CMake variables of the name
# ${OUTER_FUNC_NAME}_arg_<argNamei> and then just look of that varible exists
# or not.  That should use a hash function.  That might actually slow things
# down for short lists however so we would have to measure, measure,
# measure. I would have to pass in the function/macro name to disabiguate
# the varible names.  It would really be better if cmake would provide a
# sorted list find operation.  That would make this much faster for large
# numbers of argument and option names.


text:
using namespace zhttpd;
using namespace zhttpd::parser;

VHostParser::VHostParser()
{
    this->_hdlrs["url"] = &VHostParser::_parseUrl;
    this->_hdlrs["document-root"] = &VHostParser::_parseDocumentRoot;
    this->_hdlrs["header"] = &VHostParser::_parseHeader;
    this->_hdlrs["host"] = &VHostParser::_parseHost;
    this->_hdlrs["listen"] = &VHostParser::_parseListen;
}

VHostParser::~VHostParser()
{
}

void VHostParser::parseVHost(ticpp::Node* node, Configuration* conf, VHost* parent)
{
    try
    {
        ModuleParser module_parser;
        VHost* vhost = new VHost(parent, *conf);
        vhost->setName(node->ToElement()->GetAttribute("name"));
        ticpp::Node* child = 0;
        std::string childName;
        while ((child = node->IterateChildren(child)))
        {
            childName = child->ToElement()->Value();
            if (childName == "vhost")
                this->parseVHost(child, conf, vhost);
            else if (childName == "module")
                module_parser.parseModule(child, vhost, conf);
            else
                this->parseGuideLine(child, vhost);
        }
        if (parent == 0)
            conf->setVHost(*vhost);
        else
            parent->addChild(vhost);
    }
    catch (ticpp::Exception& e)
    {
        throw ConfigurationParserException(std::string("Undefined error while parsing VHosts: ") + e.what());
    }
}

void VHostParser::parseGuideLine(ticpp::Node* node, VHost* vhost)
{
    try
    {
        std::string node_name = node->ToElement()->Value();

        if (this->_hdlrs.find(node_name) != this->_hdlrs.end())
            (this->*this->_hdlrs[node_name])(node, vhost);
        else
            std::cout << node_name << " non gere: skip" << std::endl;
    }
    catch (ticpp::Exception&)
    {
        throw ConfigurationParserException("A virtual host guideline shoud be a valid XML tag");
    }
}

void VHostParser::_parseDocumentRoot(ticpp::Node* node, VHost* vhost)
{
    try
    {
        std::string path;
        node->ToElement()->GetAttribute("path", &path);
        vhost->setDocumentRoot(path);
    }
    catch (ticpp::Exception&)
    {
        throw ConfigurationParserException("Document-root guideline should have a 'path' attribute");
    }
}

void VHostParser::_parseUrl(ticpp::Node* node, VHost* vhost)
{
    try
    {
        ticpp::Element* urlElement = node->ToElement();
        std::string match;
        urlElement->GetAttribute("match", &match);
        std::string denyStr = urlElement->GetAttribute("deny");
        bool deny = false;
        if (denyStr == "true")
            deny = true;
        vhost->addGuideline(new UrlGuideline(match, deny));
    }
    catch (ticpp::Exception&)
    {
        throw ConfigurationParserException("URL guideline misformed. It should contain at least a 'match' attribute, and may have a 'deny' one");
    }
}

void VHostParser::_parseHeader(ticpp::Node* node, VHost* vhost)
{
    try
    {
        ticpp::Element* headerElement = node->ToElement();
        std::string key;
        std::string match;
        headerElement->GetAttribute("key", &key);
        headerElement->GetAttribute("match", &match);
        std::string denyStr = headerElement->GetAttribute("deny");
        bool deny = false;
        if (denyStr == "true")
            deny = true;
        vhost->addGuideline(new HeaderGuideline(key, match, deny));
    }
    catch (ticpp::Exception&)
    {
        throw ConfigurationParserException("header guideline misformed. It should contain 'key' and 'match' attributes, and may have a 'deny' one");
    }
}

void VHostParser::_parseHost(ticpp::Node* node, VHost* vhost)
{
    try
    {
        std::string match;
        node->ToElement()->GetAttribute("match", &match);
        std::string denyStr = node->ToElement()->GetAttribute("deny");
        bool deny = false;
        if (denyStr == "true")
            deny = true;
        vhost->addGuideline(new HostGuideline(match, deny));
    }
    catch (ticpp::Exception&)
    {
        throw ConfigurationParserException("host guideline misformed. It should have a 'match' attribute, and mey have a deny");
    }
}

void VHostParser::_parseListen(ticpp::Node* node, VHost* vhost)
{
    try
    {
        zhttpd::api::uint16_t port;
        node->ToElement()->GetAttribute("port", &port);
        std::string denyStr = node->ToElement()->GetAttribute("deny");
        bool deny = false;
        if (denyStr == "true")
            deny = true;
        vhost->addGuideline(new ListenGuideline(port, deny));
    }
    catch (ticpp::Exception&)
    {
        throw ConfigurationParserException("listen guideline misformed. It should have a 'port' attribute, containing an integer value, and may have a deny attribute");
    }
}


text:
package org.apache.jmeter.protocol.jdbc;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.save.CSVSaveService;
import org.apache.jmeter.testelement.AbstractTestElement;
import org.apache.jmeter.testelement.TestStateListener;
import org.apache.jmeter.threads.JMeterVariables;
import org.apache.jmeter.util.JMeterUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A base class for all JDBC test elements handling the basics of a SQL request.
 *
 */
public abstract class AbstractJDBCTestElement extends AbstractTestElement implements TestStateListener{
    private static final long serialVersionUID = 235L;

    private static final Logger log = LoggerFactory.getLogger(AbstractJDBCTestElement.class);

    private static final String COMMA = ","; // $NON-NLS-1$
    private static final char COMMA_CHAR = ',';

    private static final String UNDERSCORE = "_"; // $NON-NLS-1$

    // String used to indicate a null value
    private static final String NULL_MARKER =
        JMeterUtils.getPropDefault("jdbcsampler.nullmarker","]NULL["); // $NON-NLS-1$

    private static final String INOUT = "INOUT"; // $NON-NLS-1$

    private static final String OUT = "OUT"; // $NON-NLS-1$

    // TODO - should the encoding be configurable?
    protected static final String ENCODING = StandardCharsets.UTF_8.name();

    // key: name (lowercase) from java.sql.Types; entry: corresponding int value
    private static final Map<String, Integer> mapJdbcNameToInt;
    // read-only after class init

    static {
        // based on e291. Getting the Name of a JDBC Type from javaalmanac.com
        // http://javaalmanac.com/egs/java.sql/JdbcInt2Str.html
        mapJdbcNameToInt = new HashMap<>();

        //Get all fields in java.sql.Types and store the corresponding int values
        Field[] fields = java.sql.Types.class.getFields();
        for (Field field : fields) {
            try {
                String name = field.getName();
                Integer value = (Integer) field.get(null);
                mapJdbcNameToInt.put(name.toLowerCase(java.util.Locale.ENGLISH), value);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e); // should not happen
            }
        }
    }

    // Query types (used to communicate with GUI)
    // N.B. These must not be changed, as they are used in the JMX files
    static final String SELECT   = "Select Statement"; // $NON-NLS-1$
    static final String UPDATE   = "Update Statement"; // $NON-NLS-1$
    static final String CALLABLE = "Callable Statement"; // $NON-NLS-1$
    static final String PREPARED_SELECT = "Prepared Select Statement"; // $NON-NLS-1$
    static final String PREPARED_UPDATE = "Prepared Update Statement"; // $NON-NLS-1$
    static final String COMMIT   = "Commit"; // $NON-NLS-1$
    static final String ROLLBACK = "Rollback"; // $NON-NLS-1$
    static final String AUTOCOMMIT_FALSE = "AutoCommit(false)"; // $NON-NLS-1$
    static final String AUTOCOMMIT_TRUE  = "AutoCommit(true)"; // $NON-NLS-1$

    static final String RS_STORE_AS_STRING = "Store as String"; // $NON-NLS-1$
    static final String RS_STORE_AS_OBJECT = "Store as Object"; // $NON-NLS-1$
    static final String RS_COUNT_RECORDS = "Count Records"; // $NON-NLS-1$

    private String query = ""; // $NON-NLS-1$

    private String dataSource = ""; // $NON-NLS-1$

    private String queryType = SELECT;
    private String queryArguments = ""; // $NON-NLS-1$
    private String queryArgumentsTypes = ""; // $NON-NLS-1$
    private String variableNames = ""; // $NON-NLS-1$
    private String resultSetHandler = RS_STORE_AS_STRING;
    private String resultVariable = ""; // $NON-NLS-1$
    private String queryTimeout = ""; // $NON-NLS-1$
    private String resultSetMaxRows = ""; // $NON-NLS-1$

    private static final int MAX_RETAIN_SIZE = JMeterUtils.getPropDefault("jdbcsampler.max_retain_result_size", 64 * 1024);

    /**
     * Creates a JDBCSampler.
     */
    protected AbstractJDBCTestElement() {
    }

    /**
     * Execute the test element.
     *
     * @param conn a {@link Connection}
     * @return the result of the execute command
     * @throws SQLException if a database error occurs
     * @throws IOException when I/O error occurs
     * @throws UnsupportedOperationException if the user provided incorrect query type
     */
    protected byte[] execute(Connection conn) throws SQLException, IOException, UnsupportedOperationException { // NOSONAR
        return execute(conn,  new SampleResult());
    }

    /**
     * Execute the test element.
     * Use the sample given as argument to set time to first byte in the "latency" field of the SampleResult.
     *
     * @param conn a {@link Connection}
     * @param sample a {@link SampleResult} to save the latency
     * @return the result of the execute command
     * @throws SQLException if a database error occurs
     * @throws IOException when I/O error occurs
     * @throws UnsupportedOperationException if the user provided incorrect query type
     */
    protected byte[] execute(Connection conn, SampleResult sample) throws SQLException, IOException, UnsupportedOperationException {
        log.debug("executing jdbc:{}", getQuery());
        // Based on query return value, get results
        String currentQueryType = getQueryType();
        if (SELECT.equals(currentQueryType)) {
            try (Statement stmt = conn.createStatement()) {
                setQueryTimeout(stmt, getIntegerQueryTimeout());
                ResultSet rs = null;
                try {
                    rs = stmt.executeQuery(getQuery());
                    sample.latencyEnd();
                    return getStringFromResultSet(rs).getBytes(ENCODING);
                } finally {
                    close(rs);
                }
            }
        } else if (CALLABLE.equals(currentQueryType)) {
            try (CallableStatement cstmt = getCallableStatement(conn)) {
                int[] out = setArguments(cstmt);
                // A CallableStatement can return more than 1 ResultSets
                // plus a number of update counts.
                boolean hasResultSet = cstmt.execute();
                sample.latencyEnd();
                String sb = resultSetsToString(cstmt,hasResultSet, out);
                return sb.getBytes(ENCODING);
            }
        } else if (UPDATE.equals(currentQueryType)) {
            try (Statement stmt = conn.createStatement()) {
                setQueryTimeout(stmt, getIntegerQueryTimeout());
                stmt.executeUpdate(getQuery());
                sample.latencyEnd();
                int updateCount = stmt.getUpdateCount();
                String results = updateCount + " updates";
                return results.getBytes(ENCODING);
            }
        } else if (PREPARED_SELECT.equals(currentQueryType)) {
            try (PreparedStatement pstmt = getPreparedStatement(conn)) {
                setArguments(pstmt);
                ResultSet rs = null;
                try {
                    rs = pstmt.executeQuery();
                    sample.latencyEnd();
                    return getStringFromResultSet(rs).getBytes(ENCODING);
                } finally {
                    close(rs);
                }
            }
        } else if (PREPARED_UPDATE.equals(currentQueryType)) {
            try (PreparedStatement pstmt = getPreparedStatement(conn)) {
                setArguments(pstmt);
                pstmt.executeUpdate();
                sample.latencyEnd();
                String sb = resultSetsToString(pstmt,false,null);
                return sb.getBytes(ENCODING);
            }
        } else if (ROLLBACK.equals(currentQueryType)){
            conn.rollback();
            sample.latencyEnd();
            return ROLLBACK.getBytes(ENCODING);
        } else if (COMMIT.equals(currentQueryType)){
            conn.commit();
            sample.latencyEnd();
            return COMMIT.getBytes(ENCODING);
        } else if (AUTOCOMMIT_FALSE.equals(currentQueryType)){
            conn.setAutoCommit(false);
            sample.latencyEnd();
            return AUTOCOMMIT_FALSE.getBytes(ENCODING);
        } else if (AUTOCOMMIT_TRUE.equals(currentQueryType)){
            conn.setAutoCommit(true);
            sample.latencyEnd();
            return AUTOCOMMIT_TRUE.getBytes(ENCODING);
        } else { // User provided incorrect query type
            throw new UnsupportedOperationException("Unexpected query type: "+currentQueryType);
        }
    }

    private String resultSetsToString(PreparedStatement pstmt, boolean result, int[] out) throws SQLException, UnsupportedEncodingException {
        StringBuilder sb = new StringBuilder();
        int updateCount = 0;
        boolean currentResult = result;
        if (!currentResult) {
            updateCount = pstmt.getUpdateCount();
        }
        do {
            if (currentResult) {
                ResultSet rs = null;
                try {
                    rs = pstmt.getResultSet();
                    sb.append(getStringFromResultSet(rs)).append("\n"); // $NON-NLS-1$
                } finally {
                    close(rs);
                }
            } else {
                sb.append(updateCount).append(" updates.\n");
            }
            currentResult = pstmt.getMoreResults();
            if (!currentResult) {
                updateCount = pstmt.getUpdateCount();
            }
        } while (currentResult || (updateCount != -1));
        if (out!=null && pstmt instanceof CallableStatement){
            List<Object> outputValues = new ArrayList<>();
            CallableStatement cs = (CallableStatement) pstmt;
            sb.append("Output variables by position:\n");
            for(int i=0; i < out.length; i++){
                if (out[i]!=java.sql.Types.NULL){
                    Object o = cs.getObject(i+1);
                    outputValues.add(o);
                    sb.append("[");
                    sb.append(i+1);
                    sb.append("] ");
                    sb.append(o);
                    if( o instanceof java.sql.ResultSet && RS_COUNT_RECORDS.equals(resultSetHandler)) {
                        sb.append(" ").append(countRows((ResultSet) o)).append(" rows");
                    }
                    sb.append("\n");
                }
            }
            String[] varnames = getVariableNames().split(COMMA);
            if(varnames.length > 0) {
            JMeterVariables jmvars = getThreadContext().getVariables();
                for(int i = 0; i < varnames.length && i < outputValues.size(); i++) {
                    String name = varnames[i].trim();
                    if (name.length()>0){ // Save the value in the variable if present
                        Object o = outputValues.get(i);
                        if( o instanceof java.sql.ResultSet ) {
                            putIntoVar(jmvars, name, (java.sql.ResultSet) o);
                        } else if (o instanceof java.sql.Clob) {
                            putIntoVar(jmvars, name, (java.sql.Clob) o);
                        } else if (o instanceof java.sql.Blob) {
                            putIntoVar(jmvars, name, (java.sql.Blob) o);
                        }
                        else {
                            jmvars.put(name, o == null ? null : o.toString());
                        }
                    }
                }
            }
        }
        return sb.toString();
    }

    private void putIntoVar(final JMeterVariables jmvars, final String name,
            final ResultSet resultSet) throws SQLException {
        if (RS_STORE_AS_OBJECT.equals(resultSetHandler)) {
            jmvars.putObject(name, resultSet);
        } else if (RS_COUNT_RECORDS.equals(resultSetHandler)) {
            jmvars.put(name, resultSet.toString() + " " + countRows(resultSet)
                    + " rows");
        } else {
            jmvars.put(name, resultSet.toString());
        }
    }

    private void putIntoVar(final JMeterVariables jmvars, final String name,
            final Clob clob) throws SQLException {
        try {
            if (clob.length() > MAX_RETAIN_SIZE) {
                try (Reader reader = clob.getCharacterStream(0,MAX_RETAIN_SIZE)) {
                    jmvars.put(
                            name,
                            IOUtils.toString(reader)
                            + "<result cut off, it is too big>");
                }
            } else {
                try (Reader reader = clob.getCharacterStream()) {
                    jmvars.put(name, IOUtils.toString(reader));
                }
            }
        } catch (IOException e) {
            log.warn("Could not read CLOB into {}", name, e);
        }
    }

    private void putIntoVar(final JMeterVariables jmvars, final String name,
            final Blob blob) throws SQLException {
        if (RS_STORE_AS_OBJECT.equals(resultSetHandler)) {
            try {
                long length = Math.max(blob.length(), MAX_RETAIN_SIZE);
                jmvars.putObject(name,
                        IOUtils.toByteArray(blob.getBinaryStream(0, length)));
            } catch (IOException e) {
                log.warn("Could not read BLOB into {} as object.", name, e);
            }
        } else if (RS_COUNT_RECORDS.equals(resultSetHandler)) {
            jmvars.put(name, blob.length() + " bytes");
        } else {
            try {
                long length = Math.max(blob.length(), MAX_RETAIN_SIZE);
                try (InputStream is = blob.getBinaryStream(0, length)) {
                    jmvars.put(name, IOUtils.toString(is, ENCODING));
                }
            } catch (IOException e) {
                log.warn("Can't convert BLOB to String using {}", ENCODING, e);
            }
        }
    }

    /**
     * Count rows in result set
     * @param resultSet {@link ResultSet}
     * @return number of rows in resultSet
     * @throws SQLException
     */
    private int countRows(ResultSet resultSet) throws SQLException {
        int resultSetMaxRows = getIntegerResultSetMaxRows();
        if (resultSetMaxRows >= 0) {
            resultSet.absolute(resultSetMaxRows);
            if (!resultSet.isAfterLast()) {
                return resultSet.getRow();
            }
        }
        return resultSet.last() ? resultSet.getRow() : 0;
    }

    private int[] setArguments(PreparedStatement pstmt) throws SQLException, IOException {
        if (getQueryArguments().trim().length()==0) {
            return new int[]{};
        }
        String[] arguments = CSVSaveService.csvSplitString(getQueryArguments(), COMMA_CHAR);
        String[] argumentsTypes = getQueryArgumentsTypes().split(COMMA);
        if (arguments.length != argumentsTypes.length) {
            throw new SQLException("number of arguments ("+arguments.length+") and number of types ("+argumentsTypes.length+") are not equal");
        }
        int[] outputs= new int[arguments.length];
        for (int i = 0; i < arguments.length; i++) {
            String argument = arguments[i];
            String argumentType = argumentsTypes[i];
            String[] arg = argumentType.split(" ");
            String inputOutput="";
            if (arg.length > 1) {
                argumentType = arg[1];
                inputOutput=arg[0];
            }
            int targetSqlType = getJdbcType(argumentType);
            try {
                if (!OUT.equalsIgnoreCase(inputOutput)){
                    if (argument.equals(NULL_MARKER)){
                        pstmt.setNull(i+1, targetSqlType);
                    } else {
                        setArgument(pstmt, argument, targetSqlType, i+1);
                    }
                }
                if (OUT.equalsIgnoreCase(inputOutput)||INOUT.equalsIgnoreCase(inputOutput)) {
                    CallableStatement cs = (CallableStatement) pstmt;
                    cs.registerOutParameter(i+1, targetSqlType);
                    outputs[i]=targetSqlType;
                } else {
                    outputs[i]=java.sql.Types.NULL; // can't have an output parameter type null
                }
            } catch (NullPointerException e) { // thrown by Derby JDBC (at least) if there are no "?" markers in statement
                throw new SQLException("Could not set argument no: "+(i+1)+" - missing parameter marker?", e);
            }
        }
        return outputs;
    }

    private void setArgument(PreparedStatement pstmt, String argument, int targetSqlType, int index) throws SQLException {
        switch (targetSqlType) {
        case Types.INTEGER:
            pstmt.setInt(index, Integer.parseInt(argument));
            break;
        case Types.DECIMAL:
        case Types.NUMERIC:
            pstmt.setBigDecimal(index, new BigDecimal(argument));
            break;
        case Types.DOUBLE:
        case Types.FLOAT:
            pstmt.setDouble(index, Double.parseDouble(argument));
            break;
        case Types.CHAR:
        case Types.LONGVARCHAR:
        case Types.VARCHAR:
            pstmt.setString(index, argument);
            break;
        case Types.BIT:
        case Types.BOOLEAN:
            pstmt.setBoolean(index, Boolean.parseBoolean(argument));
            break;
        case Types.BIGINT:
            pstmt.setLong(index, Long.parseLong(argument));
            break;
        case Types.DATE:
            pstmt.setDate(index, Date.valueOf(argument));
            break;
        case Types.REAL:
            pstmt.setFloat(index, Float.parseFloat(argument));
            break;
        case Types.TINYINT:
            pstmt.setByte(index, Byte.parseByte(argument));
            break;
        case Types.SMALLINT:
            pstmt.setShort(index, Short.parseShort(argument));
            break;
        case Types.TIMESTAMP:
            pstmt.setTimestamp(index, Timestamp.valueOf(argument));
            break;
        case Types.TIME:
            pstmt.setTime(index, Time.valueOf(argument));
            break;
        case Types.BINARY:
        case Types.VARBINARY:
        case Types.LONGVARBINARY:
            pstmt.setBytes(index, argument.getBytes(StandardCharsets.UTF_8));
            break;
        case Types.NULL:
            pstmt.setNull(index, targetSqlType);
            break;
        default:
            pstmt.setObject(index, argument, targetSqlType);
        }
    }

    private static int getJdbcType(String jdbcType) throws SQLException {
        Integer entry = mapJdbcNameToInt.get(jdbcType.toLowerCase(java.util.Locale.ENGLISH));
        if (entry == null) {
            try {
                entry = Integer.decode(jdbcType);
            } catch (NumberFormatException e) {
                throw new SQLException("Invalid data type: "+jdbcType, e);
            }
        }
        return entry;
    }

    private CallableStatement getCallableStatement(Connection conn) throws SQLException {
        return (CallableStatement) getPreparedStatement(conn,true);

    }
    private PreparedStatement getPreparedStatement(Connection conn) throws SQLException {
        return getPreparedStatement(conn,false);
    }

    private PreparedStatement getPreparedStatement(Connection conn, boolean callable) throws SQLException {
        PreparedStatement pstmt;
        if (callable) {
            pstmt = conn.prepareCall(getQuery()); // NOSONAR closed by caller
        } else {
            pstmt = conn.prepareStatement(getQuery()); // NOSONAR closed by caller
        }
        setQueryTimeout(pstmt, getIntegerQueryTimeout());
        return pstmt;
    }

    /**
     * @param stmt {@link Statement} Statement for which we want to set timeout
     * @param timeout int timeout value in seconds, if < 0 setQueryTimeout will not be called
     * @throws SQLException
     */
    private static void setQueryTimeout(Statement stmt, int timeout) throws SQLException {
        if(timeout >= 0) {
            stmt.setQueryTimeout(timeout);
        }
    }

    /**
     * Gets a Data object from a ResultSet.
     *
     * @param rs
     *            ResultSet passed in from a database query
     * @return a Data object
     * @throws java.sql.SQLException
     * @throws UnsupportedEncodingException
     */
    private String getStringFromResultSet(ResultSet rs) throws SQLException, UnsupportedEncodingException {
        ResultSetMetaData meta = rs.getMetaData();

        StringBuilder sb = new StringBuilder();

        int numColumns = meta.getColumnCount();
        for (int i = 1; i <= numColumns; i++) {
            sb.append(meta.getColumnLabel(i));
            if (i==numColumns){
                sb.append('\n');
            } else {
                sb.append('\t');
            }
        }

        JMeterVariables jmvars = getThreadContext().getVariables();
        String[] varNames = getVariableNames().split(COMMA);
        String currentResultVariable = getResultVariable().trim();
        List<Map<String, Object> > results = null;
        if(!currentResultVariable.isEmpty()) {
            results = new ArrayList<>();
            jmvars.putObject(currentResultVariable, results);
        }
        int currentIterationIndex = 0;
        int resultSetMaxRows = getIntegerResultSetMaxRows();
        if (resultSetMaxRows < 0) {
            while (rs.next()) {
                currentIterationIndex = processRow(rs, meta, sb, numColumns, jmvars, varNames, results, currentIterationIndex);
            }
        } else {
            while (currentIterationIndex < resultSetMaxRows && rs.next()) {
                currentIterationIndex = processRow(rs, meta, sb, numColumns, jmvars, varNames, results, currentIterationIndex);
            }
        }
        // Remove any additional values from previous sample
        for (String varName : varNames) {
            String name = varName.trim();
            if (name.length() > 0 && jmvars != null) {
                final String varCount = name + "_#"; // $NON-NLS-1$
                // Get the previous count
                String prevCount = jmvars.get(varCount);
                if (prevCount != null) {
                    int prev = Integer.parseInt(prevCount);
                    for (int n = currentIterationIndex + 1; n <= prev; n++) {
                        jmvars.remove(name + UNDERSCORE + n);
                    }
                }
                jmvars.put(varCount, Integer.toString(currentIterationIndex)); // save the current count
            }
        }

        return sb.toString();
    }

    private int processRow(ResultSet rs, ResultSetMetaData meta, StringBuilder sb, int numColumns,
            JMeterVariables jmvars, String[] varNames, List<Map<String, Object>> results, int currentIterationIndex)
            throws SQLException, UnsupportedEncodingException {
        Map<String, Object> row = null;
        currentIterationIndex++;
        for (int i = 1; i <= numColumns; i++) {
            Object o = rs.getObject(i);
            if(results != null) {
                if(row == null) {
                    row = new HashMap<>(numColumns);
                    results.add(row);
                }
                row.put(meta.getColumnLabel(i), o);
            }
            if (o instanceof byte[]) {
                o = new String((byte[]) o, ENCODING);
            }
            sb.append(o);
            if (i==numColumns){
                sb.append('\n');
            } else {
                sb.append('\t');
            }
            if (i <= varNames.length) { // i starts at 1
                String name = varNames[i - 1].trim();
                if (name.length()>0){ // Save the value in the variable if present
                    jmvars.put(name+UNDERSCORE+currentIterationIndex, o == null ? null : o.toString());
                }
            }
        }
        return currentIterationIndex;
    }

    public static void close(Connection c) {
        try {
            if (c != null) {
                c.close();
            }
        } catch (SQLException e) {
            log.warn("Error closing Connection", e);
        }
    }

    public static void close(Statement s) {
        try {
            if (s != null) {
                s.close();
            }
        } catch (SQLException e) {
            log.warn("Error closing Statement {}", s, e);
        }
    }

    public static void close(ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            log.warn("Error closing ResultSet", e);
        }
    }

    /**
     * @return the integer representation queryTimeout
     */
    public int getIntegerQueryTimeout() {
        int timeout;
        if(StringUtils.isEmpty(queryTimeout)) {
            return 0;
        } else {
            try {
                timeout = Integer.parseInt(queryTimeout);
            } catch (NumberFormatException nfe) {
                timeout = 0;
            }
        }
        return timeout;
    }

    /**
     * @return the queryTimeout
     */
    public String getQueryTimeout() {
        return queryTimeout ;
    }

    /**
     * @param queryTimeout query timeout in seconds
     */
    public void setQueryTimeout(String queryTimeout) {
        this.queryTimeout = queryTimeout;
    }

    /**
     * @return the integer representation resultSetMaxRows
     */
    public int getIntegerResultSetMaxRows() {
        int maxrows;
        if(StringUtils.isEmpty(resultSetMaxRows)) {
            return -1;
        } else {
            try {
                maxrows = Integer.parseInt(resultSetMaxRows);
            } catch (NumberFormatException nfe) {
                maxrows = -1;
            }
        }
        return maxrows;
    }

    /**
     * @return the resultSetMaxRows
     */
    public String getResultSetMaxRows() {
        return resultSetMaxRows ;
    }

    /**
     * @param resultSetMaxRows max number of rows to iterate through the ResultSet
     */
    public void setResultSetMaxRows(String resultSetMaxRows) {
        this.resultSetMaxRows = resultSetMaxRows;
    }

    public String getQuery() {
        return query;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(80);
        sb.append("["); // $NON-NLS-1$
        sb.append(getQueryType());
        sb.append("] "); // $NON-NLS-1$
        sb.append(getQuery());
        sb.append("\n");
        sb.append(getQueryArguments());
        sb.append("\n");
        sb.append(getQueryArgumentsTypes());
        return sb.toString();
    }

    /**
     * @param query
     *            The query to set.
     */
    public void setQuery(String query) {
        this.query = query;
    }

    /**
     * @return Returns the dataSource.
     */
    public String getDataSource() {
        return dataSource;
    }

    /**
     * @param dataSource
     *            The dataSource to set.
     */
    public void setDataSource(String dataSource) {
        this.dataSource = dataSource;
    }

    /**
     * @return Returns the queryType.
     */
    public String getQueryType() {
        return queryType;
    }

    /**
     * @param queryType The queryType to set.
     */
    public void setQueryType(String queryType) {
        this.queryType = queryType;
    }

    public String getQueryArguments() {
        return queryArguments;
    }

    public void setQueryArguments(String queryArguments) {
        this.queryArguments = queryArguments;
    }

    public String getQueryArgumentsTypes() {
        return queryArgumentsTypes;
    }

    public void setQueryArgumentsTypes(String queryArgumentsType) {
        this.queryArgumentsTypes = queryArgumentsType;
    }

    /**
     * @return the variableNames
     */
    public String getVariableNames() {
        return variableNames;
    }

    /**
     * @param variableNames the variableNames to set
     */
    public void setVariableNames(String variableNames) {
        this.variableNames = variableNames;
    }

    /**
     * @return the resultSetHandler
     */
    public String getResultSetHandler() {
        return resultSetHandler;
    }

    /**
     * @param resultSetHandler the resultSetHandler to set
     */
    public void setResultSetHandler(String resultSetHandler) {
        this.resultSetHandler = resultSetHandler;
    }

    /**
     * @return the resultVariable
     */
    public String getResultVariable() {
        return resultVariable ;
    }

    /**
     * @param resultVariable the variable name in which results will be stored
     */
    public void setResultVariable(String resultVariable) {
        this.resultVariable = resultVariable;
    }

    /**
     * {@inheritDoc}
     * @see org.apache.jmeter.testelement.TestStateListener#testStarted()
     */
    @Override
    public void testStarted() {
        testStarted("");
    }

    /**
     * {@inheritDoc}
     * @see org.apache.jmeter.testelement.TestStateListener#testStarted(java.lang.String)
     */
    @Override
    public void testStarted(String host) {
    }

    /**
     * {@inheritDoc}
     * @see org.apache.jmeter.testelement.TestStateListener#testEnded()
     */
    @Override
    public void testEnded() {
        testEnded("");
    }

    /**
     * {@inheritDoc}
     * @see org.apache.jmeter.testelement.TestStateListener#testEnded(java.lang.String)
     */
    @Override
    public void testEnded(String host) {
    }

}


text:
package com.globant.labs.mood.resources.v1;

import com.globant.labs.mood.resources.AbstractResource;
import com.globant.labs.mood.resources.StatisticsResource;
import com.globant.labs.mood.service.StatisticsService;
import com.google.appengine.api.search.checkers.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

/**
 * @author mauro.monti (monti.mauro@gmail.com)
 */
@Component
@Path("/api/v1/stats")
public class StatisticsResourceImpl extends AbstractResource implements StatisticsResource {

    private static final Logger logger = LoggerFactory.getLogger(StatisticsResourceImpl.class);

    @Inject
    private StatisticsService statisticsService;

    @GET
    @Path("/datastore/entity")
    @Override
    public Response datastoreEntities() {
        logger.info("method=datastoreEntities()");

        return notEmptyResponse(statisticsService.datastoreEntities());
    }

    @GET
    @Path("/feedback/weekly")
    @Override
    public Response weeklyFeedback() {
        logger.info("method=weeklyFeedback()");

        return notEmptyResponse(statisticsService.weeklyFeedback());
    }

    @GET
    @Path("/campaign/{campaignId}")
    @Override
    public Response campaignStatistics(@PathParam("campaignId") final Long campaignId) {
        Preconditions.checkNotNull(campaignId, "campaignId is null");

        logger.info("method=campaignStatistics(), args=[campaignId={}]", campaignId);
        return notNullResponse(statisticsService.campaignStatistics(campaignId));
    }
}


text:
// CRulesDoc.h : interface of the CRulesDoc class
//
/////////////////////////////////////////////////////////////////////////////

#ifndef __CRULESDOC__MULBERRY__
#define __CRULESDOC__MULBERRY__

#include "CSDIDoc.h"

class CRulesDoc : public CSDIDoc
{
protected: // create from serialization only
	CRulesDoc() {}
	DECLARE_DYNCREATE(CRulesDoc)

// Attributes
public:

// Operations
public:

// Implementation
public:
	virtual ~CRulesDoc() {}

// Generated message map functions
protected:
	//{{AFX_MSG(CRulesDoc)
		// NOTE - the ClassWizard will add and remove member functions here.
		//    DO NOT EDIT what you see in these blocks of generated code !
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

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

#endif


text:
<?php

namespace wcmf\application\controller;

use wcmf\lib\config\ActionKey;
use wcmf\lib\presentation\ApplicationError;
use wcmf\lib\presentation\Controller;
use wcmf\lib\security\PermissionManager;

/**
 * PermissionController checks, gets and sets permissions.
 *
 * The controller supports the following actions:
 *
 *

 *
 __Action__ checkPermissions

 *

 * Check permissions of a set of operations for the current user.
 * | Parameter              | Description
 * |------------------------|-------------------------
 * | _in_ `operations`      | Array of resource/context/action triples in the form _resource?context?action_
 * | _out_ `result`         | Associative array with the operations as keys and boolean values indicating if permissions are given or not
 * | __Response Actions__   | |
 * | `ok`                   | In all cases
 *

 *

 *
 *

 *
 __Action__ checkPermissionsOfUser

 *

 * Check permissions of a set of operations for the given user.
 * | Parameter              | Description
 * |------------------------|-------------------------
 * | _in_ `operations`      | Array of resource/context/action triples in the form _resource?context?action_
 * | _in_ `user`            | Username to check permissions for (optional, default: the authenticated user)
 * | _out_ `result`         | Associative array with the operations as keys and boolean values indicating if permissions are given or not
 * | __Response Actions__   | |
 * | `ok`                   | In all cases
 *

 *

 *
 *

 *
 __Action__ getPermissions

 *

 * Get the permissions on an operation.
 * | Parameter             | Description
 * |-----------------------|-------------------------
 * | _in_ `operation`      | A resource/context/action triple in the form _resource?context?action_
 * | _out_ `result`        | Assoziative array with keys 'default' (boolean), 'allow', 'deny' (arrays of role names) or null, if no permissions are defined.
 *

 *

 *
 *

 *
 __Action__ setPermissions

 *

 * Set the permissions on an operation.
 * | Parameter             | Description
 * |-----------------------|-------------------------
 * | _in_ `operation`      | A resource/context/action triple in the form _resource?context?action_
 * | _in_ `permissions`    | Assoziative array with keys 'default' (boolean), 'allow', 'deny' (arrays of role names).
 *

 *

 *
 *

 *
 __Action__ createPermission

 *

 * Create/Change a permission for a role on an operation.
 * | Parameter             | Description
 * |-----------------------|-------------------------
 * | _in_ `operation`      | A resource/context/action triple in the form _resource?context?action_
 * | _in_ `role`           | The role to add.
 * | _in_ `modifier`       | _+_ or _-_ whether to allow or disallow the action for the role.
 *

 *

 *
 *

 *
 __Action__ removePermission

 *

 * Remove a role from a permission on an operation.
 * | Parameter             | Description
 * |-----------------------|-------------------------
 * | _in_ `operation`      | A resource/context/action triple in the form _resource?context?action_
 * | _in_ `role`           | The role to remove.
 *

 *

 *
 * @author ingo herwig <ingo@wemove.com>
 */
class PermissionController extends Controller {

  /**
   * @see Controller::validate()
   */
  protected function validate() {
    $request = $this->getRequest();
    $response = $this->getResponse();
    $invalidParameters = [];
    if ($request->getAction() == 'createPermission' || $request->getAction() == 'removePermission' ||
             $request->getAction() == 'getPermissions' || $request->getAction() == 'setPermissions') {
      foreach (['operation'] as $param) {
        if(!$request->hasValue($param)) {
          $invalidParameters[] = $param;
        }
      }
    }
    if ($request->getAction() == 'createPermission') {
      $permissions = $request->getValue('permissions');
      if (!isset($permissions['allow']) || !isset($permissions['deny'])) {
        $invalidParameters[] = 'permissions';
      }
    }
    if ($request->getAction() == 'createPermission') {
      $modifier = $request->getValue('modifier');
      if (!($modifier == PermissionManager::PERMISSION_MODIFIER_ALLOW ||
              $modifier == PermissionManager::PERMISSION_MODIFIER_DENY)) {
        $invalidParameters[] = 'modifier';
      }
    }

    if (sizeof($invalidParameters) > 0) {
      $response->addError(ApplicationError::get('PARAMETER_INVALID',
        ['invalidParameters' => $invalidParameters]));
      return false;
    }
    return true;
  }

  /**
   * @see Controller::doExecute()
   */
  protected function doExecute($method=null) {
    $request = $this->getRequest();
    $response = $this->getResponse();
    $permissionManager = $this->getPermissionManager();
    $action = $request->getAction();

    // process actions
    if (strpos($action, 'check') === 0) {
      $result = [];
      $operations = $request->hasValue('operations') ? $request->getValue('operations') : [];
      $user = $action == 'checkPermissionsOfUser' ? $request->getValue('user') : null;

      foreach($operations as $operation) {
        $opParts = ActionKey::parseKey($operation);
        $result[$operation] = $permissionManager->authorize($opParts['resource'], $opParts['context'], $opParts['action'],
                $user);
      }
      $response->setValue('result', $result);
    }
    else {
      $operation = $request->getValue('operation');
      $opParts = ActionKey::parseKey($operation);
      $opResource = $opParts['resource'];
      $opContext = $opParts['context'];
      $opAction = $opParts['action'];

      if ($action == 'getPermissions') {
        $result = $permissionManager->getPermissions($opResource, $opContext, $opAction);
        $response->setValue('result', $result);
      }
      elseif ($action == 'setPermissions') {
        $this->requireTransaction();
        $permissions = $request->getValue('permissions');
        $permissionManager->setPermissions($opResource, $opContext, $opAction, $permissions);
      }
      elseif ($action == 'createPermission') {
        $this->requireTransaction();
        $role = $request->getValue('role');
        $modifier = $request->getValue('modifier');
        $permissionManager->createPermission($opResource, $opContext, $opAction, $role, $modifier);
      }
      elseif ($action == 'removePermission') {
        $this->requireTransaction();
        $role = $request->getValue('role');
        $permissionManager->removePermission($opResource, $opContext, $opAction, $role);
      }
    }
    $response->setAction('ok');
  }
}
?>


text:
#ifndef ION_BASE_TESTS_BADWRITECHECKINGALLOCATOR_H_
#define ION_BASE_TESTS_BADWRITECHECKINGALLOCATOR_H_

#include <unordered_map>

#include "ion/base/allocationmanager.h"
#include "ion/base/allocator.h"

namespace ion {
namespace base {
namespace testing {

// Simple derived Allocator that enables testing for bad writes. All
// "deallocated" memory is overwritten with a special signature that is checked
// when the BadWriteCheckingAllocator is destroyed. Note that this can only
// for overruns that are within the maximum size of the instance. All
// allocations are padded to be at least 16 bytes and 16-byte aligned.
class BadWriteCheckingAllocator : public Allocator {
 public:
  static const uint8 kSignature = 0xfe;

  // Constructing a BadWriteCheckingAllocator requires a maximum size in bytes
  // and a helper Allocator to use for the actual allocations. Note that since
  // this is a fairly simple Allocator, max_size is the maximum _total_ size
  // of all allocations; deallocations do _not_ free any actual memory.
  BadWriteCheckingAllocator(size_t max_size, const AllocatorPtr& alloc) :
      max_size_(max_size),
      bytes_used_(0),
      allocation_count_(0),
      allocator_(AllocationManager::GetNonNullAllocator(alloc)),
      memory_(static_cast<uint8*>(allocator_->AllocateMemory(max_size))) {
    // Write the freed signature.
    memset(memory_, kSignature, max_size_);
    // Ensure that the memory starts at a 16-byte boundary.
    size_t memory_start = reinterpret_cast<size_t>(memory_);
    bytes_used_ = (0x10 - (memory_start & 0xf)) & 0xf;
    memory_start = reinterpret_cast<size_t>(&memory_[bytes_used_]);
    CHECK_EQ(0U, memory_start & 0xf);
  }

  ~BadWriteCheckingAllocator() override {
    if (allocation_count_)
      LOG(ERROR) << "BadWriteCheckingAllocator [" << this << "] destroyed with "
                 << allocation_count_ << "active allocations!";

    // Ensure that all memory was freed properly and contains the correct
    // signature, and that no additional memory was overwritten.
    for (size_t i = 0; i < max_size_; ++i)
      if (memory_[i] != kSignature)
        LOG(ERROR) << "Memory at offset " << i << " of " << max_size_
                   << " was overwritten!";

    // Actually free the allocated memory.
    allocator_->DeallocateMemory(memory_);
  }

 private:
  void* Allocate(size_t size) override {
    // Ensure 16-byte alignment.
    size += (0x10 - (size & 0xf)) & 0xf;
    CHECK_EQ(0U, size & 0xf);
    CHECK(bytes_used_ + size <= max_size_)
        << "BadWriteCheckingAllocator supports up to " << max_size_
        << " bytes, attempted to allocate " << (bytes_used_ + size)
        << " bytes!";
    ++allocation_count_;
    void* ptr = &memory_[bytes_used_];
    memset(ptr, 0, size);
    // Track the allocation.
    allocations_[ptr] = size;
    bytes_used_ += size;
    return ptr;
  }

  void Deallocate(void* p) override {
    if (p) {
      AllocationMap::iterator it = allocations_.find(p);
      if (it != allocations_.end()) {
        --allocation_count_;
        const size_t size = it->second;
        memset(p, kSignature, size);
      } else {
        LOG(ERROR) << "Pointer " << p
                   << " was not allocated by this BadWriteCheckingAllocator!";
      }
    }
  }

  // The maximum size of all allocations, in bytes.
  size_t max_size_;
  // The number of bytes used.
  size_t bytes_used_;
  // The total number of allocations made.
  size_t allocation_count_;
  // The Allocator used to make the actual memory allocations.
  base::AllocatorPtr allocator_;

  // The allocations made by this.
  typedef std::unordered_map<void*, size_t> AllocationMap;
  AllocationMap allocations_;

  // The actual allocated memory chunk.
  uint8* memory_;

  DISALLOW_COPY_AND_ASSIGN(BadWriteCheckingAllocator);
};

}  // namespace testing
}  // namespace base
}  // namespace ion

#endif  // ION_BASE_TESTS_BADWRITECHECKINGALLOCATOR_H_


text:
package alluxio.client.file.cache;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;

import alluxio.conf.AlluxioConfiguration;
import alluxio.conf.Configuration;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CacheManagerTest {
  private final AlluxioConfiguration mConf = Configuration.global();

  @Test
  public void factoryGet() throws Exception {
    CacheManager manager = CacheManager.Factory.get(mConf);
    assertEquals(manager, CacheManager.Factory.get(mConf));
  }

  @Test
  public void factoryGetConcurrently() throws Exception {
    CacheManager.Factory.clear();
    int cnt = 10;
    List<Future<CacheManager>> cacheManagersList = new ArrayList<>(cnt);
    ExecutorService executorService = Executors.newFixedThreadPool(cnt);
    for (int i = 0; i < cnt; i++) {
      cacheManagersList.add(executorService.submit(() -> {
        try {
          return CacheManager.Factory.get(mConf);
        } catch (Exception e) {
          return null;
        }
      }));
    }

    CacheManager checkedCacheManager = CacheManager.Factory.get(mConf);
    for (Future<CacheManager> f : cacheManagersList) {
      CacheManager cacheManager = f.get();
      assertNotNull(cacheManager);
      assertEquals(cacheManager, checkedCacheManager);
    }
  }

  @Test
  public void factoryCreate() throws Exception {
    CacheManagerOptions cacheManagerOptions = CacheManagerOptions.create(mConf);
    CacheManager manager =
        CacheManager.Factory.create(mConf, cacheManagerOptions,
            PageMetaStore.create(cacheManagerOptions));
    assertNotEquals(manager,
        CacheManager.Factory.create(mConf, cacheManagerOptions,
            PageMetaStore.create(cacheManagerOptions)));
  }

  @Test
  public void factoryClear() throws Exception {
    CacheManager manager = CacheManager.Factory.get(mConf);
    CacheManager.Factory.clear();
    assertNotEquals(manager, CacheManager.Factory.get(mConf));
  }
}


text:
Content curation website template
=================================

This doesn't do anything yet.

When it does you'll install it like this:

- virtualenv venv
- source venv/bin/activate
- pip install funfactory
- funfactory --python=2.7 --pkg=blog
- git clone https://github.com/bjdixon/curator.git blog

- create mysql database

- add mysql database to blog/settings/local.py

Includes:

- [django][django]
- [playdoh][gh-playdoh]
- [docs][docs]
- [south][south]
- [feedparser][feedparser]
- [django-request][django-request]
- BeautifulSoup4
- Bleach

[django]: http://www.djangoproject.com/
[gh-playdoh]: https://github.com/mozilla/playdoh
[docs]: http://playdoh.rtfd.org/
[django-request]: https://github.com/kylef/django-request
[south]: http://bitbucket.org/andrewgodwin/south/
[feedparser]: https://code.google.com/p/feedparser/

License
-------
This software is licensed under the [New BSD License][BSD]. For more
information, read the file ``LICENSE``.

[BSD]: http://creativecommons.org/licenses/BSD/


text:
<!DOCTYPE HTML>
<html lang="{{ page.lang | default: site.lang | default: en }}">
{% include head.html %}
<body>
{% include sidebar.html %}
{% include header.html %}
<embed src="https://chrisnguyenhi.github.io/resume.pdf" width="100%" height="800px" type='application/pdf'>
</body>


text:
package androidx.test.uiautomator.testapp;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class ClickTestActivity extends Activity {

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.click_test_activity);

        // Set up the long-clickable buttons.
        Button button4 = findViewById(R.id.button4);
        Button button5 = findViewById(R.id.button5);
        Button button6 = findViewById(R.id.button6);
        Button button7 = findViewById(R.id.button7);

        button4.setOnLongClickListener(new OnButtonLongClick());
        button5.setOnLongClickListener(new OnButtonLongClick());
        button6.setOnLongClickListener(new OnButtonLongClick());
        button7.setOnLongClickListener(new OnButtonLongClick());
    }

    public void onButtonClick(@NonNull View v) {
        ((Button) v).append("_clicked");
    }

    static class OnButtonLongClick implements OnLongClickListener {
        @Override
        public boolean onLongClick(View v) {
            ((Button) v).append("_long_clicked");
            return true;
        }
    }
}


text:
package cz.znj.kvr.sw.exp.java.jackson.protobuf;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.protobuf.ProtobufFactory;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;

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

public class ProtobufConversionTest
{
	private ObjectMapper		objectMapper = new ObjectMapper(new ProtobufFactory())
			.enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES);

	@Test(expectedExceptions = JsonParseException.class)
	public void                     testObject() throws IOException
	{
		cz.znj.kvr.sw.exp.java.jackson.json.TestObject o = objectMapper.readValue("{ testId: 1, name: \"hello\" }".getBytes(), cz.znj.kvr.sw.exp.java.jackson.json.TestObject.class);
		AssertJUnit.assertEquals(1, o.getTestId());
		AssertJUnit.assertEquals("hello", o.getName());
	}

	@Test(expectedExceptions = JsonParseException.class)
	public void                     testList() throws IOException
	{
		List<TestObject> list = objectMapper.readValue("[{ testId: 1, name: \"hello\" }, {testId: 2, name: \"world\" }]".getBytes(), new TypeReference<List<TestObject>>(){});
		{
			TestObject o = list.get(0);
			AssertJUnit.assertEquals(1, o.getTestId());
			AssertJUnit.assertEquals("hello", o.getName());
		}
		{
			TestObject o = list.get(1);
			AssertJUnit.assertEquals(2, o.getTestId());
			AssertJUnit.assertEquals("world", o.getName());
		}
	}

	@Test(expectedExceptions = JsonMappingException.class)
	public void			testSerialize() throws IOException
	{
		TestObject o = TestObject.builder()
				.name("Hello")
				.testId(9)
				.build();
		byte[] bytes = objectMapper.writeValueAsBytes(o);
		AssertJUnit.assertNotNull(bytes);
	}
}


text:
import * as React from 'react';
import { PrimaryLayoutRoutes } from '../../routes';
import Logo from './components/Logo';
import { Navigation } from './components/Navigation';
// import './assets/css/bootstrap-theme.css';

const PrimaryLayout: React.SFC<{}> = _props => {
  return (
    <React.Fragment>
      <Logo />
      <Navigation />
      <PrimaryLayoutRoutes />
    </React.Fragment>
  );
};

export default PrimaryLayout;


text:
package ar.edu.itba.command;

import static com.google.common.collect.Collections2.transform;

import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;

import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;

public class ParsedCommand {

	private final Map<CommandParam, String> _errorMessages = Maps.newHashMap();
	private final Map<String, String> _values = Maps.newHashMap();

	ParsedCommand(Map<CommandParam, String> errorMessages, Map<String, String> values) {
		_errorMessages.putAll(errorMessages);
		_values.putAll(values);
	}

	public boolean hasErrors() {
		return !_errorMessages.isEmpty();
	}

	public String getErrorString() {
		Preconditions.checkState(!_errorMessages.isEmpty());
		return StringUtils.join(transform(_errorMessages.entrySet(), getErrorMessage()), "\n");
	}

	public String param(String key) {
		return Preconditions.checkNotNull(paramOpt(key));
	}

	public String paramOpt(String key) {
		return _values.get(key);
	}

	public boolean hasParam(String key) {
		return paramOpt(key) != null;
	}

	private Function<Entry<CommandParam, String>, String> getErrorMessage() {
		return new Function<Map.Entry<CommandParam, String>, String>() {
			@Override
			public String apply(Entry<CommandParam, String> input) {
				return "[ERROR] " + input.getKey().getKey() + ": " + input.getValue();
			}
		};
	}
}


text:
<?php

$GLOBALS['botname'] = 'testbot';

$testdir = dirname(__FILE__);

require $testdir . DIRECTORY_SEPARATOR . 'bootstrap.php';

if ($argc == 1) {
    // Run all tests
    require $testdir . DIRECTORY_SEPARATOR . 'AllTests.php';
} else {
    // Run one test
    $testcase = str_replace('\\', DIRECTORY_SEPARATOR, $argv[1]) . '.php';
    require $testdir . DIRECTORY_SEPARATOR . 'unit' . DIRECTORY_SEPARATOR . $testcase;
}


text:
<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android" >

	<item android:state_pressed="true" >
         <shape android:shape="rectangle"  >
             <corners android:radius="3dip" />
             <stroke android:width="1dip" android:color="#2c2f34" />
             <gradient  android:angle="-90"  android:startColor="#090b0e" android:endColor="#363c45"  />
         </shape>
     </item>
    <item android:state_focused="true">
         <shape android:shape="rectangle"  >
             <corners android:radius="3dip" />
             <stroke android:width="1dip" android:color="#2c2f34" />
             <solid  android:color="#1d242c"/>
         </shape>
     </item>
    <item >
        <shape android:shape="rectangle"  >
             <corners android:radius="3dip" />
             <stroke android:width="1dip" android:color="#2c2f34" />
             <gradient  android:angle="-90"  android:startColor="#545c67" android:endColor="#1d242c" />
         </shape>
     </item>

</selector>


text:
import DS from 'ember-data';
import ENV from 'prep-prototype/config/environment';

export default DS.JSONAPIAdapter.extend({

  host: ENV.prepApiHost,

  urlForQuery() {
    return this.host + '/dashboards';
  },

  urlForQueryRecord() {
    return this.host + '/dashboards';
  }

});


text:
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>three.js webgl - particles</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
        <style>
            body {
                background-color: #000000;
                margin: 0px;
                overflow: hidden;
                font-family:Monospace;
                font-size:13px;
                text-align:center;
                font-weight: bold;
                text-align:center;
            }

            a {
                color:#0078ff;
            }

            #info {
                color: #fff;
                position: absolute;
                top: 0px; width: 100%;
                padding: 5px;
                z-index: 100;
            }

        </style>
    </head>
    <body>
        <script src="js/threejs.js"></script>

        <script>

            var container, stats;
            var camera, scene, renderer, particles, geometry, materials = [], parameters, i, h, color, size;
            var mouseX = 0, mouseY = 0;

            var windowHalfX = window.innerWidth / 2;
            var windowHalfY = window.innerHeight / 2;

            init();
            animate();

            function init() {

                container = document.createElement( 'div' );
                document.body.appendChild( container );

                camera = new THREE.PerspectiveCamera( 100, window.innerWidth / window.innerHeight, 1, 3000 );
                camera.position.z = 1000;

                scene = new THREE.Scene();
                scene.fog = new THREE.FogExp2( 0x000000, 0.0007 );

                geometry = new THREE.Geometry();

                for ( i = 0; i < 20000; i ++ ) {

                    var vertex = new THREE.Vector3();
                    vertex.x = Math.random() * 2000 - 1000;
                    vertex.y = Math.random() * 2000 - 1000;
                    vertex.z = Math.random() * 2000 - 1000;

                    geometry.vertices.push( vertex );

                }

                parameters = [
                    [ [1, 1, 0.5], 5 ],
                    [ [0.95, 1, 0.5], 4 ],
                    [ [0.90, 1, 0.5], 3 ],
                    [ [0.85, 1, 0.5], 2 ],
                    [ [0.80, 1, 0.5], 1 ]
                ];

                for ( i = 0; i < parameters.length; i ++ ) {

                    color = parameters[i][0];
                    size  = parameters[i][1];

                    materials[i] = new THREE.PointCloudMaterial( { size: size } );

                    particles = new THREE.PointCloud( geometry, materials[i] );

                    particles.rotation.x = Math.random() * 6;
                    particles.rotation.y = Math.random() * 6;
                    particles.rotation.z = Math.random() * 6;

                    scene.add( particles );

                }

                renderer = new THREE.WebGLRenderer();
                renderer.setPixelRatio( window.devicePixelRatio );
                renderer.setSize( window.innerWidth, window.innerHeight );
                container.appendChild( renderer.domElement );
               //

                //window.addEventListener( 'resize', onWindowResize, false );

            }

            function onWindowResize() {

                windowHalfX = window.innerWidth / 2;
                windowHalfY = window.innerHeight / 2;

                camera.aspect = window.innerWidth / window.innerHeight;
                camera.updateProjectionMatrix();

                renderer.setSize( window.innerWidth, window.innerHeight );

            }

            function animate() {

                requestAnimationFrame( animate );

                render();
                stats.update();

            }

            function render() {

                var time = Date.now() * 0.00005;

                camera.lookAt( scene.position );

                for ( i = 0; i < scene.children.length; i ++ ) {

                    var object = scene.children[ i ];

                    if ( object instanceof THREE.PointCloud ) {

                        object.rotation.y = time * ( i < 4 ? i + 1 : - ( i + 1 ) );

                    }

                }

                for ( i = 0; i < materials.length; i ++ ) {

                    color = parameters[i][0];

                    h = ( 360 * ( color[0] + time ) % 360 ) / 360;
                    materials[i].color.setHSL( h, color[1], color[2] );

                }

                renderer.render( scene, camera );

            }

        </script>
    </body>
</html>


text:
package io.gank.weixiao.component_core.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by weixiao-sm on 2017/2/21.
 */
public class DateUtils {

    public static Calendar formateDate(String date){
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
        simpleDateFormat.applyPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        Date date1 = null;
        try {
            date1 = simpleDateFormat.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        calendar.setTime(date1);
        return calendar;
    }
}


text:
const path = require('path')
const webpack = require('webpack')
const WriteFilePlugin = require('write-file-webpack-plugin')
const AutoDllPlugin = require('autodll-webpack-plugin')
const ExtractCssChunks = require('extract-css-chunks-webpack-plugin')
const statsOptions = require('./stats.config')

module.exports = {
  name: 'client',
  target: 'web',
  devtool: 'source-map',
  entry: [
    'babel-polyfill',
    'fetch-everywhere',
    'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=false&quiet=false&noInfo=false',
    'react-hot-loader/patch',
    path.resolve(__dirname, '../src/index.js'),
  ],
  output: {
    filename: '[name].js',
    chunkFilename: '[name].js',
    path: path.resolve(__dirname, '../buildClient'),
    publicPath: '/static/',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: 'babel-loader',
      },
      {
        test: /\.css$/,
        use: ExtractCssChunks.extract({
          use: {
            loader: 'css-loader',
            options: {
              modules: true,
              localIdentName: '[name]__[local]--[hash:base64:5]',
            },
          },
        }),
      },
      {
        test: /\.sol$/,
        use: ['web3-loader', 'solc-loader'],
      },
    ],
  },
  resolve: {
    extensions: ['.js', '.css'],
  },
  plugins: [
    new WriteFilePlugin(), // used so you can see what chunks are produced in dev
    new ExtractCssChunks(),
    new webpack.optimize.CommonsChunkPlugin({
      names: ['bootstrap'], // needed to put webpack bootstrap code before chunks
      filename: '[name].js',
      minChunks: Infinity,
    }),

    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('development'),
      },
    }),
    new AutoDllPlugin({
      context: path.join(__dirname, '..'),
      filename: '[name].js',
      entry: {
        vendor: [
          'react',
          'react-dom',
          'react-redux',
          'redux',
          'history/createBrowserHistory',
          'transition-group',
          'redux-first-router',
          'redux-first-router-link',
          'fetch-everywhere',
          'babel-polyfill',
          'redux-devtools-extension/logOnlyInProduction',
        ],
      },
    }),
  ],
  stats: statsOptions,
}


text:
using System;

namespace OrigoDB.Core
{

    public class Engine<TModel> : Engine, IEngine<TModel> where TModel : Model
    {
        public Engine(TModel model, EngineConfiguration config) : base(model, config) { }

        public TResult Execute<TResult>(Func<TModel, TResult> query)
        {
            return Execute(new DelegateQuery<TModel, TResult>(query));
        }

        public TResult Execute<TResult>(Query<TModel, TResult> query)
        {
            return base.Execute(query);
        }

        public void Execute(Command<TModel> command)
        {
            base.Execute(command);
        }

        public TResult Execute<TResult>(Command<TModel, TResult> command)
        {
            return (TResult) base.Execute(command);
        }
    }
}