text:
package raven.sqdev.sqf.processing;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.eclipse.core.resources.IMarker;
import dataStructures.ESQFOperatorType;
import dataStructures.ESQFTokentype;
import dataStructures.IBuildableIndexTree;
import dataStructures.ISQFTreeListener;
import dataStructures.ITokenSource;
import dataStructures.IndexTreeElement;
import dataStructures.SQFToken;
import raven.sqdev.constants.ProblemMessages;
import raven.sqdev.exceptions.ValidationException;
import raven.sqdev.infoCollection.base.SQFCommand;
import raven.sqdev.infoCollection.base.Variable;
import raven.sqdev.interfaces.ISQFInformation;
import raven.sqdev.interfaces.ITreeProcessingResult;
import raven.sqdev.misc.DataTypeList;
import raven.sqdev.misc.EDataType;
import raven.sqdev.parser.misc.TreeProcessingResult;
import raven.sqdev.parser.sqf.ERelativePosition;
import raven.sqdev.parser.sqf.SQFSyntaxProcessor;

public class SQFProcessor implements ISQFTreeListener {

	/**
	 * A {@linkplain DataTypeList} containing the datatype ANYTHING
	 */
	public static final DataTypeList ANYTHING = new DataTypeList(EDataType.ANYTHING);
	/**
	 * A {@linkplain DataTypeList} containing the datatype CODE
	 */
	public static final DataTypeList CODE = new DataTypeList(EDataType.CODE);
	/**
	 * A {@linkplain DataTypeList} containing the datatype ARRAY
	 */
	public static final DataTypeList ARRAY = new DataTypeList(EDataType.ARRAY);
	/**
	 * A {@linkplain DataTypeList} containing the datatype STRING
	 */
	public static final DataTypeList STRING = new DataTypeList(EDataType.STRING);
	/**
	 * A {@linkplain DataTypeList} containing the datatype NUMBER
	 */
	public static final DataTypeList NUMBER = new DataTypeList(EDataType.NUMBER);

	/**
	 * The buffer holding all tokens
	 */
	protected ITokenSource<SQFToken> tokenBuffer;
	/**
	 * The object containing all results of parsing and validating
	 */
	protected TreeProcessingResult result;
	/**
	 * The set of so far declared variables. All names are in lowercase
	 */
	protected HashSet<String> declaredVariables;
	/**
	 * The object holding all necessary meta-information
	 */
	protected ISQFInformation sqfInformation;
	/**
	 * A map of all resolved return values
	 */
	protected Map<IndexTreeElement, DataTypeList> resolvedReturnValues;
	/**
	 * The {@linkplain SQFSyntaxProcessor} to use internally
	 */
	protected SQFSyntaxProcessor syntaxProcessor;

	/**
	 * Creates a new instance of this processor
	 *
	 * @param info
	 *            The {@linkplain ISQFInformation} holding all necessary meta
	 *            information about the available commands
	 * @param result
	 *            The {@linkplain TreeProcessingResult} to put all results of this
	 *            processing to
	 * @param tokenBuffer
	 *            The buffer holding all tokens to the tree that is going to be
	 *            processed
	 */
	public SQFProcessor(ISQFInformation info, TreeProcessingResult result, ITokenSource<SQFToken> tokenBuffer) {
		assert (info != null);
		assert (result != null);
		assert (tokenBuffer != null);

		declaredVariables = new HashSet<>();
		this.result = result;
		this.sqfInformation = info;
		this.tokenBuffer = tokenBuffer;
		resolvedReturnValues = new HashMap<>();
		syntaxProcessor = new SQFSyntaxProcessor();
	}

	@Override
	public void nularExpression(SQFToken expression, IndexTreeElement node) {
		assert (expression.operatorType() != ESQFOperatorType.MACRO);

		switch (expression.type()) {
		case ID:
		case OPERATOR:
			// process operators or variables only
			break;
		default:
			return;
		}

		final String operatorName = expression.getText();
		final String operatorNameLower = operatorName.toLowerCase();
		SQFCommand operator = sqfInformation.getNularOperators().get(operatorNameLower);

		if (!declaredVariables.contains(operatorName.toLowerCase())
				&& !sqfInformation.getMagicVariables().keySet().contains(operatorNameLower)) {
			if (operator == null && operatorName.startsWith("_")) {
				// it is an unknown local variable -> error
				error(expression, ProblemMessages.undefinedLocalVariable(operatorName));

				// assume any type for variables
				resolvedReturnValues.put(node, ANYTHING);
				return;
			} else {
				if (operator == null) {
					// try to see if it is another operator
					operator = sqfInformation.getUnaryOperators().get(operatorNameLower);
					if (operator == null) {
						operator = sqfInformation.getBinaryOperators().get(operatorNameLower);
					}

					if (operator == null && expression.type() == ESQFTokentype.ID) {
						// this is an implicitly declared global variable
						// TODO: potential error
						declaredVariables.add(operatorName.toLowerCase());

						// assume any type for variables
						resolvedReturnValues.put(node, ANYTHING);
						return;
					}
				}
			}
		} else {
			// assume any type for variables
			resolvedReturnValues.put(node, ANYTHING);
			return;
		}

		if (operator == null || !operator.isNularOperator()) {
			// assume any type for erroneous input
			error(expression, ProblemMessages.operatorIsNotNular(operatorName));

			resolvedReturnValues.put(node, ANYTHING);
		} else {
			resolvedReturnValues.put(node, operator.getAllReturnTypes());
		}
	}

	@Override
	public void unaryExpression(SQFToken expression, IndexTreeElement node) {
		assert (expression.operatorType() != ESQFOperatorType.MACRO);
		assert (node.getChildrenCount() == 1);

		final String operatorName = expression.getText();
		final String operatorNameLower = operatorName.toLowerCase();
		SQFCommand operator = sqfInformation.getUnaryOperators().get(operatorNameLower);
		if (operator == null) {
			// might be a binary operator used in unary syntax
			operator = sqfInformation.getBinaryOperators().get(operatorNameLower);
		}

		if (operatorNameLower.equals("private")) {
			// handle private separately
			handlePrivate(node.getChildren().get(0));
			return;
		}

		if (operator == null) {
			// if it's still null then this is not a unary operator
			error(expression, ProblemMessages.operatorIsNotUnary(operatorName));

			// assume any type for erroneous input
			resolvedReturnValues.put(node, ANYTHING);

			return;
		}

		if (!operator.isUnaryOperator()) {
			// This operator can't be used in a unary way
			error(expression, ProblemMessages.operatorIsNotUnary(operator.getKeyword()));
			return;
		}

		// check whether the given argument is of a valid type
		syntaxProcessor.reset();
		syntaxProcessor.setOperator(operator);
		syntaxProcessor.setRightArgumentTypes(getReturnValues(node.getChildren().get(0)));

		// buffer return value for this node
		resolvedReturnValues.put(node, syntaxProcessor.getReturnValues());

		if (!syntaxProcessor.isValid()) {
			if (syntaxProcessor.getErrorMarkerPosition() == ERelativePosition.RIGHT) {
				error(node.getChildren().get(0), syntaxProcessor.getErrorMessage());
			} else {
				error(expression, syntaxProcessor.getErrorMessage());
			}
		} else {
			// check for special cases in which a variable-name extraction has to be
			// performed
			switch (operatorNameLower) {
			case "params":
				handleParams(node.getChildren().get(0));
				break;

			case "for":
				handleFor(node.getChildren().get(0));
				break;
			}
		}
	}

	@Override
	public void binaryExpression(SQFToken expression, IndexTreeElement node) {
		final String operatorName = expression.getText();

		switch (operatorName.toLowerCase()) {
		case "=":
			// assignment
			assignment(node);
			break;

		default:
			// "normal" binary operator
			SQFCommand operator = sqfInformation.getBinaryOperators().get(operatorName.toLowerCase());

			if (operator != null) {
				DataTypeList leftTypes = getReturnValues(node.getChildren().get(0));
				DataTypeList rightTypes = getReturnValues(node.getChildren().get(1));

				syntaxProcessor.reset();
				syntaxProcessor.setOperator(operator);
				syntaxProcessor.setLeftArgumentTypes(leftTypes);
				syntaxProcessor.setRightArgumentTypes(rightTypes);

				if (!syntaxProcessor.isValid()) {
					int[] positionData;

					try {
						switch (syntaxProcessor.getErrorMarkerPosition()) {
						case CENTER:
							positionData = new int[] { expression.start(), expression.length() };
							break;
						case LEFT:
							positionData = getNodeDimension(node.getChildren().get(0));
							break;
						case RIGHT:
							positionData = getNodeDimension(node.getChildren().get(1));
							break;
						case NONE:
						default:
							positionData = new int[] { 0, 0 };
							error(node, ProblemMessages.internalError());
							System.err.println("Unexpected marker position for binary expression");
							// TODO: log
						}
					} catch (ValidationException e) {
						e.printStackTrace();
						positionData = new int[] { 0, 0 };
						error(node, ProblemMessages.internalError());
					}

					error(positionData[0], positionData[1], syntaxProcessor.getErrorMessage());
				}

				// map the resolved processor to the respective node
				resolvedReturnValues.put(node, syntaxProcessor.getReturnValues());

				if (operatorName.toLowerCase().equals("params")) {
					handleParams(node.getChildren().get(1));
				}
			} else {
				// apparently it is not a binary operator -> shouldn't even be reachable
				error(expression, ProblemMessages.operatorIsNotBinary(operatorName));
			}

			break;
		}
	}

	@Override
	public void array(IndexTreeElement node) {
		// check whether all array elements are separated by a comma

		boolean wasComma = true;
		int lastTokenIndex = node.getChildren().get(node.getChildrenCount() - 1).getIndex();
		// If the last token is the closing bracket, don't iterate over it (if not an
		// error should occur somewhere else)
		int length = (lastTokenIndex >= 0
				&& tokenBuffer.get(lastTokenIndex).type() == ESQFTokentype.SQUARE_BRACKET_CLOSE)
						? node.getChildrenCount() - 1
						: node.getChildrenCount();

		for (int i = 1; i < length; i++) {
			IndexTreeElement element = node.getChildren().get(i);

			if (wasComma) {
				if (element.getIndex() >= 0 && (tokenBuffer.get(element.getIndex()).type() == ESQFTokentype.COMMA
						|| tokenBuffer.get(element.getIndex()).type() == ESQFTokentype.SEMICOLON)) {
					// two commas next to each other or a semicolon -> invalid
					error(element, ProblemMessages.misplacedToken(","));
				}
				wasComma = false;
			} else {
				// this element has to be a comma or the closing square bracket
				if (element.getIndex() < 0 || tokenBuffer.get(element.getIndex()).type() != ESQFTokentype.COMMA) {
					// missing comma
					SQFToken lastToken = getLastToken(node.getChildren().get(i - 1));
					error(lastToken, ProblemMessages.missingComma(lastToken.getText()));
				} else {
					wasComma = true;
				}
			}
		}

		if (wasComma && node.getChildrenCount() > 2) {
			// The last token in the array before the closing bracket was a comma -> error
			error(node.getChildren().get(node.getChildrenCount() - 2), ProblemMessages.misplacedToken(","));
		}
	}

	@Override
	public void code(IndexTreeElement node) {
		checkSemicolons(node.getChildren());
	}

	@Override
	public void start(IBuildableIndexTree tree) {
		checkSemicolons(tree.branches());
	}

	@Override
	public void finished(IBuildableIndexTree tree) {
		// add all found variables to the result
		Iterator<String> varIterator = declaredVariables.iterator();

		while (varIterator.hasNext()) {
			Variable var = new Variable(varIterator.next());

			if (var.isLocal()) {
				result.getDeclaredLocalVariables().put(var.getKeyword(), var);
			} else {
				result.getDeclaredGlobalVariables().put(var.getKeyword(), var);
			}
		}
	}

