text:
/**
 * rc.app.js
 * rc.js application-side functions
 *
 * Eric Schmidt 2014
 */

(function(win) {

    // Create rc namespace
    var rc = win.rc = win.rc || {};

    // Event handlers
    var _handlers = {};

    // The main WebSocket
    var _socket = io("http://www.rcjs.me:8000");

    // rc.initApp
    rc.initApp = function(id, callback) {
        _socket.removeAllListeners("connection-error");
        _socket.removeAllListeners("connection-success");
        _socket.on("connection-error", function(msg) {
            callback({error: msg});
        });
        _socket.on("connection-success", function(data) {
            if(data) {
                _bindListen();
                callback({success: true});
            }
        });
        _socket.emit("initialize-application", {id: id});
    };

    // rc.listen
    var _listen = function(eventType, handler) {
        if(_handlers[eventType]) {
            _handlers[eventType].push(handler);
        } else {
            _handlers[eventType] = [handler];
        }
    };

    function _bindListen() {
        _socket.on("controller-event", _handleEvent);
        rc.listen = _listen;
    }

    function _handleEvent(data) {
        if(_handlers[data._eventType]) {
            for(var i=0; i<_handlers[data._eventType].length; i++) {
                _handlers[data._eventType][i](data);
            }
        }
    }

})(window);


text:
@interface TTLauncherScrollView : UIScrollView
@end

redpajama_set_name: RedPajamaGithub


text:
#include <mrpt/vision.h>  // Precompiled headers

#include <mrpt/vision/chessboard_find_corners.h>

// Universal include for all versions of OpenCV
#include <mrpt/otherlibs/do_opencv_includes.h>
#include "checkerboard_ocamcalib_detector.h"

using namespace mrpt;
using namespace mrpt::vision;
using namespace mrpt::utils;
using namespace mrpt::math;
using namespace std;

/** Look for the corners of a chessboard in the image
  * \param cornerCoords [OUT] The pixel coordinates of all the corners.
  * \param check_size_x [IN] The number of squares, in the X direction
  * \param check_size_y [IN] The number of squares, in the Y direction
  * \param normalize_image [IN] Whether to normalize the image before detection
  * \param useScaramuzzaMethod [IN] Whether to use the alternative, more robust method by M. Rufli, D. Scaramuzza, and R. Siegwart.
  *
  * \return true on success
  */
bool mrpt::vision::findChessboardCorners(
	const mrpt::utils::CImage &in_img,
	std::vector<TPixelCoordf> 	&cornerCoords,
	unsigned int  check_size_x,
	unsigned int  check_size_y,
	bool		normalize_image,
	bool		useScaramuzzaMethod)
{
#if MRPT_HAS_OPENCV
	MRPT_START

	ASSERT_(check_size_y>0 && check_size_x>0)

	// Grayscale version:
	const CImage img( in_img, FAST_REF_OR_CONVERT_TO_GRAY );

	// Try with expanded versions of the image if it fails to detect the checkerboard:
	int corners_count;
	bool corners_found=false;

	const CvSize check_size = cvSize(check_size_x, check_size_y);

	const int CORNERS_COUNT = check_size_x * check_size_y;

	vector<CvPoint2D32f> corners_list;
	corners_count = CORNERS_COUNT;
	corners_list.resize( CORNERS_COUNT );

	cornerCoords.clear();

	int find_chess_flags = CV_CALIB_CB_ADAPTIVE_THRESH;
	if (normalize_image)
		find_chess_flags |= CV_CALIB_CB_NORMALIZE_IMAGE;

	if (!useScaramuzzaMethod)
	{
		// Standard OpenCV's function:
		corners_found = 0 != cvFindChessboardCorners(
			img.getAs<IplImage>(),
			check_size,
			&corners_list[0],
			&corners_count,
			find_chess_flags);
	}
	else
	{
		// Return: -1: errors, 0: not found, 1: found OK
		corners_found = 1 == cvFindChessboardCorners3(
			img,
			check_size,
			corners_list
			);
	}

	// Check # of corners:
	if (corners_found && corners_count!=CORNERS_COUNT)
		corners_found=false;

	if( corners_found )
	{
		// Refine corners:
		cvFindCornerSubPix(
			img.getAs<IplImage>(),
			&corners_list[0],
			corners_count,
			cvSize(5,5), 	// window
			cvSize(-1,-1),
			cvTermCriteria( CV_TERMCRIT_ITER|CV_TERMCRIT_EPS, 10, 0.01f ));

		// save the corners in the data structure:
		int y;
		unsigned int k;
		for( y = 0, k = 0; y < check_size.height; y++ )
			for( int x = 0; x < check_size.width; x++, k++ )
				cornerCoords.push_back(  TPixelCoordf( corners_list[k].x, corners_list[k].y ) );
	}

	return corners_found;

	MRPT_END
#else
	return false;
#endif
}

/** Look for the corners of one or more chessboard/checkerboards in the image.
  *  This method uses an improved version of OpenCV's cvFindChessboardCorners published
  *   by M. Rufli, D. Scaramuzza, and R. Siegwart.
  *  That method has been extended in this MRPT implementation to automatically detect a
  *   number of different checkerboards in the same image.
  *
  * \param cornerCoords [OUT] A vector of N vectors of pixel coordinates, for each of the N chessboards detected.
  * \param check_size_x [IN] The number of squares, in the X direction
  * \param check_size_y [IN] The number of squares, in the Y direction
  *
  *
  * \sa mrpt::vision::checkerBoardCameraCalibration, drawChessboardCorners
  */
void mrpt::vision::findMultipleChessboardsCorners(
	const mrpt::utils::CImage &in_img,
	std::vector<std::vector<TPixelCoordf> > 	&cornerCoords,
	unsigned int  check_size_x,
	unsigned int  check_size_y )
{
#if MRPT_HAS_OPENCV
	// Grayscale version:
	const CImage img( in_img, FAST_REF_OR_CONVERT_TO_GRAY );

	std::vector<std::vector<CvPoint2D32f> >  corners_list;

	// Return: -1: errors, 0: not found, 1: found OK
	bool corners_found = find_chessboard_corners_multiple(
		img,
		cvSize(check_size_x,check_size_y),
		corners_list);

	if( corners_found && !corners_list.empty() )
	{
		// Alloc space for output points:
		cornerCoords.resize( corners_list.size() );

		// Refine corners:
		for (size_t i=0;i<corners_list.size();i++)
		{
			ASSERT_(corners_list[i].size()==check_size_x*check_size_y)

			cvFindCornerSubPix(
				img.getAs<IplImage>(),
				&corners_list[i][0],
				check_size_x*check_size_y,
				cvSize(5,5), 	// window
				cvSize(-1,-1),
				cvTermCriteria( CV_TERMCRIT_ITER|CV_TERMCRIT_EPS, 10, 0.01f ));

			// save the corners in the data structure:
			for( unsigned int y = 0, k = 0; y < check_size_y; y++ )
				for( unsigned int x = 0; x < check_size_x; x++, k++ )
					cornerCoords[i].push_back(  TPixelCoordf( corners_list[i][k].x, corners_list[i][k].y ) );
		}
	}
	else
	{	// Not found.
		cornerCoords.clear();
		return;
	}

#endif
}


text:
class Roda
  module RodaPlugins
    # The hooks plugin adds before and after hooks to the request cycle.
    #
    #   plugin :hooks
    #
    #   before do
    #     request.redirect('/login') unless logged_in?
    #     @time = Time.now
    #   end
    #
    #   after do |res|
    #     logger.notice("Took #{Time.now - @time} seconds")
    #   end
    #
    # Note that in general, before hooks are not needed, since you can just
    # run code at the top of the route block:
    #
    #   route do |r|
    #     r.redirect('/login') unless logged_in?
    #     # ...
    #   end
    #
    # However, this code makes it easier to write after hooks, as well as
    # handle cases where before hooks are added after the route block.
    #
    # Note that the after hook is called with the rack response array
    # of status, headers, and body.  If it wants to change the response,
    # it must mutate this argument, calling <tt>response.status=</tt> inside
    # an after block will not affect the returned status.
    module Hooks
      def self.configure(app)
        app.opts[:before_hook] ||= nil
        app.opts[:after_hook] ||= nil
      end

      module ClassMethods
        # Add an after hook.  If there is already an after hook defined,
        # use a proc that instance_execs the existing after proc and
        # then instance_execs the given after proc, so that the given
        # after proc always executes after the previous one.
        def after(&block)
          opts[:after_hook] = if b = opts[:after_hook]
            proc do |res|
              instance_exec(res, &b)
              instance_exec(res, &block)
            end
          else
            block
          end
        end

        # Add a before hook.  If there is already a before hook defined,
        # use a proc that instance_execs the give before proc and
        # then instance_execs the existing before proc, so that the given
        # before proc always executes before the previous one.
        def before(&block)
          opts[:before_hook] = if b = opts[:before_hook]
            proc do
              instance_exec(&block)
              instance_exec(&b)
            end
          else
            block
          end
        end
      end

      module InstanceMethods
        # Before routing, execute the before hooks, and
        # execute the after hooks before returning.
        def call
          if b = opts[:before_hook]
            instance_exec(&b)
          end

          res = super
        ensure
          if b = opts[:after_hook]
            instance_exec(res, &b)
          end
        end
      end
    end

    register_plugin(:hooks, Hooks)
  end
end


text:
class AddTopicsNickname < ActiveRecord::Migration
  def up
    # can't start null: false with default: null, so start with default: ''
    add_column :topics, :nickname, :string, null: false, default: ''
    change_column_default :topics, :nickname, nil
    execute "update topics set nickname = case
      when title = 'Output numbers and blank lines' then 'puts'
      when title = 'Multiple outputs sharing a line' then 'print'
      when title = 'Variables' then 'vars'
      when title = 'Accepting input' then 'gets'
      when title = 'Multiple inputs' then 'gets2'
      when title = 'Copying variables' then 'copy_vars'
      when title = 'String literals vs. variables' then 'str_literals'
      when title = 'Arithmetic with input' then 'int_gets'
      when title = 'Spaces and strings' then 'spaces'
      when title = 'Array aliasing' then 'alias_array'
      when title = '`Array#map`' then 'array_map'
      when title = 'Functional programming' then 'functional'
      when title = 'Lambda and `->`' then 'lambda'
      when title = 'Demo of advanced debugger features' then 'advanced'
    end"
    add_index :topics, :nickname, unique: true

    # so that we can preserve exercise ids
    add_index :exercises, [:topic_id, :color, :rep_num], unique: true
  end
  def down
    remove_index :topics, :nickname
    remove_column :topics, :nickname
    remove_index :exercises, [:topic_id, :color, :rep_num]
  end
end


text:
package org.apache.taverna.activities.interaction.velocity;

import java.util.Map;

import org.apache.velocity.runtime.parser.node.ASTDirective;
import org.apache.velocity.runtime.visitor.BaseVisitor;

