text:
package org.springframework.expression.spel.ast;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;

import org.springframework.asm.MethodVisitor;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.expression.AccessException;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.PropertyAccessor;
import org.springframework.expression.TypeConverter;
import org.springframework.expression.TypedValue;
import org.springframework.expression.spel.CodeFlow;
import org.springframework.expression.spel.ExpressionState;
import org.springframework.expression.spel.SpelEvaluationException;
import org.springframework.expression.spel.SpelMessage;
import org.springframework.expression.spel.support.ReflectivePropertyAccessor;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;

/**
 * An Indexer can index into some proceeding structure to access a particular piece of it.
 * Supported structures are: strings / collections (lists/sets) / arrays.
 *
 * @author Andy Clement
 * @author Phillip Webb
 * @author Stephane Nicoll
 * @author Sam Brannen
 * @since 3.0
 */
// TODO support multidimensional arrays
// TODO support correct syntax for multidimensional [][][] and not [,,,]
public class Indexer extends SpelNodeImpl {

	private enum IndexedType {ARRAY, LIST, MAP, STRING, OBJECT}

	// These fields are used when the indexer is being used as a property read accessor.
	// If the name and target type match these cached values then the cachedReadAccessor
	// is used to read the property. If they do not match, the correct accessor is
	// discovered and then cached for later use.

	@Nullable
	private String cachedReadName;

	@Nullable
	private Class<?> cachedReadTargetType;

	@Nullable
	private PropertyAccessor cachedReadAccessor;

	// These fields are used when the indexer is being used as a property write accessor.
	// If the name and target type match these cached values then the cachedWriteAccessor
	// is used to write the property. If they do not match, the correct accessor is
	// discovered and then cached for later use.

	@Nullable
	private String cachedWriteName;

	@Nullable
	private Class<?> cachedWriteTargetType;

	@Nullable
	private PropertyAccessor cachedWriteAccessor;

	@Nullable
	private IndexedType indexedType;

	public Indexer(int startPos, int endPos, SpelNodeImpl expr) {
		super(startPos, endPos, expr);
	}