	/**
	 * Checks whether semicolons are provided where needed and issues errors if this
	 * is not the case
	 *
	 * @param nodes
	 *            The collection of nodes representing the code-elements
	 */
	protected void checkSemicolons(Collection<? extends IndexTreeElement> nodes) {
		boolean wasStatement = false;
		IndexTreeElement prevNode = null;

		for (IndexTreeElement currentNode : nodes) {
			if (currentNode.getIndex() < 0) {
				// it's definitely a statement
				wasStatement = true;
			} else {
				SQFToken currentToken = tokenBuffer.get(currentNode.getIndex());

				boolean isStatement = currentToken.operatorType() != ESQFOperatorType.OTHER
						&& currentToken.type() != ESQFTokentype.SEMICOLON;

				if (wasStatement && isStatement) {
					// there should have been a semicolon in between
					assert (prevNode != null);
					SQFToken lastToken = getLastToken(prevNode);
					error(lastToken, ProblemMessages.missingSemicolon(lastToken.getText()));
				}

				wasStatement = isStatement && currentToken.operatorType() != ESQFOperatorType.MACRO;

				prevNode = currentNode;
			}
		}
	}

	/**
	 * This method processes any occurring assignments done by the "=" operator
	 *
	 * @param node
	 *            The parse tree node of the assignment. The two children are
	 *            considered to be assignment arguments (there have to be two!)
	 */
	protected void assignment(IndexTreeElement node) {
		assert (node.getChildrenCount() == 2);

		IndexTreeElement variableNode = node.getChildren().get(0);

		boolean isPrivate = variableNode.hasChildren();

		if (isPrivate) {
			int index = variableNode.getIndex();

			if (index < 0) {
				// The assignment is corrupted
				error(variableNode, ProblemMessages.invalidExpression("assignment"));
			}

			SQFToken varOperatorToken = tokenBuffer.get(index);

			if (varOperatorToken.operatorType() == ESQFOperatorType.MACRO) {
				// handle macros assembling the variable name -> can't really validate -> assume
				// it's valid
				declaredVariables.add(getFullText(variableNode));
				// abort as other checks and routines don't apply to macros
				return;
			}

			if (!varOperatorToken.getText().toLowerCase().equals("private")) {
				// only private is allowed as a modifier
				error(tokenBuffer.get(node.getIndex()), ProblemMessages.privateIsOnlyValidModifierForAssignments());

				// assume for the moment that the modifier came here by accident
				isPrivate = false;
			}

			variableNode = variableNode.getChildren().get(0);

			if (variableNode.getIndex() < 0) {
				// something's really f*cked up
				error(node.getChildren().get(0), ProblemMessages.internalError());

				return;
			}
		}

		String varName = tokenBuffer.get(variableNode.getIndex()).getText();
		if (isPrivate && !varName.startsWith("_")) {
			// don't add global, private variables
			// The error is produced as soon as the unary private keyword is being processed
			return;
		}
		if (!isOperatorName(varName)) {
			declaredVariables.add(varName.toLowerCase());
		} else {
			error(tokenBuffer.get(variableNode.getIndex()), ProblemMessages.reservedKeyword(varName));
		}
	}

	/**
	 * Adds a new error marker to {@link #result}
	 *
	 * @param start
	 *            The starting offset of the error area
	 * @param length
	 *            The length of the error area
	 * @param message
	 *            The problem message
	 */
	protected void error(int start, int length, String message) {
		addProblemMarker(IMarker.SEVERITY_ERROR, start, length, message);
	}

	/**
	 * Adds a new error marker to {@link #result}
	 *
	 * @param token
	 *            The token corresponding to the error
	 * @param message
	 *            The problem message
	 */
	protected void error(SQFToken token, String message) {
		addProblemMarker(IMarker.SEVERITY_ERROR, token, message);
	}

	/**
	 * Adds a new error marker to {@link #result}
	 *
	 * @param node
	 *            The tree node corresponding to the error
	 * @param message
	 *            The problem message
	 */
	protected void error(IndexTreeElement node, String message) {
		addProblemMarker(IMarker.SEVERITY_ERROR, node, message);
	}

	/**
	 * Adds a new warning marker to {@link #result}
	 *
	 * @param start
	 *            The starting offset of the warning area
	 * @param length
	 *            The length of the warning area
	 * @param message
	 *            The problem message
	 */
	protected void warning(int start, int length, String message) {
		addProblemMarker(IMarker.SEVERITY_WARNING, start, length, message);
	}

	/**
	 * Adds a new warning marker to {@link #result}
	 *
	 * @param token
	 *            The token corresponding to the warning
	 * @param message
	 *            The problem message
	 */
	protected void warning(SQFToken token, String message) {
		addProblemMarker(IMarker.SEVERITY_WARNING, token, message);
	}

	/**
	 * Adds a new warning marker to {@link #result}
	 *
	 * @param node
	 *            The tree node corresponding to the warning
	 * @param message
	 *            The problem message
	 */
	protected void warning(IndexTreeElement node, String message) {
		addProblemMarker(IMarker.SEVERITY_WARNING, node, message);
	}

	/**
	 * Adds a new info marker to {@link #result}
	 *
	 * @param start
	 *            The starting offset of the info area
	 * @param length
	 *            The length of the info area
	 * @param message
	 *            The problem message
	 */
	protected void info(int start, int length, String message) {
		addProblemMarker(IMarker.SEVERITY_INFO, start, length, message);
	}

	/**
	 * Adds a new info marker to {@link #result}
	 *
	 * @param token
	 *            The token corresponding to the info
	 * @param message
	 *            The problem message
	 */
	protected void info(SQFToken token, String message) {
		addProblemMarker(IMarker.SEVERITY_INFO, token, message);
	}

	/**
	 * Adds a new info marker to {@link #result}
	 *
	 * @param node
	 *            The tree node corresponding to the info
	 * @param message
	 *            The problem message
	 */
	protected void info(IndexTreeElement node, String message) {
		addProblemMarker(IMarker.SEVERITY_INFO, node, message);
	}

	/**
	 * Adds a new problem marker to {@link #result}
	 *
	 * @param severity
	 *            The severity of the marker to be created. See {@linkplain IMarker}
	 *            for the respective constants
	 * @param start
	 *            The starting offset of the problem area
	 * @param length
	 *            The length of the problem area
	 * @param message
	 *            The problem message
	 */
	protected void addProblemMarker(int severity, int start, int length, String message) {
		result.createMarker(IMarker.PROBLEM, start, length, message, severity);
	}

	/**
	 * Adds a new problem marker to {@link #result}
	 *
	 * @param severity
	 *            The severity of the marker to be created. See {@linkplain IMarker}
	 *            for the respective constants
	 * @param token
	 *            The token corresponding to the problem
	 * @param message
	 *            The problem message
	 */
	protected void addProblemMarker(int severity, SQFToken token, String message) {
		addProblemMarker(severity, token.start(), token.length(), message);
	}

	/**
	 * Adds a new problem marker to {@link #result}. This method will consider the
	 * whole dimension of the given node as the problem area
	 *
	 * @param severity
	 *            The severity of the marker to be created. See {@linkplain IMarker}
	 *            for the respective constants
	 * @param node
	 *            The tree node corresponding to the problem
	 * @param message
	 *            The problem message
	 */
	protected void addProblemMarker(int severity, IndexTreeElement node, String message) {
		// verify that the given indexTreeElement has a corresponding token
		int[] dimension;
		try {
			dimension = getNodeDimension(node);
		} catch (ValidationException e) {
			e.printStackTrace();
			dimension = new int[] { 0, 0 };
			message = "Error on invalid tree node: " + message;
		}

		addProblemMarker(severity, dimension[0], dimension[1], message);
	}

	/**
	 * Gets a node's dimension which is the text area from the start of the token
	 * associated leftmost child-node and the end of the token associated with the
	 * rightmost child-node. If this node doesn't have children the token associated
	 * with this node is used in order to determine the node's dimension.
	 *
	 * @param node
	 *            The node whose dimension should be obtained
	 * @return The dimension of the node in form of a 2D array: [start, length]
	 * @throws ValidationException
	 *             If asked to determine the dimension of an invalid node
	 */
	protected int[] getNodeDimension(IndexTreeElement node) throws ValidationException {
		if (!node.hasChildren()) {
			int index = node.getIndex();

			if (index < 0) {
				throw new ValidationException("Failed at getting node dimension!");
			}

			SQFToken token = tokenBuffer.get(node.getIndex());

			return new int[] { token.start(), token.length() };
		}

		SQFToken first = getFirstToken(node);
		SQFToken last = getLastToken(node);

		if (first == null || last == null) {
			throw new ValidationException("Failed at getting node dimension!");
		}

		// use the left- and rightmost token in order to determine the dimension
		return new int[] { first.start(), last.stop() - first.start() };
	}

	/**
	 * Gets the possible return values of the given node. Calling this method will
	 * trigger the return-value-buffering which means that it will populate
	 * {@link #resolvedReturnValues} if there is no entry for the given node yet. If
	 * there is the previously determined return values will be returned
	 *
	 * @param node
	 *            The node whose return values are to be determined
	 * @return The list of return values
	 */
	protected DataTypeList getReturnValues(IndexTreeElement node) {
		// Check whether the return value for that node has already been determined ->
		// Especially used for context sensitive return values of operators
		if (!resolvedReturnValues.containsKey(node)) {
			resolvedReturnValues.put(node, doGetReturnValues(node));
		}

		return resolvedReturnValues.get(node);
	}

	/**
	 * Gets all the possible return values of the given node. Calling this method
	 * directly will bypass the return-value-buffering system
	 *
	 * @param node
	 *            The node whose return values are to be determined
	 * @return The list of return values
	 */
	protected DataTypeList doGetReturnValues(IndexTreeElement node) {
		if (node.getIndex() >= 0) {
			SQFToken token = tokenBuffer.get(node.getIndex());

			// handle primitives first
			switch (token.type()) {
			case CURLY_BRACKET_OPEN:
				return CODE;
			case ERROR_TOKEN:
				return ANYTHING;
			case NUMBER:
				return NUMBER;
			case SQUARE_BRACKET_OPEN:
				return ARRAY;
			case STRING:
				return STRING;
			case SUBSTRING:
				return STRING;
			default:
				// do nothing -> will be handled below
			}

			switch (token.operatorType()) {
			case MACRO:
				return ANYTHING;
			case BINARY:
				SQFCommand operator = sqfInformation.getBinaryOperators().get(token.getText().toLowerCase());
				if (operator == null) {
					// If it is not recognized it will be handled elsewhere
					return ANYTHING;
				} else {
					return operator.getAllReturnTypes();
				}
			case NULAR:
				operator = sqfInformation.getNularOperators().get(token.getText().toLowerCase());
				if (operator == null) {
					// If it is not recognized it will be handled elsewhere
					return ANYTHING;
				} else {
					return operator.getAllReturnTypes();
				}
			case UNARY:
				operator = sqfInformation.getUnaryOperators().get(token.getText().toLowerCase());
				if (operator == null) {
					// If it is not recognized it will be handled elsewhere
					return ANYTHING;
				} else {
					return operator.getAllReturnTypes();
				}
			default:
				// Shouldn't get reached
				error(node, ProblemMessages.internalError());
				return ANYTHING;
			}
		} else {
			if (node.hasChildren()) {
				return getReturnValues(node.getChildren().get(0));
			} else {
				// Shouldn't get reached
				error(node, ProblemMessages.internalError());
				return ANYTHING;
			}
		}
	}