/**
 * @author alanrw
 *
 */
public class ProduceChecker extends BaseVisitor {

	@Override
	public Object visit(final ASTDirective node, final Object data) {
		@SuppressWarnings("unchecked")
		final Map<String, Integer> map = ((Map<String, Integer>) data);
		if (node.getDirectiveName().equals("produce")) {
			final String key = String.valueOf(node.jjtGetChild(0).value(
					this.context));
			if (node.jjtGetNumChildren() > 1) {
				final Integer depth = (Integer) node.jjtGetChild(1).value(
						this.context);
				map.put(key, depth);
			} else {
				map.put(key, 0);
			}
		}
		return map;
	}

}


text:
<!doctype HTML>
<html>
  <head>
    <title>jsonpath-object-transform</title>
  </head>
  <body>
    <script data-main="./example.amd.js"
            src="../bower_components/requirejs/require.js">
    </script>
  </body>
</html>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <name>Asakusa Vanilla Compiler Common Classes</name>
  <artifactId>asakusa-vanilla-compiler-common</artifactId>
  <parent>
    <artifactId>project</artifactId>
    <groupId>com.asakusafw.vanilla.compiler</groupId>
    <version>0.5.5-SNAPSHOT</version>
  </parent>

  <packaging>jar</packaging>

  <dependencies>
    <dependency>
      <groupId>com.asakusafw.lang.utils</groupId>
      <artifactId>asakusa-lang-common</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>com.asakusafw.lang.compiler</groupId>
      <artifactId>asakusa-compiler-common</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-simple</artifactId>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.hamcrest</groupId>
      <artifactId>hamcrest-library</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>


text:
/*!
 * cake-hash
 * CakePHP in Utility.Hash class like a collection manipulation. In JavaScript.
 *
 * @author tsuyoshiwada
 * @homepage https://github.com/tsuyoshiwada/cake-hash
 * @license MIT
 * @version 0.0.6
 */
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  typeof define === 'function' && define.amd ? define(factory) :
  global.CakeHash = factory();
}(this, function () { 'use strict';

  var babelHelpers = {};

  babelHelpers.typeof = function (obj) {
    return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
  };

  babelHelpers.defineProperty = function (obj, key, value) {
    if (key in obj) {
      Object.defineProperty(obj, key, {
        value: value,
        enumerable: true,
        configurable: true,
        writable: true
      });
    } else {
      obj[key] = value;
    }

    return obj;
  };

  babelHelpers.slicedToArray = (function () {
    function sliceIterator(arr, i) {
      var _arr = [];
      var _n = true;
      var _d = false;
      var _e = undefined;

      try {
        for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
          _arr.push(_s.value);

          if (i && _arr.length === i) break;
        }
      } catch (err) {
        _d = true;
        _e = err;
      } finally {
        try {
          if (!_n && _i["return"]) _i["return"]();
        } finally {
          if (_d) throw _e;
        }
      }

      return _arr;
    }

    return function (arr, i) {
      if (Array.isArray(arr)) {
        return arr;
      } else if (Symbol.iterator in Object(arr)) {
        return sliceIterator(arr, i);
      } else {
        throw new TypeError("Invalid attempt to destructure non-iterable instance");
      }
    };
  })();

  babelHelpers;
  var classTypeList = ["Boolean", "Number", "String", "Function", "Array", "Date", "RegExp", "Object", "Error", "Symbol"];
  var classTypes = {};

  classTypeList.forEach(function (name) {
    classTypes["[object " + name + "]"] = name.toLowerCase();
  });

  function getType(obj) {
    if (obj == null) {
      return obj + "";
    }
    return (typeof obj === "undefined" ? "undefined" : babelHelpers.typeof(obj)) === "object" || typeof obj === "function" ? classTypes[Object.prototype.toString.call(obj)] || "object" : typeof obj === "undefined" ? "undefined" : babelHelpers.typeof(obj);
  }

  function isArray(obj) {
    return Array.isArray(obj);
  }

  function isObject(obj) {
    return !isArray(obj) && getType(obj) === "object";
  }

  function isNumber(obj) {
    return getType(obj) === "number";
  }

  function isString(obj) {
    return getType(obj) === "string";
  }

  function isBoolean(obj) {
    return getType(obj) === "boolean";
  }

  function isCollection(obj) {
    return isArray(obj) || isObject(obj);
  }

  function isNumeric(obj) {
    var type = getType(obj);
    return (type === "number" || type === "string") && obj - parseFloat(obj) + 1 >= 0;
  }

  function isInteger(obj) {
    var type = getType(obj);
    return (type === "number" || type === "string") && /^([1-9]\d*|0)$/.test(obj);
  }

  function empty(obj) {
    if (isArray(obj)) {
      return obj.length === 0;
    } else if (isObject(obj)) {
      return Object.keys(obj).length === 0;
    } else if (isNumeric(obj)) {
      return parseFloat(obj) === 0;
    }
    return !obj;
  }

  function hasProp(obj, key) {
    return obj && obj.hasOwnProperty(key);
  }

  function clone(obj) {
    var _isArray = isArray(obj);
    var _isObject = isObject(obj);

    if (!_isArray && !_isObject) return undefined;

    var result = _isArray ? [] : {},
        key = undefined,
        val = undefined;

    for (key in obj) {
      if (!hasProp(obj, key)) continue;
      val = obj[key];
      if (isCollection(val)) val = clone(val);
      result[key] = val;
    }

    return result;
  }

  function merge(obj, source) {
    var deep = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];

    each(source, function (value, key) {
      if (deep && hasProp(obj, key) && isCollection(value)) {
        merge(obj[key], value, deep);
      } else {
        obj[key] = value;
      }
    });
    return obj;
  }

  function each(obj, iterate, context) {
    if (obj == null) return obj;

    context = context || obj;

    if (isObject(obj)) {
      for (var key in obj) {
        if (!hasProp(obj, key)) continue;
        if (iterate.call(context, obj[key], key) === false) break;
      }
    } else if (isArray(obj)) {
      var i = undefined,
          length = obj.length;
      for (i = 0; i < length; i++) {
        if (iterate.call(context, obj[i], i) === false) break;
      }
    }

    return obj;
  }

  function arrayCombine(keys, values) {
    var data = {};
    var keyCount = keys && keys.length;
    var i = 0,
        key = undefined;

    if (!isCollection(keys) || !isCollection(values) || !isNumber(keyCount) || !isNumber(values.length) || !keyCount) {
      return null;
    }

    if (keyCount !== values.length) {
      return null;
    }

    for (i = 0; i < keyCount; i++) {
      key = keys[i];
      if (isInteger(key)) {
        key = parseInt(key, 10);
      }
      data[key] = values[i];
    }

    return objToArray(data);
  }

  function arrayFill(startIndex, num, mixedVal) {
    var key = undefined,
        arr = [];
    if (!isNaN(startIndex) && !isNaN(num)) {
      for (key = 0; key < num; key++) {
        arr[key + startIndex] = mixedVal;
      }
    }
    return arr;
  }

  function objToArray(obj) {
    if (!isObject(obj)) return obj;
    if (!Object.keys(obj).every(function (key) {
      return isInteger(key);
    })) return obj;

    var array = [];
    each(obj, function (value, i) {
      array[i] = value;
    });
    return array;
  }

  function simpleOp(op, data, path) {
    var values = arguments.length <= 3 || arguments[3] === undefined ? null : arguments[3];

    var length = path.length;
    var last = length - 1;
    var list = data;

    each(path, function (key, i) {
      if ((isNumeric(key) && parseInt(key, 10) > 0 || key === "0") && key.indexOf("0") !== 0) {
        key = parseInt(key, 10);
      }
      switch (op) {
        case "insert":
          if (i === last) {
            list[key] = values;
            return false;
          }
          if (list[key] == null || !hasProp(list, key)) {
            list[key] = {};
          }
          if (!isCollection(list[key])) {
            list[key] = {};
          }
          list = list[key];
          break;

        case "remove":
          if (i === last) {
            delete list[key];
            return false;
          }
          if (list[key] == null || !hasProp(list, key)) {
            return false;
          }
          list = list[key];
          break;
      }
    });

    return data;
  }

  function trim(input) {
    return input.replace(/^\s+|\s+$/g, "");
  }

  function split(input, separator) {
    var tokens = (input + "").split(separator);
    var results = [];
    var previousValue = null;

    each(tokens, function (token) {
      if (/^.*\\$/.test(token)) {
        previousValue = token;
      } else {
        if (previousValue != null) {
          token = previousValue.slice(0, previousValue.length - 1) + separator + token;
          previousValue = null;
        }
        results.push(token);
      }
    });

    return results;
  }

  function tokenize(str) {
    var separator = arguments.length <= 1 || arguments[1] === undefined ? "," : arguments[1];
    var left = arguments.length <= 2 || arguments[2] === undefined ? "(" : arguments[2];
    var right = arguments.length <= 3 || arguments[3] === undefined ? ")" : arguments[3];

    if (empty(str)) {
      return [];
    }

    var depth = 0;
    var offset = 0;
    var buffer = "";
    var results = [];
    var length = str.length;
    var open = false;

    while (offset <= length) {
      var tmpOffset = -1;
      var offsets = [str.indexOf(separator, offset), str.indexOf(left, offset), str.indexOf(right, offset)];
      for (var i = 0; i < 3; i++) {
        if (offsets[i] !== -1 && (offsets[i] < tmpOffset || tmpOffset === -1)) {
          tmpOffset = offsets[i];
        }
      }
      // console.log(depth, buffer);
      if (tmpOffset !== -1) {
        buffer += str.substr(offset, tmpOffset - offset);
        var char = str.substr(tmpOffset, 1);
        if (!depth && char === separator && str.substr(tmpOffset - 1, 1) !== "\\") {
          results.push(buffer);
          buffer = "";
        } else {
          if (depth === 0 && /^.*\\$/.test(buffer)) {
            buffer = buffer.slice(0, buffer.length - 1) + char;
          } else {
            buffer += char;
          }
        }
        if (left !== right) {
          if (char === left) {
            depth++;
          }
          if (char === right) {
            depth--;
          }
        } else {
          if (char === left) {
            if (!open) {
              depth++;
              open = true;
            } else {
              depth--;
            }
          }
        }
        offset = ++tmpOffset;
      } else {
        results.push(buffer + str.substr(offset));
        offset = length + 1;
      }
    }

    if (empty(results) && !empty(buffer)) {
      results.push(buffer);
    }

    if (!empty(results)) {
      return results.map(function (val) {
        return trim(val);
      });
    }

    return [];
  }

  function splitConditions(token) {
    var conditions = false;
    var position = token.indexOf("[");
    if (position > -1) {
      conditions = token.substr(position);
      token = token.substr(0, position);
    }
    return [token, conditions];
  }

  function matchToken(key, token) {
    switch (token) {
      case "{n}":
        return isNumeric(key);
      case "{s}":
        return isString(key);
      case "{*}":
        return true;
      default:
        return isNumeric(token) ? key == token : key === token;
    }
  }

  function matches(data, selector) {
    var identifier = "(?:\\\\.|[\\w-_\.]|[^\\x00-\\xa0])+";
    var attributes = new RegExp("\\s*(" + identifier + ")(?:\\s*([><!]?[=]|[><])\\s*(\\/.*?\\/|" + identifier + ")|)\\s*]", "g");
    var cond = undefined;

    while (cond = attributes.exec(selector)) {
      var attr = cond[1];
      var op = cond[2] || null;
      var val = cond[3] || null;
      var hasProperty = hasProp(data, attr);

      if (empty(op) && empty(val) && !hasProperty) {
        return false;
      }

      if (!(hasProperty || data[attr] != null)) {
        return false;
      }

      var prop = hasProperty ? prop = data[attr] : undefined;
      var _isBoolean = isBoolean(prop) || prop === "true" || prop === "false";

      if (_isBoolean && isNumeric(val)) {
        prop = prop ? "1" : "0";
      } else if (_isBoolean) {
        prop = prop ? "true" : "false";
      }

      if (op === "=" && val && val[0] === "/" && val[val.length - 1] === "/") {
        prop = isString(prop) || isNumeric(prop) ? prop : "";
        if (!new RegExp(val.substr(1, val.length - 2)).test(prop)) {
          return false;
        }
      } else if (op === "=" && prop != val || op === "!=" && prop == val || op === ">" && prop <= val || op === "<" && prop >= val || op === ">=" && prop < val || op === "<=" && prop > val) {
        return false;
      }
    }

    return true;
  }

  function get(data, path) {
    var defaultValue = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];

    var parts = undefined,
        val = undefined;

    if (!isCollection(data)) {
      return defaultValue;
    }

    if (empty(data) || path == null || path === "") {
      return defaultValue;
    }

    if (isString(path) || isNumeric(path)) {
      parts = split(path, ".");
    } else {
      if (!isArray(path)) {
        return defaultValue;
      }
      parts = path;
    }

    val = isCollection(data) ? clone(data) : data;
    each(parts, function (v) {
      if (isCollection(val) && hasProp(val, v)) {
        val = val[v];
      } else {
        val = defaultValue;
        return false;
      }
    });

    return val;
  }

  function extract(data, path) {
    if (!isCollection(data)) {
      return null;
    }

    if (empty(path)) {
      return data;
    }

    if (!/[{\[]/.test(path)) {
      return get(data, path, null);
    }

    var key = "__set_item__";
    var tokens = undefined;
    var context = babelHelpers.defineProperty({}, key, [data]);

    if (path.indexOf("[") < 0) {
      tokens = split(path, ".");
    } else {
      tokens = tokenize(path, ".", "[", "]");
    }

    each(tokens, function (token) {
      var next = [];

      var _Text$splitConditions = splitConditions(token);

      var _Text$splitConditions2 = babelHelpers.slicedToArray(_Text$splitConditions, 2);

      var _token = _Text$splitConditions2[0];
      var conditions = _Text$splitConditions2[1];

      each(context[key], function (item) {
        each(item, function (v, k) {
          if (matchToken(k, _token)) {
            next.push(v);
          }
        });
      });

      if (conditions) {
        (function () {
          var filter = [];
          each(next, function (item) {
            if (isCollection(item) && matches(item, conditions)) {
              filter.push(item);
            }
          });
          next = filter;
        })();
      }
      context = babelHelpers.defineProperty({}, key, next);
    });

    return context[key];
  }

  function insert(data, path) {
    var value = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];

    var noTokens = path.indexOf("[") < 0;
    if (noTokens && path.indexOf(".") < 0) {
      data[path] = value;
      return data;
    }

    var tokens = undefined;
    if (noTokens) {
      tokens = path.split(".");
    } else {
      tokens = tokenize(path, ".", "[", "]");
    }

    if (noTokens && path.indexOf("{") < 0) {
      return simpleOp("insert", data, tokens, value);
    }

    var token = tokens.shift();
    var nextPath = tokens.join(".");

    var _Text$splitConditions = splitConditions(token);

    var _Text$splitConditions2 = babelHelpers.slicedToArray(_Text$splitConditions, 2);

    var _token = _Text$splitConditions2[0];
    var conditions = _Text$splitConditions2[1];

    each(data, function (v, k) {
      if (matchToken(k, _token)) {
        if (!conditions || matches(v, conditions)) {
          data[k] = nextPath ? insert(v, nextPath, value) : merge(v, value);
        }
      }
    });

    return data;
  }

  function remove(data, path) {
    var noTokens = path.indexOf("[") < 0;
    var noExpansion = path.indexOf("{") < 0;

    if (noExpansion && noTokens && path.indexOf(".") < 0) {
      delete data[path];
      return data;
    }

    var tokens = noTokens ? path.split(".") : tokenize(path, ".", "[", "]");

    if (noExpansion && noTokens) {
      return simpleOp("remove", data, tokens);
    }

    var token = tokens.shift();
    var nextPath = tokens.join(".");

    var _Text$splitConditions = splitConditions(token);

    var _Text$splitConditions2 = babelHelpers.slicedToArray(_Text$splitConditions, 2);

    var _token = _Text$splitConditions2[0];
    var conditions = _Text$splitConditions2[1];

    each(data, function (v, k) {
      var match = matchToken(k, _token);
      if (match && isCollection(v)) {
        if (conditions) {
          if (matches(v, conditions)) {
            if (nextPath) {
              data[k] = remove(v, nextPath);
            } else {
              delete data[k];
            }
          }
        } else {
          data[k] = remove(v, nextPath);
        }
        if (empty(data[k])) {
          delete data[k];
        }
      } else if (match && empty(nextPath)) {
        delete data[k];
      }
    });

    return data;
  }

  function combine(data, keyPath) {
    var valuePath = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];
    var groupPath = arguments.length <= 3 || arguments[3] === undefined ? null : arguments[3];

    if (empty(data)) {
      return [];
    }

    var keys = extract(data, keyPath);
    var vals = undefined;

    if (empty(keys)) {
      return [];
    }

    if (!empty(valuePath)) {
      vals = extract(data, valuePath);
    }
    if (empty(vals)) {
      vals = arrayFill(0, keys.length, null);
    }

    if (keys.length !== vals.length) {
      return [];
    }

    if (groupPath != null) {
      var group = extract(data, groupPath);
      if (!empty(group)) {
        var c = keys.length;
        var out = {};
        for (var i = 0; i < c; i++) {
          if (group[i] == null || !hasProp(group, i)) {
            group[i] = 0;
          }
          if (out[group[i]] == null || !hasProp(out, group[i])) {
            out[group[i]] = {};
          }
          out[group[i]][keys[i]] = vals[i];
        }
        return objToArray(out);
      }
    }

    if (empty(vals)) {
      return [];
    }

    return arrayCombine(keys, vals);
  }

  function check(data, path) {
    var results = extract(data, path);

    if (isCollection(results)) {
      return !empty(results);
    }

    return results != null;
  }

  function flatten(data) {
    var separator = arguments.length <= 1 || arguments[1] === undefined ? "." : arguments[1];

    return _flatten(data, separator);
  }

  function _flatten(input, separator) {
    var currentPath = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];

    var results = {};
    var path = null;

    if (isArray(input) && input.length === 0) {
      path = currentPath == null ? 0 : currentPath;
      results[path] = input;
      return results;
    }

    each(input, function (val, key) {
      key = (key + "").split(separator).join("\\" + separator);
      path = currentPath == null ? key : "" + currentPath + separator + key;
      if (isCollection(val)) {
        var children = _flatten(val, separator, path);
        if (Object.keys(children).length > 0) {
          results = merge(results, children);
        }
      } else if (val !== undefined) {
        results[path] = val;
      }
    });

    return objToArray(results);
  }

  function expand(data) {
    var separator = arguments.length <= 1 || arguments[1] === undefined ? "." : arguments[1];

    var results = {};

    each(data, function (value, flat) {
      var keys = split(flat, separator).reverse();
      var child = {};
      child[keys.shift()] = value;
      each(keys, function (k) {
        child = babelHelpers.defineProperty({}, k, child);
      });
      results = merge(results, child, true);
    });

    return objToArray(results);
  }

  function map(data, path, callback) {
    var values = objToArray(extract(data, path));
    return !isArray(values) ? null : values.map(callback);
  }

  function reduce(data, path, callback) {
    var values = objToArray(extract(data, path));
    return !isArray(values) ? null : values.reduce(callback);
  }

  var VERSION = "0.0.6";

  // Core
  function CakeHash() {}
  CakeHash.VERSION = VERSION;
  CakeHash.get = get;
  CakeHash.extract = extract;
  CakeHash.insert = insert;
  CakeHash.remove = remove;
  CakeHash.combine = combine;
  CakeHash.check = check;
  CakeHash.flatten = flatten;
  CakeHash.expand = expand;
  CakeHash.map = map;
  CakeHash.reduce = reduce;

  return CakeHash;

}));