	@Override
	public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
		return getValueRef(state).getValue();
	}

	@Override
	public void setValue(ExpressionState state, @Nullable Object newValue) throws EvaluationException {
		getValueRef(state).setValue(newValue);
	}

	@Override
	public boolean isWritable(ExpressionState expressionState) throws SpelEvaluationException {
		return true;
	}

	@Override
	protected ValueRef getValueRef(ExpressionState state) throws EvaluationException {
		TypedValue context = state.getActiveContextObject();
		Object target = context.getValue();
		TypeDescriptor targetDescriptor = context.getTypeDescriptor();
		TypedValue indexValue;
		Object index;

		// This first part of the if clause prevents a 'double dereference' of the property (SPR-5847)
		if (target instanceof Map && (this.children[0] instanceof PropertyOrFieldReference reference)) {
			index = reference.getName();
			indexValue = new TypedValue(index);
		}
		else {
			// In case the map key is unqualified, we want it evaluated against the root object
			// so temporarily push that on whilst evaluating the key
			try {
				state.pushActiveContextObject(state.getRootContextObject());
				indexValue = this.children[0].getValueInternal(state);
				index = indexValue.getValue();
				Assert.state(index != null, "No index");
			}
			finally {
				state.popActiveContextObject();
			}
		}

		// Raise a proper exception in case of a null target
		if (target == null) {
			throw new SpelEvaluationException(getStartPosition(), SpelMessage.CANNOT_INDEX_INTO_NULL_VALUE);
		}
		// At this point, we need a TypeDescriptor for a non-null target object
		Assert.state(targetDescriptor != null, "No type descriptor");

		// Indexing into a Map
		if (target instanceof Map<?, ?> map) {
			Object key = index;
			if (targetDescriptor.getMapKeyTypeDescriptor() != null) {
				key = state.convertValue(key, targetDescriptor.getMapKeyTypeDescriptor());
			}
			this.indexedType = IndexedType.MAP;
			return new MapIndexingValueRef(state.getTypeConverter(), map, key, targetDescriptor);
		}

		// If the object is something that looks indexable by an integer,
		// attempt to treat the index value as a number
		if (target.getClass().isArray() || target instanceof Collection || target instanceof String) {
			int idx = (Integer) state.convertValue(index, TypeDescriptor.valueOf(Integer.class));
			if (target.getClass().isArray()) {
				this.indexedType = IndexedType.ARRAY;
				return new ArrayIndexingValueRef(state.getTypeConverter(), target, idx, targetDescriptor);
			}
			else if (target instanceof Collection) {
				if (target instanceof List) {
					this.indexedType = IndexedType.LIST;
				}
				return new CollectionIndexingValueRef((Collection<?>) target, idx, targetDescriptor,
						state.getTypeConverter(), state.getConfiguration().isAutoGrowCollections(),
						state.getConfiguration().getMaximumAutoGrowSize());
			}
			else {
				this.indexedType = IndexedType.STRING;
				return new StringIndexingLValue((String) target, idx, targetDescriptor);
			}
		}

		// Try and treat the index value as a property of the context object
		// TODO: could call the conversion service to convert the value to a String
		TypeDescriptor valueType = indexValue.getTypeDescriptor();
		if (valueType != null && String.class == valueType.getType()) {
			this.indexedType = IndexedType.OBJECT;
			return new PropertyIndexingValueRef(
					target, (String) index, state.getEvaluationContext(), targetDescriptor);
		}

		throw new SpelEvaluationException(
				getStartPosition(), SpelMessage.INDEXING_NOT_SUPPORTED_FOR_TYPE, targetDescriptor);
	}

	@Override
	public boolean isCompilable() {
		if (this.indexedType == IndexedType.ARRAY) {
			return (this.exitTypeDescriptor != null);
		}
		else if (this.indexedType == IndexedType.LIST) {
			return this.children[0].isCompilable();
		}
		else if (this.indexedType == IndexedType.MAP) {
			return (this.children[0] instanceof PropertyOrFieldReference || this.children[0].isCompilable());
		}
		else if (this.indexedType == IndexedType.OBJECT) {
			// If the string name is changing the accessor is clearly going to change (so no compilation possible)
			return (this.cachedReadAccessor != null &&
					this.cachedReadAccessor instanceof ReflectivePropertyAccessor.OptimalPropertyAccessor &&
					getChild(0) instanceof StringLiteral);
		}
		return false;
	}

	@Override
	public void generateCode(MethodVisitor mv, CodeFlow cf) {
		String descriptor = cf.lastDescriptor();
		if (descriptor == null) {
			// Stack is empty, should use context object
			cf.loadTarget(mv);
		}

		if (this.indexedType == IndexedType.ARRAY) {
			int insn;
			if ("D".equals(this.exitTypeDescriptor)) {
				mv.visitTypeInsn(CHECKCAST, "[D");
				insn = DALOAD;
			}
			else if ("F".equals(this.exitTypeDescriptor)) {
				mv.visitTypeInsn(CHECKCAST, "[F");
				insn = FALOAD;
			}
			else if ("J".equals(this.exitTypeDescriptor)) {
				mv.visitTypeInsn(CHECKCAST, "[J");
				insn = LALOAD;
			}
			else if ("I".equals(this.exitTypeDescriptor)) {
				mv.visitTypeInsn(CHECKCAST, "[I");
				insn = IALOAD;
			}
			else if ("S".equals(this.exitTypeDescriptor)) {
				mv.visitTypeInsn(CHECKCAST, "[S");
				insn = SALOAD;
			}
			else if ("B".equals(this.exitTypeDescriptor)) {
				mv.visitTypeInsn(CHECKCAST, "[B");
				insn = BALOAD;
			}
			else if ("C".equals(this.exitTypeDescriptor)) {
				mv.visitTypeInsn(CHECKCAST, "[C");
				insn = CALOAD;
			}
			else {
				mv.visitTypeInsn(CHECKCAST, "["+ this.exitTypeDescriptor +
						(CodeFlow.isPrimitiveArray(this.exitTypeDescriptor) ? "" : ";"));
						//depthPlusOne(exitTypeDescriptor)+"Ljava/lang/Object;");
				insn = AALOAD;
			}
			SpelNodeImpl index = this.children[0];
			cf.enterCompilationScope();
			index.generateCode(mv, cf);
			cf.exitCompilationScope();
			mv.visitInsn(insn);
		}

		else if (this.indexedType == IndexedType.LIST) {
			mv.visitTypeInsn(CHECKCAST, "java/util/List");
			cf.enterCompilationScope();
			this.children[0].generateCode(mv, cf);
			cf.exitCompilationScope();
			mv.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "get", "(I)Ljava/lang/Object;", true);
		}

		else if (this.indexedType == IndexedType.MAP) {
			mv.visitTypeInsn(CHECKCAST, "java/util/Map");
			// Special case when the key is an unquoted string literal that will be parsed as
			// a property/field reference
			if ((this.children[0] instanceof PropertyOrFieldReference reference)) {
				String mapKeyName = reference.getName();
				mv.visitLdcInsn(mapKeyName);
			}
			else {
				cf.enterCompilationScope();
				this.children[0].generateCode(mv, cf);
				cf.exitCompilationScope();
			}
			mv.visitMethodInsn(
					INVOKEINTERFACE, "java/util/Map", "get", "(Ljava/lang/Object;)Ljava/lang/Object;", true);
		}

		else if (this.indexedType == IndexedType.OBJECT) {
			ReflectivePropertyAccessor.OptimalPropertyAccessor accessor =
					(ReflectivePropertyAccessor.OptimalPropertyAccessor) this.cachedReadAccessor;
			Assert.state(accessor != null, "No cached read accessor");
			Member member = accessor.member;
			boolean isStatic = Modifier.isStatic(member.getModifiers());
			String classDesc = member.getDeclaringClass().getName().replace('.', '/');

			if (!isStatic) {
				if (descriptor == null) {
					cf.loadTarget(mv);
				}
				if (descriptor == null || !classDesc.equals(descriptor.substring(1))) {
					mv.visitTypeInsn(CHECKCAST, classDesc);
				}
			}

			if (member instanceof Method method) {
				mv.visitMethodInsn((isStatic? INVOKESTATIC : INVOKEVIRTUAL), classDesc, member.getName(),
						CodeFlow.createSignatureDescriptor(method), false);
			}
			else {
				mv.visitFieldInsn((isStatic ? GETSTATIC : GETFIELD), classDesc, member.getName(),
						CodeFlow.toJvmDescriptor(((Field) member).getType()));
			}
		}

		cf.pushDescriptor(this.exitTypeDescriptor);
	}

	@Override
	public String toStringAST() {
		StringJoiner sj = new StringJoiner(",", "[", "]");
		for (int i = 0; i < getChildCount(); i++) {
			sj.add(getChild(i).toStringAST());
		}
		return sj.toString();
	}

	private void setArrayElement(TypeConverter converter, Object ctx, int idx, @Nullable Object newValue,
			Class<?> arrayComponentType) throws EvaluationException {

		if (arrayComponentType == Boolean.TYPE) {
			boolean[] array = (boolean[]) ctx;
			checkAccess(array.length, idx);
			array[idx] = convertValue(converter, newValue, Boolean.class);
		}
		else if (arrayComponentType == Byte.TYPE) {
			byte[] array = (byte[]) ctx;
			checkAccess(array.length, idx);
			array[idx] = convertValue(converter, newValue, Byte.class);
		}
		else if (arrayComponentType == Character.TYPE) {
			char[] array = (char[]) ctx;
			checkAccess(array.length, idx);
			array[idx] = convertValue(converter, newValue, Character.class);
		}
		else if (arrayComponentType == Double.TYPE) {
			double[] array = (double[]) ctx;
			checkAccess(array.length, idx);
			array[idx] = convertValue(converter, newValue, Double.class);
		}
		else if (arrayComponentType == Float.TYPE) {
			float[] array = (float[]) ctx;
			checkAccess(array.length, idx);
			array[idx] = convertValue(converter, newValue, Float.class);
		}
		else if (arrayComponentType == Integer.TYPE) {
			int[] array = (int[]) ctx;
			checkAccess(array.length, idx);
			array[idx] = convertValue(converter, newValue, Integer.class);
		}
		else if (arrayComponentType == Long.TYPE) {
			long[] array = (long[]) ctx;
			checkAccess(array.length, idx);
			array[idx] = convertValue(converter, newValue, Long.class);
		}
		else if (arrayComponentType == Short.TYPE) {
			short[] array = (short[]) ctx;
			checkAccess(array.length, idx);
			array[idx] = convertValue(converter, newValue, Short.class);
		}
		else {
			Object[] array = (Object[]) ctx;
			checkAccess(array.length, idx);
			array[idx] = convertValue(converter, newValue, arrayComponentType);
		}
	}

	private Object accessArrayElement(Object ctx, int idx) throws SpelEvaluationException {
		Class<?> arrayComponentType = ctx.getClass().getComponentType();
		if (arrayComponentType == Boolean.TYPE) {
			boolean[] array = (boolean[]) ctx;
			checkAccess(array.length, idx);
			this.exitTypeDescriptor = "Z";
			return array[idx];
		}
		else if (arrayComponentType == Byte.TYPE) {
			byte[] array = (byte[]) ctx;
			checkAccess(array.length, idx);
			this.exitTypeDescriptor = "B";
			return array[idx];
		}
		else if (arrayComponentType == Character.TYPE) {
			char[] array = (char[]) ctx;
			checkAccess(array.length, idx);
			this.exitTypeDescriptor = "C";
			return array[idx];
		}
		else if (arrayComponentType == Double.TYPE) {
			double[] array = (double[]) ctx;
			checkAccess(array.length, idx);
			this.exitTypeDescriptor = "D";
			return array[idx];
		}
		else if (arrayComponentType == Float.TYPE) {
			float[] array = (float[]) ctx;
			checkAccess(array.length, idx);
			this.exitTypeDescriptor = "F";
			return array[idx];
		}
		else if (arrayComponentType == Integer.TYPE) {
			int[] array = (int[]) ctx;
			checkAccess(array.length, idx);
			this.exitTypeDescriptor = "I";
			return array[idx];
		}
		else if (arrayComponentType == Long.TYPE) {
			long[] array = (long[]) ctx;
			checkAccess(array.length, idx);
			this.exitTypeDescriptor = "J";
			return array[idx];
		}
		else if (arrayComponentType == Short.TYPE) {
			short[] array = (short[]) ctx;
			checkAccess(array.length, idx);
			this.exitTypeDescriptor = "S";
			return array[idx];
		}
		else {
			Object[] array = (Object[]) ctx;
			checkAccess(array.length, idx);
			Object retValue = array[idx];
			this.exitTypeDescriptor = CodeFlow.toDescriptor(arrayComponentType);
			return retValue;
		}
	}

	private void checkAccess(int arrayLength, int index) throws SpelEvaluationException {
		if (index >= arrayLength) {
			throw new SpelEvaluationException(getStartPosition(), SpelMessage.ARRAY_INDEX_OUT_OF_BOUNDS,
					arrayLength, index);
		}
	}

	@SuppressWarnings("unchecked")
	private <T> T convertValue(TypeConverter converter, @Nullable Object value, Class<T> targetType) {
		T result = (T) converter.convertValue(
				value, TypeDescriptor.forObject(value), TypeDescriptor.valueOf(targetType));
		if (result == null) {
			throw new IllegalStateException("Null conversion result for index [" + value + "]");
		}
		return result;
	}

	private class ArrayIndexingValueRef implements ValueRef {

		private final TypeConverter typeConverter;

		private final Object array;

		private final int index;

		private final TypeDescriptor typeDescriptor;

		ArrayIndexingValueRef(TypeConverter typeConverter, Object array, int index, TypeDescriptor typeDescriptor) {
			this.typeConverter = typeConverter;
			this.array = array;
			this.index = index;
			this.typeDescriptor = typeDescriptor;
		}

		@Override
		public TypedValue getValue() {
			Object arrayElement = accessArrayElement(this.array, this.index);
			return new TypedValue(arrayElement, this.typeDescriptor.elementTypeDescriptor(arrayElement));
		}

		@Override
		public void setValue(@Nullable Object newValue) {
			TypeDescriptor elementType = this.typeDescriptor.getElementTypeDescriptor();
			Assert.state(elementType != null, "No element type");
			setArrayElement(this.typeConverter, this.array, this.index, newValue, elementType.getType());
		}

		@Override
		public boolean isWritable() {
			return true;
		}
	}

	@SuppressWarnings({"rawtypes", "unchecked"})
	private class MapIndexingValueRef implements ValueRef {

		private final TypeConverter typeConverter;

		private final Map map;

		@Nullable
		private final Object key;

		private final TypeDescriptor mapEntryDescriptor;

		public MapIndexingValueRef(
				TypeConverter typeConverter, Map map, @Nullable Object key, TypeDescriptor mapEntryDescriptor) {

			this.typeConverter = typeConverter;
			this.map = map;
			this.key = key;
			this.mapEntryDescriptor = mapEntryDescriptor;
		}

		@Override
		public TypedValue getValue() {
			Object value = this.map.get(this.key);
			exitTypeDescriptor = CodeFlow.toDescriptor(Object.class);
			return new TypedValue(value, this.mapEntryDescriptor.getMapValueTypeDescriptor(value));
		}

		@Override
		public void setValue(@Nullable Object newValue) {
			if (this.mapEntryDescriptor.getMapValueTypeDescriptor() != null) {
				newValue = this.typeConverter.convertValue(newValue, TypeDescriptor.forObject(newValue),
						this.mapEntryDescriptor.getMapValueTypeDescriptor());
			}
			this.map.put(this.key, newValue);
		}

		@Override
		public boolean isWritable() {
			return true;
		}
	}

	private class PropertyIndexingValueRef implements ValueRef {

		private final Object targetObject;

		private final String name;

		private final EvaluationContext evaluationContext;

		private final TypeDescriptor targetObjectTypeDescriptor;

		public PropertyIndexingValueRef(Object targetObject, String value,
				EvaluationContext evaluationContext, TypeDescriptor targetObjectTypeDescriptor) {

			this.targetObject = targetObject;
			this.name = value;
			this.evaluationContext = evaluationContext;
			this.targetObjectTypeDescriptor = targetObjectTypeDescriptor;
		}

		@Override
		public TypedValue getValue() {
			Class<?> targetObjectRuntimeClass = getObjectClass(this.targetObject);
			try {
				if (Indexer.this.cachedReadName != null && Indexer.this.cachedReadName.equals(this.name) &&
						Indexer.this.cachedReadTargetType != null &&
						Indexer.this.cachedReadTargetType.equals(targetObjectRuntimeClass)) {
					// It is OK to use the cached accessor
					PropertyAccessor accessor = Indexer.this.cachedReadAccessor;
					Assert.state(accessor != null, "No cached read accessor");
					return accessor.read(this.evaluationContext, this.targetObject, this.name);
				}
				List<PropertyAccessor> accessorsToTry = AstUtils.getPropertyAccessorsToTry(
						targetObjectRuntimeClass, this.evaluationContext.getPropertyAccessors());
				for (PropertyAccessor accessor : accessorsToTry) {
					if (accessor.canRead(this.evaluationContext, this.targetObject, this.name)) {
						if (accessor instanceof ReflectivePropertyAccessor reflectivePropertyAccessor) {
							accessor = reflectivePropertyAccessor.createOptimalAccessor(
									this.evaluationContext, this.targetObject, this.name);
						}
						Indexer.this.cachedReadAccessor = accessor;
						Indexer.this.cachedReadName = this.name;
						Indexer.this.cachedReadTargetType = targetObjectRuntimeClass;
						if (accessor instanceof ReflectivePropertyAccessor.OptimalPropertyAccessor optimalAccessor) {
							Member member = optimalAccessor.member;
							Indexer.this.exitTypeDescriptor = CodeFlow.toDescriptor(member instanceof Method method ?
									method.getReturnType() : ((Field) member).getType());
						}
						return accessor.read(this.evaluationContext, this.targetObject, this.name);
					}
				}
			}
			catch (AccessException ex) {
				throw new SpelEvaluationException(getStartPosition(), ex,
						SpelMessage.INDEXING_NOT_SUPPORTED_FOR_TYPE, this.targetObjectTypeDescriptor.toString());
			}
			throw new SpelEvaluationException(getStartPosition(),
					SpelMessage.INDEXING_NOT_SUPPORTED_FOR_TYPE, this.targetObjectTypeDescriptor.toString());
		}

		@Override
		public void setValue(@Nullable Object newValue) {
			Class<?> contextObjectClass = getObjectClass(this.targetObject);
			try {
				if (Indexer.this.cachedWriteName != null && Indexer.this.cachedWriteName.equals(this.name) &&
						Indexer.this.cachedWriteTargetType != null &&
						Indexer.this.cachedWriteTargetType.equals(contextObjectClass)) {
					// It is OK to use the cached accessor
					PropertyAccessor accessor = Indexer.this.cachedWriteAccessor;
					Assert.state(accessor != null, "No cached write accessor");
					accessor.write(this.evaluationContext, this.targetObject, this.name, newValue);
					return;
				}
				List<PropertyAccessor> accessorsToTry = AstUtils.getPropertyAccessorsToTry(
						contextObjectClass, this.evaluationContext.getPropertyAccessors());
				for (PropertyAccessor accessor : accessorsToTry) {
					if (accessor.canWrite(this.evaluationContext, this.targetObject, this.name)) {
						Indexer.this.cachedWriteName = this.name;
						Indexer.this.cachedWriteTargetType = contextObjectClass;
						Indexer.this.cachedWriteAccessor = accessor;
						accessor.write(this.evaluationContext, this.targetObject, this.name, newValue);
						return;
					}
				}
			}
			catch (AccessException ex) {
				throw new SpelEvaluationException(getStartPosition(), ex,
						SpelMessage.EXCEPTION_DURING_PROPERTY_WRITE, this.name, ex.getMessage());
			}
		}

		@Override
		public boolean isWritable() {
			return true;
		}
	}

	@SuppressWarnings({"rawtypes", "unchecked"})
	private class CollectionIndexingValueRef implements ValueRef {

		private final Collection collection;

		private final int index;

		private final TypeDescriptor collectionEntryDescriptor;

		private final TypeConverter typeConverter;

		private final boolean growCollection;

		private final int maximumSize;

		public CollectionIndexingValueRef(Collection collection, int index, TypeDescriptor collectionEntryDescriptor,
				TypeConverter typeConverter, boolean growCollection, int maximumSize) {

			this.collection = collection;
			this.index = index;
			this.collectionEntryDescriptor = collectionEntryDescriptor;
			this.typeConverter = typeConverter;
			this.growCollection = growCollection;
			this.maximumSize = maximumSize;
		}

		@Override
		public TypedValue getValue() {
			growCollectionIfNecessary();
			if (this.collection instanceof List list) {
				Object o = list.get(this.index);
				exitTypeDescriptor = CodeFlow.toDescriptor(Object.class);
				return new TypedValue(o, this.collectionEntryDescriptor.elementTypeDescriptor(o));
			}
			int pos = 0;
			for (Object o : this.collection) {
				if (pos == this.index) {
					return new TypedValue(o, this.collectionEntryDescriptor.elementTypeDescriptor(o));
				}
				pos++;
			}
			throw new IllegalStateException("Failed to find indexed element " + this.index + ": " + this.collection);
		}

		@Override
		public void setValue(@Nullable Object newValue) {
			growCollectionIfNecessary();
			if (this.collection instanceof List list) {
				if (this.collectionEntryDescriptor.getElementTypeDescriptor() != null) {
					newValue = this.typeConverter.convertValue(newValue, TypeDescriptor.forObject(newValue),
							this.collectionEntryDescriptor.getElementTypeDescriptor());
				}
				list.set(this.index, newValue);
			}
			else {
				throw new SpelEvaluationException(getStartPosition(), SpelMessage.INDEXING_NOT_SUPPORTED_FOR_TYPE,
						this.collectionEntryDescriptor.toString());
			}
		}

		private void growCollectionIfNecessary() {
			if (this.index >= this.collection.size()) {
				if (!this.growCollection) {
					throw new SpelEvaluationException(getStartPosition(), SpelMessage.COLLECTION_INDEX_OUT_OF_BOUNDS,
							this.collection.size(), this.index);
				}
				if (this.index >= this.maximumSize) {
					throw new SpelEvaluationException(getStartPosition(), SpelMessage.UNABLE_TO_GROW_COLLECTION);
				}
				if (this.collectionEntryDescriptor.getElementTypeDescriptor() == null) {
					throw new SpelEvaluationException(
							getStartPosition(), SpelMessage.UNABLE_TO_GROW_COLLECTION_UNKNOWN_ELEMENT_TYPE);
				}
				TypeDescriptor elementType = this.collectionEntryDescriptor.getElementTypeDescriptor();
				try {
					Constructor<?> ctor = getDefaultConstructor(elementType.getType());
					int newElements = this.index - this.collection.size();
					while (newElements >= 0) {
						// Insert a null value if the element type does not have a default constructor.
						this.collection.add(ctor != null ? ctor.newInstance() : null);
						newElements--;
					}
				}
				catch (Throwable ex) {
					throw new SpelEvaluationException(getStartPosition(), ex, SpelMessage.UNABLE_TO_GROW_COLLECTION);
				}
			}
		}

		@Nullable
		private Constructor<?> getDefaultConstructor(Class<?> type) {
			try {
				return ReflectionUtils.accessibleConstructor(type);
			}
			catch (Throwable ex) {
				return null;
			}
		}

		@Override
		public boolean isWritable() {
			return true;
		}
	}

	private class StringIndexingLValue implements ValueRef {

		private final String target;

		private final int index;

		private final TypeDescriptor typeDescriptor;

		public StringIndexingLValue(String target, int index, TypeDescriptor typeDescriptor) {
			this.target = target;
			this.index = index;
			this.typeDescriptor = typeDescriptor;
		}

		@Override
		public TypedValue getValue() {
			if (this.index >= this.target.length()) {
				throw new SpelEvaluationException(getStartPosition(), SpelMessage.STRING_INDEX_OUT_OF_BOUNDS,
						this.target.length(), this.index);
			}
			return new TypedValue(String.valueOf(this.target.charAt(this.index)));
		}

		@Override
		public void setValue(@Nullable Object newValue) {
			throw new SpelEvaluationException(getStartPosition(), SpelMessage.INDEXING_NOT_SUPPORTED_FOR_TYPE,
					this.typeDescriptor.toString());
		}

		@Override
		public boolean isWritable() {
			return true;
		}
	}

}