	/**
	 * Gets the full text of a {@linkplain IndexTreeElement} which is the text of
	 * all its associated tokens
	 *
	 * @param node
	 *            The node whose text should be obtained
	 * @return The text corresponding to the given node
	 */
	protected String getFullText(IndexTreeElement node) {
		StringBuilder builder = new StringBuilder();

		Collection<Integer> indices = new ArrayList<>();
		getAllTokenIndices(node, indices);

		indices.stream().filter((e) -> {
			return e.intValue() >= 0;
		}).sorted().forEach((element) -> builder.append(tokenBuffer.get(element.intValue()).getText()));

		return builder.toString();
	}

	/**
	 * Gets all token indices associated with the given node and its sub-nodes
	 * except the invalid (< 0) ones
	 *
	 * @param node
	 *            The node to process
	 * @param indices
	 *            An integer collection to store the indices in
	 */
	protected void getAllTokenIndices(IndexTreeElement node, Collection<Integer> indices) {
		if (node.getIndex() >= 0) {
			indices.add(node.getIndex());
		}

		if (node.hasChildren()) {
			node.getChildren().forEach((e) -> getAllTokenIndices(e, indices));
		}
	}

	/**
	 * Handles the argument of the "private" operator/keyword
	 *
	 * @param node
	 *            The {@linkplain IndexTreeElement} corresponding to the argument of
	 *            "private" (or the ID of the variable private was used as a keyword
	 *            for)
	 */
	protected void handlePrivate(IndexTreeElement node) {
		assert (node.getIndex() != IndexTreeElement.INVALID);

		if (node.getIndex() < 0) {
			// the argument has to be an array of variable names
			if (!node.hasChildren()) {
				error(node, ProblemMessages.invalidExpression("private-array"));
				return;
			}

			// iterate through all children and extract declared variables
			for (IndexTreeElement currentElement : node.getChildren()) {
				if (currentElement.getIndex() < 0) {
					error(currentElement, ProblemMessages.invalidExpression("private-array"));
				} else {
					SQFToken varToken = tokenBuffer.get(currentElement.getIndex());

					if (varToken.type() != ESQFTokentype.STRING) {
						if (varToken.type() != ESQFTokentype.COMMA
								&& varToken.type() != ESQFTokentype.SQUARE_BRACKET_OPEN
								&& varToken.type() != ESQFTokentype.SQUARE_BRACKET_CLOSE) {
							// comma and square brackets are obviously allowed in an array
							error(varToken, ProblemMessages.invalidExpression("private-array-element"));
						}
					} else {
						extractVariableFromString(varToken, varToken.getText(), true);
					}
				}
			}
		} else {
			// the argument is either a String containing a variable name or an ID
			SQFToken argToken = tokenBuffer.get(node.getIndex());

			if (argToken.type() == ESQFTokentype.STRING) {
				extractVariableFromString(argToken, argToken.getText(), true);
			} else {
				if (argToken.type() == ESQFTokentype.ID) {
					String varName = argToken.getText();

					if (!varName.startsWith("_")) {
						error(argToken, ProblemMessages.privateVariablesMustBeLocal());
						return;
					}

					if (!isOperatorName(varName)) {
						declaredVariables.add(varName.toLowerCase());
					} else {
						error(argToken, ProblemMessages.reservedKeyword(varName));
					}
				} else {
					error(argToken, ProblemMessages.invalidExpression("private"));
				}
			}
		}
	}

	/**
	 * Handles the argument of the "for"-keyword. This method assumes that it has
	 * already been assured that the respective argument is either of type array or
	 * of type String
	 *
	 * @param arg
	 *            The respective {@linkplain IndexTreeElement} corresponding to the
	 *            argument of a "for" operator
	 */
	protected void handleFor(IndexTreeElement arg) {
		if (arg.getIndex() < 0) {
			// it's the array syntax (has been validated before to assure that it is the
			// correct type)

			if (!arg.hasChildren()) {
				error(arg, ProblemMessages.internalError());
			}

			boolean wasComma = true;
			int elements = 0;

			for (int i = 1; i < arg.getChildrenCount() - 1; i++) {
				IndexTreeElement currentElement = arg.getChildren().get(i);

				if (wasComma) {
					// validate that all elements are of type code
					DataTypeList types = getReturnValues(currentElement);
					if (types != CODE) {
						error(currentElement, ProblemMessages.expectedTypeButGot(CODE, types));
					}

					elements++;
					wasComma = false;
				} else {
					wasComma = true;
				}

			}

			if (elements != 3) {
				error(arg, ProblemMessages.expectedArrayLength(3, elements));
			}
		} else {
			// it's the string-syntax (has been validated before to assure that it is the
			// correct type)
			SQFToken token = tokenBuffer.get(arg.getIndex());
			extractVariableFromString(token, token.getText(), true);
		}
	}

	/**
	 * Handles the argument of the "params"-operator. This method assumes that it
	 * has already been assured that the respective argument is of type array.
	 *
	 * @param arg
	 *            The respective {@linkplain IndexTreeElement} corresponding to the
	 *            argument of a "params" operator
	 */
	protected void handleParams(IndexTreeElement arg) {
		assert (arg.hasChildren());

		for (IndexTreeElement currentChild : arg.getChildren()) {
			if (currentChild.getIndex() >= 0
					&& tokenBuffer.get(currentChild.getIndex()).operatorType() == ESQFOperatorType.OTHER) {
				// skip brackets and commas
				continue;
			}

			if (currentChild.getIndex() < 0) {
				// array syntax
				if (!currentChild.hasChildren()) {
					error(currentChild, ProblemMessages.internalError());
					continue;
				}
				handleParamsArray(currentChild);
			} else {
				// String syntax
				SQFToken stringToken = tokenBuffer.get(currentChild.getIndex());

				if (stringToken.type() != ESQFTokentype.STRING) {
					error(stringToken, ProblemMessages.expectedTypeButGot(STRING, getReturnValues(currentChild)));
				} else {
					if (stringToken.getText().length() > 2) {
						// empty strings are allowed in this context but there is no variable to extract
						// from them
						extractVariableFromString(stringToken, stringToken.getText(), true);
					}
				}
			}
		}
	}

	/**
	 * Processes the sub-array-construct that may appear inside the argument-array
	 * of the "params"-operator
	 *
	 * @param array
	 *            The sub-array to process
	 */
	protected void handleParamsArray(IndexTreeElement array) {
		if (array.getChildrenCount() < 5) {
			error(array, ProblemMessages.expectedMinimumArrayLength(2, (array.getChildrenCount() - 1) / 2));
			return;
		}

		if (array.getChildrenCount() > 9) {
			error(array, ProblemMessages.expectedMaximalArrayLength(4, (array.getChildrenCount() - 1) / 2));
			return;
		}

		for (int i = 1; i < array.getChildrenCount() - 1; i++) {
			IndexTreeElement currentElement = array.getChildren().get(i);

			if (currentElement.getIndex() > 0) {
				if (tokenBuffer.get(currentElement.getIndex()).operatorType() == ESQFOperatorType.OTHER) {
					// skip commas
					continue;
				}
			}

			DataTypeList types = getReturnValues(currentElement);

			switch (i) {
			case 1:
				// first element has to be a String
				if (types.findExchangableDataType(EDataType.STRING, true) < 0) {
					error(currentElement, ProblemMessages.expectedTypeButGot(STRING, types));
				} else {
					SQFToken varToken = tokenBuffer.get(currentElement.getIndex());
					extractVariableFromString(varToken, varToken.getText(), true);
				}
				break;
			case 3:
				// second element can be anything
				break;
			case 5:
				// third element (if present) has to be an array
				if (types.findExchangableDataType(EDataType.ARRAY, true) < 0) {
					error(currentElement, ProblemMessages.expectedTypeButGot(ARRAY, types));
				}
				break;
			case 7:
				// forth element (if present) can either be an array or a number
				if (types.findExchangableDataType(EDataType.ARRAY, true) < 0
						&& types.findExchangableDataType(EDataType.NUMBER, true) < 0) {
					error(currentElement, ProblemMessages.expectedTypeButGot(
							new DataTypeList(new EDataType[] { EDataType.NUMBER, EDataType.ARRAY }), types));
				}
				break;
			}
		}
	}

	/**
	 * Extracts a variable from a String as it occurs with private, params and for
	 *
	 * @param token
	 *            The token corresponding to said String
	 * @param varString
	 *            The string containing the variable name. Its first and last
	 *            character will be removed in order to "destringify" it
	 * @param mustBePrivate
	 *            Whether the extracted variable is expected to be a private
	 *            variable
	 */
	protected void extractVariableFromString(SQFToken token, String varString, boolean mustBePrivate) {
		// remove quotes
		varString = varString.substring(1, varString.length() - 1);

		if (varString.contains(" ")) {
			error(token, ProblemMessages.variableMayNotContainBlank());
			return;
		}

		if (varString.isEmpty()) {
			error(token, ProblemMessages.stringMayNotBeEmpty());
			return;
		}

		if (mustBePrivate && !varString.startsWith("_")) {
			error(token, ProblemMessages.canOnlyDeclareLocalVariable());
			return;
		}

		if (!isOperatorName(varString)) {
			declaredVariables.add(varString.toLowerCase());
		} else {
			error(token, ProblemMessages.reservedKeyword(varString));
		}
	}

	/**
	 * Checks whether the given name corresponds to an operator-keyword
	 *
	 * @param name
	 *            The name to check. It will be transformed to lowercase
	 *            automatically
	 */
	protected boolean isOperatorName(String name) {
		name = name.toLowerCase();
		return sqfInformation.getBinaryOperators().containsKey(name)
				|| sqfInformation.getUnaryOperators().containsKey(name)
				|| sqfInformation.getNularOperators().containsKey(name);
	}

	/**
	 * Gets the token with the lowest index in the given node
	 *
	 * @param node
	 *            The node to search for the respective token
	 * @return The leftmost token
	 */
	protected SQFToken getFirstToken(IndexTreeElement node) {
		List<Integer> indices = new ArrayList<>();

		getAllTokenIndices(node, indices);

		Collections.sort(indices);

		return tokenBuffer.get(indices.get(0));
	}

	/**
	 * Gets the token with the highest index in the given node
	 *
	 * @param node
	 *            The node to search for the respective token
	 * @return The rightmost token
	 */
	protected SQFToken getLastToken(IndexTreeElement node) {
		List<Integer> indices = new ArrayList<>();

		getAllTokenIndices(node, indices);

		Collections.sort(indices);

		return tokenBuffer.get(indices.get(indices.size() - 1));
	}

	/**
	 * Gets the result of this validation
	 */
	public ITreeProcessingResult getResult() {
		return result;
	}
}


text:
@implementation SNPDeleteAllStreamsOperation

- (void)main {

    self.endpoint = [[SNPAPIUtils sharedInstance] deleteAllStreamsEndpointURL];
    self.method = @"DELETE";
    self.serializationArrayClass = [SNPStream class];

    [super main];
}

@end

redpajama_set_name: RedPajamaGithub


text:
<ng:include src="'/app/partials/menu.html'" xmlns:ng="http://angularjs.org"></ng:include>

Doctors

Doctors in the center

		Create new

			#
			Name
			Actions

			{{ $index+1 }}
			{{ doctor.name }}

				Details
				Edit

No doctors


text:
<?xml version="1.0"?>
<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one
  ~ or more contributor license agreements.  See the NOTICE file
  ~ distributed with this work for additional information
  ~ regarding copyright ownership.  The ASF licenses this file
  ~ to you 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.
  -->