text:
FROM ubuntu
MAINTAINER Eugene Petrenko <eugene.petrenko@gmail.com>

#Update packages
RUN apt-get update

# Installing base requirements from openCV build
RUN apt-get install -y g++
RUN apt-get install -y gcc
RUN apt-get install -y libc6
RUN apt-get install -y libc6-dev
RUN apt-get install -y build-essential
RUN apt-get install -y cmake
RUN apt-get install -y git
RUN apt-get install -y libgtk2.0-dev
RUN apt-get install -y pkg-config
RUN apt-get install -y libavcodec-dev
RUN apt-get install -y libavformat-dev
RUN apt-get install -y libswscale-dev
RUN apt-get install -y python-dev
RUN apt-get install -y python-numpy
RUN apt-get install -y libtbb2
RUN apt-get install -y libtbb-dev
RUN apt-get install -y libjpeg-dev
RUN apt-get install -y libpng-dev
RUN apt-get install -y libtiff-dev
RUN apt-get install -y libjasper-dev
RUN apt-get install -y libdc1394-22-dev

# tools to checkout and prepare OpenCV package
RUN apt-get install -y git-core

# LLVM
RUN apt-get install -y clang
RUN apt-get install -y llvm

# OpenCV sources
RUN mkdir -p /opencv/src
RUN git clone --depth=1 --branch 2.4.9 https://github.com/Itseez/opencv.git /opencv/src

# emscripten
RUN apt-get install -y emscripten

# cmake init for OpenCV
RUN mkdir -p /opencv/build
WORKDIR /opencv/build
RUN cmake /opencv/src