text:
from netpyne import specs
from netpyne.batch import Batch

def batchTauWeight():
        # Create variable of type ordered dictionary (NetPyNE's customized version)
        params = specs.ODict()

        # fill in with parameters to explore and range of values (key has to coincide with a variable in simConfig)
        params['synMechTau2'] = [3.0, 5.0, 7.0]
        params['connWeight'] = [0.005, 0.01, 0.15]

        # create Batch object with parameters to modify, and specifying files to use
        b = Batch(params=params, cfgFile='tut8_cfg.py', netParamsFile='tut8_netParams.py',)

        # Set output folder, grid method (all param combinations), and run configuration
        b.batchLabel = 'tauWeight'
        b.saveFolder = 'tut8_data'
        b.method = 'grid'
        b.runCfg = {'type': 'mpi_bulletin',
                            'script': 'tut8_init.py',
                            'skip': True}

        # Run batch simulations
        b.run()

# Main code
if __name__ == '__main__':
        batchTauWeight()

redpajama_set_name: RedPajamaGithub


text:
REM    Copyright 2014 Steve Francia
REM
REM    Licensed under the Apache License, Version 2.0 (the "License");
REM    you may not use this file except in compliance with the License.
REM    You may obtain a copy of the License at
REM
REM        http://www.apache.org/licenses/LICENSE-2.0
REM
REM    Unless required by applicable law or agreed to in writing, software
REM    distributed under the License is distributed on an "AS IS" BASIS,
REM    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
REM    See the License for the specific language governing permissions and
REM    limitations under the License.

@if not exist "%HOME%" @set HOME=%HOMEDRIVE%%HOMEPATH%
@if not exist "%HOME%" @set HOME=%USERPROFILE%

@set APP_PATH=%HOME%\.all3n-vim

@if not exist "%APP_PATH%" (
    echo backing up existing vim config
    @set today=%DATE%
    @if exist "%HOME%\.vim" call xcopy /s/e/h/y/r/q/i "%HOME%\.vim" "%HOME%\.vim.%today%"
    @if exist "%HOME%\.vimrc" call copy "%HOME%\.vimrc" "%HOME%\.vimrc.%today%"
    @if exist "%HOME%\_vimrc" call copy "%HOME%\_vimrc" "%HOME%\_vimrc.%today%"
    @if exist "%HOME%\.gvimrc" call copy "%HOME%\.gvimrc" "%HOME%\.gvimrc.%today%"
)

@if exist "%APP_PATH%" (
    @set ORIGINAL_DIR=%CD%
    echo updating spf13-vim
    chdir /d "%APP_PATH%" && git pull
    chdir /d "%ORIGINAL_DIR%"
) else (
    echo cloning spf13-vim
    call git clone --depth=1 -b all3n git://github.com/all3n/spf13-vim.git "%APP_PATH%"
)

@if not exist  "%APP_PATH%\.vim\bundle" call mkdir "%APP_PATH%\.vim\bundle"
call xcopy /s/e/h/y/r/q/i "%APP_PATH%\.vim" "%HOME%\.vim"
call copy "%APP_PATH%\.vimrc" "%HOME%\.vimrc"
call copy "%APP_PATH%\.vimrc" "%HOME%\_vimrc"
call copy "%APP_PATH%\.vimrc.fork" "%HOME%\.vimrc.fork"
call copy "%APP_PATH%\.vimrc.bundles" "%HOME%\.vimrc.bundles"
call copy "%APP_PATH%\.vimrc.bundles.fork" "%HOME%\.vimrc.bundles.fork"
call copy "%APP_PATH%\.vimrc.before" "%HOME%\.vimrc.before"
call copy "%APP_PATH%\.vimrc.before.fork" "%HOME%\.vimrc.before.fork"

@if not exist "%HOME%/.vim/bundle/vundle" call git clone https://github.com/gmarik/vundle.git "%HOME%/.vim/bundle/vundle"
call vim -u "%APP_PATH%/.vimrc.bundles" - +BundleInstall! +BundleClean +qall


text:
<!doctype html>

	<meta charset="utf-8">
	<title>Index</title>
 	<meta name="description" content="Home page">
 	<meta name="author" content="The Average Joes">
	<link rel="stylesheet" href="css/style.css">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	 	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

AVERAGE JOES VOTING

Brought to you by The Average Joes

			Want to hold an election without having to trust a central authority?
			Want to have transparency, anonymity, and integrity in your election?
			Then this is the right place for you.

			Welcome to our decentralised voting system, which uses blockchain technology to ensure a fair and transparent process.

			This system uses ethereum an open-source, public, blockchain-based distributed computing platform.
			To connect to the ethereum network we recommend using the browser plugin MetaMask.

Click on start election.

There you can set the question, how long everyone has to register, and to vote. You can chose to do basic voting

i.e. pick one candidate out of a list, or preferential voting,

i.e. pick a first and second preferences, and preferences are distributed until one candidate has the majority of votes.

			Happy Voting!

			<button id=startelection, onclick="admin()">Start an election</button>

			<button id=register, onclick="voter()">Register/Vote</button>


text:
/**
 * @author mrdoob / http://mrdoob.com/
 * @author Alex Pletzer
 */

THREE.VTKLoader = function ( manager ) {

	this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;

};

THREE.VTKLoader.prototype = {

	constructor: THREE.VTKLoader,

	load: function ( url, onLoad, onProgress, onError ) {

		// Will we bump into trouble reading the whole file into memory?
		var scope = this;
		var loader = new THREE.XHRLoader( scope.manager );
		loader.load( url, function ( text ) {

			onLoad( scope.parse( text ) );

		},

		onProgress, onError );

	},

	parse: function ( data ) {

		// connectivity of the triangles
		var indices = [];

		// triangles vertices
		var positions = [];

		// red, green, blue colors in the range 0 to 1
		var colors = [];

		// normal vector, one per vertex
		var normals = [];

		var result;

		// pattern for reading vertices, 3 floats or integers
		var pat3Floats = /(\-?\d+\.?[\d\-\+e]*)\s+(\-?\d+\.?[\d\-\+e]*)\s+(\-?\d+\.?[\d\-\+e]*)/g;

		// pattern for connectivity, an integer followed by any number of ints
		// the first integer is the number of polygon nodes
		var patConnectivity = /^(\d+)\s+([\s\d]*)/;

		// indicates start of vertex data section
		var patPOINTS = /^POINTS /;

		// indicates start of polygon connectivity section
		var patPOLYGONS = /^POLYGONS /;

		// POINT_DATA number_of_values
		var patPOINT_DATA = /^POINT_DATA[ ]+(\d+)/;

		// CELL_DATA number_of_polys
		var patCELL_DATA = /^CELL_DATA[ ]+(\d+)/;

		// Start of color section
		var patCOLOR_SCALARS = /^COLOR_SCALARS[ ]+(\w+)[ ]+3/;

		// NORMALS Normals float
		var patNORMALS = /^NORMALS[ ]+(\w+)[ ]+(\w+)/;

		var inPointsSection = false;
		var inPolygonsSection = false;
		var inPointDataSection = false;
		var inCellDataSection = false;
		var inColorSection = false;
		var inNormalsSection = false;

		var lines = data.split( '\n' );

		for ( var i in lines ) {

			var line = lines[ i ];

			if ( inPointsSection ) {

				// get the vertices
				while ( ( result = pat3Floats.exec( line ) ) !== null ) {

					var x = parseFloat( result[ 1 ] );
					var y = parseFloat( result[ 2 ] );
					var z = parseFloat( result[ 3 ] );
					positions.push( x, y, z );

				}

			} else if ( inPolygonsSection ) {

				if ( ( result = patConnectivity.exec( line ) ) !== null ) {

					// numVertices i0 i1 i2 ...
					var numVertices = parseInt( result[ 1 ] );
					var inds = result[ 2 ].split( /\s+/ );

					if ( numVertices >= 3 ) {

						var i0 = parseInt( inds[ 0 ] );
						var i1, i2;
						var k = 1;
						// split the polygon in numVertices - 2 triangles
						for ( var j = 0; j < numVertices - 2; ++ j ) {

							i1 = parseInt( inds[ k ] );
							i2 = parseInt( inds[ k  + 1 ] );
							indices.push( i0, i1, i2 );
							k ++;

						}

					}

				}

			} else if ( inPointDataSection || inCellDataSection ) {

				if ( inColorSection ) {

					// Get the colors

					while ( ( result = pat3Floats.exec( line ) ) !== null ) {

						var r = parseFloat( result[ 1 ] );
						var g = parseFloat( result[ 2 ] );
						var b = parseFloat( result[ 3 ] );
						colors.push( r, g, b );

					}

				} else if ( inNormalsSection ) {

					// Get the normal vectors

					while ( ( result = pat3Floats.exec( line ) ) !== null ) {

						var nx = parseFloat( result[ 1 ] );
						var ny = parseFloat( result[ 2 ] );
						var nz = parseFloat( result[ 3 ] );
						normals.push( nx, ny, nz );

					}

				}

			}

			if ( patPOLYGONS.exec( line ) !== null ) {

				inPolygonsSection = true;
				inPointsSection = false;

			} else if ( patPOINTS.exec( line ) !== null ) {

				inPolygonsSection = false;
				inPointsSection = true;

			} else if ( patPOINT_DATA.exec( line ) !== null ) {

				inPointDataSection = true;
				inPointsSection = false;
				inPolygonsSection = false;

			} else if ( patCELL_DATA.exec( line ) !== null ) {

				inCellDataSection = true;
				inPointsSection = false;
				inPolygonsSection = false;

			} else if ( patCOLOR_SCALARS.exec( line ) !== null ) {

				inColorSection = true;
				inNormalsSection = false;
				inPointsSection = false;
				inPolygonsSection = false;

			} else if ( patNORMALS.exec( line ) !== null ) {

				inNormalsSection = true;
				inColorSection = false;
				inPointsSection = false;
				inPolygonsSection = false;

			}

		}

		var geometry;
		var stagger = 'point';

		if ( colors.length == indices.length ) {

			stagger = 'cell';

		}

		if ( stagger == 'point' ) {

			// Nodal. Use BufferGeometry
			geometry = new THREE.BufferGeometry();
			geometry.setIndex( new THREE.BufferAttribute( new ( indices.length > 65535 ? Uint32Array : Uint16Array )( indices ), 1 ) );
			geometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( positions ), 3 ) );

			if ( colors.length == positions.length ) {

				geometry.addAttribute( 'color', new THREE.BufferAttribute( new Float32Array( colors ), 3 ) );

			}

			if ( normals.length == positions.length ) {

				geometry.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( normals ), 3 ) );

			}

		} else {

			// Cell centered colors. The only way to attach a solid color to each triangle
			// is to use Geometry, which is less efficient than BufferGeometry
			geometry = new THREE.Geometry();

			var numTriangles = indices.length / 3;
			var numPoints = positions.length / 3;
			var va, vb, vc;
			var face;
			var ia, ib, ic;
			var x, y, z;
			var r, g, b;

			for ( var j = 0; j < numPoints; ++ j ) {

				x = positions[ 3 * j + 0 ];
				y = positions[ 3 * j + 1 ];
				z = positions[ 3 * j + 2 ];
				geometry.vertices.push( new THREE.Vector3( x, y, z ) );

			}

			for ( var i = 0; i < numTriangles; ++ i ) {

				ia = indices[ 3 * i + 0 ];
				ib = indices[ 3 * i + 1 ];
				ic = indices[ 3 * i + 2 ];
				geometry.faces.push( new THREE.Face3( ia, ib, ic ) );

			}

			if ( colors.length == numTriangles * 3 ) {

				for ( var i = 0; i < numTriangles; ++ i ) {

					face = geometry.faces[ i ];
					r = colors[ 3 * i + 0 ];
					g = colors[ 3 * i + 1 ];
					b = colors[ 3 * i + 2 ];
					face.color = new THREE.Color().setRGB( r, g, b );

				}

			 }

		}

		return geometry;

	}

};