<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
    <id>bin</id>
    <formats>
        <format>tar.gz</format>
    </formats>
    <fileSets>
        <fileSet>
            <directory>${project.build.directory}/extensions</directory>
            <includes>
                <include>*/*</include>
            </includes>
            <excludes>
                <exclude>mysql-metadata-storage/**</exclude>
            </excludes>
            <outputDirectory>extensions</outputDirectory>
        </fileSet>

        <fileSet>
            <directory>${project.build.directory}/hadoop-dependencies</directory>
            <includes>
                <include>*/*/*</include>
            </includes>
            <outputDirectory>hadoop-dependencies</outputDirectory>
        </fileSet>

        <fileSet>
            <directory>../examples/quickstart/</directory>
            <includes>
                <include>*</include>
            </includes>
            <outputDirectory>quickstart</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>../examples/quickstart/tutorial</directory>
            <includes>
                <include>*</include>
            </includes>
            <outputDirectory>quickstart/tutorial</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>../examples/quickstart/tutorial/conf</directory>
            <includes>
                <include>*</include>
            </includes>
            <outputDirectory>quickstart/tutorial/conf</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>../examples/quickstart/tutorial/conf/druid</directory>
            <includes>
                <include>*</include>
            </includes>
            <outputDirectory>quickstart/tutorial/conf/druid</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>../examples/quickstart/tutorial/conf/druid/_common</directory>
            <includes>
                <include>*</include>
            </includes>
            <outputDirectory>quickstart/tutorial/conf/druid/_common/</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>../examples/quickstart/tutorial/conf/druid/broker</directory>
            <includes>
                <include>*</include>
            </includes>
            <outputDirectory>quickstart/tutorial/conf/druid/broker</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>../examples/quickstart/tutorial/conf/druid/coordinator</directory>
            <includes>
                <include>*</include>
            </includes>
            <outputDirectory>quickstart/tutorial/conf/druid/coordinator</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>../examples/quickstart/tutorial/conf/druid/historical</directory>
            <includes>
                <include>*</include>
            </includes>
            <outputDirectory>quickstart/tutorial/conf/druid/historical</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>../examples/quickstart/tutorial/conf/druid/overlord</directory>
            <includes>
                <include>*</include>
            </includes>
            <outputDirectory>quickstart/tutorial/conf/druid/overlord</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>../examples/quickstart/tutorial/conf/druid/middleManager</directory>
            <includes>
                <include>*</include>
            </includes>
            <outputDirectory>quickstart/tutorial/conf/druid/middleManager</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>../examples/quickstart/tutorial/conf/tranquility</directory>
            <includes>
                <include>*</include>
            </includes>
            <outputDirectory>quickstart/tutorial/conf/tranquility</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>../examples/quickstart/tutorial/conf/zk</directory>
            <includes>
                <include>*</include>
            </includes>
            <outputDirectory>quickstart/tutorial/conf/zk</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>../examples/quickstart/tutorial/hadoop</directory>
            <includes>
                <include>*</include>
            </includes>
            <outputDirectory>quickstart/tutorial/hadoop</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>../examples/quickstart/tutorial/hadoop/docker</directory>
            <includes>
                <include>*</include>
            </includes>
            <outputDirectory>quickstart/tutorial/hadoop/docker</outputDirectory>
        </fileSet>

        <fileSet>
            <directory>../examples/quickstart/protobuf</directory>
            <includes>
                <include>*</include>
            </includes>
            <outputDirectory>quickstart/protobuf</outputDirectory>
        </fileSet>

        <fileSet>
            <directory>../examples/conf</directory>
            <includes>
                <include>*</include>
            </includes>
            <outputDirectory>conf</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>../examples/conf/druid/_common</directory>
            <includes>
                <include>*</include>
            </includes>
            <outputDirectory>conf/druid/_common</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>../examples/conf/druid/broker</directory>
            <includes>
                <include>*</include>
            </includes>
            <outputDirectory>conf/druid/broker</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>../examples/conf/druid/coordinator</directory>
            <includes>
                <include>*</include>
            </includes>
            <outputDirectory>conf/druid/coordinator</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>../examples/conf/druid/historical</directory>
            <includes>
                <include>*</include>
            </includes>
            <outputDirectory>conf/druid/historical</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>../examples/conf/druid/overlord</directory>
            <includes>
                <include>*</include>
            </includes>
            <outputDirectory>conf/druid/overlord</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>../examples/conf/druid/middleManager</directory>
            <includes>
                <include>*</include>
            </includes>
            <outputDirectory>conf/druid/middleManager</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>../examples/conf/tranquility</directory>
            <includes>
                <include>*</include>
            </includes>
            <outputDirectory>conf/tranquility</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>../examples/bin</directory>
            <includes>
                <include>*</include>
            </includes>
            <fileMode>744</fileMode>
            <outputDirectory>bin</outputDirectory>
        </fileSet>

        <fileSet>
            <directory>../</directory>
            <includes>
                <include>LICENSE</include>
                <include>NOTICE</include>
            </includes>
        </fileSet>
    </fileSets>
    <dependencySets>
        <dependencySet>
            <useProjectArtifact>false</useProjectArtifact>
            <useTransitiveDependencies>true</useTransitiveDependencies>
            <outputDirectory>lib</outputDirectory>
            <excludes>
                <exclude>org.apache.druid:extensions-distribution</exclude>
            </excludes>
        </dependencySet>
        <dependencySet>
            <unpack>true</unpack>
            <includes>
                <include>org.apache.druid:extensions-distribution</include>
            </includes>
        </dependencySet>
    </dependencySets>
</assembly>


text:
<?php

	Class Widget{

		public static function Label($name=NULL, XMLElement $child=NULL, $class=NULL, $id=NULL){
			$label = new XMLElement('label', ($name ? $name : NULL));

			if(is_object($child)) $label->appendChild($child);

			if($class) $label->setAttribute('class', $class);
			if($id) $label->setAttribute('id', $id);

			return $label;
		}

		public static function Input($name, $value=NULL, $type='text', $attributes=NULL){
			$obj = new XMLElement('input');
			$obj->setAttribute('name', $name);

			if(is_array($attributes) && !empty($attributes)){
				foreach($attributes as $key => $val)
					$obj->setAttribute($key, $val);
			}

			if($type) $obj->setAttribute('type', $type);

			if(strlen($value) != 0) $obj->setAttribute('value', $value);

			return $obj;
		}

		public static function Textarea($name, $rows, $cols, $value=NULL, $attributes=NULL){
			$obj = new XMLElement('textarea', $value);

			$obj->setSelfClosingTag(false);

			$obj->setAttribute('name', $name);
			$obj->setAttribute('rows', $rows);
			$obj->setAttribute('cols', $cols);

			if(is_array($attributes) && !empty($attributes)){
				foreach($attributes as $key => $val)
					$obj->setAttribute($key, $val);
			}

			return $obj;
		}

		public static function Anchor($value, $href, $title=NULL, $class=NULL, $id=NULL){
			$a = new XMLElement('a', $value);
			$a->setAttribute('href', $href);

			if($title) $a->setAttribute('title', $title);
			if($class) $a->setAttribute('class', $class);
			if($id) $a->setAttribute('id', $id);

			return $a;
		}

		public static function Form($action, $method, $class=NULL, $id=NULL, $attributes=NULL){
			$form = new XMLElement('form');
			$form->setAttribute('action', $action);
			$form->setAttribute('method', $method);

			if(is_array($attributes) && !empty($attributes)){
				foreach($attributes as $key => $val)
					$form->setAttribute($key, $val);
			}

			if($class) $form->setAttribute('class', $class);
			if($id) $form->setAttribute('id', $id);

			return $form;
		}

		###
		# Simple way to create generic Symphony table wrapper
		public static function Table($head=NULL, $foot=NULL, $body=NULL, $class=NULL, $id=NULL){
 			$table = new XMLElement('table');

			if($class) $table->setAttribute('class', $class);
			if($id) $table->setAttribute('id', $id);

			if($head) $table->appendChild($head);
			if($foot) $table->appendChild($foot);
			if($body) $table->appendChild($body);

			return $table;
		}

		## Provided with an array of colum names, this will return an XML object
		public static function TableHead($array){

			$thead = new XMLElement('thead');
			$tr = new XMLElement('tr');

			foreach($array as $col){

				$th = new XMLElement('th');

				$value = $scope = $attr = NULL;

				$value = $col[0];
				if(isset($col[1])) $scope = $col[1];
				if(isset($col[2])) $attr = $col[2];

				if(is_object($value)) $th->appendChild($value);
				else $th->setValue($value);

				if($scope && $scope != '') $th->setAttribute('scope', $scope);

				if(is_array($attr) && !empty($attr)) $th->setAttributeArray($attr);

				$tr->appendChild($th);
			}

			$thead->appendChild($tr);

			return $thead;

		}

		public static function TableBody($rows, $class=NULL, $id=NULL){
			$tbody = new XMLElement('tbody');

			if($class) $tbody->setAttribute('class', $class);
			if($id) $tbody->setAttribute('id', $id);

			foreach($rows as $r) $tbody->appendChild($r);

			return $tbody;
		}

		public static function TableData($value, $class=NULL, $id=NULL, $colspan=NULL, array $attr=NULL){

			if(is_object($value)){
				$td = new XMLElement('td');
				$td->appendChild($value);
			}

			else $td = new XMLElement('td', $value);

			if($class) $td->setAttribute('class', $class);
			if($id) $td->setAttribute('id', $id);
			if($colspan) $td->setAttribute('colspan', $colspan);

			if($attr) $td->setAttributeArray($attr);

			return $td;
		}

		public static function TableRow($data, $class=NULL, $id=NULL, $rowspan=NULL){
			$tr = new XMLElement('tr');

			if($class) $tr->setAttribute('class', $class);
			if($id) $tr->setAttribute('id', $id);
			if($rowspan) $tr->setAttribute('rowspan', $rowspan);

			foreach($data as $d) $tr->appendChild($d);

			return $tr;
		}

		public static function Select($name, $options, $attributes=NULL){
			$obj = new XMLElement('select');
			$obj->setAttribute('name', $name);

			$obj->setSelfClosingTag(false);

			if(is_array($attributes) && !empty($attributes)){
				foreach($attributes as $key => $value)
					$obj->setAttribute($key, $value);
			}

			if(!is_array($options) || empty($options)){
				if(!isset($attributes['disabled'])) $obj->setAttribute('disabled', 'disabled');

				//$option = new XMLElement('option', ' ');
				//$option->setAttribute('value', '');
				//$obj->appendChild($option);

				return $obj;
			}

			foreach($options as $o){

				## Opt Group
				if(isset($o['label'])){

					$optgroup = new XMLElement('optgroup');
					$optgroup->setAttribute('label', $o['label']);

					foreach($o['options'] as $opt){
						$optgroup->appendChild(Widget::__SelectBuildOption($opt));
					}

					$obj->appendChild($optgroup);
				}

				## Non-Opt group
				else $obj->appendChild(Widget::__SelectBuildOption($o));

			}

			return $obj;
		}

		private static function __SelectBuildOption($option){

			@list($value, $selected, $desc, $class, $id, $attr) = $option;
			if(!$desc) $desc = $value;

			$obj = new XMLElement('option', "$desc");
			$obj->setSelfClosingTag(false);
			$obj->setAttribute('value', "$value");

			if(!empty($class)) $obj->setAttribute('class', $class);

			if(!empty($id)) $obj->setAttribute('id', $id);

			if(!empty($attr)) $obj->setAttributeArray($attr);

			if($selected) $obj->setAttribute('selected', 'selected');

			return $obj;

		}

		public static function wrapFormElementWithError($element, $message){
			$div = new XMLElement('div');
			$div->setAttributeArray(array('id' => 'error', 'class' => 'invalid'));

			$div->appendChild($element);
			$div->appendChild(new XMLElement('p', $message));

			return $div;

		}

	}


text:
public.prototype.attr = function(key, value)
{
    var output = [];

    // Loop through current elements
    this.forEach(this.elements, function(element)
    {
        // If no value is specified, return the current value of the attribute
        if(value === undefined)
        {
            output.push(element.getAttribute(key))
        }
        else
        {
            // If the value is true, create the attribute without any value
            if(value === true)
            {
                element.setAttribute(key, '');
            }
            // If the value is false, remove the attribute
            else if(value === false)
            {
                element.removeAttribute(key);
            }
            // Otherwise set the value as is
            else
            {
                element.setAttribute(key, value);
            }
        }
    });

    return this.returnAllOrOne(output, this);
}


text:
<?php

namespace Payum2\Heartland\Soap\Base;

/**
 * This class is generated from the following WSDL:
 * https://heartlandpaymentservices.net/BillingDataManagement/v3/BillingDataManagementService.svc?xsd=xsd2
 */