text:
namespace net {

namespace test {
class QuicConfigPeer;
}  // namespace test

class CryptoHandshakeMessage;

// Describes whether or not a given QuicTag is required or optional in the
// handshake message.
enum QuicConfigPresence {
  // This negotiable value can be absent from the handshake message. Default
  // value is selected as the negotiated value in such a case.
  PRESENCE_OPTIONAL,
  // This negotiable value is required in the handshake message otherwise the
  // Process*Hello function returns an error.
  PRESENCE_REQUIRED,
};

// Whether the CryptoHandshakeMessage is from the client or server.
enum HelloType {
  CLIENT,
  SERVER,
};

// An abstract base class that stores a value that can be sent in CHLO/SHLO
// message. These values can be OPTIONAL or REQUIRED, depending on |presence_|.
class QUIC_EXPORT_PRIVATE QuicConfigValue {
 public:
  QuicConfigValue(QuicTag tag, QuicConfigPresence presence);
  virtual ~QuicConfigValue();

  // Serialises tag name and value(s) to |out|.
  virtual void ToHandshakeMessage(CryptoHandshakeMessage* out) const = 0;

  // Selects a mutually acceptable value from those offered in |peer_hello|
  // and those defined in the subclass.
  virtual QuicErrorCode ProcessPeerHello(
      const CryptoHandshakeMessage& peer_hello,
      HelloType hello_type,
      std::string* error_details) = 0;

 protected:
  const QuicTag tag_;
  const QuicConfigPresence presence_;
};

class QUIC_EXPORT_PRIVATE QuicNegotiableValue : public QuicConfigValue {
 public:
  QuicNegotiableValue(QuicTag tag, QuicConfigPresence presence);
  ~QuicNegotiableValue() override;

  bool negotiated() const { return negotiated_; }

 protected:
  void set_negotiated(bool negotiated) { negotiated_ = negotiated; }

 private:
  bool negotiated_;
};

class QUIC_EXPORT_PRIVATE QuicNegotiableUint32 : public QuicNegotiableValue {
  // TODO(fayang): some negotiated values use uint32 as bool (e.g., silent
  // close). Consider adding a QuicNegotiableBool type.
 public:
  // Default and max values default to 0.
  QuicNegotiableUint32(QuicTag name, QuicConfigPresence presence);
  ~QuicNegotiableUint32() override;

  // Sets the maximum possible value that can be achieved after negotiation and
  // also the default values to be assumed if PRESENCE_OPTIONAL and the *HLO msg
  // doesn't contain a value corresponding to |name_|. |max| is serialised via
  // ToHandshakeMessage call if |negotiated_| is false.
  void set(uint32_t max, uint32_t default_value);

  // Returns the value negotiated if |negotiated_| is true, otherwise returns
  // default_value_ (used to set default values before negotiation finishes).
  uint32_t GetUint32() const;

  // Returns the maximum value negotiable.
  uint32_t GetMax() const;

  // Serialises |name_| and value to |out|. If |negotiated_| is true then
  // |negotiated_value_| is serialised, otherwise |max_value_| is serialised.
  void ToHandshakeMessage(CryptoHandshakeMessage* out) const override;

  // Sets |negotiated_value_| to the minimum of |max_value_| and the
  // corresponding value from |peer_hello|. If the corresponding value is
  // missing and PRESENCE_OPTIONAL then |negotiated_value_| is set to
  // |default_value_|.
  QuicErrorCode ProcessPeerHello(const CryptoHandshakeMessage& peer_hello,
                                 HelloType hello_type,
                                 std::string* error_details) override;

 private:
  uint32_t max_value_;
  uint32_t default_value_;
  uint32_t negotiated_value_;
};

// Stores uint32_t from CHLO or SHLO messages that are not negotiated.
class QUIC_EXPORT_PRIVATE QuicFixedUint32 : public QuicConfigValue {
 public:
  QuicFixedUint32(QuicTag name, QuicConfigPresence presence);
  ~QuicFixedUint32() override;

  bool HasSendValue() const;

  uint32_t GetSendValue() const;

  void SetSendValue(uint32_t value);

  bool HasReceivedValue() const;

  uint32_t GetReceivedValue() const;

  void SetReceivedValue(uint32_t value);

  // If has_send_value is true, serialises |tag_| and |send_value_| to |out|.
  void ToHandshakeMessage(CryptoHandshakeMessage* out) const override;

  // Sets |value_| to the corresponding value from |peer_hello_| if it exists.
  QuicErrorCode ProcessPeerHello(const CryptoHandshakeMessage& peer_hello,
                                 HelloType hello_type,
                                 std::string* error_details) override;

 private:
  uint32_t send_value_;
  bool has_send_value_;
  uint32_t receive_value_;
  bool has_receive_value_;
};

// Stores tag from CHLO or SHLO messages that are not negotiated.
class QUIC_EXPORT_PRIVATE QuicFixedTagVector : public QuicConfigValue {
 public:
  QuicFixedTagVector(QuicTag name, QuicConfigPresence presence);
  QuicFixedTagVector(const QuicFixedTagVector& other);
  ~QuicFixedTagVector() override;

  bool HasSendValues() const;

  QuicTagVector GetSendValues() const;

  void SetSendValues(const QuicTagVector& values);

  bool HasReceivedValues() const;

  QuicTagVector GetReceivedValues() const;

  void SetReceivedValues(const QuicTagVector& values);

  // If has_send_value is true, serialises |tag_vector_| and |send_value_| to
  // |out|.
  void ToHandshakeMessage(CryptoHandshakeMessage* out) const override;

  // Sets |receive_values_| to the corresponding value from |client_hello_| if
  // it exists.
  QuicErrorCode ProcessPeerHello(const CryptoHandshakeMessage& peer_hello,
                                 HelloType hello_type,
                                 std::string* error_details) override;

 private:
  QuicTagVector send_values_;
  bool has_send_values_;
  QuicTagVector receive_values_;
  bool has_receive_values_;
};

// Stores QuicSocketAddress from CHLO or SHLO messages that are not negotiated.
class QUIC_EXPORT_PRIVATE QuicFixedSocketAddress : public QuicConfigValue {
 public:
  QuicFixedSocketAddress(QuicTag tag, QuicConfigPresence presence);
  ~QuicFixedSocketAddress() override;

  bool HasSendValue() const;

  const QuicSocketAddress& GetSendValue() const;

  void SetSendValue(const QuicSocketAddress& value);

  bool HasReceivedValue() const;

  const QuicSocketAddress& GetReceivedValue() const;

  void SetReceivedValue(const QuicSocketAddress& value);

  void ToHandshakeMessage(CryptoHandshakeMessage* out) const override;

  QuicErrorCode ProcessPeerHello(const CryptoHandshakeMessage& peer_hello,
                                 HelloType hello_type,
                                 std::string* error_details) override;

 private:
  QuicSocketAddress send_value_;
  bool has_send_value_;
  QuicSocketAddress receive_value_;
  bool has_receive_value_;
};

// QuicConfig contains non-crypto configuration options that are negotiated in
// the crypto handshake.
class QUIC_EXPORT_PRIVATE QuicConfig {
 public:
  QuicConfig();
  QuicConfig(const QuicConfig& other);
  ~QuicConfig();

  void SetConnectionOptionsToSend(const QuicTagVector& connection_options);

  bool HasReceivedConnectionOptions() const;

  // Sets initial received connection options.  All received connection options
  // will be initialized with these fields. Initial received options may only be
  // set once per config, prior to the setting of any other options.  If options
  // have already been set (either by previous calls or via handshake), this
  // function does nothing and returns false.
  bool SetInitialReceivedConnectionOptions(const QuicTagVector& tags);

  QuicTagVector ReceivedConnectionOptions() const;

  bool HasSendConnectionOptions() const;

  QuicTagVector SendConnectionOptions() const;

  // Returns true if the client is sending or the server has received a
  // connection option.
  // TODO(ianswett): Rename to HasClientRequestedSharedOption
  bool HasClientSentConnectionOption(QuicTag tag,
                                     Perspective perspective) const;

  void SetClientConnectionOptions(
      const QuicTagVector& client_connection_options);

  // Returns true if the client has requested the specified connection option.
  // Checks the client connection options if the |perspective| is client and
  // connection options if the |perspective| is the server.
  bool HasClientRequestedIndependentOption(QuicTag tag,
                                           Perspective perspective) const;

  void SetIdleNetworkTimeout(QuicTime::Delta max_idle_network_timeout,
                             QuicTime::Delta default_idle_network_timeout);

  QuicTime::Delta IdleNetworkTimeout() const;

  void SetSilentClose(bool silent_close);

  bool SilentClose() const;

  void SetMaxStreamsPerConnection(size_t max_streams, size_t default_streams);

  uint32_t MaxStreamsPerConnection() const;

  void SetMaxIncomingDynamicStreamsToSend(
      uint32_t max_incoming_dynamic_streams);

  uint32_t GetMaxIncomingDynamicStreamsToSend();

  bool HasReceivedMaxIncomingDynamicStreams();

  uint32_t ReceivedMaxIncomingDynamicStreams();

  void set_max_time_before_crypto_handshake(
      QuicTime::Delta max_time_before_crypto_handshake) {
    max_time_before_crypto_handshake_ = max_time_before_crypto_handshake;
  }

  QuicTime::Delta max_time_before_crypto_handshake() const {
    return max_time_before_crypto_handshake_;
  }

  void set_max_idle_time_before_crypto_handshake(
      QuicTime::Delta max_idle_time_before_crypto_handshake) {
    max_idle_time_before_crypto_handshake_ =
        max_idle_time_before_crypto_handshake;
  }

  QuicTime::Delta max_idle_time_before_crypto_handshake() const {
    return max_idle_time_before_crypto_handshake_;
  }

  QuicNegotiableUint32 idle_network_timeout_seconds() const {
    return idle_network_timeout_seconds_;
  }

  void set_max_undecryptable_packets(size_t max_undecryptable_packets) {
    max_undecryptable_packets_ = max_undecryptable_packets;
  }

  size_t max_undecryptable_packets() const {
    return max_undecryptable_packets_;
  }

  bool HasSetBytesForConnectionIdToSend() const;

  // Sets the peer's connection id length, in bytes.
  void SetBytesForConnectionIdToSend(uint32_t bytes);

  bool HasReceivedBytesForConnectionId() const;

  uint32_t ReceivedBytesForConnectionId() const;

  // Sets an estimated initial round trip time in us.
  void SetInitialRoundTripTimeUsToSend(uint32_t rtt_us);

  bool HasReceivedInitialRoundTripTimeUs() const;

  uint32_t ReceivedInitialRoundTripTimeUs() const;

  bool HasInitialRoundTripTimeUsToSend() const;

  uint32_t GetInitialRoundTripTimeUsToSend() const;

  // Sets an initial stream flow control window size to transmit to the peer.
  void SetInitialStreamFlowControlWindowToSend(uint32_t window_bytes);

  uint32_t GetInitialStreamFlowControlWindowToSend() const;

  bool HasReceivedInitialStreamFlowControlWindowBytes() const;

  uint32_t ReceivedInitialStreamFlowControlWindowBytes() const;

  // Sets an initial session flow control window size to transmit to the peer.
  void SetInitialSessionFlowControlWindowToSend(uint32_t window_bytes);