THREE.EventDispatcher.prototype.apply( THREE.VTKLoader.prototype );


text:
/*
  RandomShuffleSequencer.hpp

  visit pixels in a random shuffled order

  Li-Yi Wei
  August 24, 2014

*/

#ifndef _RANDOM_SHUFFLE_SEQUENCER_HPP
#define _RANDOM_SHUFFLE_SEQUENCER_HPP

#include "Sequencer.hpp"

class RandomShuffleSequencer : public Sequencer
{
public:
    RandomShuffleSequencer(void);
    virtual bool Reset(const Texture & target);
    virtual bool Next(Position & answer);

private:
    vector<Position> _positions;
    unsigned int _current_position;
};
#endif


text:
<?php

namespace BabiPHP\Negotiation\Exception;

class InvalidArgument extends \InvalidArgumentException implements Exception
{
}


text:
<link href="../../../polymer-elements/polymer-flex-layout/polymer-flex-layout.html" rel="import">
<link href="test-dashboard-cell.html" rel="import">
<polymer-element name="test-dashboard-row" attributes="project builderResponse">
	<template>

{{project}}

		<template repeat="{{plat in platforms}}">
			<buildbot-ajax-builder builder="{{project}} {{plat}}" response="{{builderResponse}}"></buildbot-ajax-builder>
			{{plat}} <test-dashboard-cell class="{{pending: builderResponse.pendingBuilds && builderResponse.state !== 'building'}}" builder="{{project}} {{plat}}"></test-dashboard-cell>
		</template>
	</template>

</polymer-element>


text:
package org.lxd.cniprSeg.test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

/**
 * 类说明
 * @author  添加者 E-mail: lixaodong@gintong.com;
 * @author  修改者 E-mail:暂无
 * @version 创建时间:2013-9-25 上午9:22:44;
 * @version 修改时间:暂无
 */
public class FileUtils {

	public static final String UTF8="UTF-8";
	public static final String GBK="GBK";