class ReversalAuthorizationRecord extends AuthorizationRecord
{
    /**
     * ReversalAmount
     *
     * The property has the following characteristics/restrictions:
     * - SchemaType: xs:decimal
     *
     * @var float
     */
    protected $ReversalAmount;

    /**
     * ReversalReferenceNumber
     *
     * The property has the following characteristics/restrictions:
     * - SchemaType: xs:string
     *
     * @var string
     */
    protected $ReversalReferenceNumber = null;

    /**
     * @param float $reversalAmount
     *
     * @return ReversalAuthorizationRecord
     */
    public function setReversalAmount($reversalAmount)
    {
        $this->ReversalAmount = $reversalAmount;

        return $this;
    }

    /**
     * @return float
     */
    public function getReversalAmount()
    {
        return $this->ReversalAmount;
    }

    /**
     * @param string $reversalReferenceNumber
     *
     * @return ReversalAuthorizationRecord
     */
    public function setReversalReferenceNumber($reversalReferenceNumber)
    {
        $this->ReversalReferenceNumber = $reversalReferenceNumber;

        return $this;
    }

    /**
     * @return string
     */
    public function getReversalReferenceNumber()
    {
        return $this->ReversalReferenceNumber;
    }
}


text:
package io.github.mandar2812.dynaml.examples

import breeze.linalg.{DenseMatrix, DenseVector}
import io.github.mandar2812.dynaml.evaluation.RegressionMetrics
import io.github.mandar2812.dynaml.kernels._
import io.github.mandar2812.dynaml.models.gp.GPRegression
import io.github.mandar2812.dynaml.optimization.{GPMLOptimizer, GridSearch}
import io.github.mandar2812.dynaml.pipes.{StreamDataPipe, DataPipe}
import io.github.mandar2812.dynaml.utils

/**
  * Created by mandar on 15/12/15.
  */
object TestGPHousing {

  def apply(kernel: CovarianceFunction[DenseVector[Double], Double, DenseMatrix[Double]],
            bandwidth: Double = 0.5, noise: Double = 0.0,
            trainFraction: Double = 0.75,
            columns: List[Int] = List(13,0,1,2,3,4,5,6,7,8,9,10,11,12),
            grid: Int = 5, step: Double = 0.2, globalOpt: String = "ML",
            stepSize: Double = 0.01, maxIt: Int = 300): Unit =
    runExperiment(kernel, bandwidth,
      noise, (506*trainFraction).toInt, columns,
      grid, step, globalOpt,
      Map("tolerance" -> "0.0001",
        "step" -> stepSize.toString,
        "maxIterations" -> maxIt.toString
      )
    )

  def apply(kern: String,
            bandwidth: Double, noise: Double,
            trainFraction: Double,
            columns: List[Int],
            grid: Int, step: Double, globalOpt: String,
            stepSize: Double, maxIt: Int): Unit = {

    val kernel: CovarianceFunction[DenseVector[Double], Double, DenseMatrix[Double]] =
      kern match {
        case "RBF" =>
          new RBFKernel(bandwidth)
        case "Cauchy" =>
          new CauchyKernel(bandwidth)
        case "Laplacian" =>
          new LaplacianKernel(bandwidth)
        case "RationalQuadratic" =>
          new RationalQuadraticKernel(bandwidth)
        case "FBM" => new FBMKernel(bandwidth)
        case "Student" => new TStudentKernel(bandwidth)
        case "Periodic" => new PeriodicKernel(bandwidth, bandwidth)
      }

    val num_training = 506*trainFraction

    runExperiment(kernel, bandwidth,
      noise, num_training.toInt, columns,
      grid, step, globalOpt,
      Map("tolerance" -> "0.0001",
        "step" -> stepSize.toString,
        "maxIterations" -> maxIt.toString
      )
    )

  }

  def runExperiment(kernel: CovarianceFunction[DenseVector[Double], Double, DenseMatrix[Double]],
                    bandwidth: Double = 0.5, noise: Double = 0.0,
                    num_training: Int = 200, columns: List[Int] = List(40,16,21,23,24,22,25),
                    grid: Int = 5, step: Double = 0.2,
                    globalOpt: String = "ML", opt: Map[String, String]): Unit = {

    //Load Housing data into a stream
    //Extract the time and Dst values
    //separate data into training and test
    //pipe training data to model and then generate test predictions
    //create RegressionMetrics instance and produce plots

    val replaceWhiteSpaces = (s: Stream[String]) => s.map(utils.replace("\\s+")(","))

    val extractTrainingFeatures = (l: Stream[String]) =>
      utils.extractColumns(l, ",", columns, Map())

    val normalizeData =
      (trainTest: (Stream[(DenseVector[Double], Double)], Stream[(DenseVector[Double], Double)])) => {

        val (mean, variance) = utils.getStats(trainTest._1.map(tup =>
          DenseVector(tup._1.toArray ++ Array(tup._2))).toList)

        val stdDev: DenseVector[Double] = variance.map(v =>
          math.sqrt(v/(trainTest._1.length.toDouble - 1.0)))

        val normalizationFunc = (point: (DenseVector[Double], Double)) => {
          val extendedpoint = DenseVector(point._1.toArray ++ Array(point._2))

          val normPoint = (extendedpoint - mean) :/ stdDev
          val length = normPoint.length
          (normPoint(0 until length-1), normPoint(-1))
        }

        ((trainTest._1.map(normalizationFunc),
          trainTest._2.map(normalizationFunc)), (mean, stdDev))
      }

    val modelTrainTest =
      (trainTest: ((Stream[(DenseVector[Double], Double)],
        Stream[(DenseVector[Double], Double)]),
        (DenseVector[Double], DenseVector[Double]))) => {
        val model = new GPRegression(kernel, trainTest._1._1.toSeq).setNoiseLevel(noise)

        val gs = globalOpt match {
          case "GS" => new GridSearch[model.type](model)
            .setGridSize(grid)
            .setStepSize(step)
            .setLogScale(false)

          case "ML" => new GPMLOptimizer[DenseVector[Double],
            Seq[(DenseVector[Double], Double)],
            GPRegression](model)
        }

        val startConf = kernel.state ++ Map("noiseLevel" -> noise)
        val (_, conf) = gs.optimize(kernel.state + ("noiseLevel" -> noise), opt)

        model.setState(conf)

        val res = model.test(trainTest._1._2.toSeq)
        val scoresAndLabelsPipe =
          DataPipe(
            (res: Seq[(DenseVector[Double], Double, Double, Double, Double)]) =>
              res.map(i => (i._3, i._2)).toList) > DataPipe((list: List[(Double, Double)]) =>
            list.map{l => (l._1*trainTest._2._2(-1) + trainTest._2._1(-1),
              l._2*trainTest._2._2(-1) + trainTest._2._1(-1))})

        val scoresAndLabels = scoresAndLabelsPipe.run(res)

        val metrics = new RegressionMetrics(scoresAndLabels,
          scoresAndLabels.length)

        //println(scoresAndLabels)
        metrics.print()
        metrics.generatePlots()
      }

    val preProcessPipe = DataPipe(utils.textFileToStream _) >
      DataPipe((s: Stream[String]) => s.map(_.trim())) >
      DataPipe(replaceWhiteSpaces) >
      DataPipe(extractTrainingFeatures) >
      StreamDataPipe((line: String) => {
        val split = line.split(",")
        (DenseVector(split.tail.map(_.toDouble)), split.head.toDouble)
      })

    val trainTestPipe = DataPipe(preProcessPipe, preProcessPipe) >
      DataPipe((data: (Stream[(DenseVector[Double], Double)],
        Stream[(DenseVector[Double], Double)])) => {
        (data._1.take(num_training.toInt), data._2.takeRight(506-num_training.toInt))
      }) >
      DataPipe(normalizeData) >
      DataPipe(modelTrainTest)

    trainTestPipe.run(("data/housing.data", "data/housing.data"))

  }

}


text:
package org.pac4j.core.authorization.authorizer;

import org.pac4j.core.context.WebContext;
import org.pac4j.core.profile.CommonProfile;

import java.util.List;

/**
 * XFrame options header.
 *
 * @author Jerome Leleu
 * @since 1.8.1
 */
public class XFrameOptionsHeader implements Authorizer<CommonProfile> {

    @Override
    public boolean isAuthorized(final WebContext context, final List<CommonProfile> profiles) {
        context.setResponseHeader("X-Frame-Options", "DENY");
        return true;
    }
}


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

    <string name="app_name">Androidtools</string>

</resources>


text:
package org.apache.giraph.conf;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.giraph.combiner.MessageCombiner;
import org.apache.giraph.comm.messages.MessageEncodeAndStoreType;
import org.apache.giraph.factories.DefaultMessageValueFactory;
import org.apache.giraph.factories.MessageValueFactory;
import org.apache.giraph.utils.ReflectionUtils;
import org.apache.giraph.utils.WritableUtils;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import com.google.common.base.Preconditions;

/**
 * Default implementation of MessageClasses
 *
 * @param <I> Vertex id type
 * @param <M> Message type
 */