  uint32_t GetInitialSessionFlowControlWindowToSend() const;

  bool HasReceivedInitialSessionFlowControlWindowBytes() const;

  uint32_t ReceivedInitialSessionFlowControlWindowBytes() const;

  // Sets socket receive buffer to transmit to the peer.
  void SetSocketReceiveBufferToSend(uint32_t window_bytes);

  bool HasReceivedSocketReceiveBuffer() const;

  uint32_t ReceivedSocketReceiveBuffer() const;

  void SetMultipathEnabled(bool multipath_enabled);

  bool MultipathEnabled() const;

  void SetDisableConnectionMigration();

  bool DisableConnectionMigration() const;

  void SetAlternateServerAddressToSend(
      const QuicSocketAddress& alternate_server_address);

  bool HasReceivedAlternateServerAddress() const;

  const QuicSocketAddress& ReceivedAlternateServerAddress() const;

  void SetForceHolBlocking();

  bool ForceHolBlocking(Perspective perspective) const;

  void SetSupportMaxHeaderListSize();

  bool SupportMaxHeaderListSize() const;

  bool negotiated() const;

  // ToHandshakeMessage serialises the settings in this object as a series of
  // tags /value pairs and adds them to |out|.
  void ToHandshakeMessage(CryptoHandshakeMessage* out) const;

  // Calls ProcessPeerHello on each negotiable parameter. On failure returns
  // the corresponding QuicErrorCode and sets detailed error in |error_details|.
  QuicErrorCode ProcessPeerHello(const CryptoHandshakeMessage& peer_hello,
                                 HelloType hello_type,
                                 std::string* error_details);

 private:
  friend class test::QuicConfigPeer;

  // SetDefaults sets the members to sensible, default values.
  void SetDefaults();

  // Configurations options that are not negotiated.
  // Maximum time the session can be alive before crypto handshake is finished.
  QuicTime::Delta max_time_before_crypto_handshake_;
  // Maximum idle time before the crypto handshake has completed.
  QuicTime::Delta max_idle_time_before_crypto_handshake_;
  // Maximum number of undecryptable packets stored before CHLO/SHLO.
  size_t max_undecryptable_packets_;

  // Connection options which affect the server side.  May also affect the
  // client side in cases when identical behavior is desirable.
  QuicFixedTagVector connection_options_;
  // Connection options which only affect the client side.
  QuicFixedTagVector client_connection_options_;
  // Idle network timeout in seconds.
  QuicNegotiableUint32 idle_network_timeout_seconds_;
  // Whether to use silent close.  Defaults to 0 (false) and is otherwise true.
  QuicNegotiableUint32 silent_close_;
  // Maximum number of streams that the connection can support.
  // TODO(rjshade): Remove when removing QUIC_VERSION_34
  QuicNegotiableUint32 max_streams_per_connection_;
  // Maximum number of incoming dynamic streams that the connection can support.
  QuicFixedUint32 max_incoming_dynamic_streams_;
  // The number of bytes required for the connection ID.
  QuicFixedUint32 bytes_for_connection_id_;
  // Initial round trip time estimate in microseconds.
  QuicFixedUint32 initial_round_trip_time_us_;

  // Initial stream flow control receive window in bytes.
  QuicFixedUint32 initial_stream_flow_control_window_bytes_;
  // Initial session flow control receive window in bytes.
  QuicFixedUint32 initial_session_flow_control_window_bytes_;

  // Socket receive buffer in bytes.
  // TODO(ianswett): Deprecate once QUIC_VERSION_34 is deprecated.
  QuicFixedUint32 socket_receive_buffer_;

  // Whether to support multipath for this connection.
  QuicNegotiableUint32 multipath_enabled_;

  // Whether tell peer not to attempt connection migration.
  QuicFixedUint32 connection_migration_disabled_;

  // An alternate server address the client could connect to.
  QuicFixedSocketAddress alternate_server_address_;

  // Force HOL blocking for measurement purposes.
  QuicFixedUint32 force_hol_blocking_;

  // Whether support HTTP/2 SETTINGS_MAX_HEADER_LIST_SIZE SETTINGS frame.
  QuicFixedUint32 support_max_header_list_size_;
};

}  // namespace net

#endif  // NET_QUIC_CORE_QUIC_CONFIG_H_


text:
package org.elasticsearch.index.get;

import org.apache.lucene.index.DocValuesType;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.IndexOptions;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.index.IndexableFieldType;
import org.apache.lucene.index.StoredFieldVisitor;
import org.apache.lucene.index.Term;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.document.DocumentField;
import org.elasticsearch.common.lucene.uid.Versions;
import org.elasticsearch.common.lucene.uid.VersionsAndSeqNoResolver.DocIdAndVersion;
import org.elasticsearch.common.metrics.CounterMetric;
import org.elasticsearch.common.metrics.MeanMetric;
import org.elasticsearch.common.util.set.Sets;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.common.xcontent.support.XContentMapValues;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.VersionType;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.engine.TranslogLeafReader;
import org.elasticsearch.index.fieldvisitor.CustomFieldsVisitor;
import org.elasticsearch.index.fieldvisitor.FieldsVisitor;
import org.elasticsearch.index.mapper.DocumentMapper;
import org.elasticsearch.index.mapper.IdFieldMapper;
import org.elasticsearch.index.mapper.Mapper;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.ParsedDocument;
import org.elasticsearch.index.mapper.RoutingFieldMapper;
import org.elasticsearch.index.mapper.SourceFieldMapper;
import org.elasticsearch.index.mapper.SourceToParse;
import org.elasticsearch.index.mapper.Uid;
import org.elasticsearch.index.shard.AbstractIndexShardComponent;
import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_PRIMARY_TERM;
import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO;

public final class ShardGetService extends AbstractIndexShardComponent {
    private final MapperService mapperService;
    private final MeanMetric existsMetric = new MeanMetric();
    private final MeanMetric missingMetric = new MeanMetric();
    private final CounterMetric currentMetric = new CounterMetric();
    private final IndexShard indexShard;

    public ShardGetService(IndexSettings indexSettings, IndexShard indexShard,
                             MapperService mapperService) {
        super(indexShard.shardId(), indexSettings);
        this.mapperService = mapperService;
        this.indexShard = indexShard;
    }

    public GetStats stats() {
        return new GetStats(existsMetric.count(), TimeUnit.NANOSECONDS.toMillis(existsMetric.sum()),
            missingMetric.count(), TimeUnit.NANOSECONDS.toMillis(missingMetric.sum()), currentMetric.count());
    }

    public GetResult get(String id, String[] gFields, boolean realtime, long version,
                            VersionType versionType, FetchSourceContext fetchSourceContext) {
        return
            get(id, gFields, realtime, version, versionType, UNASSIGNED_SEQ_NO, UNASSIGNED_PRIMARY_TERM, fetchSourceContext);
    }

    private GetResult get(String id, String[] gFields, boolean realtime, long version, VersionType versionType,
                          long ifSeqNo, long ifPrimaryTerm, FetchSourceContext fetchSourceContext) {
        currentMetric.inc();
        try {
            long now = System.nanoTime();
            GetResult getResult =
                innerGet(id, gFields, realtime, version, versionType, ifSeqNo, ifPrimaryTerm, fetchSourceContext);

            if (getResult.isExists()) {
                existsMetric.inc(System.nanoTime() - now);
            } else {
                missingMetric.inc(System.nanoTime() - now);
            }
            return getResult;
        } finally {
            currentMetric.dec();
        }
    }

    public GetResult getForUpdate(String id, long ifSeqNo, long ifPrimaryTerm) {
        return get(id, new String[]{RoutingFieldMapper.NAME}, true,
            Versions.MATCH_ANY, VersionType.INTERNAL, ifSeqNo, ifPrimaryTerm, FetchSourceContext.FETCH_SOURCE);
    }

    /**
     * Returns {@link GetResult} based on the specified {@link org.elasticsearch.index.engine.Engine.GetResult} argument.
     * This method basically loads specified fields for the associated document in the engineGetResult.
     * This method load the fields from the Lucene index and not from transaction log and therefore isn't realtime.
     *

     * Note: Call must release engine searcher associated with engineGetResult!
     */
    public GetResult get(Engine.GetResult engineGetResult, String id,
                            String[] fields, FetchSourceContext fetchSourceContext) {
        if (!engineGetResult.exists()) {
            return new GetResult(shardId.getIndexName(), id, UNASSIGNED_SEQ_NO, UNASSIGNED_PRIMARY_TERM, -1, false, null, null, null);
        }

        currentMetric.inc();
        try {
            long now = System.nanoTime();
            fetchSourceContext = normalizeFetchSourceContent(fetchSourceContext, fields);
            GetResult getResult = innerGetLoadFromStoredFields(id, fields, fetchSourceContext, engineGetResult, mapperService);
            if (getResult.isExists()) {
                existsMetric.inc(System.nanoTime() - now);
            } else {
                missingMetric.inc(System.nanoTime() - now); // This shouldn't happen...
            }
            return getResult;
        } finally {
            currentMetric.dec();
        }
    }

    /**
     * decides what needs to be done based on the request input and always returns a valid non-null FetchSourceContext
     */
    private FetchSourceContext normalizeFetchSourceContent(@Nullable FetchSourceContext context, @Nullable String[] gFields) {
        if (context != null) {
            return context;
        }
        if (gFields == null) {
            return FetchSourceContext.FETCH_SOURCE;
        }
        for (String field : gFields) {
            if (SourceFieldMapper.NAME.equals(field)) {
                return FetchSourceContext.FETCH_SOURCE;
            }
        }
        return FetchSourceContext.DO_NOT_FETCH_SOURCE;
    }

    private GetResult innerGet(String id, String[] gFields, boolean realtime, long version, VersionType versionType,
                               long ifSeqNo, long ifPrimaryTerm, FetchSourceContext fetchSourceContext) {
        fetchSourceContext = normalizeFetchSourceContent(fetchSourceContext, gFields);

        Term uidTerm = new Term(IdFieldMapper.NAME, Uid.encodeId(id));
        Engine.GetResult get = indexShard.get(new Engine.Get(realtime, realtime, id, uidTerm)
            .version(version).versionType(versionType).setIfSeqNo(ifSeqNo).setIfPrimaryTerm(ifPrimaryTerm));
        assert get.isFromTranslog() == false || realtime : "should only read from translog if realtime enabled";
        if (get.exists() == false) {
            get.close();
        }

        if (get == null || get.exists() == false) {
            return new GetResult(shardId.getIndexName(), id, UNASSIGNED_SEQ_NO, UNASSIGNED_PRIMARY_TERM, -1, false, null, null, null);
        }

        try {
            // break between having loaded it from translog (so we only have _source), and having a document to load
            return innerGetLoadFromStoredFields(id, gFields, fetchSourceContext, get, mapperService);
        } finally {
            get.close();
        }
    }