	/**
	 * 获取文件中的全部内容
	 * @author  添加者 E-mail: lixaodong@gintong.com;
	 * @author  修改者 E-mail:无
	 * @version 创建时间:2013-9-25 上午9:47:19;
	 * @version 修改时间:无
	 * @param file
	 * @param encode
	 * @return
	 */
	public static String getContentFromFile( File file,String encode,String lineSeparator )
	{
		if( file==null )
			return "";

		if( !file.exists() )
			return "";

		try {
			StringBuffer sb = new StringBuffer(4096);
			BufferedReader br = new BufferedReader( new InputStreamReader( new FileInputStream(file),encode) );

			String line=null;
			while( (line=br.readLine())!=null )
			{
				sb.append(line);
				sb.append(lineSeparator);
			}
			return sb.toString();

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "";
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * 向文件中写入内容
	 * @author  添加者 E-mail: lixaodong@gintong.com;
	 * @author  修改者 E-mail:无
	 * @version 创建时间:2013-9-25 上午9:47:23;
	 * @version 修改时间:无
	 * @param file
	 * @param content
	 * @param encode
	 */
	public static void writeFile( File file,String content,String encode )
	{
		try {

			BufferedWriter fw = new BufferedWriter( new OutputStreamWriter( new FileOutputStream( file ),encode ));
			fw.append(content);
			fw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}


text:
<?php
App::uses('Job', 'Model');

/**
 * Job Test Case
 *
 */
class JobTest extends CakeTestCase {

/**
 * Fixtures
 *
 * @var array
 */
	public $fixtures = array(
		'app.job',
		'app.company',
		'app.cv',
		'app.education',
		'app.experience',
		'app.cvs_job'
	);

/**
 * setUp method
 *
 * @return void
 */
	public function setUp() {
		parent::setUp();
		$this->Job = ClassRegistry::init('Job');
	}

/**
 * tearDown method
 *
 * @return void
 */
	public function tearDown() {
		unset($this->Job);

		parent::tearDown();
	}

	// #fuckyeah mocks!
	public function testTodayIsWorkdaySuccessAndFail() {
		$jobMock = $this->getMockForModel('Job', array('getNow'));
		// $this->at(0) sets up the mock only for the first call
		$jobMock->expects($this->at(0))
			->method('getNow')
			->will($this->returnValue(strtotime('next sunday')));

		// $this->at(1) sets up the mock only for the second call
		$jobMock->expects($this->at(1))
			->method('getNow')
			->will($this->returnValue(strtotime('next thursday')));

		$result = $jobMock->todayIsWorkday(array());
		$this->assertFalse($result, 'next sunday should NOT be a workday');
		$result = $jobMock->todayIsWorkday(array());
		$this->assertTrue($result, 'next thursday should NOT be a workday');
	}
}


text:
package org.asteriskjava.pbx.internal.core;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.asteriskjava.manager.TimeoutException;
import org.asteriskjava.pbx.Activity;
import org.asteriskjava.pbx.ActivityCallback;
import org.asteriskjava.pbx.ActivityStatusEnum;
import org.asteriskjava.pbx.AsteriskSettings;
import org.asteriskjava.pbx.CallerID;
import org.asteriskjava.pbx.Channel;
import org.asteriskjava.pbx.EndPoint;
import org.asteriskjava.pbx.ListenerPriority;
import org.asteriskjava.pbx.PBX;
import org.asteriskjava.pbx.PBXException;
import org.asteriskjava.pbx.PBXFactory;
import org.asteriskjava.pbx.asterisk.wrap.actions.GetVarAction;
import org.asteriskjava.pbx.asterisk.wrap.actions.OriginateAction;
import org.asteriskjava.pbx.asterisk.wrap.events.HangupEvent;
import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent;
import org.asteriskjava.pbx.asterisk.wrap.events.NewChannelEvent;
import org.asteriskjava.pbx.asterisk.wrap.events.OriginateResponseEvent;
import org.asteriskjava.pbx.asterisk.wrap.response.ManagerResponse;
import org.asteriskjava.pbx.internal.managerAPI.EventListenerBaseClass;
import org.asteriskjava.pbx.internal.managerAPI.OriginateBaseClass;
import org.asteriskjava.util.Log;
import org.asteriskjava.util.LogFactory;

public class DialLocalToAgiActivity extends EventListenerBaseClass implements Runnable, Activity
{

    private EndPoint from;
    private CallerID fromCallerID;
    private Thread thread;
    private final Log logger = LogFactory.getLog(this.getClass());
    private String originateId;

    CountDownLatch latch = new CountDownLatch(1);
    private List<Channel> channels = new LinkedList<>();
    private ActivityCallback<DialLocalToAgiActivity> callback;
    private Map<String, String> channelVarsToSet;

    public DialLocalToAgiActivity(EndPoint from, CallerID fromCallerID, ActivityCallback<DialLocalToAgiActivity> callback,
            Map<String, String> channelVarsToSet)
    {
        super("Dial " + from + " to AGI");
        this.from = from;
        this.fromCallerID = fromCallerID;
        this.callback = callback;
        this.channelVarsToSet = channelVarsToSet;

        this.startListener(PBXFactory.getActivePBX());
        thread = new Thread(this, "Dial " + from + " to AGI");
        thread.start();
    }
    // Logger logger = LogManager.getLogger();

    @Override
    public void run()
    {
        logger.info("*******************************************************************************");
        logger.info("***********                    begin dial local to AGI                  ****************");
        logger.info("***********                         " + "                              ****************");
        logger.info("*******************************************************************************");
        final AsteriskSettings settings = PBXFactory.getActiveProfile();

        AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX();

        final OriginateAction originate = new OriginateAction();
        originate.setEndPoint(from);
        originate.setContext(settings.getManagementContext());
        originate.setExten(pbx.getExtensionAgi());
        originate.setPriority(1);
        originate.setCallerId(fromCallerID);
        originate.setTimeout(30000);
        originateId = originate.getActionId();

        Map<String, String> myVars = new HashMap<>();

        myVars.put("__" + OriginateBaseClass.NJR_ORIGINATE_ID, this.originateId);
        if (channelVarsToSet != null)
        {
            myVars.putAll(channelVarsToSet);
        }

        originate.setVariables(myVars);

        try
        {
            pbx.sendAction(originate, 30000);
            latch.await(30, TimeUnit.SECONDS);
            callback.progress(this, ActivityStatusEnum.SUCCESS, ActivityStatusEnum.SUCCESS.getDefaultMessage());

        }
        catch (IllegalArgumentException | IllegalStateException | IOException | TimeoutException e)
        {
            // TODO Auto-generated catch block
            logger.error(e, e);
        }
        catch (InterruptedException e)
        {
            // TODO Auto-generated catch block
            logger.error(e, e);
        }

    }

    public void abort(final String reason)
    {
        logger.debug("Aborting originate ");//$NON-NLS-1$
        this.close();

        for (Channel channel : channels)
        {
            PBX pbx = PBXFactory.getActivePBX();
            try
            {
                pbx.hangup(channel);
            }
            catch (IllegalArgumentException | IllegalStateException | PBXException e)
            {
                logger.error(e, e);

            }
        }
        latch.countDown();

    }

    @Override
    synchronized public void onManagerEvent(final ManagerEvent event)
    {
        if (event instanceof HangupEvent)
        {
            this.close();
        }
        if (event instanceof NewChannelEvent)
        {
            final NewChannelEvent newState = (NewChannelEvent) event;
            final Channel channel = newState.getChannel();
            AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX();
            final GetVarAction var = new GetVarAction(channel, OriginateBaseClass.NJR_ORIGINATE_ID);

            ManagerResponse response;
            try
            {
                if (channel.isLocal())
                {
                    int wait = 5;
                    while (wait > 0)
                    {
                        wait--;
                        response = pbx.sendAction(var, 500);
                        String channelsOriginateId = response.getAttribute("value");
                        if (originateId.equalsIgnoreCase(channelsOriginateId))
                        {
                            logger.info("Found the local channel " + channel);
                            channels.add(channel);
                            wait = 0;
                            if (channels.size() == 2)
                            {
                                latch.countDown();
                            }
                        }
                        else if (channelsOriginateId == null || channelsOriginateId.length() == 0)

                        {
                            Thread.sleep(100);
                            logger.error("Waiting for variables on " + channel);
                        }
                        else
                        {
                            logger.error("Didn't match " + channel + " " + channelsOriginateId + "!=" + originateId);

                            wait = 0;
                        }
                    }
                }
            }
            catch (IllegalArgumentException | IllegalStateException | IOException | TimeoutException e)
            {
                // TODO Auto-generated catch block
                logger.error(e, e);
            }
            catch (InterruptedException e)
            {
                // TODO Auto-generated catch block
                logger.error(e, e);
            }

        }
    }

    @Override
    public HashSet<Class< ? extends ManagerEvent>> requiredEvents()
    {
        HashSet<Class< ? extends ManagerEvent>> required = new HashSet<>();

        required.add(OriginateResponseEvent.class);
        required.add(HangupEvent.class);
        required.add(NewChannelEvent.class);

        return required;
    }

    @Override
    public ListenerPriority getPriority()
    {
        return ListenerPriority.NORMAL;
    }

    @Override
    public Throwable getLastException()
    {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean isSuccess()
    {
        // TODO Auto-generated method stub
        return channels.size() == 2;
    }

    public Channel getChannel1()
    {
        return channels.get(0);

    }

    public Channel getChannel2()
    {
        return channels.get(1);

    }
}


text:
namespace ceres {
namespace internal {

TEST(SuiteSparse, BlockPermutationToScalarPermutation) {
  vector<int> blocks;
  //  Block structure
  //  0  --1-  ---2---  ---3---  4
  // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  blocks.push_back(1);
  blocks.push_back(2);
  blocks.push_back(3);
  blocks.push_back(3);
  blocks.push_back(1);

  // Block ordering
  // [1, 0, 2, 4, 5]
  vector<int> block_ordering;
  block_ordering.push_back(1);
  block_ordering.push_back(0);
  block_ordering.push_back(2);
  block_ordering.push_back(4);
  block_ordering.push_back(3);

  // Expected ordering
  // [1, 2, 0, 3, 4, 5, 9, 6, 7, 8]
  vector<int> expected_scalar_ordering;
  expected_scalar_ordering.push_back(1);
  expected_scalar_ordering.push_back(2);
  expected_scalar_ordering.push_back(0);
  expected_scalar_ordering.push_back(3);
  expected_scalar_ordering.push_back(4);
  expected_scalar_ordering.push_back(5);
  expected_scalar_ordering.push_back(9);
  expected_scalar_ordering.push_back(6);
  expected_scalar_ordering.push_back(7);
  expected_scalar_ordering.push_back(8);

  vector<int> scalar_ordering;
  SuiteSparse::BlockOrderingToScalarOrdering(blocks,
                                             block_ordering,
                                             &scalar_ordering);
  EXPECT_EQ(scalar_ordering.size(), expected_scalar_ordering.size());
  for (int i = 0; i < expected_scalar_ordering.size(); ++i) {
    EXPECT_EQ(scalar_ordering[i], expected_scalar_ordering[i]);
  }
}

// Helper function to fill the sparsity pattern of a TripletSparseMatrix.
int FillBlock(const vector<int>& row_blocks,
              const vector<int>& col_blocks,
              const int row_block_id,
              const int col_block_id,
              int* rows,
              int* cols) {
  int row_pos = 0;
  for (int i = 0; i < row_block_id; ++i) {
    row_pos += row_blocks[i];
  }

  int col_pos = 0;
  for (int i = 0; i < col_block_id; ++i) {
    col_pos += col_blocks[i];
  }

  int offset = 0;
  for (int r = 0; r < row_blocks[row_block_id]; ++r) {
    for (int c = 0; c < col_blocks[col_block_id]; ++c, ++offset) {
      rows[offset] = row_pos + r;
      cols[offset] = col_pos + c;
    }
  }
  return offset;
}

TEST(SuiteSparse, ScalarMatrixToBlockMatrix) {
  // Block sparsity.
  //
  //     [1 2 3 2]
  // [1]  x   x
  // [2]    x   x
  // [2]  x x
  // num_nonzeros = 1 + 3 + 4 + 4 + 1 + 2 = 15

  vector<int> col_blocks;
  col_blocks.push_back(1);
  col_blocks.push_back(2);
  col_blocks.push_back(3);
  col_blocks.push_back(2);

  vector<int> row_blocks;
  row_blocks.push_back(1);
  row_blocks.push_back(2);
  row_blocks.push_back(2);

  TripletSparseMatrix tsm(5, 8, 18);
  int* rows = tsm.mutable_rows();
  int* cols = tsm.mutable_cols();
  fill(tsm.mutable_values(), tsm.mutable_values() + 18, 1.0);
  int offset = 0;

#define CERES_TEST_FILL_BLOCK(row_block_id, col_block_id) \
  offset += FillBlock(row_blocks, col_blocks, \
                      row_block_id, col_block_id, \
                      rows + offset, cols + offset);

  CERES_TEST_FILL_BLOCK(0, 0);
  CERES_TEST_FILL_BLOCK(2, 0);
  CERES_TEST_FILL_BLOCK(1, 1);
  CERES_TEST_FILL_BLOCK(2, 1);
  CERES_TEST_FILL_BLOCK(0, 2);
  CERES_TEST_FILL_BLOCK(1, 3);
#undef CERES_TEST_FILL_BLOCK

  tsm.set_num_nonzeros(offset);

  SuiteSparse ss;
  scoped_ptr<cholmod_sparse> ccsm(ss.CreateSparseMatrix(&tsm));

  vector<int> expected_block_rows;
  expected_block_rows.push_back(0);
  expected_block_rows.push_back(2);
  expected_block_rows.push_back(1);
  expected_block_rows.push_back(2);
  expected_block_rows.push_back(0);
  expected_block_rows.push_back(1);

  vector<int> expected_block_cols;
  expected_block_cols.push_back(0);
  expected_block_cols.push_back(2);
  expected_block_cols.push_back(4);
  expected_block_cols.push_back(5);
  expected_block_cols.push_back(6);

  vector<int> block_rows;
  vector<int> block_cols;
  SuiteSparse::ScalarMatrixToBlockMatrix(ccsm.get(),
                                         row_blocks,
                                         col_blocks,
                                         &block_rows,
                                         &block_cols);

  EXPECT_EQ(block_cols.size(), expected_block_cols.size());
  EXPECT_EQ(block_rows.size(), expected_block_rows.size());

  for (int i = 0; i < expected_block_cols.size(); ++i) {
    EXPECT_EQ(block_cols[i], expected_block_cols[i]);
  }

  for (int i = 0; i < expected_block_rows.size(); ++i) {
    EXPECT_EQ(block_rows[i], expected_block_rows[i]);
  }

  ss.Free(ccsm.release());
}

}  // namespace internal
}  // namespace ceres


text:
package summer.util;

import java.util.List;

/**
 * @author li
 * @version 1 (2015年10月11日 下午2:38:12)
 * @since Java7
 */
public class StringUtil {
    public static String join(Object[] array, String linker) {
        StringBuilder stringBuilder = new StringBuilder();
        if (null == array || 0 == array.length) {
            return stringBuilder.toString();
        }
        stringBuilder.append(array[0]);
        for (int i = 1; i < array.length; i++) {
            stringBuilder.append(linker).append(array[i]);
        }
        return stringBuilder.toString();
    }

    @SuppressWarnings("rawtypes")
    public static String join(List list, String linker) {
        return join(list.toArray(), linker);
    }
}


text:
namespace remoting {

namespace {

// Size of the buffer to allocate for RecvFrom().
const int kReceiveBufferSize = 65536;

// Maximum amount of data in the send buffers. This is necessary to
// prevent out-of-memory crashes if the caller sends data faster than
// Pepper's UDP API can handle it. This maximum should never be
// reached under normal conditions.
const int kMaxSendBufferSize = 256 * 1024;

class UdpPacketSocket : public talk_base::AsyncPacketSocket {
 public:
  explicit UdpPacketSocket(const pp::InstanceHandle& instance);
  virtual ~UdpPacketSocket();

  // |min_port| and |max_port| are set to zero if the port number
  // should be assigned by the OS.
  bool Init(const talk_base::SocketAddress& local_address,
            int min_port,
            int max_port);

  // talk_base::AsyncPacketSocket interface.
  virtual talk_base::SocketAddress GetLocalAddress() const OVERRIDE;
  virtual talk_base::SocketAddress GetRemoteAddress() const OVERRIDE;
  virtual int Send(const void* data, size_t data_size,
                   talk_base::DiffServCodePoint dscp) OVERRIDE;
  virtual int SendTo(const void* data,
                     size_t data_size,
                     const talk_base::SocketAddress& address,
                     talk_base::DiffServCodePoint dscp) OVERRIDE;
  virtual int Close() OVERRIDE;
  virtual State GetState() const OVERRIDE;
  virtual int GetOption(talk_base::Socket::Option opt, int* value) OVERRIDE;
  virtual int SetOption(talk_base::Socket::Option opt, int value) OVERRIDE;
  virtual int GetError() const OVERRIDE;
  virtual void SetError(int error) OVERRIDE;

 private:
  struct PendingPacket {
    PendingPacket(const void* buffer,
                  int buffer_size,
                  const pp::NetAddress& address);

    scoped_refptr<net::IOBufferWithSize> data;
    pp::NetAddress address;
  };

  void OnBindCompleted(int error);

  void DoSend();
  void OnSendCompleted(int result);

  void DoRead();
  void OnReadCompleted(int result, pp::NetAddress address);
  void HandleReadResult(int result, pp::NetAddress address);

  pp::InstanceHandle instance_;

  pp::UDPSocket socket_;

  State state_;
  int error_;

  talk_base::SocketAddress local_address_;

  // Used to scan ports when necessary. Both values are set to 0 when
  // the port number is assigned by OS.
  uint16_t min_port_;
  uint16_t max_port_;

  std::vector<char> receive_buffer_;

  bool send_pending_;
  std::list<PendingPacket> send_queue_;
  int send_queue_size_;

  pp::CompletionCallbackFactory<UdpPacketSocket> callback_factory_;

  DISALLOW_COPY_AND_ASSIGN(UdpPacketSocket);
};

UdpPacketSocket::PendingPacket::PendingPacket(
    const void* buffer,
    int buffer_size,
    const pp::NetAddress& address)
    : data(new net::IOBufferWithSize(buffer_size)),
      address(address) {
  memcpy(data->data(), buffer, buffer_size);
}

UdpPacketSocket::UdpPacketSocket(const pp::InstanceHandle& instance)
    : instance_(instance),
      socket_(instance),
      state_(STATE_CLOSED),
      error_(0),
      min_port_(0),
      max_port_(0),
      send_pending_(false),
      send_queue_size_(0),
      callback_factory_(this) {
}

UdpPacketSocket::~UdpPacketSocket() {
  Close();
}

bool UdpPacketSocket::Init(const talk_base::SocketAddress& local_address,
                           int min_port,
                           int max_port) {
  if (socket_.is_null()) {
    return false;
  }

  local_address_ = local_address;
  max_port_ = max_port;
  min_port_ = min_port;

  pp::NetAddress pp_local_address;
  if (!SocketAddressToPpNetAddressWithPort(
          instance_, local_address_, &pp_local_address, min_port_)) {
    return false;
  }

  pp::CompletionCallback callback =
      callback_factory_.NewCallback(&UdpPacketSocket::OnBindCompleted);
  int result = socket_.Bind(pp_local_address, callback);
  DCHECK_EQ(result, PP_OK_COMPLETIONPENDING);
  state_ = STATE_BINDING;

  return true;
}

void UdpPacketSocket::OnBindCompleted(int result) {
  DCHECK(state_ == STATE_BINDING || state_ == STATE_CLOSED);

  if (result == PP_ERROR_ABORTED) {
    // Socket is being destroyed while binding.
    return;
  }

  if (result == PP_OK) {
    pp::NetAddress address = socket_.GetBoundAddress();
    PpNetAddressToSocketAddress(address, &local_address_);
    state_ = STATE_BOUND;
    SignalAddressReady(this, local_address_);
    DoRead();
    return;
  }

  if (min_port_ < max_port_) {
    // Try to bind to the next available port.
    ++min_port_;
    pp::NetAddress pp_local_address;
    if (SocketAddressToPpNetAddressWithPort(
            instance_, local_address_, &pp_local_address, min_port_)) {
      pp::CompletionCallback callback =
          callback_factory_.NewCallback(&UdpPacketSocket::OnBindCompleted);
      int result = socket_.Bind(pp_local_address, callback);
      DCHECK_EQ(result, PP_OK_COMPLETIONPENDING);
    }
  } else {
    LOG(ERROR) << "Failed to bind UDP socket: " << result;
  }
}

talk_base::SocketAddress UdpPacketSocket::GetLocalAddress() const {
  DCHECK_EQ(state_, STATE_BOUND);
  return local_address_;
}

talk_base::SocketAddress UdpPacketSocket::GetRemoteAddress() const {
  // UDP sockets are not connected - this method should never be called.
  NOTREACHED();
  return talk_base::SocketAddress();
}

int UdpPacketSocket::Send(const void* data, size_t data_size,
                          talk_base::DiffServCodePoint dscp) {
  // UDP sockets are not connected - this method should never be called.
  NOTREACHED();
  return EWOULDBLOCK;
}

int UdpPacketSocket::SendTo(const void* data,
                            size_t data_size,
                            const talk_base::SocketAddress& address,
                            talk_base::DiffServCodePoint dscp) {
  if (state_ != STATE_BOUND) {
    // TODO(sergeyu): StunPort may try to send stun request before we
    // are bound. Fix that problem and change this to DCHECK.
    return EINVAL;
  }

  if (error_ != 0) {
    return error_;
  }

  pp::NetAddress pp_address;
  if (!SocketAddressToPpNetAddress(instance_, address, &pp_address)) {
    return EINVAL;
  }

  if (send_queue_size_ >= kMaxSendBufferSize) {
    return EWOULDBLOCK;
  }

  send_queue_.push_back(PendingPacket(data, data_size, pp_address));
  send_queue_size_ += data_size;
  DoSend();
  return data_size;
}

int UdpPacketSocket::Close() {
  state_ = STATE_CLOSED;
  socket_.Close();
  return 0;
}

talk_base::AsyncPacketSocket::State UdpPacketSocket::GetState() const {
  return state_;
}

int UdpPacketSocket::GetOption(talk_base::Socket::Option opt, int* value) {
  // Options are not supported for Pepper UDP sockets.
  return -1;
}

int UdpPacketSocket::SetOption(talk_base::Socket::Option opt, int value) {
  // Options are not supported for Pepper UDP sockets.
  return -1;
}

int UdpPacketSocket::GetError() const {
  return error_;
}

void UdpPacketSocket::SetError(int error) {
  error_ = error;
}

void UdpPacketSocket::DoSend() {
  if (send_pending_ || send_queue_.empty())
    return;

  pp::CompletionCallback callback =
      callback_factory_.NewCallback(&UdpPacketSocket::OnSendCompleted);
  int result = socket_.SendTo(
      send_queue_.front().data->data(), send_queue_.front().data->size(),
      send_queue_.front().address,
      callback);
  DCHECK_EQ(result, PP_OK_COMPLETIONPENDING);
  send_pending_ = true;
}

void UdpPacketSocket::OnSendCompleted(int result) {
  if (result == PP_ERROR_ABORTED) {
    // Send is aborted when the socket is being destroyed.
    // |send_queue_| may be already destroyed, it's not safe to access
    // it here.
    return;
  }

  send_pending_ = false;

  if (result < 0) {
    LOG(ERROR) << "Send failed on a UDP socket: " << result;

    // OS (e.g. OSX) may return EHOSTUNREACH when the peer has the
    // same subnet address as the local host but connected to a
    // different network. That error must be ingored because the
    // socket may still be useful for other ICE canidadates (e.g. for
    // STUN candidates with a different address). Unfortunately pepper
    // interface currently returns PP_ERROR_FAILED for any error (see
    // crbug.com/136406). It's not possible to distinguish that case
    // from other errors and so we have to ingore all of them. This
    // behavior matchers the libjingle's AsyncUDPSocket used by the
    // host.
    //
    // TODO(sergeyu): Once implementation of the Pepper UDP interface
    // is fixed, uncomment the code below, but ignore
    // host-unreacheable error.

    // error_ = EINVAL;
    // return;
  }

  send_queue_size_ -= send_queue_.front().data->size();
  send_queue_.pop_front();
  DoSend();
}

void UdpPacketSocket::DoRead() {
  receive_buffer_.resize(kReceiveBufferSize);
  pp::CompletionCallbackWithOutput<pp::NetAddress> callback =
      callback_factory_.NewCallbackWithOutput(
          &UdpPacketSocket::OnReadCompleted);
  int result =
      socket_.RecvFrom(&receive_buffer_[0], receive_buffer_.size(), callback);
  DCHECK_EQ(result, PP_OK_COMPLETIONPENDING);
}

void UdpPacketSocket::OnReadCompleted(int result, pp::NetAddress address) {
  HandleReadResult(result, address);
  if (result > 0) {
    DoRead();
  }
}

  void UdpPacketSocket::HandleReadResult(int result, pp::NetAddress address) {
  if (result > 0) {
    talk_base::SocketAddress socket_address;
    PpNetAddressToSocketAddress(address, &socket_address);
    SignalReadPacket(this, &receive_buffer_[0], result, socket_address);
  } else if (result != PP_ERROR_ABORTED) {
    LOG(ERROR) << "Received error when reading from UDP socket: " << result;
  }
}

}  // namespace

PepperPacketSocketFactory::PepperPacketSocketFactory(
    const pp::InstanceHandle& instance)
    : pp_instance_(instance) {
}

PepperPacketSocketFactory::~PepperPacketSocketFactory() {
}

talk_base::AsyncPacketSocket* PepperPacketSocketFactory::CreateUdpSocket(
      const talk_base::SocketAddress& local_address,
      int min_port,
      int max_port) {
  scoped_ptr<UdpPacketSocket> result(new UdpPacketSocket(pp_instance_));
  if (!result->Init(local_address, min_port, max_port))
    return NULL;
  return result.release();
}

talk_base::AsyncPacketSocket* PepperPacketSocketFactory::CreateServerTcpSocket(
    const talk_base::SocketAddress& local_address,
    int min_port,
    int max_port,
    int opts) {
  // We don't use TCP sockets for remoting connections.
  NOTREACHED();
  return NULL;
}

talk_base::AsyncPacketSocket* PepperPacketSocketFactory::CreateClientTcpSocket(
      const talk_base::SocketAddress& local_address,
      const talk_base::SocketAddress& remote_address,
      const talk_base::ProxyInfo& proxy_info,
      const std::string& user_agent,
      int opts) {
  // We don't use TCP sockets for remoting connections.
  NOTREACHED();
  return NULL;
}

}  // namespace remoting


text:
class Administration::AdminSessionsController < Administration::ApplicationController
  resource_controller

  skip_before_filter :require_admin, :except => :destroy

  create.wants.html {redirect_to administration_root_path}
  create.flash "You are now logged in as admin"
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/deployer-recipies.iml" filepath="$PROJECT_DIR$/.idea/deployer-recipies.iml" />
    </modules>
  </component>
</project>


text:
"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var chai_1 = require("chai");
var SelectionModel_1 = require("./SelectionModel");
var BufferSet_1 = require("./BufferSet");
var TestUtils_1 = require("./utils/TestUtils");
var TestSelectionModel = (function (_super) {
    __extends(TestSelectionModel, _super);
    function TestSelectionModel(terminal) {
        return _super.call(this, terminal) || this;
    }
    return TestSelectionModel;
}(SelectionModel_1.SelectionModel));
describe('SelectionManager', function () {
    var window;
    var document;
    var terminal;
    var model;
    beforeEach(function () {
        terminal = new TestUtils_1.MockTerminal();
        terminal.cols = 80;
        terminal.rows = 2;
        terminal.scrollback = 10;
        terminal.buffers = new BufferSet_1.BufferSet(terminal);
        terminal.buffer = terminal.buffers.active;
        model = new TestSelectionModel(terminal);
    });
    describe('clearSelection', function () {
        it('should clear the final selection', function () {
            model.selectionStart = [0, 0];
            model.selectionEnd = [10, 2];
            chai_1.assert.deepEqual(model.finalSelectionStart, [0, 0]);
            chai_1.assert.deepEqual(model.finalSelectionEnd, [10, 2]);
            model.clearSelection();
            chai_1.assert.deepEqual(model.finalSelectionStart, null);
            chai_1.assert.deepEqual(model.finalSelectionEnd, null);
        });
    });
    describe('areSelectionValuesReversed', function () {
        it('should return true when the selection end is before selection start', function () {
            model.selectionStart = [1, 0];
            model.selectionEnd = [0, 0];
            chai_1.assert.equal(model.areSelectionValuesReversed(), true);
            model.selectionStart = [10, 2];
            model.selectionEnd = [0, 0];
            chai_1.assert.equal(model.areSelectionValuesReversed(), true);
        });
        it('should return false when the selection end is after selection start', function () {
            model.selectionStart = [0, 0];
            model.selectionEnd = [1, 0];
            chai_1.assert.equal(model.areSelectionValuesReversed(), false);
            model.selectionStart = [0, 0];
            model.selectionEnd = [10, 2];
            chai_1.assert.equal(model.areSelectionValuesReversed(), false);
        });
    });
    describe('onTrim', function () {
        it('should trim a portion of the selection when a part of it is trimmed', function () {
            model.selectionStart = [0, 0];
            model.selectionEnd = [10, 2];
            model.onTrim(1);
            chai_1.assert.deepEqual(model.finalSelectionStart, [0, 0]);
            chai_1.assert.deepEqual(model.finalSelectionEnd, [10, 1]);
            model.onTrim(1);
            chai_1.assert.deepEqual(model.finalSelectionStart, [0, 0]);
            chai_1.assert.deepEqual(model.finalSelectionEnd, [10, 0]);
        });
        it('should clear selection when it is trimmed in its entirety', function () {
            model.selectionStart = [0, 0];
            model.selectionEnd = [10, 0];
            model.onTrim(1);
            chai_1.assert.deepEqual(model.finalSelectionStart, null);
            chai_1.assert.deepEqual(model.finalSelectionEnd, null);
        });
    });
    describe('finalSelectionStart', function () {
        it('should return the start of the buffer if select all is active', function () {
            model.isSelectAllActive = true;
            chai_1.assert.deepEqual(model.finalSelectionStart, [0, 0]);
        });
        it('should return selection start if there is no selection end', function () {
            model.selectionStart = [2, 2];
            chai_1.assert.deepEqual(model.finalSelectionStart, [2, 2]);
        });
        it('should return selection end if values are reversed', function () {
            model.selectionStart = [2, 2];
            model.selectionEnd = [3, 2];
            chai_1.assert.deepEqual(model.finalSelectionStart, [2, 2]);
            model.selectionEnd = [1, 2];
            chai_1.assert.deepEqual(model.finalSelectionStart, [1, 2]);
        });
    });
    describe('finalSelectionEnd', function () {
        it('should return the end of the buffer if select all is active', function () {
            model.isSelectAllActive = true;
            chai_1.assert.deepEqual(model.finalSelectionEnd, [80, 1]);
        });
        it('should return null if there is no selection start', function () {
            chai_1.assert.equal(model.finalSelectionEnd, null);
            model.selectionEnd = [1, 2];
            chai_1.assert.equal(model.finalSelectionEnd, null);
        });
        it('should return selection start + length if there is no selection end', function () {
            model.selectionStart = [2, 2];
            model.selectionStartLength = 2;
            chai_1.assert.deepEqual(model.finalSelectionEnd, [4, 2]);
        });
        it('should return selection start + length if values are reversed', function () {
            model.selectionStart = [2, 2];
            model.selectionStartLength = 2;
            model.selectionEnd = [2, 1];
            chai_1.assert.deepEqual(model.finalSelectionEnd, [4, 2]);
        });
        it('should return selection start + length if selection end is inside the start selection', function () {
            model.selectionStart = [2, 2];
            model.selectionStartLength = 2;
            model.selectionEnd = [3, 2];
            chai_1.assert.deepEqual(model.finalSelectionEnd, [4, 2]);
        });
        it('should return selection end if selection end is after selection start + length', function () {
            model.selectionStart = [2, 2];
            model.selectionStartLength = 2;
            model.selectionEnd = [5, 2];
            chai_1.assert.deepEqual(model.finalSelectionEnd, [5, 2]);
        });
    });
});

//# sourceMappingURL=SelectionModel.test.js.map


text:
<?php

class RecorderTest extends PHPUnit_Framework_TestCase
{

    public function setup ()
    {
        $this->container = new \Mockery\Container(\Mockery::getDefaultGenerator(), \Mockery::getDefaultLoader());
    }

    public function teardown()
    {
        $this->container->mockery_close();
    }

    public function testRecorderWithSimpleObject()
    {
        $mock = $this->container->mock(new MockeryTestSubject);
        $mock->shouldExpect(function ($subject) {
            $user = new MockeryTestSubjectUser($subject);
            $user->doFoo();
        });

        $this->assertEquals(1, $mock->foo());
        $mock->mockery_verify();
    }

    public function testArgumentsArePassedAsMethodExpectations()
    {
        $mock = $this->container->mock(new MockeryTestSubject);
        $mock->shouldExpect(function ($subject) {
            $user = new MockeryTestSubjectUser($subject);
            $user->doBar();
        });

        $this->assertEquals(4, $mock->bar(2));
        $mock->mockery_verify();
    }

    public function testArgumentsLooselyMatchedByDefault()
    {
        $mock = $this->container->mock(new MockeryTestSubject);
        $mock->shouldExpect(function ($subject) {
            $user = new MockeryTestSubjectUser($subject);
            $user->doBar();
        });

        $this->assertEquals(4, $mock->bar('2'));
        $mock->mockery_verify();
    }

    public function testMultipleMethodExpectations()
    {
        $mock = $this->container->mock(new MockeryTestSubject);
        $mock->shouldExpect(function ($subject) {
            $user = new MockeryTestSubjectUser($subject);
            $user->doFoo();
            $user->doBar();
        });

        $this->assertEquals(1, $mock->foo());
        $this->assertEquals(4, $mock->bar(2));
        $mock->mockery_verify();
    }

    public function testRecordingDoesNotSpecifyExactOrderByDefault()
    {
        $mock = $this->container->mock(new MockeryTestSubject);
        $mock->shouldExpect(function ($subject) {
            $user = new MockeryTestSubjectUser($subject);
            $user->doFoo();
            $user->doBar();
        });

        $this->assertEquals(4, $mock->bar(2));
        $this->assertEquals(1, $mock->foo());
        $mock->mockery_verify();
    }

    /**
     * @expectedException \Mockery\Exception
     */
    public function testRecordingDoesSpecifyExactOrderInStrictMode()
    {
        $mock = $this->container->mock(new MockeryTestSubject);
        $mock->shouldExpect(function ($subject) {
            $subject->shouldBeStrict();
            $user = new MockeryTestSubjectUser($subject);
            $user->doFoo();
            $user->doBar();
        });

        $mock->bar(2);
        $mock->foo();
        $mock->mockery_verify();
    }

    /**
     * @expectedException \Mockery\Exception
     */
    public function testArgumentsAreMatchedExactlyUnderStrictMode()
    {
        $mock = $this->container->mock(new MockeryTestSubject);
        $mock->shouldExpect(function ($subject) {
            $subject->shouldBeStrict();
            $user = new MockeryTestSubjectUser($subject);
            $user->doBar();
        });

        $mock->bar('2');
    }

    /**
     * @expectedException \Mockery\Exception
     */
    public function testThrowsExceptionWhenArgumentsNotExpected()
    {
        $mock = $this->container->mock(new MockeryTestSubject);
        $mock->shouldExpect(function ($subject) {
            $user = new MockeryTestSubjectUser($subject);
            $user->doBar();
        });

        $mock->bar(4);
    }

    public function testCallCountUnconstrainedByDefault()
    {
        $mock = $this->container->mock(new MockeryTestSubject);
        $mock->shouldExpect(function ($subject) {
            $user = new MockeryTestSubjectUser($subject);
            $user->doBar();
        });

        $mock->bar(2);
        $this->assertEquals(4, $mock->bar(2));
        $mock->mockery_verify();
    }

    /**
     * @expectedException \Mockery\CountValidator\Exception
     */
    public function testCallCountConstrainedInStrictMode()
    {
        $mock = $this->container->mock(new MockeryTestSubject);
        $mock->shouldExpect(function ($subject) {
            $subject->shouldBeStrict();
            $user = new MockeryTestSubjectUser($subject);
            $user->doBar();
        });

        $mock->bar(2);
        $mock->bar(2);
        $mock->mockery_verify();
    }

}

class MockeryTestSubject {
    function foo() { return 1; }
    function bar($i) { return $i * 2; }
}

class MockeryTestSubjectUser {
    public $subject = null;
    function __construct($subject) { $this->subject = $subject; }
    function doFoo () { return $this->subject->foo(); }
    function doBar () { return $this->subject->bar(2); }
}


text:
class TerraformProviderCoreosver < Formula
  desc "Get latest coreos version for region"
  homepage "https://github.com/Samsung-AG/terraform-provider-coreosver"
  url "https://github.com/Samsung-AG/terraform-provider-coreosver/releases/download/v0.0.1/terraform-provider-coreosver_darwin_amd64.tar.gz"
  version "0.0.1"
  sha256 "de7e3887bc7229fb39d09d05c9e1e3b0de8647cb4b2ad2a2dc40d26e6f714078"

  def install
    bin.install "terraform-provider-coreosver"
  end
end


text:
"""
Copyright (c) 2018, Jairus Martin.

Distributed under the terms of the MIT License.

The full license is in the file LICENSE, distributed with this software.

Created on May 15, 2018

Converts Java classes to Python classes.

"""
import os
from jinja2 import Template
import fnmatch
import javalang
from javalang.tree import ClassDeclaration
from os.path import exists, join
from textwrap import dedent
from atom.api import *

SDK = os.path.expanduser('~/Android/Sdk/sources/android-27/')

class RefType(Atom):
    name = Str('JavaBridgeObject')

class Import(Atom):
    name = Str()
    pkg = Str()

def convert(path, node):
    """

    Parameters
    ----------
    path: String
        Path of the Java source file
    node: javalang node

    """
    root = node.package.name.replace(".", os.path.sep)
    if not exists(root):
        os.makedirs(root)
    if not exists(join(root, '__init__.py')):
        with open(join(root, '__init__.py'), 'w') as f:
            pass
    if not node.types or not isinstance(node.types[0], ClassDeclaration):
        print("No class in {}".format(path))
        return
    # Class
    cls = node.types[0]

    with open(join(root, cls.name+'.py'), 'w') as f:
        # Format imports
        scope = set()
        for imp in node.imports:
            imp.pkg = ".".join(imp.path.split(".")[:-1])
            imp.name = "*" if imp.wildcard else imp.path.split(".")[-1]
            scope.add(imp.name)

        # Import from local package if needed
        if cls.extends and cls.extends.name not in scope:
            node.imports.append(Import(pkg='.', name=cls.extends.name))

        # Format fields
        for f in cls.fields:
            if not hasattr(f, 'name'):
                f.name = f.decorators[0].name

        if cls.documentation:
            docs = '"""{}"""'.format("\n    ".join([
                l.lstrip().lstrip("*").replace("/*", "").replace("*/", "")
                for l in cls.documentation.split("\n")
            ]))
        else:
            docs = "# No docs"

        f.write(Template(dedent("""
        from atom.api import set_default
        {% for imp in node.imports %}
        from {{ imp.pkg }} import {{ imp.name }}
        {% endfor %}

        class {{cls.name}}({{base.name}}):
            {{ docs }}
            __nativeclass__ = set_default('{{node.package.name}}.{{cls.name}}')
        {% for f in cls.fields %}
            {{ f.name }} = JavaField({{f.type.name}}){% endfor %}
        {% for m in cls.methods %}{% if 'public' in m.modifiers %}
            {{ m.name }} = {% if 'static' in m.modifiers %}JavaStaticMethod{% else %}JavaMethod{% endif %}({% for p in m.parameters %}'{{p.type.name}}',{% endfor %}){% endif %}{% endfor %}

        """)).render(imports=node.imports,
                     node=node,
                     docs=docs,
                     cls=cls,
                     base=cls.extends or RefType()
        ))

def main():
    matches = []
    for root, dirnames, filenames in os.walk(SDK):
        rroot = os.path.relpath(root, SDK)
        if rroot.startswith('java') or rroot.startswith('android'):
            for filename in fnmatch.filter(filenames, '*.java'):
                matches.append(os.path.join(root, filename))

    for path in matches:
        print("Parsing {}".format(path))
        with open(path) as f:
            node = javalang.parse.parse(f.read())
        convert(path, node)

if __name__ == '__main__':
    main()


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="DataSourceManagerImpl" format="xml" hash="3023584877">
    <data-source source="LOCAL" name="MySQL - dev@127.0.0.1" uuid="30e49011-fe4c-4fb9-8456-9cb4c0143b28">
      <driver-ref>mysql</driver-ref>
      <synchronize>true</synchronize>
      <jdbc-driver>com.mysql.jdbc.Driver</jdbc-driver>
      <jdbc-url>jdbc:mysql://127.0.0.1:3306/dev</jdbc-url>
      <driver-properties>
        <property name="zeroDateTimeBehavior" value="convertToNull" />
        <property name="tinyInt1isBit" value="false" />
        <property name="characterEncoding" value="utf8" />
        <property name="characterSetResults" value="utf8" />
        <property name="yearIsDateType" value="false" />
      </driver-properties>
      <libraries />
    </data-source>
  </component>
</project>


text:
<?php

namespace Intacct\Functions\Traits;

use Intacct\Xml\XMLWriter;

trait CustomFieldsTrait
{

    /** @var array */
    protected $customFields = [];

    /**
     * Get custom fields
     *
     * @return array
     */
    public function getCustomFields(): array
    {
        return $this->customFields;
    }

    /**
     * Set custom fields
     *
     * @param array $customFields
     */
    public function setCustomFields(array $customFields)
    {
        $this->customFields = $customFields;
    }

    /**
     * @param XMLWriter $xml
     */
    protected function writeXmlExplicitCustomFields(XMLWriter &$xml)
    {
        if (count($this->customFields) > 0) {
            $xml->startElement('customfields');
            foreach ($this->customFields as $customFieldName => $customFieldValue) {
                $xml->startElement('customfield');
                $xml->writeElement('customfieldname', $customFieldName, true);
                $xml->writeElement('customfieldvalue', $customFieldValue, true);
                $xml->endElement(); //customfield
            }
            $xml->endElement(); //customfields
        }
    }

    /**
     * @param XMLWriter $xml
     */
    protected function writeXmlImplicitCustomFields(XMLWriter &$xml)
    {
        if (count($this->customFields) > 0) {
            foreach ($this->customFields as $customFieldName => $customFieldValue) {
                $xml->writeElement($customFieldName, $customFieldValue, true);
            }
        }
    }
}


text:
require 'adwords_api'

def add_site_links(campaign_id, ad_group_id)
  # AdwordsApi::Api will read a config file from ENV['HOME']/adwords_api.yml
  # when called without parameters.
  adwords = AdwordsApi::Api.new

  # To enable logging of SOAP requests, set the log_level value to 'DEBUG' in
  # the configuration file or provide your own logger:
  # adwords.logger = Logger.new('adwords_xml.log')

  feed_srv = adwords.service(:FeedService, API_VERSION)
  feed_item_srv = adwords.service(:FeedItemService, API_VERSION)
  feed_item_target_srv = adwords.service(:FeedItemTargetService, API_VERSION)
  feed_mapping_srv = adwords.service(:FeedMappingService, API_VERSION)
  campaign_feed_srv = adwords.service(:CampaignFeedService, API_VERSION)

  sitelinks_data = {}

  # Create site links feed first.
  site_links_feed = {
    :name => 'Feed For Site Links',
    :attributes => [
      {:type => 'STRING', :name => 'Link Text'},
      {:type => 'URL_LIST', :name => 'Final URLs'},
      {:type => 'STRING', :name => 'Line 2 Description'},
      {:type => 'STRING', :name => 'Line 3 Description'}
    ]
  }

  response = feed_srv.mutate([
      {:operator => 'ADD', :operand => site_links_feed}
  ])
  unless response.nil? || response[:value].nil?
    feed = response[:value].first
    # Attribute of type STRING.
    link_text_feed_attribute_id = feed[:attributes][0][:id]
    # Attribute of type URL_LIST.
    final_url_feed_attribute_id = feed[:attributes][1][:id]
    # Attribute of type STRING.
    line_2_feed_attribute_id = feed[:attributes][2][:id]
    # Attribute of type STRING.
    line_3_feed_attribute_id = feed[:attributes][3][:id]
    puts "Feed with name '%s' and ID %d was added with" %
        [feed[:name], feed[:id]]
    puts ("\tText attribute ID %d and Final URLs attribute ID %d " +
        "and Line 2 attribute ID %d and Line 3 attribute ID %d.") % [
          link_text_feed_attribute_id,
          final_url_feed_attribute_id,
          line_2_feed_attribute_id,
          line_3_feed_attribute_id
        ]

    sitelinks_data[:feed_id] = feed[:id]
    sitelinks_data[:link_text_feed_id] = link_text_feed_attribute_id
    sitelinks_data[:final_url_feed_id] = final_url_feed_attribute_id
    sitelinks_data[:line_2_feed_id] = line_2_feed_attribute_id
    sitelinks_data[:line_3_feed_id] = line_3_feed_attribute_id
  else
    raise new StandardError, 'No feeds were added.'
  end

  # Create site links feed items.
  items_data = [
    {
      :text => 'Home',
      :final_urls => ['http://www.example.com'],
      :line_2 => 'Home line 2',
      :line_3 => 'Home line 3'
    },
    {
      :text => 'Stores',
      :final_urls => ['http://www.example.com/stores'],
      :line_2 => 'Stores line 2',
      :line_3 => 'Stores line 3'
     },
    {
      :text => 'On Sale',
      :final_urls => ['http://www.example.com/sale'],
      :line_2 => 'On Sale line 2',
      :line_3 => 'On Sale line 3'
    },
    {
      :text => 'Support',
      :final_urls => ['http://www.example.com/support'],
      :line_2 => 'Support line 2',
      :line_3 => 'Support line 3'
    },
    {
      :text => 'Products',
      :final_urls => ['http://www.example.com/products'],
      :line_2 => 'Products line 2',
      :line_3 => 'Products line 3'
    },
    {
      :text => 'About Us',
      :final_urls => ['http://www.example.com/about'],
      :line_2 => 'About line 2',
      :line_3 => 'About line 3'
    }
  ]

  feed_items = items_data.map do |item|
    {
      :feed_id => sitelinks_data[:feed_id],
      :attribute_values => [
        {
          :feed_attribute_id => sitelinks_data[:link_text_feed_id],
          :string_value => item[:text]
        },
        {
          :feed_attribute_id => sitelinks_data[:final_url_feed_id],
          :string_values => item[:final_urls]
        },
        {
          :feed_attribute_id => sitelinks_data[:line_2_feed_id],
          :string_value => item[:line_2]
        },
        {
          :feed_attribute_id => sitelinks_data[:line_3_feed_id],
          :string_value => item[:line_3]
        }
      ]
    }
  end
  # The "About us" site link is using geographical targeting to use
  # LOCATION_OF_PRESENCE.
  feed_items.last[:geo_targeting_restriction] = {
    :geo_restriction => 'LOCATION_OF_PRESENCE'
  }

  feed_items_operations = feed_items.map do |item|
    {:operator => 'ADD', :operand => item}
  end

  response = feed_item_srv.mutate(feed_items_operations)
  unless response.nil? || response[:value].nil?
    sitelinks_data[:feed_item_ids] = []
    response[:value].each do |feed_item|
      puts 'Feed item with ID %d was added.' % feed_item[:feed_item_id]
      sitelinks_data[:feed_item_ids] << feed_item[:feed_item_id]
    end
  else
    raise new StandardError, 'No feed items were added.'
  end

  # Target the "About Us" sitelink to geographically target California.
  # See https://developers.google.com/adwords/api/docs/appendix/geotargeting
  # for location criteria for supported locations.
  criterion_target = {
    :xsi_type => 'FeedItemCriterionTarget',
    :feed_id => feed_items[5][:feed_id],
    :feed_item_id => sitelinks_data[:feed_item_ids][5],
    :criterion => {
      :xsi_type => 'Location',
      :id => 21137 # California
    }
  }

  retval = feed_item_target_srv.mutate([{
    :operator => 'ADD',
    :operand => criterion_target
  }])
  new_location_target = retval[:value].first
  puts ('Feed item target for feed ID %d and feed item ID %d was created to' +
      'restrict serving to location ID %d.') % [new_location_target[:feed_id],
      new_location_target[:feed_item_id], new_location_target[:criterion][:id]]

  # Create site links feed mapping.
  feed_mapping = {
    :placeholder_type => PLACEHOLDER_SITELINKS,
    :feed_id => sitelinks_data[:feed_id],
    :attribute_field_mappings => [
      {
        :feed_attribute_id => sitelinks_data[:link_text_feed_id],
        :field_id => PLACEHOLDER_FIELD_SITELINK_LINK_TEXT
      },
      {
        :feed_attribute_id => sitelinks_data[:final_url_feed_id],
        :field_id => PLACEHOLDER_FIELD_SITELINK_FINAL_URLS
      },
      {
        :feed_attribute_id => sitelinks_data[:line_2_feed_id],
        :field_id => PLACEHOLDER_FIELD_SITELINK_LINE_2_TEXT
      },
      {
        :feed_attribute_id => sitelinks_data[:line_3_feed_id],
        :field_id => PLACEHOLDER_FIELD_SITELINK_LINE_3_TEXT
      }
    ]
  }

  response = feed_mapping_srv.mutate([
      {:operator => 'ADD', :operand => feed_mapping}
  ])
  unless response.nil? || response[:value].nil?
    feed_mapping = response[:value].first
    puts ('Feed mapping with ID %d and placeholder type %d was saved for feed' +
        ' with ID %d.') % [
          feed_mapping[:feed_mapping_id],
          feed_mapping[:placeholder_type],
          feed_mapping[:feed_id]
        ]
  else
    raise new StandardError, 'No feed mappings were added.'
  end

  # Construct a matching function that associates the sitelink feeditems to the
  # campaign, and set the device preference to Mobile. See the matching function
  # guide at:
  # https://developers.google.com/adwords/api/docs/guides/feed-matching-functions
  # for more details.
  matching_function_string =
      "AND(IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, 'Mobile'))" %
      sitelinks_data[:feed_item_ids].join(',')

  # Create site links campaign feed.
  campaign_feed = {
    :feed_id => sitelinks_data[:feed_id],
    :campaign_id => campaign_id,
    :matching_function => {:function_string => matching_function_string},
    # Specifying placeholder types on the CampaignFeed allows the same feed
    # to be used for different placeholders in different Campaigns.
    :placeholder_types => [PLACEHOLDER_SITELINKS]
  }

  response = campaign_feed_srv.mutate([
      {:operator => 'ADD', :operand => campaign_feed}
  ])
  unless response.nil? || response[:value].nil?
    campaign_feed = response[:value].first
    puts 'Campaign with ID %d was associated with feed with ID %d.' %
      [campaign_feed[:campaign_id], campaign_feed[:feed_id]]
  else
    raise new StandardError, 'No campaign feeds were added.'
  end

  # Optional: Restrict the first feed item to only serve with ads for the
  # specified ad group ID.
  if !ad_group_id.nil? && ad_group_id != 0
    feed_item_target = {
      :xsi_type => 'FeedItemAdGroupTarget',
      :feed_id => sitelinks_data[:feed_id],
      :feed_item_id => sitelinks_data[:feed_item_ids].first,
      :ad_group_id => ad_group_id
    }

    operation = {
      :operator => 'ADD',
      :operand => feed_item_target
    }

    response = feed_item_target_srv.mutate([operation])
    unless response.nil? || response[:value].nil?
      feed_item_target = response[:value].first
      puts ('Feed item target for feed ID %d and feed item ID %d' +
          ' was created to restrict serving to ad group ID %d') %
          [feed_item_target[:feed_id], feed_item_target[:feed_item_id],
          feed_item_target[:ad_group_id]]
    end
  end
end

if __FILE__ == $0
  API_VERSION = :v201809

  # See the Placeholder reference page for a list of all the placeholder types
  # and fields, see:
  #     https://developers.google.com/adwords/api/docs/appendix/placeholders
  PLACEHOLDER_SITELINKS = 1
  PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = 1
  PLACEHOLDER_FIELD_SITELINK_FINAL_URLS = 5
  PLACEHOLDER_FIELD_SITELINK_LINE_2_TEXT = 3
  PLACEHOLDER_FIELD_SITELINK_LINE_3_TEXT = 4

  begin
    # Campaign ID to add site link to.
    campaign_id = 'INSERT_CAMPAIGN_ID_HERE'.to_i
    # Optional: Ad group to restrict targeting to.
    ad_group_id = 'INSERT_AD_GROUP_ID_HERE'.to_i
    add_site_links(campaign_id, ad_group_id)

  # Authorization error.
  rescue AdsCommon::Errors::OAuth2VerificationRequired => e
    puts "Authorization credentials are not valid. Edit adwords_api.yml for " +
        "OAuth2 client ID and secret and run misc/setup_oauth2.rb example " +
        "to retrieve and store OAuth2 tokens."
    puts "See this wiki page for more details:\n\n  " +
        'https://github.com/googleads/google-api-ads-ruby/wiki/OAuth2'

  # HTTP errors.
  rescue AdsCommon::Errors::HttpError => e
    puts "HTTP Error: %s" % e

  # API errors.
  rescue AdwordsApi::Errors::ApiException => e
    puts "Message: %s" % e.message
    puts 'Errors:'
    e.errors.each_with_index do |error, index|
      puts "\tError [%d]:" % (index + 1)
      error.each do |field, value|
        puts "\t\t%s: %s" % [field, value]
      end
    end
  end
end