public class DefaultMessageClasses
    <I extends WritableComparable, M extends Writable>
    implements MessageClasses<I, M> {
  /** message class */
  private Class<M> messageClass;
  /** message value factory class */
  private Class<? extends MessageValueFactory<M>>
  messageValueFactoryClass;
  /** message combiner class */
  private Class<? extends MessageCombiner<? super I, M>> messageCombinerClass;
  /** whether message class was manually modified in this superstep */
  private boolean messageClassModified;
  /** message encode and store type */
  private MessageEncodeAndStoreType messageEncodeAndStoreType;

  /** Constructor */
  public DefaultMessageClasses() {
  }

  /**
   * Constructor
   * @param messageClass message class
   * @param messageValueFactoryClass message value factory class
   * @param messageCombinerClass message combiner class
   * @param messageEncodeAndStoreType message encode and store type
   */
  public DefaultMessageClasses(
      Class<M> messageClass,
      Class<? extends MessageValueFactory<M>> messageValueFactoryClass,
      Class<? extends MessageCombiner<? super I, M>> messageCombinerClass,
        MessageEncodeAndStoreType messageEncodeAndStoreType) {
    this.messageClass = messageClass;
    this.messageValueFactoryClass = messageValueFactoryClass;
    this.messageCombinerClass = messageCombinerClass;
    this.messageClassModified = false;
    this.messageEncodeAndStoreType = messageEncodeAndStoreType;
  }

  @Override
  public Class<M> getMessageClass() {
    return messageClass;
  }

  @Override
  public MessageValueFactory<M> createMessageValueFactory(
      ImmutableClassesGiraphConfiguration conf) {
    if (messageValueFactoryClass.equals(DefaultMessageValueFactory.class)) {
      return new DefaultMessageValueFactory<>(messageClass, conf);
    }

    MessageValueFactory factory = ReflectionUtils.newInstance(
        messageValueFactoryClass, conf);
    if (!factory.newInstance().getClass().equals(messageClass)) {
      throw new IllegalStateException("Message factory " +
        messageValueFactoryClass + " creates " +
        factory.newInstance().getClass().getName() + ", but message type is " +
        messageClass.getName());
    }
    return factory;
  }

  @Override
  public MessageCombiner<? super I, M> createMessageCombiner(
      ImmutableClassesGiraphConfiguration conf) {
    if (messageCombinerClass == null) {
      return null;
    }

    MessageCombiner combiner =
        ReflectionUtils.newInstance(messageCombinerClass, conf);
    if (combiner != null) {
      Preconditions.checkState(
          combiner.createInitialMessage().getClass().equals(messageClass));
    }
    return combiner;
  }

  @Override
  public boolean useMessageCombiner() {
    return messageCombinerClass != null;
  }

  @Override
  public boolean ignoreExistingVertices() {
    return false;
  }

  @Override
  public MessageEncodeAndStoreType getMessageEncodeAndStoreType() {
    return messageEncodeAndStoreType;
  }

  @Override
  public MessageClasses<I, M> createCopyForNewSuperstep() {
    return new DefaultMessageClasses<>(messageClass, messageValueFactoryClass,
        messageCombinerClass, messageEncodeAndStoreType);
  }

  @Override
  public void verifyConsistent(
      ImmutableClassesGiraphConfiguration conf) {
    Class<?>[] factoryTypes = ReflectionUtils.getTypeArguments(
        MessageValueFactory.class, messageValueFactoryClass);
    ReflectionUtils.verifyTypes(messageClass, factoryTypes[0],
        "Message factory", messageValueFactoryClass);

    if (messageCombinerClass != null) {
      Class<?>[] combinerTypes = ReflectionUtils.getTypeArguments(
          MessageCombiner.class, messageCombinerClass);
      ReflectionUtils.verifyTypes(conf.getVertexIdClass(), combinerTypes[0],
          "Vertex id", messageCombinerClass);
      ReflectionUtils.verifyTypes(messageClass, combinerTypes[1],
          "Outgoing message", messageCombinerClass);
    }
  }

  /**
   * Set message class
   * @param messageClass message classs
   */
  public void setMessageClass(Class<M> messageClass) {
    this.messageClassModified = true;
    this.messageClass = messageClass;
  }

  /**
   * Set message class if not set already in this superstep
   * @param messageClass message class
   */
  public void setIfNotModifiedMessageClass(Class<M> messageClass) {
    if (!messageClassModified) {
      this.messageClass = messageClass;
    }
  }

  public void setMessageCombinerClass(
      Class<? extends MessageCombiner<? super I, M>> messageCombinerClass) {
    this.messageCombinerClass = messageCombinerClass;
  }

  public void setMessageValueFactoryClass(
      Class<? extends MessageValueFactory<M>> messageValueFactoryClass) {
    this.messageValueFactoryClass = messageValueFactoryClass;
  }

  public void setMessageEncodeAndStoreType(
      MessageEncodeAndStoreType messageEncodeAndStoreType) {
    this.messageEncodeAndStoreType = messageEncodeAndStoreType;
  }

  @Override
  public void write(DataOutput out) throws IOException {
    WritableUtils.writeClass(messageClass, out);
    WritableUtils.writeClass(messageValueFactoryClass, out);
    WritableUtils.writeClass(messageCombinerClass, out);
    out.writeBoolean(messageClassModified);
    out.writeByte(messageEncodeAndStoreType.ordinal());
  }

  @Override
  public void readFields(DataInput in) throws IOException {
    messageClass = WritableUtils.readClass(in);
    messageValueFactoryClass = WritableUtils.readClass(in);
    messageCombinerClass = WritableUtils.readClass(in);
    messageClassModified = in.readBoolean();
    messageEncodeAndStoreType =
        messageEncodeAndStoreType.values()[in.readByte()];
  }
}


text:
Writing new mailer backends
===========================

If you wish to implement an alternate method of sending email, you can do so by subclassing the
:class:`~asphalt.mailer.api.Mailer` class. There are two methods implementors typically override:

* :meth:`~asphalt.mailer.api.Mailer.start` (optional)
* :meth:`~asphalt.mailer.api.Mailer.deliver`

The ``start`` method is a coroutine that is called by the component from its own
:meth:`~asphalt.core.component.Component.start` method. You can handle any necessary resource
related setup there.

The ``deliver`` method must be overridden and needs to:

#. handle both a single :class:`~email.message.EmailMessage` and an iterable of them
#. remove any ``Bcc`` header from each message to avoid revealing the hidden recipients

If you want your mailer to be available as a backend for the
:class:`~asphalt.mailer.component.MailerComponent`, you need to add the corresponding entry point
for it. Suppose your mailer class is named ``AwesomeMailer``, lives in the package
``foo.bar.awesome`` and you want to give it the alias ``awesome``, add this line to your project's
``setup.py`` under the ``entrypoints`` argument in the ``asphalt.mailer.mailers`` namespace::

    setup(
        # (...other arguments...)
        entry_points={
            'asphalt.mailer.mailers': [
                'awesome = foo.bar.awesome:AwesomeMailer'
            ]
        }
    )


text:
// TypeScript Version: 2.0

/**
* Number of minutes in a day.
*
* @example
* var num = MINUTES_IN_DAY;
* // returns 1440
*/
declare const MINUTES_IN_DAY: number;

// EXPORTS //

export = MINUTES_IN_DAY;


text:
require 'spec_helper'

def sample_metadata_triples(subject_string="_:test")
  triples = <<-EOS
#{subject_string} <http://purl.org/dc/terms/title> "Sample title" .
#{subject_string} <http://purl.org/dc/terms/creator> "Sample, Example" .
#{subject_string} <http://purl.org/dc/terms/type> "Image" .
#{subject_string} <http://purl.org/dc/terms/type> "Still Image" .
#{subject_string} <http://purl.org/dc/terms/spatial> "Durham County (NC)" .
#{subject_string} <http://purl.org/dc/terms/spatial> "Durham (NC)" .
#{subject_string} <http://purl.org/dc/terms/date> "1981-01" .
#{subject_string} <http://purl.org/dc/terms/rights> "The copyright for these materials is unknown." .
#{subject_string} <http://library.duke.edu/metadata/terms/print_number> "12-345-6" .
#{subject_string} <http://library.duke.edu/metadata/terms/series> "Photographic Materials Series" .
#{subject_string} <http://library.duke.edu/metadata/terms/subseries> "Local Court House" .
EOS
end

def sample_mets_xml
  xml = <<-EOS
  <mets xmlns:duke="http://library.duke.edu/metadata/terms" xmlns:dcterms="http://purl.org/dc/terms" xmlns:xlink="http://www.w3.org/TR/xlink/" ID="abcd_efghi01003" TYPE="Resource:slideshow">
    <metsHdr>
      <agent ID="library" ROLE="CUSTODIAN">
        <name>Library</name>
      </agent>
    </metsHdr>
    <dmdSec ID="abcd_efghi01003">
      <mdWrap>
        <xmlData>
          <dcterms:title>Sample title</dcterms:title>
          <dcterms:creator>Sample, Example</dcterms:creator>
          <dcterms:type>Image</dcterms:type>
          <dcterms:type>Still Image</dcterms:type>
          <dcterms:spatial>Durham County (NC)</dcterms:spatial>
          <dcterms:spatial>Durham (NC)</dcterms:spatial>
          <dcterms:date>1981-01</dcterms:date>
          <dcterms:rights>The copyright for these materials is unknown.</dcterms:rights>
          <duke:print_number>12-345-6</duke:print_number>
          <duke:series>Photographic Materials Series</duke:series>
          <duke:subseries>Local Court House</duke:series>
        </xmlData>
      </mdWrap>
    </dmdSec>
  </mets>
  EOS
end

def sample_mets_with_element_attribute
  xml = <<-EOS
  <mets xmlns:duke="http://library.duke.edu/metadata/terms" xmlns:dcterms="http://purl.org/dc/terms" xmlns:xlink="http://www.w3.org/TR/xlink/" ID="abcd_efghi01003" TYPE="Resource:slideshow">
    <metsHdr>
      <agent ID="library" ROLE="CUSTODIAN">
        <name>Library</name>
      </agent>
    </metsHdr>
    <dmdSec ID="abcd_efghi01003">
      <mdWrap>
        <xmlData>
          <duke:dcmitype>Still Image</duke:dcmitype>
          <dcterms:extent unit="inches">12.5 in x 9.5 in</dcterms:extent>
          <dcterms:title>Document Title</dcterms:title>
          <dcterms:abstract>Document abstract.</dcterms:abstract>
        </xmlData>
      </mdWrap>
    </dmdSec>
  </mets>
  EOS
end

def sample_mets_with_unknown_duketerm
  xml = <<-EOS
  <mets xmlns:duke="http://library.duke.edu/metadata/terms" xmlns:dcterms="http://purl.org/dc/terms" xmlns:xlink="http://www.w3.org/TR/xlink/" ID="abcd_efghi01003" TYPE="Resource:slideshow">
    <metsHdr>
      <agent ID="library" ROLE="CUSTODIAN">
        <name>Library</name>
      </agent>
    </metsHdr>
    <dmdSec ID="abcd_efghi01003">
      <mdWrap>
        <xmlData>
          <duke:unknown>Still Image</duke:unknown>
          <dcterms:extent>12.5 in x 9.5 in</dcterms:extent>
          <dcterms:title>Document Title</dcterms:title>
          <dcterms:abstract>Document abstract.</dcterms:abstract>
        </xmlData>
      </mdWrap>
    </dmdSec>
  </mets>
  EOS
end

def sample_mets_with_no_namespace_element
  xml = <<-EOS
  <mets xmlns:duke="http://library.duke.edu/metadata/terms" xmlns:dcterms="http://purl.org/dc/terms" xmlns:xlink="http://www.w3.org/TR/xlink/" ID="abcd_efghi01003" TYPE="Resource:slideshow">
    <metsHdr>
      <agent ID="library" ROLE="CUSTODIAN">
        <name>Library</name>
      </agent>
    </metsHdr>
    <dmdSec ID="abcd_efghi01003">
      <mdWrap>
        <xmlData>
          <duke:dcmitype>Still Image</duke:dcmitype>
          <dcterms:extent>12.5 in x 9.5 in</dcterms:extent>
          <dcterms:title>Document Title</dcterms:title>
          <abstract>Document abstract.<abstract>
        </xmlData>
      </mdWrap>
    </dmdSec>
  </mets>
  EOS
end

def sample_mets_with_unknown_namespace
  xml = <<-EOS
  <mets xmlns:special="http://special.org/" xmlns:duke="http://library.duke.edu/metadata/terms" xmlns:dcterms="http://purl.org/dc/terms" xmlns:xlink="http://www.w3.org/TR/xlink/" ID="abcd_efghi01003" TYPE="Resource:slideshow">
    <metsHdr>
      <agent ID="library" ROLE="CUSTODIAN">
        <name>Library</name>
      </agent>
    </metsHdr>
    <dmdSec ID="abcd_efghi01003">
      <mdWrap>
        <xmlData>
          <duke:dcmitype>Still Image</duke:dcmitype>
          <special:extent>12.5 in x 9.5 in</special:extent>
          <dcterms:title>Document Title</dcterms:title>
          <dcterms:abstract>Document abstract.<dcterms:abstract>
        </xmlData>
      </mdWrap>
    </dmdSec>
  </mets>
  EOS
end

def sample_mets_with_invalid_namespace_href
  xml = <<-EOS
  <mets xmlns:duke="http://library.duke.edu/metadata/duketerms" xmlns:dcterms="http://purl.org/dc/terms" xmlns:xlink="http://www.w3.org/TR/xlink/" ID="abcd_efghi01003" TYPE="Resource:slideshow">
    <metsHdr>
      <agent ID="library" ROLE="CUSTODIAN">
        <name>Library</name>
      </agent>
    </metsHdr>
    <dmdSec ID="abcd_efghi01003">
      <mdWrap>
        <xmlData>
          <duke:dcmitype>Still Image</duke:dcmitype>
          <dcterms:extent>12.5 in x 9.5 in</dcterms:extent>
          <dcterms:title>Document Title</dcterms:title>
          <dcterms:abstract>Document abstract.</dcterms:abstract>
        </xmlData>
      </mdWrap>
    </dmdSec>
  </mets>
  EOS