    private GetResult innerGetLoadFromStoredFields(String id, String[] storedFields, FetchSourceContext fetchSourceContext,
                                                   Engine.GetResult get, MapperService mapperService) {
        assert get.exists() : "method should only be called if document could be retrieved";

        // check first if stored fields to be loaded don't contain an object field
        DocumentMapper docMapper = mapperService.documentMapper();
        if (storedFields != null) {
            for (String field : storedFields) {
                Mapper fieldMapper = docMapper.mappers().getMapper(field);
                if (fieldMapper == null) {
                    if (docMapper.objectMappers().get(field) != null) {
                        // Only fail if we know it is a object field, missing paths / fields shouldn't fail.
                        throw new IllegalArgumentException("field [" + field + "] isn't a leaf field");
                    }
                }
            }
        }

        Map<String, DocumentField> documentFields = null;
        Map<String, DocumentField> metadataFields = null;
        BytesReference source = null;
        DocIdAndVersion docIdAndVersion = get.docIdAndVersion();
        // force fetching source if we read from translog and need to recreate stored fields
        boolean forceSourceForComputingTranslogStoredFields = get.isFromTranslog() && storedFields != null &&
                Stream.of(storedFields).anyMatch(f -> TranslogLeafReader.ALL_FIELD_NAMES.contains(f) == false);
        FieldsVisitor fieldVisitor = buildFieldsVisitors(storedFields,
            forceSourceForComputingTranslogStoredFields ? FetchSourceContext.FETCH_SOURCE : fetchSourceContext);
        if (fieldVisitor != null) {
            try {
                docIdAndVersion.reader.document(docIdAndVersion.docId, fieldVisitor);
            } catch (IOException e) {
                throw new ElasticsearchException("Failed to get id [" + id + "]", e);
            }
            source = fieldVisitor.source();

            // in case we read from translog, some extra steps are needed to make _source consistent and to load stored fields
            if (get.isFromTranslog()) {
                // Fast path: if only asked for the source or stored fields that have been already provided by TranslogLeafReader,
                // just make source consistent by reapplying source filters from mapping (possibly also nulling the source)
                if (forceSourceForComputingTranslogStoredFields == false) {
                    try {
                        source = indexShard.mapperService().documentMapper().sourceMapper().applyFilters(source, null);
                    } catch (IOException e) {
                        throw new ElasticsearchException("Failed to reapply filters for [" + id + "] after reading from translog", e);
                    }
                } else {
                    // Slow path: recreate stored fields from original source
                    assert source != null : "original source in translog must exist";
                    SourceToParse sourceToParse = new SourceToParse(shardId.getIndexName(), id, source, XContentHelper.xContentType(source),
                        fieldVisitor.routing());
                    ParsedDocument doc = indexShard.mapperService().documentMapper().parse(sourceToParse);
                    assert doc.dynamicMappingsUpdate() == null : "mapping updates should not be required on already-indexed doc";
                    // update special fields
                    doc.updateSeqID(docIdAndVersion.seqNo, docIdAndVersion.primaryTerm);
                    doc.version().setLongValue(docIdAndVersion.version);

                    // retrieve stored fields from parsed doc
                    fieldVisitor = buildFieldsVisitors(storedFields, fetchSourceContext);
                    for (IndexableField indexableField : doc.rootDoc().getFields()) {
                        IndexableFieldType fieldType = indexableField.fieldType();
                        if (fieldType.stored()) {
                            FieldInfo fieldInfo = new FieldInfo(indexableField.name(), 0, false, false, false, IndexOptions.NONE,
                                DocValuesType.NONE, -1, Collections.emptyMap(), 0, 0, 0, false);
                            StoredFieldVisitor.Status status = fieldVisitor.needsField(fieldInfo);
                            if (status == StoredFieldVisitor.Status.YES) {
                                if (indexableField.numericValue() != null) {
                                    fieldVisitor.objectField(fieldInfo, indexableField.numericValue());
                                } else if (indexableField.binaryValue() != null) {
                                    fieldVisitor.binaryField(fieldInfo, indexableField.binaryValue());
                                } else if (indexableField.stringValue() != null) {
                                    fieldVisitor.objectField(fieldInfo, indexableField.stringValue());
                                }
                            } else if (status == StoredFieldVisitor.Status.STOP) {
                                break;
                            }
                        }
                    }
                    // retrieve source (with possible transformations, e.g. source filters
                    source = fieldVisitor.source();
                }
            }

            // put stored fields into result objects
            if (!fieldVisitor.fields().isEmpty()) {
                fieldVisitor.postProcess(mapperService);
                documentFields = new HashMap<>();
                metadataFields = new HashMap<>();
                for (Map.Entry<String, List<Object>> entry : fieldVisitor.fields().entrySet()) {
                    if (mapperService.isMetadataField(entry.getKey())) {
                        metadataFields.put(entry.getKey(), new DocumentField(entry.getKey(), entry.getValue()));
                    } else {
                        documentFields.put(entry.getKey(), new DocumentField(entry.getKey(), entry.getValue()));
                    }
                }
            }
        }

        if (source != null) {
            // apply request-level source filtering
            if (fetchSourceContext.fetchSource() == false) {
                source = null;
            } else if (fetchSourceContext.includes().length > 0 || fetchSourceContext.excludes().length > 0) {
                Map<String, Object> sourceAsMap;
                // TODO: The source might be parsed and available in the sourceLookup but that one uses unordered maps so different.
                //  Do we care?
                Tuple<XContentType, Map<String, Object>> typeMapTuple = XContentHelper.convertToMap(source, true);
                XContentType sourceContentType = typeMapTuple.v1();
                sourceAsMap = typeMapTuple.v2();
                sourceAsMap = XContentMapValues.filter(sourceAsMap, fetchSourceContext.includes(), fetchSourceContext.excludes());
                try {
                    source = BytesReference.bytes(XContentFactory.contentBuilder(sourceContentType).map(sourceAsMap));
                } catch (IOException e) {
                    throw new ElasticsearchException("Failed to get id [" + id + "] with includes/excludes set", e);
                }
            }
        }

        return new GetResult(shardId.getIndexName(), id, get.docIdAndVersion().seqNo, get.docIdAndVersion().primaryTerm,
            get.version(), get.exists(), source, documentFields, metadataFields);
    }

    private static FieldsVisitor buildFieldsVisitors(String[] fields, FetchSourceContext fetchSourceContext) {
        if (fields == null || fields.length == 0) {
            return fetchSourceContext.fetchSource() ? new FieldsVisitor(true) : null;
        }

        return new CustomFieldsVisitor(Sets.newHashSet(fields), fetchSourceContext.fetchSource());
    }
}


text:
package com.thoughtworks.xstream.io.xml;

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

import com.thoughtworks.xstream.converters.reflection.ObjectAccessException;
import com.thoughtworks.xstream.io.naming.NameCoder;

/**
 * Encode and decode tag and attribute names in XML drivers.
 *

 * This NameCoder is designed to ensure the correct encoding and decoding of names used for Java types and fields to XML
 * tags and attribute names.
 *

 *

 * The default replacements are:
 *

 *

 *
$ (dollar) chars are replaced with _- (underscore dash) string.

 *
_ (underscore) chars are replaced with __ (double underscore) string.

 *
other characters that are invalid in XML names are encoded with _.XXXX (underscore dot followed by hex
 * representation of character).

 *

 *
 * @author Jörg Schaible
 * @author Mauro Talevi
 * @author Tatu Saloranta
 * @author Michael Schnell
 * @see XML 1.0 name definition
 * @see XML 1.1 name definition
 * @see Java identifier definition
 * @since 1.4
 */
public class XmlFriendlyNameCoder implements NameCoder, Cloneable {
    private static final IntPair[] XML_NAME_START_CHAR_BOUNDS;
    private static final IntPair[] XML_NAME_CHAR_EXTRA_BOUNDS;
    static {
        class IntPairList extends ArrayList<IntPair> {
            private static final long serialVersionUID = 20151010L;

            void add(final int min, final int max) {
                super.add(new IntPair(min, max));
            }

            void add(final char cp) {
                super.add(new IntPair(cp, cp));
            }
        }

        // legal characters in XML names according to
        // http://www.w3.org/TR/REC-xml/#NT-Name and
        // http://www.w3.org/TR/xml11/#NT-Name
        final IntPairList list = new IntPairList();

        list.add(':');
        list.add('A', 'Z');
        list.add('a', 'z');
        list.add('_');

        list.add(0xC0, 0xD6);
        list.add(0xD8, 0xF6);
        list.add(0xF8, 0x2FF);
        list.add(0x370, 0x37D);
        list.add(0x37F, 0x1FFF);
        list.add(0x200C, 0x200D);
        list.add(0x2070, 0x218F);
        list.add(0x2C00, 0x2FEF);
        list.add(0x3001, 0xD7FF);
        list.add(0xF900, 0xFDCF);
        list.add(0xFDF0, 0xFFFD);
        list.add(0x10000, 0xEFFFF);
        XML_NAME_START_CHAR_BOUNDS = list.toArray(new IntPair[list.size()]);

        list.clear();
        list.add('-');
        list.add('.');
        list.add('0', '9');
        list.add('\u00b7');
        list.add(0x0300, 0x036F);
        list.add(0x203F, 0x2040);
        XML_NAME_CHAR_EXTRA_BOUNDS = list.toArray(new IntPair[list.size()]);
    }

    private final String dollarReplacement;
    private final String escapeCharReplacement;
    private transient Map<String, String> escapeCache;
    private transient Map<String, String> unescapeCache;
    private final String hexPrefix;

    /**
     * Construct a new XmlFriendlyNameCoder.
     *
     * @since 1.4
     */
    public XmlFriendlyNameCoder() {
        this("_-", "__");
    }

    /**
     * Construct a new XmlFriendlyNameCoder with custom replacement strings for dollar and the escape character.
     *
     * @param dollarReplacement
     * @param escapeCharReplacement
     * @since 1.4
     */
    public XmlFriendlyNameCoder(final String dollarReplacement, final String escapeCharReplacement) {
        this(dollarReplacement, escapeCharReplacement, "_.");
    }

    /**
     * Construct a new XmlFriendlyNameCoder with custom replacement strings for dollar, the escape character and the
     * prefix for hexadecimal encoding of invalid characters in XML names.
     *
     * @param dollarReplacement
     * @param escapeCharReplacement
     * @since 1.4
     */
    public XmlFriendlyNameCoder(
            final String dollarReplacement, final String escapeCharReplacement, final String hexPrefix) {
        this.dollarReplacement = dollarReplacement;
        this.escapeCharReplacement = escapeCharReplacement;
        this.hexPrefix = hexPrefix;
        readResolve();
    }

    @Override
    public String decodeAttribute(final String attributeName) {
        return decodeName(attributeName);
    }

    @Override
    public String decodeNode(final String elementName) {
        return decodeName(elementName);
    }