end


text:
CGFloat degreesToRadians(CGFloat degrees) {
    return degrees * M_PI/180;
}

CGFloat radiansToDegrees(CGFloat radians) {
    return radians * 180 / M_PI;
}

@implementation UIView (SubView)

#pragma mark extendBottomWithSubview
-(void)_updateFramesForSubviewAtBottom:(UIView *)subview {
    CGFloat subViewNewY = self.frame.size.height;
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y,
                            self.frame.size.width, self.frame.size.height + subview.frame.size.height);
    subview.frame = CGRectMake(subview.frame.origin.x, subViewNewY,
                               subview.frame.size.width, subview.frame.size.height);

}

-(void)extendBottomWithSubview:(UIView *)subview {
    [self _updateFramesForSubviewAtBottom:subview];
    [self addSubview:subview];
}

-(void)extendBottomWithSubview:(UIView *)subview1 aboveSubview:(UIView *)subview2 {
    [self _updateFramesForSubviewAtBottom:subview1];
    [self insertSubview:subview1 aboveSubview:subview2];
}

-(void)extendBottomWithSubview:(UIView *)subview1 belowSubview:(UIView *)subview2 {
    [self _updateFramesForSubviewAtBottom:subview1];
    [self insertSubview:subview1 belowSubview:subview2];
}

-(void)extendBottomWithSubview:(UIView *)subview atIndex:(NSInteger)index {
    [self _updateFramesForSubviewAtBottom:subview];
    [self insertSubview:subview atIndex:index];
}

#pragma mark extendRightWithSubview
-(void)_updateFramesForSubviewAtRight:(UIView *)subview {
    subview.frame = CGRectMake(self.frame.size.width, subview.frame.origin.y,
                               subview.frame.size.width, subview.frame.size.height);

    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y,
                            self.frame.size.width + subview.frame.size.width, self.frame.size.height);
}

-(void)extendRightWithSubview:(UIView *)subview {
    [self _updateFramesForSubviewAtRight:subview];
    [self addSubview:subview];
}

-(void)extendRightWithSubview:(UIView *)subview1 aboveSubview:(UIView *)subview2 {
    [self _updateFramesForSubviewAtRight:subview1];
    [self insertSubview:subview1 aboveSubview:subview2];
}

-(void)extendRightWithSubview:(UIView *)subview1 belowSubview:(UIView *)subview2 {
    [self _updateFramesForSubviewAtRight:subview1];
    [self insertSubview:subview1 belowSubview:subview2];
}

-(void)extendRightWithSubview:(UIView *)subview atIndex:(NSInteger)index {
    [self _updateFramesForSubviewAtRight:subview];
    [self insertSubview:subview atIndex:index];
}

@end


text:
import brokkoly

import tasks  # NOQA

application = brokkoly.producer()


text:
> state: **closed** opened by: **elis47** on: **5/23/2017**

{% raw %}