    @Override
    public String encodeAttribute(final String name) {
        return encodeName(name);
    }

    @Override
    public String encodeNode(final String name) {
        return encodeName(name);
    }

    private String encodeName(final String name) {
        String s = escapeCache.get(name);
        if (s == null) {
            final int length = name.length();

            // First, fast (common) case: nothing to escape
            int i = 0;

            for (; i < length; i++) {
                final char c = name.charAt(i);
                if (c == '$' || c == '_' || c <= 27 || c >= 127) {
                    break;
                }
            }

            if (i == length) {
                return name;
            }

            // Otherwise full processing
            final StringBuffer result = new StringBuffer(length + 8);

            // We know first N chars are safe
            if (i > 0) {
                result.append(name.substring(0, i));
            }

            for (; i < length; i++) {
                final char c = name.charAt(i);
                if (c == '$') {
                    result.append(dollarReplacement);
                } else if (c == '_') {
                    result.append(escapeCharReplacement);
                } else if (i == 0 && !isXmlNameStartChar(c) || i > 0 && !isXmlNameChar(c)) {
                    result.append(hexPrefix);
                    if (c < 16) {
                        result.append("000");
                    } else if (c < 256) {
                        result.append("00");
                    } else if (c < 4096) {
                        result.append("0");
                    }
                    result.append(Integer.toHexString(c));
                } else {
                    result.append(c);
                }
            }
            s = result.toString();
            escapeCache.put(name, s);
        }
        return s;
    }

    private String decodeName(final String name) {
        String s = unescapeCache.get(name);
        if (s == null) {
            final char dollarReplacementFirstChar = dollarReplacement.charAt(0);
            final char escapeReplacementFirstChar = escapeCharReplacement.charAt(0);
            final char hexPrefixFirstChar = hexPrefix.charAt(0);
            final int length = name.length();

            // First, fast (common) case: nothing to decode
            int i = 0;

            for (; i < length; i++) {
                final char c = name.charAt(i);
                // We'll do a quick check for potential match
                if (c == dollarReplacementFirstChar || c == escapeReplacementFirstChar || c == hexPrefixFirstChar) {
                    // and if it might be a match, just quit, will check later on
                    break;
                }
            }

            if (i == length) {
                return name;
            }

            // Otherwise full processing
            final StringBuffer result = new StringBuffer(length + 8);

            // We know first N chars are safe
            if (i > 0) {
                result.append(name.substring(0, i));
            }

            for (; i < length; i++) {
                char c = name.charAt(i);
                if (c == dollarReplacementFirstChar && name.startsWith(dollarReplacement, i)) {
                    i += dollarReplacement.length() - 1;
                    result.append('$');
                } else if (c == hexPrefixFirstChar && name.startsWith(hexPrefix, i)) {
                    i += hexPrefix.length();
                    c = (char)Integer.parseInt(name.substring(i, i + 4), 16);
                    i += 3;
                    result.append(c);
                } else if (c == escapeReplacementFirstChar && name.startsWith(escapeCharReplacement, i)) {
                    i += escapeCharReplacement.length() - 1;
                    result.append('_');
                } else {
                    result.append(c);
                }
            }

            s = result.toString();
            unescapeCache.put(name, s);
        }
        return s;
    }

    @Override
    public Object clone() {
        try {
            final XmlFriendlyNameCoder coder = (XmlFriendlyNameCoder)super.clone();
            coder.readResolve();
            return coder;

        } catch (final CloneNotSupportedException e) {
            throw new ObjectAccessException("Cannot clone XmlFriendlyNameCoder", e);
        }
    }

    private Object readResolve() {
        escapeCache = createCacheMap();
        unescapeCache = createCacheMap();
        return this;
    }

    protected Map<String, String> createCacheMap() {
        return new HashMap<>();
    }

    private static class IntPair {
        int min;
        int max;

        public IntPair(final int min, final int max) {
            this.min = min;
            this.max = max;
        }
    }

    private static boolean isXmlNameStartChar(final int cp) {
        return isInNameCharBounds(cp, XML_NAME_START_CHAR_BOUNDS);
    }

    private static boolean isXmlNameChar(final int cp) {
        if (isXmlNameStartChar(cp)) {
            return true;
        }
        return isInNameCharBounds(cp, XML_NAME_CHAR_EXTRA_BOUNDS);
    }

    private static boolean isInNameCharBounds(final int cp, final IntPair[] nameCharBounds) {
        for (final IntPair p : nameCharBounds) {
            if (cp >= p.min && cp <= p.max) {
                return true;
            }
        }
        return false;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<workingSetManager>
<workingSet aggregate="true" factoryID="org.eclipse.ui.internal.WorkingSetFactory" id="1604022982728_0" label="Window Working Set" name="Aggregate for window 1604022982727"/>
<workingSet aggregate="true" factoryID="org.eclipse.ui.internal.WorkingSetFactory" id="1605229727116_1" label="Window Working Set" name="Aggregate for window 1605229727116"/>
</workingSetManager>


text:
#pragma once
#include <aws/comprehend/Comprehend_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace Comprehend
{
namespace Model
{
  enum class DocumentReadFeatureTypes
  {
    NOT_SET,
    TABLES,
    FORMS
  };

namespace DocumentReadFeatureTypesMapper
{
AWS_COMPREHEND_API DocumentReadFeatureTypes GetDocumentReadFeatureTypesForName(const Aws::String& name);

AWS_COMPREHEND_API Aws::String GetNameForDocumentReadFeatureTypes(DocumentReadFeatureTypes value);
} // namespace DocumentReadFeatureTypesMapper
} // namespace Model
} // namespace Comprehend
} // namespace Aws


text:
<?php

namespace XssBadWebApp\Application;

use \XssBadWebApp\Utilities\Request;
use \XssBadWebApp\Utilities\Session;
use \XssBadWebApp\Models\User as UserModel;

class Application {

    protected $request = null;
    protected $session = null;

    public function __construct() {
        $this->request = new Request($_GET, $_POST, $_SERVER);
        $this->session = new Session();
    }

    public function setup() {
        if (!$this->session->has('user')) {
            $this->session->set('user', new UserModel());
        }
    }

    public function run() {
        $controller = $this->findController();
        $view = $controller->dispatch();
        $view->render();
    }

    protected function findController() {
        $controller = $this->request->get('controller', 'GuestBook');
        $className = '\XssBadWebApp\Controllers\\' . $controller;
        if (class_exists($className)) {
            return new $className($this->request, $this->session);
        }
        return new \XssBadWebApp\Controllers\GuestBook($this->request, $this->session);
    }

}


text:
<?php

App::uses('AppHelper', 'View/Helper');

class AssetsAdminHelper extends AppHelper {

	public $helpers = array(
		'Html',
	);

	public function beforeRender($viewFile) {
		if (empty($this->request->params['admin'])) {
			return;
		}

		if ($this->_View->theme === 'AdminExtras') {
			$this->Html->css(array(
				'bootstrap-editable',
			), array(
				'inline' => false,
			));
			$this->Html->script(array(
				'bootstrap-editable.min',
			), array(
				'block' => 'scriptBottom',
			));
		}
	}

}


text:
namespace internal {
class PermissionMenuButton;
}

namespace views {
class ImageView;
class MenuRunner;
}

// A custom view for selecting a permission setting for the given permission
// |type|.
class PermissionSelectorView : public views::View,
                               public PermissionMenuModel::Delegate {
 public:
  PermissionSelectorView(const GURL& url,
                         ContentSettingsType type,
                         ContentSetting default_setting,
                         ContentSetting current_setting,
                         content_settings::SettingSource source);

  void AddObserver(PermissionSelectorViewObserver* observer);

  // Returns the selected setting.
  ContentSetting current_setting() const { return current_setting_; }

  // Returns the permission type.
  ContentSettingsType type() const { return type_; }

 protected:
  // Overridden from views::View.
  virtual void ChildPreferredSizeChanged(View* child) OVERRIDE;

 private:
  virtual ~PermissionSelectorView();

  // Overridden from PermissionMenuModel::Delegate.
  virtual void ExecuteCommand(int command_id) OVERRIDE;
  virtual bool IsCommandIdChecked(int command_id) OVERRIDE;

  views::ImageView* icon_;  // Owned by the views hierachy.
  internal::PermissionMenuButton* menu_button_;  // Owned by the views hierachy.
  scoped_ptr<PermissionMenuModel> menu_button_model_;

  // The site permission (the |ContentSettingsType|) for which the menu model
  // provides settings.
  ContentSettingsType type_;

  // The global default setting for the permission |type_|.
  ContentSetting default_setting_;

  // The currently active setting for the permission |type_|.
  ContentSetting current_setting_;

  ObserverList<PermissionSelectorViewObserver, false> observer_list_;

  DISALLOW_COPY_AND_ASSIGN(PermissionSelectorView);
};

#endif  // CHROME_BROWSER_UI_VIEWS_WEBSITE_SETTINGS_PERMISSION_SELECTOR_VIEW_H_


text:
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;

namespace OpenDis.Enumerations.Entity.Management
{
    /// <summary>
    /// Enumeration values for AggregateState (eman.aggregate.state, Aggregate State,
    /// section 11.1.1)
    /// The enumeration values are generated from the SISO DIS XML EBV document (R35), which was
    /// obtained from http://discussions.sisostds.org/default.asp?action=10&fd=31
    /// </summary>
    [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
    [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
    [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
    [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
    [Serializable]
    public enum AggregateState : byte
    {
        /// <summary>
        /// Other.
        /// </summary>
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
        [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
        [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
        [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
        [Description("Other.")]
        Other = 0,

        /// <summary>
        /// Aggregated.
        /// </summary>
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
        [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
        [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
        [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
        [Description("Aggregated.")]
        Aggregated = 1,

        /// <summary>
        /// Disaggregated.
        /// </summary>
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
        [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
        [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
        [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
        [Description("Disaggregated.")]
        Disaggregated = 2,

        /// <summary>
        /// Fully disaggregated.
        /// </summary>
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
        [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
        [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
        [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
        [Description("Fully disaggregated.")]
        FullyDisaggregated = 3,

        /// <summary>
        /// Pseudo-disaggregated.
        /// </summary>
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
        [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
        [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
        [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
        [Description("Pseudo-disaggregated.")]
        PseudoDisaggregated = 4,

        /// <summary>
        /// Partially-disaggregated.
        /// </summary>
        [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
        [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
        [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
        [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
        [Description("Partially-disaggregated.")]
        PartiallyDisaggregated = 5
    }
}


text:
// -----------------------------------------------------------------------
//  <copyright file="HttpRequestException.cs" company="Binary Overdrive">
//      Copyright (c) Binary Overdrive.
//  </copyright>
//  <project>BotSuite.Net</project>
//  <purpose>Framework for creating automation applications.</purpose>
//  <homepage>https://bitbucket.org/KarillEndusa/botsuite.net</homepage>
//  <license>https://bitbucket.org/KarillEndusa/botsuite.net/wiki/license</license>
// -----------------------------------------------------------------------

namespace BotSuite.Net
{
	using System;
	using System.Runtime.Serialization;

	/// <summary>
	///     Exception class for wrapping exceptions thrown by one of the request methods (POST/GET)
	/// </summary>
	[Serializable]
	public class HttpRequestException : Exception
	{
		/// <summary>
		///     Initializes a new instance of the <see cref="HttpRequestException" /> class
		/// </summary>
		public HttpRequestException()
		{
		}

		/// <summary>
		///     Initializes a new instance of the <see cref="HttpRequestException" /> class
		/// </summary>
		/// <param name="message">
		///     the message of the exception
		/// </param>
		public HttpRequestException(string message)
			: base(message)
		{
		}

		/// <summary>
		///     Initializes a new instance of the <see cref="HttpRequestException" /> class
		/// </summary>
		/// <param name="message">
		///     the message of the exception
		/// </param>
		/// <param name="inner">
		///     the inner exception
		/// </param>
		public HttpRequestException(string message, Exception inner)
			: base(message, inner)
		{
		}

		/// <summary>
		///     Initializes a new instance of the <see cref="HttpRequestException" /> class
		/// </summary>
		/// <param name="info">
		///     an instance of the SerializationInfo class
		/// </param>
		/// <param name="context">
		///     an instance of the StreamingContext class
		/// </param>
		protected HttpRequestException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Copyright 2013 Cloudera Inc.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License. -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.kitesdk</groupId>
    <artifactId>kite-morphlines</artifactId>
    <version>1.1.1-SNAPSHOT</version>
    <relativePath>../pom.xml</relativePath>
  </parent>

  <artifactId>kite-morphlines-all-except-tika</artifactId>
  <name>Kite Morphlines Dependency Aggregator (Excluding Tika)</name>
  <packaging>pom</packaging>

  <dependencies>
      <dependency>
        <groupId>org.kitesdk</groupId>
        <artifactId>kite-morphlines-core</artifactId>
      </dependency>
      <dependency>
        <groupId>org.kitesdk</groupId>
        <artifactId>kite-morphlines-avro</artifactId>
      </dependency>
      <dependency>
        <groupId>org.kitesdk</groupId>
        <artifactId>kite-morphlines-json</artifactId>
      </dependency>
      <dependency>
        <groupId>org.kitesdk</groupId>
        <artifactId>kite-morphlines-saxon</artifactId>
      </dependency>
      <dependency>
        <groupId>org.kitesdk</groupId>
        <artifactId>kite-morphlines-hadoop-core</artifactId>
      </dependency>
      <dependency>
        <groupId>org.kitesdk</groupId>
        <artifactId>kite-morphlines-hadoop-parquet-avro</artifactId>
      </dependency>
      <dependency>
        <groupId>org.kitesdk</groupId>
        <artifactId>kite-morphlines-hadoop-sequencefile</artifactId>
      </dependency>
      <dependency>
        <groupId>org.kitesdk</groupId>
        <artifactId>kite-morphlines-hadoop-rcfile</artifactId>
      </dependency>
      <dependency>
        <groupId>org.kitesdk</groupId>
        <artifactId>kite-morphlines-solr-core</artifactId>
      </dependency>
      <dependency>
        <groupId>org.kitesdk</groupId>
        <artifactId>kite-morphlines-twitter</artifactId>
      </dependency>
      <dependency>
        <groupId>org.kitesdk</groupId>
        <artifactId>kite-morphlines-maxmind</artifactId>
      </dependency>
      <dependency>
        <groupId>org.kitesdk</groupId>
        <artifactId>kite-morphlines-metrics-servlets</artifactId>
      </dependency>
      <dependency>
        <groupId>org.kitesdk</groupId>
        <artifactId>kite-morphlines-useragent</artifactId>
      </dependency>
  </dependencies>
</project>


text:
package test.com.sasbury.sting;

import com.sasbury.sting.*;
import junit.framework.*;

public abstract class PushOpTest extends TestCase implements StingConstants
{
    public abstract String getOperationName();
    public abstract StingStack getCorrectStack(ExecutionContext context);

	public PushOpTest(String name)
	{
		super(name);
	}

    public void testOperation() throws Exception
    {
        StingProgram program = new StingProgram(getOperationName());
        ExecutionContext context = program.execute();
        StingStack correct = getCorrectStack(context);
        assertTrue(correct.equals(context.getStack()));
    }
}


text:
package org.keycloak.authorization.identity;

import org.keycloak.authorization.attribute.Attributes;

import java.util.Collection;
import java.util.Map;
import java.util.function.Predicate;

/**
 *
Represents a security identity, which can be a person or non-person entity that was previously authenticated.
 *
 *
An {@link Identity} plays an important role during the evaluation of policies as they represent the entity to which one or more permissions
 * should be granted or not, providing additional information and attributes that can be relevant to the different
 * access control methods involved during the evaluation of policies.
 *
 * @author Pedro Igor
 */
public interface Identity {

    /**
     * Returns the unique identifier of this identity.
     *
     * @return the unique identifier of this identity
     */
    String getId();

    /**
     * Returns the attributes or claims associated with this identity.
     *
     * @return the attributes or claims associated with this identity
     */
    Attributes getAttributes();

    /**
     * Indicates if this identity is granted with a role (realm or client) with the given roleName.
     *
     * @param roleName the name of the role
     *
     * @return true if the identity has the given role. Otherwise, it returns false.
     */
    default boolean hasRole(String roleName) {
        return hasRealmRole(roleName) || hasClientRole(roleName);
    }

    /**
     * Indicates if this identity is granted with a realm role with the given roleName.
     *
     * @param roleName the name of the role
     *
     * @return true if the identity has the given role. Otherwise, it returns false.
     */
    default boolean hasRealmRole(String roleName) {
        return getAttributes().containsValue("kc.realm.roles", roleName);
    }

    /**
     * Indicates if this identity is granted with a client role with the given roleName.
     *
     * @param clientId the client id
     * @param roleName the name of the role
     *
     * @return true if the identity has the given role. Otherwise, it returns false.
     */
    default boolean hasClientRole(String clientId, String roleName) {
        return getAttributes().containsValue("kc.client." + clientId + ".roles", roleName);
    }

    /**
     * Indicates if this identity is granted with a client role with the given roleName.
     *
     * @param roleName the name of the role
     *
     * @return true if the identity has the given role. Otherwise, it returns false.
     */
    default boolean hasClientRole(String roleName) {
        return getAttributes().toMap().entrySet().stream().filter(entry -> {
            String key = entry.getKey();
            if (key.startsWith("kc.client") && key.endsWith(".roles")) {
                return getAttributes().containsValue(key, roleName);
            }
            return false;
        }).findFirst().isPresent();
    }
}


text:
<!--
  #%L
  content-resolver-service
  %%
  Copyright (C) 2012 The State and University Library, Denmark
  %%
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  #L%
  -->
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <display-name>content-resolver</display-name>
    <description>Content Resolver</description>

    <env-entry>
        <env-entry-name>contentresolver/configfile</env-entry-name>
        <env-entry-type>java.lang.String</env-entry-type>
        <env-entry-value>contentresolver-default.xml</env-entry-value>
    </env-entry>

    <servlet>
        <servlet-name>workflowstatemonitor</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>dk.statsbiblioteket.medieplatform.contentresolver.service</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>workflowstatemonitor</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>


text:
package io.realm;

import androidx.test.ext.junit.runners.AndroidJUnit4;

import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.Arrays;

import io.realm.annotations.RealmModule;
import io.realm.entities.AllTypes;
import io.realm.entities.AnimalModule;
import io.realm.entities.Cat;
import io.realm.entities.CatOwner;
import io.realm.entities.Dog;
import io.realm.entities.HumanModule;
import io.realm.internal.modules.CompositeMediator;
import io.realm.internal.modules.FilterableMediator;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

@RunWith(AndroidJUnit4.class)
public class MediatorTest {

    @SuppressWarnings("AssertEqualsBetweenInconvertibleTypes")
    @Test
    public void mediatorsEquality() {
        final DefaultRealmModuleMediator defaultMediator = new DefaultRealmModuleMediator();
        final CompositeMediator compositeMediator = new CompositeMediator(defaultMediator);
        final FilterableMediator filterableMediator = new FilterableMediator(defaultMediator, defaultMediator.getModelClasses());

        assertEquals(defaultMediator, defaultMediator);
        assertEquals(defaultMediator.hashCode(), defaultMediator.hashCode());
        assertEquals(defaultMediator, compositeMediator);
        assertEquals(defaultMediator.hashCode(), compositeMediator.hashCode());
        assertEquals(defaultMediator, filterableMediator);
        assertEquals(defaultMediator.hashCode(), filterableMediator.hashCode());

        assertEquals(compositeMediator, defaultMediator);
        assertEquals(compositeMediator.hashCode(), defaultMediator.hashCode());
        assertEquals(compositeMediator, compositeMediator);
        assertEquals(compositeMediator.hashCode(), compositeMediator.hashCode());
        assertEquals(compositeMediator, filterableMediator);
        assertEquals(compositeMediator.hashCode(), filterableMediator.hashCode());

        assertEquals(filterableMediator, defaultMediator);
        assertEquals(filterableMediator.hashCode(), defaultMediator.hashCode());
        assertEquals(filterableMediator, compositeMediator);
        assertEquals(filterableMediator.hashCode(), compositeMediator.hashCode());
        assertEquals(filterableMediator, filterableMediator);
        assertEquals(filterableMediator.hashCode(), filterableMediator.hashCode());
    }

    @Test
    public void compositeMediatorModelClassesCount() {
        final CompositeMediator mediator = new CompositeMediator(
                new HumanModuleMediator(),
                new AnimalModuleMediator()
        );

        final int modelsInHumanModule = HumanModule.class.getAnnotation(RealmModule.class).classes().length;
        final int modelsInAnimalModule = AnimalModule.class.getAnnotation(RealmModule.class).classes().length;

        assertEquals(modelsInHumanModule + modelsInAnimalModule, mediator.getModelClasses().size());
    }

    @Test
    public void filterableMediatorModelClassesCount() {
        //noinspection unchecked
        final FilterableMediator mediator = new FilterableMediator(new AnimalModuleMediator(), Arrays.<Class<? extends RealmModel>>asList(Cat.class, CatOwner.class));

        assertTrue(mediator.getModelClasses().contains(Cat.class));
        // CatOwner is not a member of AnimalModuleMediator
        assertFalse(mediator.getModelClasses().contains(CatOwner.class));
        assertFalse(mediator.getModelClasses().contains(Dog.class));
        assertFalse(mediator.getModelClasses().contains(AllTypes.class));
    }

    @Test
    public void defaultMediatorWasTransformed() {
        final DefaultRealmModuleMediator defaultMediator = new DefaultRealmModuleMediator();
        assertTrue(defaultMediator.transformerApplied());
    }
}