<!-- Reviewable:start -->
This change is [<img src="https://reviewable.io/review_button.svg" height="34" align="absmiddle" alt="Reviewable"/>](https://reviewable.io/reviews/adrianharabula/condr/119)
<!-- Reviewable:end -->

{% endraw %}

### Comments

---
> from: [**adrianharabula**](https://github.com/adrianharabula/condr/pull/119#issuecomment-303291527) on: **5/23/2017**

{% raw %}

Reviewed 12 of 12 files at r1.
Review status: all files reviewed at latest revision, 3 unresolved discussions.

---

*[.gitignore, line 5 at r1](https://reviewable.io:443/reviews/adrianharabula/condr/119#-Kknfu1ei8P4YpRQNE74:-Kknfu1fsp5dpXgSHtTM:bhpwav7) ([raw file](https://github.com/adrianharabula/condr/blob/80e9356a5cc55018cdbf93771823b1cca2d3f516/.gitignore#L5)):*
> ```
> app/config/algolia\.php
>
> app/config/scout\.php
> ```

o să vedem aici cum facem cu fişierele de configurare. Trebuie pe cât posibil să evităm punerea datelor de autentificare pe git, dar în acelaşi timp fişierele astea ar trebui să fie pe git

---

*[app/app/Http/Controllers/GroupsController.php, line 28 at r1](https://reviewable.io:443/reviews/adrianharabula/condr/119#-KkngQC4DBHNxeAG-QYO:-KkngQC5hLbGZFTcHAI_:bo3kmwv) ([raw file](https://github.com/adrianharabula/condr/blob/80e9356a5cc55018cdbf93771823b1cca2d3f516/app/app/Http/Controllers/GroupsController.php#L28)):*
> ```PHP
>   function search(Request $request) {
>     $name = $request->group_name;
>     $groups = Group::search($name)->get();
> ```

uite ce frumos arată searchul :)

---

*[app/resources/views/addpreferences.blade.php, line 24 at r1](https://reviewable.io:443/reviews/adrianharabula/condr/119#-KkngZiJpedYrePCWiMW:-KkngZiJpedYrePCWiMX:btump5u) ([raw file](https://github.com/adrianharabula/condr/blob/80e9356a5cc55018cdbf93771823b1cca2d3f516/app/resources/views/addpreferences.blade.php#L24)):*
> ```PHP
>                 <div class="checkbox">
>                   <label>
>                     <input name="wanted" type="checkbox" value="">I want the following characteristics
> ```

ce legătură are asta cu modificările pentru search?

---

*Comments from [Reviewable](https://reviewable.io:443/reviews/adrianharabula/condr/119)*
<!-- Sent from Reviewable.io -->

{% endraw %}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Trionic5Tools;

namespace Trionic5Controls
{
    public partial class MapEditButton : DevExpress.XtraEditors.XtraUserControl
    {
        public delegate void NotifyMapOpenRequest(object sender, ShowSymbolEventArgs e);
        public event MapEditButton.NotifyMapOpenRequest onRequestMapDisplay;

        private frmMapSelect mapselect = null;
        private SymbolCollection _relevantsymbols = new SymbolCollection();

        public SymbolCollection Relevantsymbols
        {
            get { return _relevantsymbols; }
            set
            {
                _relevantsymbols = value;
                if (_relevantsymbols == null)
                {
                    _relevantsymbols = new SymbolCollection();
                    this.Enabled = false;
                }
                if (_relevantsymbols.Count == 0)
                {
                    this.Enabled = false;
                }
                else
                {
                    SymbolHelper sh_close = new SymbolHelper();
                    sh_close.Varname = "Close";
                    sh_close.Helptext = "Close";
                    _relevantsymbols.Add(sh_close);
                    this.Enabled = true;
                }
            }
        }

        public MapEditButton()
        {
            InitializeComponent();
        }

        private void btnMapChooser_Click(object sender, EventArgs e)
        {
            // show a little window with maps to choose from

            if (_relevantsymbols.Count > 0)
            {
                mapselect = new frmMapSelect();
                Point p2 = this.Parent.PointToScreen(this.Location);
                //Point p = PointToScreen(this.Location);
                p2.Offset(-mapselect.Width - 6, this.Height - mapselect.Height);
                mapselect.Location = p2;// PointToClient(p);
                mapselect.SetSymbolCollection(_relevantsymbols);
                mapselect.ShowDialog();
                //Console.WriteLine("Selected map after dialog: " + mapselect.SelectedMap);
                // let the main application know what map to display!
                if (mapselect.SelectedMap != "Close" && mapselect.SelectedMap != "")
                {
                    CastShowMapEvent(mapselect.SelectedMap);
                }

            }

        }

        private void CastShowMapEvent(string mapname)
        {
            if (onRequestMapDisplay != null)
            {
                onRequestMapDisplay(this, new ShowSymbolEventArgs(mapname));
            }
        }

        public class ShowSymbolEventArgs : System.EventArgs
        {

            private string _mapname;

            public string SymbolName
            {
                get
                {
                    return _mapname;
                }
            }

            public ShowSymbolEventArgs(string mapname)
            {
                this._mapname = mapname;
            }
        }
    }
}


text:
package com.sequenceiq.flow.reactor;

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

import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;
import com.sequenceiq.cloudbreak.eventbus.Event;
import com.sequenceiq.cloudbreak.logger.MDCBuilder;

/**
 * Event factory that registers an error handler into the event.
 */
@Service
public class ErrorHandlerAwareReactorEventFactory {

    public <P> Event<P> createEventWithErrHandler(P payLoad) {
        return createEventWithErrHandler(Maps.newHashMap(), payLoad);
    }

    public <P> Event<P> createEventWithErrHandler(Map<String, Object> headers, P payLoad) {
        Map<String, Object> extendedHeaders = new HashMap<>(headers);
        extendedHeaders.put(MDCBuilder.MDC_CONTEXT_ID, MDCBuilder.getMdcContextMap());
        return new Event<>(new Event.Headers(extendedHeaders), payLoad);
    }

    public <P> Event<P> createEvent(P payLoad) {
        return createEvent(Maps.newHashMap(), payLoad);
    }

    public <P> Event<P> createEvent(Map<String, Object> headers, P payLoad) {
        Map<String, Object> extendedHeaders = new HashMap<>(headers);
        extendedHeaders.put(MDCBuilder.MDC_CONTEXT_ID, MDCBuilder.getMdcContextMap());
        return new Event<>(new Event.Headers(extendedHeaders), payLoad);
    }
}


text: @import"test.css"


text:
<?php
class Membership_model extends CI_Model{

	public function validate(){
		$this->db->where('email',$this->input->post('email'));
		$this->db->where('password',md5($this->input->post('password')));
		$query_result = $this->db->get('author');
		return $query_result->num_rows();
	}
	public function create_member(){
		$new_member_insert_data = array(
			'name'=>$this->input->post('name'),
			'email'=>$this->input->post('email'),
			'password'=>md5($this->input->post('password')),
			'dob'=>$this->input->post('dob')
		);
		$insert = $this->db->insert('author',$new_member_insert_data);
		return $insert;
	}
	public function check_if_email_exists($email){
		$this->db->where('email',$email);
		$result=$this->db->get('author');
		if($result->num_rows()>0){
			return FALSE; //Email id exists
		} else {
			return TRUE;
		}
	}
}
?>


text:
package structs

import (
	"time"
)

// PersonMetrics has all data about a single person, including a list of measurements (body metrics)
type PersonMetrics struct {
	Person      int
	Gender      string
	Age         int
	Size        int
	Activity    string
	Updated     bool
	BodyMetrics map[int]BodyMetric
}

// BodyMetrics is shorthand for a list of BodyMetrics
type BodyMetrics []BodyMetric

// BodyMetric is a single tuple of measurements for a given person
type BodyMetric struct {
	Timestamp int
	Weight    float32
	Fat       float32
	Muscle    float32
	Bone      float32
	Tbw       float32
	Kcal      int
	Bmi       float32
}

// AnnotatedBodyMetric contains the values of BodyMetric plus some custom annotations plugins to show
type AnnotatedBodyMetric struct {
	BodyMetric  BodyMetric
	Annotations BodyMetricAnnotations
}

// BodyMetricAnnotations contains annotations to a given BodyMetric
type BodyMetricAnnotations struct {
	Time        time.Time
	DeltaWeight float32
	DeltaFat    float32
	DeltaMuscle float32
	DeltaBone   float32
	DeltaTbw    float32
	DeltaKcal   int
	DeltaBmi    float32
}

// Person contains some fairly static data about a person
type Person struct {
	Valid    bool
	Person   int
	Gender   string
	Age      int
	Size     int
	Activity string
}

// Weight contains a single weight measurement for a person
type Weight struct {
	Valid     bool
	Weight    float32
	Timestamp int
	Person    int
}

// Body contains a secondary measurements for a person
type Body struct {
	Valid     bool
	Timestamp int
	Person    int
	Kcal      int
	Fat       float32
	Tbw       float32
	Muscle    float32
	Bone      float32
}

// PartialMetric contains either type of measurement sent by the scale
type PartialMetric struct {
	Person Person
	Weight Weight
	Body   Body
}

// Plugin interface describes what a plugin should implement
type Plugin interface {
	Initialize(c Config) Plugin
	ParseData(person *PersonMetrics) bool
}

// Config contains the configuration for the application
type Config struct {
	Device       string
	ScanDuration duration
	DeviceID     string
	Sub          duration
	CsvDir       string
	TimeOffset   int
	Fakeit       bool
	Plugins      map[string]PluginConfig
}

// PluginConfig contains any possible Plugin configuration
type PluginConfig struct {
	Server        string
	SenderName    string
	SenderAddress string
	TemplateFile  string
	Subject       string
	Metrics       int
	Dir           string
	StartTLS      bool
	Recipients    map[string]MailRecipient
}

// MailRecipient contains a person's name and a list of mail addresses to get updates
type MailRecipient struct {
	Name    string
	Address []string
}

type duration struct {
	time.Duration
}

func (d *duration) UnmarshalText(text []byte) error {
	var err error
	d.Duration, err = time.ParseDuration(string(text))
	return err
}
func (d duration) AsTimeDuration() time.Duration {
	return d.Duration
}


text:
namespace arangodb {

namespace aql {
struct Collection;
class Condition;
class ExecutionBlock;
class ExecutionEngine;
class ExecutionPlan;
class Expression;
class Projections;
template<typename T> struct RegisterPlanT;
using RegisterPlan = RegisterPlanT<ExecutionNode>;

/// @brief struct to hold the member-indexes in the _condition node
struct NonConstExpression {
  std::unique_ptr<Expression> expression;
  std::vector<size_t> const indexPath;

  NonConstExpression(std::unique_ptr<Expression> exp, std::vector<size_t>&& idxPath);
};

/// @brief class IndexNode
class IndexNode : public ExecutionNode, public DocumentProducingNode, public CollectionAccessingNode {
  friend class ExecutionBlock;

 public:
  IndexNode(ExecutionPlan* plan, ExecutionNodeId id, aql::Collection const* collection,
            Variable const* outVariable,
            std::vector<transaction::Methods::IndexHandle> const& indexes,
            std::unique_ptr<Condition> condition, IndexIteratorOptions const&);

  IndexNode(ExecutionPlan*, arangodb::velocypack::Slice const& base);

  ~IndexNode() override;

  /// @brief return the type of the node
  NodeType getType() const override final;

  /// @brief return the condition for the node
  Condition* condition() const;

  /// @brief whether or not all indexes are accessed in reverse order
  IndexIteratorOptions options() const;

  /// @brief set reverse mode
  void setAscending(bool value);

  /// @brief whether or not the index node needs a post sort of the results
  /// of multiple shards in the cluster (via a GatherNode).
  /// not all queries that use an index will need to produce a sorted result
  /// (e.g. if the index is used only for filtering)
  bool needsGatherNodeSort() const;
  void needsGatherNodeSort(bool value);

  /// @brief export to VelocyPack
  void toVelocyPackHelper(arangodb::velocypack::Builder&, unsigned flags,
                          std::unordered_set<ExecutionNode const*>& seen) const override final;

  /// @brief creates corresponding ExecutionBlock
  std::unique_ptr<ExecutionBlock> createBlock(
      ExecutionEngine& engine,
      std::unordered_map<ExecutionNode*, ExecutionBlock*> const&) const override;

  /// @brief clone ExecutionNode recursively
  ExecutionNode* clone(ExecutionPlan* plan, bool withDependencies,
                       bool withProperties) const override final;

  /// @brief getVariablesSetHere
  std::vector<Variable const*> getVariablesSetHere() const override final;

  /// @brief getVariablesUsedHere, modifying the set in-place
  void getVariablesUsedHere(VarSet& vars) const override final;

  /// @brief estimateCost
  CostEstimate estimateCost() const override final;

  /// @brief getIndexes, hand out the indexes used
  std::vector<transaction::Methods::IndexHandle> const& getIndexes() const;

  bool isLateMaterialized() const noexcept {
    TRI_ASSERT((_outNonMaterializedDocId == nullptr && _outNonMaterializedIndVars.second.empty()) ||
               !(_outNonMaterializedDocId == nullptr || _outNonMaterializedIndVars.second.empty()));
    return !_outNonMaterializedIndVars.second.empty();
  }

  bool canApplyLateDocumentMaterializationRule() const {
    return isProduceResult() && !_projections.supportsCoveringIndex();
  }

  struct IndexVariable {
    size_t indexFieldNum;
    Variable const* var;
  };

  using IndexValuesVars =
      std::pair<IndexId, std::unordered_map<Variable const*, size_t>>;

  using IndexValuesRegisters = std::pair<IndexId, std::unordered_map<size_t, RegisterId>>;

  using IndexVarsInfo = std::unordered_map<std::vector<arangodb::basics::AttributeName> const*, IndexVariable>;

  void setLateMaterialized(aql::Variable const* docIdVariable, IndexId commonIndexId,
                           IndexVarsInfo const& indexVariables);

  void setProjections(arangodb::aql::Projections projections);

 private:
  void initializeOnce(bool& hasV8Expression, std::vector<Variable const*>& inVars,
                      std::vector<RegisterId>& inRegs,
                      std::vector<std::unique_ptr<NonConstExpression>>& nonConstExpressions) const;

  bool isProduceResult() const {
    return (isVarUsedLater(_outVariable) || _filter != nullptr) && !doCount();
  }

  /// @brief adds a UNIQUE() to a dynamic IN condition
  arangodb::aql::AstNode* makeUnique(arangodb::aql::AstNode*) const;

 private:
  /// @brief the index
  std::vector<transaction::Methods::IndexHandle> _indexes;

  /// @brief the index(es) condition
  std::unique_ptr<Condition> _condition;

  /// @brief the index sort order - this is the same order for all indexes
  bool _needsGatherNodeSort;

  /// @brief the index iterator options - same for all indexes
  IndexIteratorOptions _options;

  /// @brief output variable to write only non-materialized document ids
  aql::Variable const* _outNonMaterializedDocId;

  /// @brief output variables to non-materialized document index references
  IndexValuesVars _outNonMaterializedIndVars;
};

}  // namespace aql
}  // namespace arangodb


text:
import React, { Component, PropTypes } from 'react';

import ColumnSetupRow from './ColumnSetupRow';

class ColumnSetup extends Component {
  constructor() {
    super();

    this.state = {
      states: [],
      labels: [],
      availableStates: [],
      canAdd: true
    };
  }

  componentWillMount() {
    this.setState({
      states: this.props.states || [],
      labels: this.props.labels || [],
      availableStates: this.props.availableStates
    });
  }

  handleRowChange(index, type, value, isDelete, isTypeChange) {
    let states = this.props.states;
    let labels = this.props.labels;

    if (isTypeChange === true) {
      if (type === "state") {
        labels.splice(index);
        states.push(value);
      } else {
        states.splice(index);
        labels.push(value);
      }
    } else if (type === "state") {
      if (isDelete) {
        states.splice(index, 1);
      } else {
        states[index] = value;
      }
    } else {
      if (isDelete) {
        labels.splice(index, 1);
      } else {
        labels[index] = value;
      }
    }

    this.setState({
      labels: labels,
      states: states,
      canAdd: isDelete || value.length > 0
    });

    this.props.callback(this.props.id, states, labels);
  }

  handleAddClick() {
    if (this.props.availableStates.length > 0) {
      let states = this.props.states;

      states.push(this.props.availableStates[0]);

      this.setState({ states: states });
    } else {
      let labels = this.props.labels;

      labels.push("");

      this.setState({ labels: labels, canAdd: false });
    }

    this.props.callback(this.props.id, this.props.states, this.props.labels);
  }

  render() {
    const states = this.props.states;
    let stateRows = [];
    const labels = this.props.labels;
    let labelRows = [];
    const availableStates = this.props.availableStates;
    let addButton;

    states.forEach((state, index) => {
      stateRows.push(<ColumnSetupRow key={index} id={index} type="state"
        options={availableStates} value={state}
        callback={this.handleRowChange.bind(this)} />);
    });

    labels.forEach((label, index) => {
      labelRows.push(<ColumnSetupRow key={index} id={index} type="label"
        options={availableStates} value={label}
        callback={this.handleRowChange.bind(this)} />);
    });

    if (this.state.canAdd) {
      addButton = (<button onClick={this.handleAddClick.bind(this)}>
        Add Row</button>);
    } else {
      addButton = <button disabled>Add Row</button>;
    }

    return (<fieldset className="settings__columnsetup__row__rules">

Column Rules

      {labelRows}
      {stateRows}
      {addButton}
    </fieldset>);
  }
}

ColumnSetup.propTypes = {
  states: PropTypes.array,
  labels: PropTypes.array,
  availableStates: PropTypes.array.isRequired,
  callback: PropTypes.func.isRequired,
  id: PropTypes.number.isRequired
};

export default ColumnSetup;


text:
<AML>
 <Item type="Method" id="BEE17CF9F1C54D68AC5264CD4E1F2E5E" action="edit">
  <execution_allowed_to keyed_name="World" type="Identity">A73B655731924CD0B027E4F4D5FCC0A9</execution_allowed_to>
  <method_code><![CDATA[' Build Dashboard
' Generic server method that takes the name of a dashboard item as a parameter and returns
'  chart xml.  Called from dashboard.html.

' Load the Dashboard query, getting only the necessary information
Dim aml As String = _
  "<Item type='Dashboard' action='get' select='background_style,width,height'>" & _
  "  <name>" & Me.getProperty("DashboardName") & "</name>" & _
  "  <Relationships>" & _
  "    <Item type='Dashboard Chart' action='get' select='related_id,x,y'>" & _
  "      <related_id>" & _
  "        <Item type='Chart' action='get'>" & _
  "          <Relationships>" & _
  "            <Item type='Chart Series' action='get' select='related_id,sort_order,markers'>" & _
  "              <related_id>" & _
  "                <Item type='Metric' action='get' select='label,color,pattern,link,stylesheet,method'>" & _
  "                  <Relationships>" & _
  "                    <Item type='Metric Value' action='get' select='sort_order,value,color,link,label,calculate,query,source_id'/>" & _
  "                  </Relationships>" & _
  "                </Item>" & _
  "              </related_id>" & _
  "            </Item>" & _
  "          </Relationships>" & _
  "        </Item>" & _
  "      </related_id>" & _
  "    </Item>" & _
  "  </Relationships>" & _
  "</Item>"

Dim innovator As Innovator = Me.getInnovator()
Dim dashItem As Item = Me.newItem()
dashItem.loadAML(aml)
' Run the dashboard query
dashItem = dashItem.apply()

' Check for an error or for a lack of Metric Value items (see IR-003972)
If (dashItem.isError() OrElse dashItem.dom.selectSingleNode("//Item[@type='Metric Value']") Is Nothing) Then
 Return innovator.newError(dashItem.getErrorDetail())
End If

' Transform to the chart format
Dim chart As Item = Me.newItem()
chart.dom.LoadXml(dashItem.applyStylesheet(CCO.Server.MapPath("styles/aml2chart.xsl"),"URL"))

' Check for errors in the chart dom
If chart.dom.selectSingleNode("//palette") Is Nothing Then
 Return innovator.newError("Error building chart setup information")
Else
 Return chart
End If]]></method_code>
  <method_type>VB</method_type>
  <name>Build Dashboard</name>
 </Item>
</AML>


text:
package org.apache.kafka.common.errors;

/**
 * Indicates that a consumer group is already at its configured maximum capacity and cannot accommodate more members
 */
public class GroupMaxSizeReachedException extends ApiException {
    private static final long serialVersionUID = 1L;

    public GroupMaxSizeReachedException(String message) {
        super(message);
    }
}