text:
package chav1961.funnypro.core;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

import chav1961.funnypro.core.FProUtil.ContentType;
import chav1961.funnypro.core.entities.AnonymousEntity;
import chav1961.funnypro.core.entities.IntegerEntity;
import chav1961.funnypro.core.entities.ListEntity;
import chav1961.funnypro.core.entities.OperatorDefEntity;
import chav1961.funnypro.core.entities.OperatorEntity;
import chav1961.funnypro.core.entities.PredicateEntity;
import chav1961.funnypro.core.entities.RealEntity;
import chav1961.funnypro.core.entities.StringEntity;
import chav1961.funnypro.core.entities.VariableEntity;
import chav1961.funnypro.core.interfaces.IFProEntitiesRepo;
import chav1961.funnypro.core.interfaces.IFProEntitiesRepo.Classification;
import chav1961.funnypro.core.interfaces.IFProEntity;
import chav1961.funnypro.core.interfaces.IFProEntity.EntityType;
import chav1961.funnypro.core.interfaces.IFProExternalEntity;
import chav1961.funnypro.core.interfaces.IFProList;
import chav1961.funnypro.core.interfaces.IFProOperator;
import chav1961.funnypro.core.interfaces.IFProOperator.OperatorSort;
import chav1961.funnypro.core.interfaces.IFProOperator.OperatorType;
import chav1961.funnypro.core.interfaces.IFProParserAndPrinter;
import chav1961.funnypro.core.interfaces.IFProPredicate;
import chav1961.funnypro.core.interfaces.IFProRuledEntity;
import chav1961.funnypro.core.interfaces.IFProVariable;
import chav1961.funnypro.core.interfaces.IFProModule;
import chav1961.purelib.basic.BitCharSet;
import chav1961.purelib.basic.CharUtils;
import chav1961.purelib.basic.ExtendedBitCharSet;
import chav1961.purelib.basic.SubstitutableProperties;
import chav1961.purelib.basic.exceptions.ContentException;
import chav1961.purelib.basic.exceptions.PrintingException;
import chav1961.purelib.basic.exceptions.SyntaxException;
import chav1961.purelib.basic.growablearrays.GrowableCharArray;
import chav1961.purelib.basic.interfaces.LoggerFacade;
import chav1961.purelib.streams.interfaces.CharacterSource;
import chav1961.purelib.streams.interfaces.CharacterTarget;

public class ParserAndPrinter implements IFProParserAndPrinter, IFProModule {
	private static final ExtendedBitCharSet	VALID_LETTERS = new ExtendedBitCharSet();
	private static final ExtendedBitCharSet	VALID_UPPER_LETTERS = new ExtendedBitCharSet();
	private static final ExtendedBitCharSet	VALID_LOWER_LETTERS = new ExtendedBitCharSet();
	private static final BitCharSet			PUNCTUATIONS = new BitCharSet();

	private final long						colonId, tailId, goalId, emptyStringId = 0;
	private final LoggerFacade				log;
	private final SubstitutableProperties	props;
	private final IFProEntitiesRepo			repo;
	private final long						tempLong[] = new long[2], entityId[] = new long[1];

	private enum NameClassification {
		anonymous, term
	}

	static {
		VALID_LETTERS.add('_');
		VALID_LETTERS.addRange('a','z');
		VALID_LETTERS.addRange('A','Z');
		VALID_LETTERS.addRange('\u0410','\u044F');
		VALID_LETTERS.add('\u0401');
		VALID_LETTERS.add('\u0451');
		VALID_LETTERS.addRange('0','9');

		VALID_UPPER_LETTERS.addRange('A','Z');
		VALID_UPPER_LETTERS.addRange('\u0410','\u042F');
		VALID_UPPER_LETTERS.add('\u0401');

		VALID_LOWER_LETTERS.addRange('a','z');
		VALID_LOWER_LETTERS.addRange('\u0430','\u044F');
		VALID_LOWER_LETTERS.add('\u0451');

		PUNCTUATIONS.addRange((char)0x21,(char)0x26);
		PUNCTUATIONS.addRange((char)0x2A,(char)0x2D);
		PUNCTUATIONS.add((char)0x2F);
		PUNCTUATIONS.add((char)0x3A);
		PUNCTUATIONS.addRange((char)0x3C,(char)0x3F);
		PUNCTUATIONS.add((char)0x5C);
		PUNCTUATIONS.add((char)0x60);
		PUNCTUATIONS.add((char)0x7E);
		PUNCTUATIONS.add((char)0x2E);	// .
	}

	private final int[]		forIntResult = new int[2];

	public ParserAndPrinter(final LoggerFacade log, final SubstitutableProperties prop, final IFProEntitiesRepo repo) throws SyntaxException, NullPointerException {
		if (log == null) {
			throw new NullPointerException("Log can't be null");
		}
		else if (prop == null) {
			throw new NullPointerException("Properties can't be null");
		}
		else if (repo == null) {
			throw new NullPointerException("Entities repo can't bw null");
		}
		else {
			this.log = log;			this.props = prop;
			this.repo = repo;
			this.colonId = repo.termRepo().seekName(",");
			this.tailId = repo.termRepo().seekName("|");
			this.goalId = repo.termRepo().seekName(":-");
		}
	}

	@Override public LoggerFacade getDebug() {return log;}
	@Override public Properties getParameters() {return props;}

	public IFProEntitiesRepo getRepo() {
		return repo;
	}

	@Override
	public void parseEntities(final CharacterSource source, final FProParserCallback callback) throws SyntaxException, IOException, ContentException, NullPointerException {
		if (source == null) {
			throw new NullPointerException("Source reader can't be null");
		}
		else if (callback == null) {
			throw new NullPointerException("Callback can't be null");
		}
		else {
			final GrowableCharArray<GrowableCharArray<?>>	gca = new GrowableCharArray<>(false);
			char						symbol;

			while ((symbol = source.next()) != CharacterSource.EOF) {
				gca.append(symbol);
			}
			parseEntities(gca.extract(),0,callback);
			gca.clear();
		}
	}

	@Override
	public int parseEntities(final char[] source, int from, final FProParserCallback callback) throws SyntaxException, IOException, NullPointerException, IllegalArgumentException {
		if (source == null) {
			throw new NullPointerException("Source array can't be null");
		}
		else if (from < 0 || from >= source.length) {
			throw new IllegalArgumentException("From position ["+from+"] out of range 0.."+(source.length-1));
		}
		else if (callback == null) {
			throw new NullPointerException("Parser callback can't be null");
		}
		else {
			final List<IFProVariable>	vars = new ArrayList<>();

			try{final IFProEntity[]		result = new IFProEntity[1];

				while (from < source.length) {
					try(final VarRepo	varRepo = new VarRepo(vars)) {
						from = parse(source,from,repo.getOperatorPriorities(),IFProOperator.MAX_PRTY,varRepo,result);
					}
					if (result[0] != null) {
						if (!callback.process(result[0],vars)) {
							break;
						}
						else {
							vars.clear();
						}
					}
					else {
						break;
					}
				}
				return from;
			} catch (Exception e) {
				if (e instanceof SyntaxException) {
					throw (SyntaxException)e;
				}
				else {
					e.printStackTrace();
					throw new SyntaxException(0,0,e.getMessage(),e);
				}
			}
		}
	}

	@Override
	public void putEntity(final IFProEntity entity, final CharacterTarget target) throws IOException, PrintingException , NullPointerException{
		if (entity == null) {
			throw new NullPointerException("Entity to put can't be null!");
		}
		else if (target == null) {
			throw new NullPointerException("Target stream can't be null!");
		}
		else {
			switch (entity.getEntityType()) {
				case string				:
					if (entity.getEntityId() == StringEntity.EMPTY_STRING_ID) {
						target.put("\"\"");
					}
					else {
						target.put('\"').put(getRepo().stringRepo().getName(entity.getEntityId())).put('\"');
					}
					break;
				case integer			:
					target.put(String.valueOf(entity.getEntityId()));
					break;
				case real				:
					target.put(String.valueOf(Double.longBitsToDouble(entity.getEntityId())));
					break;
				case anonymous			:
					target.put('_');
					break;
				case variable			:
					target.put(getRepo().termRepo().getName(entity.getEntityId()));
					break;
				case list				:
					if (((IFProList)entity).getChild() == null && ((IFProList)entity).getTail() == null) {
						target.put("[]");
					}
					else {
						char			start = '[';
						IFProEntity		actual = entity;

						while (actual instanceof IFProList) {
							target.put(start);		start = ',';
							putEntity(((IFProList)actual).getChild(),target);
							actual = ((IFProList)actual).getTail();
						}

						if (actual != null) {
							target.put('|');	putEntity(actual,target);
						}
						target.put("]");
					}
					break;
				case operator			:
					final String	opName = blankedName(getRepo().termRepo().getName(entity.getEntityId()));

					switch (((IFProOperator)entity).getOperatorType().getSort()) {
						case prefix		:
							printBracket(target,(IFProOperator)entity,((IFProOperator)entity).getLeft());
							target.put(opName);
							break;
						case postfix	:
							target.put(opName);
							printBracket(target,(IFProOperator)entity,((IFProOperator)entity).getRight());
							break;
						case infix		:
							printBracket(target,(IFProOperator)entity,((IFProOperator)entity).getLeft());
							target.put(opName);
							printBracket(target,(IFProOperator)entity,((IFProOperator)entity).getRight());
							break;
					}
					if (((IFProRuledEntity)entity).getRule() != null) {
						target.put(":-");
						putEntity(((IFProRuledEntity)entity).getRule(),target);
					}
					break;
				case predicate			:
					target.put(getRepo().termRepo().getName(entity.getEntityId()));
					if (((IFProPredicate)entity).getArity() > 0) {
						char	prefix = '(';

						for (int index = 0; index < ((IFProPredicate)entity).getArity(); index++) {
							target.put(prefix);	prefix = ',';
							putEntity(((IFProPredicate)entity).getParameters()[index],target);
						}
						target.put(')');
					}
					if (((IFProRuledEntity)entity).getRule() != null) {
						target.put(":-");
						putEntity(((IFProRuledEntity)entity).getRule(),target);
					}
					break;
				case operatordef		:
					target.put(String.format("op(%1$d,%2$s,%3$s)",((IFProOperator)entity).getPriority(),((IFProOperator)entity).getOperatorType(),repo.termRepo().getName(entity.getEntityId())));
					break;
				default :
					throw new UnsupportedOperationException("Unknown type ti upload: "+entity.getEntityType());
			}
		}
	}

	@Override
	public int putEntity(final IFProEntity entity, final char[] target, int from) throws IOException, PrintingException {
		final int	result = internalPutEntity(entity,target,from);

		return result > target.length ? -result : result;
	}

	@FunctionalInterface
	private interface ValidationError {
		void print(String validationError) throws SyntaxException;
	}

	private int parse(final char[] source, int from, final int[] priorities, final int maxPrty, final VarRepo vars, final IFProEntity[] result) throws ContentException, IOException, SyntaxException {
		final IFProEntity[]	top = new IFProEntity[priorities.length+1];
		final int			maxLen = source.length;
		boolean				prefixNow = true, found;
		int					actualMin = IFProOperator.MIN_PRTY, actualMax = maxPrty;

		while (from < maxLen && source[from] <= ' ') from++;

loop:	while (from < maxLen && source[from] != '.') {
			while (from < maxLen && source[from] <= ' ') from++;

			switch (source[from]) {
				case '%'	:
					while (from < maxLen && source[from] != '\n') {
						from++;
					}
				case '\n'	:
					continue loop;
				case '\r'	:
					from++;
					continue loop;
				case '['	:
					from++;
					if (!prefixNow) {
						throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Two operands witout infix operators detected");
					}
					else {
						while (from < maxLen && source[from] <= ' ') from++;

						if (from < maxLen && source[from] == ']') {
							from++;
							top[0] = new ListEntity(null,null);
							actualMin = IFProOperator.MIN_PRTY+1;		actualMax = maxPrty;
							prefixNow = false;
						}
						else {
							from = parse(source,from,priorities,1151,vars,result);

							if (from < maxLen && source[from] == ']') {
								from++;
								top[0] = convert2List(source,from,result[0]);
								actualMin = IFProOperator.MIN_PRTY+1;		actualMax = maxPrty;
								prefixNow = false;
							}
							else {
								throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Close bracket ']' missing!");
							}
						}
					}
					break;
				case '('	:
					from++;
					if (!prefixNow) {
						throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Two operands witout infix operators detected");
					}
					else {
						from = parse(source,from,priorities,1101,vars,result);

						while (from < maxLen && source[from] <= ' ') from++;
						if (from < maxLen && source[from] == ')') {
							from++;
							top[0] = result[0];
							actualMin = IFProOperator.MIN_PRTY+1;		actualMax = maxPrty;
							prefixNow = false;
						}
						else {
							throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Close bracket ')' missing!");
						}
					}
					break;
				case ')'	:
				case ']'	:
					break loop;
				case '\"'	:
					final int	startConst = from++;

					while (from < maxLen && source[from] != '\"' && source[from] != '\n') {
						from++;
					}

					if (from < maxLen && source[from] == '\"') {
						final long	stringId = startConst+1 == from ? emptyStringId : getRepo().stringRepo().placeName(source,startConst+1,from,null);

						if (!prefixNow) {
							throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Two operands witout infix operators detected");
						}
						else {
							top[0] = new StringEntity(stringId);
							actualMin = IFProOperator.MIN_PRTY+1;		actualMax = maxPrty;
							prefixNow = false;
							from++;
						}
					}
					else {
						throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Unclosed quoted string detected");
					}
					break;
				case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : case '9' :

					from = CharUtils.parseNumber(source,from,tempLong,CharUtils.PREF_ANY,false);
					if (!prefixNow) {
						throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Two operands witout infix operators detected");
					}
					else {
						switch ((int)tempLong[1]) {
							case CharUtils.PREF_INT 	: top[0] = new IntegerEntity(tempLong[0]); break;
							case CharUtils.PREF_LONG 	: top[0] = new IntegerEntity(tempLong[0]); break;
							case CharUtils.PREF_FLOAT 	: top[0] = new RealEntity(Float.intBitsToFloat((int)tempLong[0])); break;
							case CharUtils.PREF_DOUBLE	: top[0] = new RealEntity(Double.longBitsToDouble(tempLong[0])); break;
						}
						actualMin = IFProOperator.MIN_PRTY+1;		actualMax = maxPrty;
						prefixNow = false;
					}
					break;
				case '!' :	// 'cut' predicate
					from++;
					if (!prefixNow) {
						throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Two operands witout infix operators detected");
					}
					else {
						top[0] = new PredicateEntity(repo.termRepo().placeName("!",null));
						actualMin = IFProOperator.MIN_PRTY+1;		actualMax = maxPrty;
						prefixNow = false;
					}
					break;
				default :
					if (VALID_UPPER_LETTERS.contains(source[from])) {
						final int	startVar = from, endVar = from = skipName(source,from);
						final long	varId = getRepo().termRepo().placeName(source,startVar,endVar,null);
						final IFProVariable		var = new VariableEntity(varId);

						if (!prefixNow) {
							throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Two operands witout infix operators detected");
						}
						else {
							top[0] = var;
							vars.storeVariable(var);
							actualMin = IFProOperator.MIN_PRTY+1;		actualMax = maxPrty;
							prefixNow = false;
						}
					}
					else if (VALID_LOWER_LETTERS.contains(source[from]) || source[from] == '_') {
						final int	startName = from, endName = from = skipName(source,from);
						final long	nameId = getRepo().termRepo().placeName(source,startName,endName,null);

						switch (classifyName(source,startName,endName)) {
							case anonymous	:
								if (!prefixNow) {
									throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Two operands witout infix operators detected");
								}
								else {
									top[0] = new AnonymousEntity();
									prefixNow = false;
								}
								break;
							case term		:
								switch (getRepo().classify(nameId)) {
									case operator 	:
										found = false;

										if (prefixNow) {
											for (IFProOperator item : getRepo().getOperatorDef(nameId // See prefix operators with nearest priorities
																						,actualMax
																						,actualMin
																						,OperatorSort.postfix)) {
												final int 	location = Arrays.binarySearch(priorities,item.getPriority()) + 1;

												if (location > 0) {
													final IFProOperator	op = new OperatorEntity(item);

													if (top[location] != null) {
														op.setParent(top[location]);
														((IFProOperator)top[location]).setRight(op);
														top[location] = op;
													}
													else {
														top[location] = op;
													}
													actualMax = item.getUnderlyingPriority();
													found = true;		break;
												}
											}
										}
										else {
											for (IFProOperator item : getRepo().getOperatorDef(nameId // See postfix operators with nearest priorities
																						,actualMin
																						,actualMax
																						,OperatorSort.prefix)) {
												final int 	location = Arrays.binarySearch(priorities,item.getPriority()) + 1;

												if (location > 0) {
													final IFProOperator	op = new OperatorEntity(item);

													top[location] = op.setLeft(collapse(top,location).setParent(op));
													actualMin = item.getPriority() + (item.getOperatorType() == OperatorType.xf ? 1 : 0);
													found = true;
													break;
												}
											}
											if (!found) {
												for (IFProOperator item : getRepo().getOperatorDef(nameId // See infix operators with nearest priorities
																							,actualMin
																							,actualMax
																							,OperatorSort.infix)) {
													final int 	location = Arrays.binarySearch(priorities,item.getPriority()) + 1;

													if (location > 0) {
														final IFProOperator	op = new OperatorEntity(item);

														top[location] = op.setLeft(collapse(top,location).setParent(op));
														actualMax = item.getUnderlyingPriority(IFProOperator.RIGHT);
														actualMin = IFProOperator.MIN_PRTY;
														prefixNow = true;
														found = true;
														break;
													}
												}
											}
										}
										if (!found) {
											throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Illegal nesting!");
										}
										break;
									case term 		:
										if (!prefixNow) {
											throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Two operands witout infix operators detected");
										}
										else {
											top[0] = new PredicateEntity(nameId);

											while (from < maxLen && source[from] <= ' ') {
												from++;
											}
											if (from < maxLen && source[from] == '(') {
												from++;
												while (from < maxLen && source[from] <= ' ') {
													from++;
												}
												if (from < maxLen && source[from] == ')') {
													from++;
												}
												else {
													from = parse(source,from,priorities,1101,vars,result);

													while (from < maxLen && source[from] <= ' ') {
														from++;
													}
													if (from < maxLen && source[from] == ')') {
														from++;
														((IFProPredicate)top[0]).setParameters(andChain2Array(result[0],top[0],colonId));
													}
													else {
														throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Close bracket ')' missing!");
													}
												}
											}
											actualMin = IFProOperator.MIN_PRTY+1;		actualMax = maxPrty;
											prefixNow = false;
										}
										break;
									case op		:
										if (!prefixNow) {
											throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Two operands witout infix operators detected");
										}
										else {
											from = parseOp(source,from,result);
											top[0] = result[0];
											actualMin = IFProOperator.MIN_PRTY+1;		actualMax = maxPrty;
											prefixNow = false;
										}
										break;
									default :
										throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Unsupported classification ["+getRepo().classify(nameId)+"] for the term");
								}
								break;
							default:
								throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Unsupported classification ["+classifyName(source,startName,endName)+"] for the term");
						}
					}
					else {
						from = extractEntityId(source,from,entityId);
						found = false;

						if (repo.classify(entityId[0]) != Classification.operator) {
							throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Operator awaited!");
						}

						if (prefixNow) {
							for (IFProOperator item : getRepo().getOperatorDef(entityId[0] // See prefix operators with nearest priorities
																		,actualMax
																		,actualMin
																		,OperatorSort.postfix)) {
								final int 	location = Arrays.binarySearch(priorities,item.getPriority()) + 1;

								if (location > 0) {
									final IFProOperator	op = new OperatorEntity(item);

									if (top[location] != null) {
										op.setParent(top[location]);
										((IFProOperator)top[location]).setRight(op);
										top[location] = op;
									}
									else {
										top[location] = op;
									}
									actualMax = item.getUnderlyingPriority();
									found = true;		break;
								}
							}
						}
						else {
							for (IFProOperator item : getRepo().getOperatorDef(entityId[0] // See postfix operators with nearest priorities
																		,actualMin
																		,actualMax
																		,OperatorSort.prefix)) {
								final int 	location = Arrays.binarySearch(priorities,item.getPriority()) + 1;

								if (location > 0) {
									final IFProOperator	op = new OperatorEntity(item);

									top[location] = op.setLeft(collapse(top,location).setParent(op));
									actualMin = item.getPriority() + (item.getOperatorType() == OperatorType.xf ? 1 : 0);
									found = true;
									break;
								}
							}
							if (!found) {
								for (IFProOperator item : getRepo().getOperatorDef(entityId[0] // See infix operators with nearest priorities
																			,actualMin
																			,actualMax
																			,OperatorSort.infix)) {
									final int 	location = Arrays.binarySearch(priorities,item.getPriority()) + 1;

									if (location > 0) {
										final IFProOperator	op = new OperatorEntity(item);

										if (top[location] == null) {
											top[location] = op.setLeft(collapse(top,location).setParent(op));
										}
										else if (((IFProOperator)top[location]).getOperatorType() == OperatorType.fy || ((IFProOperator)top[location]).getOperatorType() == OperatorType.yf || ((IFProOperator)top[location]).getOperatorType() == OperatorType.xfy) {
											((IFProOperator)top[location]).setRight(op.setLeft(collapse(top,location-1).setParent(top[location])));
											top[location] = op.setParent(top[location]);
										}
										else if (op.getOperatorType() == OperatorType.yfx) {
											top[location] = op.setLeft(collapse(top,location).setParent(op));
										}
										else {
											throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Illegal nesting for operator ["+repo.termRepo().getName(entityId[0])+"]!");
										}
										actualMax = item.getUnderlyingPriority(IFProOperator.RIGHT);
										actualMin = IFProOperator.MIN_PRTY;
										prefixNow = true;
										found = true;
										break;
									}
								}
							}
						}
						if (!found) {
							throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Illegal nesting for operator ["+repo.termRepo().getName(entityId[0])+"]!");
						}
						break;
					}
			}
			while (from < maxLen && source[from] <= ' ') from++;
		}
		if (from < maxLen && source[from] == '.') {
			from++;
		}
		result[0] = collapse(top,top.length-1);
		if (result[0] != null && result[0].getEntityType() == EntityType.operator
			&& ((IFProOperator)result[0]).getOperatorType() == OperatorType.xfx
			&& ((IFProOperator)result[0]).getEntityId() == goalId
			&& ((IFProOperator)result[0]).getLeft().getEntityType() == EntityType.predicate) {

			if (((IFProOperator)result[0]).getRight() == null) {
				throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Missing rule in ruled predicate/operator ["+repo.termRepo().getName(((IFProOperator)result[0]).getLeft().getEntityId())+"]!");
			}
			else {
				result[0] = convert2Ruled(result[0]);
			}
		}
		final int	localFrom = from;

		if (result[0] != null) {
			validateResult(result[0],(e)->{throw new SyntaxException(SyntaxException.toRow(source,localFrom),SyntaxException.toCol(source,localFrom),"Invalid parsed entity: "+e);});
		}
		return from;
	}

	private void validateResult(final IFProEntity entity, final ValidationError print) throws SyntaxException {
		switch (entity.getEntityType()) {
			case anonymous			:
				break;
			case externalplugin		:
				break;
			case integer			:
				break;
			case list				:
				if (((IFProList)entity).getChild() != null) {
					validateResult(((IFProList)entity).getChild(),print);
				}
				if (((IFProList)entity).getTail() != null) {
					validateResult(((IFProList)entity).getTail(),print);
				}
				break;
			case operator:
				switch (((IFProOperator)entity).getOperatorType().getSort()) {
					case infix		:
						if (((IFProOperator)entity).getLeft() == null) {
							print.print("Left operand of infix operator is missing");
						}
						else {
							validateResult(((IFProOperator)entity).getLeft(), print);
						}
						if (((IFProOperator)entity).getRight() == null) {
							print.print("Right operand of infix operator is missing");
						}
						else {
							validateResult(((IFProOperator)entity).getRight(), print);
						}
						break;
					case postfix	:
						if (((IFProOperator)entity).getRight() == null) {
							print.print("Operand of postfix operator is missing");
						}
						else {
							validateResult(((IFProOperator)entity).getRight(), print);
						}
						break;
					case prefix		:
						if (((IFProOperator)entity).getLeft() == null) {
							print.print("Operand of prefix operator is missing");
						}
						else {
							validateResult(((IFProOperator)entity).getLeft(), print);
						}
						break;
					default:
						throw new UnsupportedOperationException();
				}
				if (entity.isRuled()) {
					validateResult(((IFProOperator)entity).getRule(),print);
				}
				break;
			case operatordef	:
				break;
			case predicate		:
				final IFProEntity[]	parm = ((IFProPredicate)entity).getParameters();

				for (int index = 0; index < parm.length; index++) {
					if (parm[index] == null) {
						print.print("Parameter #["+index+"] of predicate is missing");
					}
				}
				if (entity.isRuled()) {
					validateResult(((IFProPredicate)entity).getRule(),print);
				}
				break;
			case real			:
				break;
			case string			:
				break;
			case variable		:
				break;
			default:
				throw new UnsupportedOperationException();
		}
	}

	private IFProEntity collapse(final IFProEntity[] top, final int location) {
		IFProEntity		result = null;

		for (int index = 0; index <= location; index++) {
			if (top[index] != null) {
				if (result  == null) {
					result = top[index];
				}
				else {
					result.setParent(top[index]);
					switch (((IFProOperator)top[index]).getOperatorType().getSort()) {
						case postfix : case infix :
							((IFProOperator)top[index]).setRight(result);
							result = top[index];
							break;
						case prefix :
							((IFProOperator)top[index]).setLeft(result);
							result = top[index];
							break;
					}
				}
				while (result.getParent() != null) {
					result = result.getParent();
				}
				top[index] = null;
			}
		}
		return result;
	}

	private IFProEntity convert2List(final char[] source, final int from, final IFProEntity root) throws SyntaxException {
		IFProList		actual;		// Note: list builds from tail to head!

		if (root.getEntityId() == tailId && (root instanceof IFProOperator)) {	// Tail '|' priority is greater than ','
			if (((IFProOperator)root).getRight() != null && !FProUtil.isEntityA(((IFProOperator)root).getRight(),ContentType.NonVar)) {
				actual = new ListEntity(null,((IFProOperator)root).getRight());
				actual.getTail().setParent(actual);

				final IFProEntity[]		args = andChain2Array(((IFProOperator)root).getLeft(),actual,colonId);

				for (int index = args.length-1; index > 0; index--){
					actual.setChild(args[index]);
					args[index].setParent(actual);
					actual = new ListEntity(null,actual);
					actual.getTail().setParent(actual);
				}
				actual.setChild(args[0]);
				args[0].setParent(actual);

				return actual;
			}
			else {
				throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Tail of the list can be variable or anonymous only!");
			}
		}
		else if (root.getEntityId() == colonId && (root instanceof IFProOperator)) { // List without tail
			actual = new ListEntity(null,null);

			final IFProEntity[]		args = andChain2Array(root,actual,colonId);
			for (int index = args.length-1; index > 0; index--){
				actual.setChild(args[index]);
				args[index].setParent(actual);
				actual = new ListEntity(null,actual);
				actual.getTail().setParent(actual);
			}
			actual.setChild(args[0]);
			args[0].setParent(actual);

			return actual;
		}
		else {	// List has one element only
			actual = new ListEntity(root,null);

			root.setParent(actual);
			return actual;
		}
	}

	private static IFProEntity[] andChain2Array(final IFProEntity root, final IFProEntity parent, final long colonId) {
		int				count = 0;
		IFProEntity		actual = root;

		while (actual.getEntityType() == EntityType.operator && actual.getEntityId() == colonId) {
			actual = ((IFProOperator)actual).getRight();
			count++;
		}

		final IFProEntity[]	data = new IFProEntity[count+1];

		actual = root;
		for (int index = 0; index < count; index++) {
			(data[index] = ((IFProOperator)actual).getLeft()).setParent(parent);
			actual = ((IFProOperator)actual).getRight();
		}
		data[count] = actual;
		data[count].setParent(parent);

		return data;
	}

	private int extractEntityId(final char[] source, int from, final long[] result) throws SyntaxException {
		final int	maxLength = source.length;

		if (from < maxLength && source[from] == '\'') {
			int		startName = from++;

			while (from < maxLength && source[from] != '\'') {
				from++;
			}
			if (from < maxLength) {
				from++;
				result[0] = getRepo().termRepo().placeName(source,startName,from-1,null);
				return from;
			}
			else {
				throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Missing quote (\')!");
			}
		}
		else {
			final int	startName = from, endName;
			final long	maxLex = getRepo().termRepo().seekName(source,startName,source.length);

			if (maxLex == -startName - 1) {
				throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Unknown term/operator was detected!");
			}
			else if (maxLex >= 0) {
				endName = startName + getRepo().termRepo().getNameLength(maxLex);
				result[0] = maxLex;
				return endName;
			}
			else {
				endName = (int) - maxLex - 1;
				result[0] = getRepo().termRepo().seekName(source,startName,endName);
				return endName;
			}
		}
	}

	private int parseOp(final char[] source, int from, final IFProEntity[] result) throws SyntaxException, SyntaxException {
		final int			maxLen = source.length, prty;
		final OperatorType	type;
		final long			operatorId;

		from = CharUtils.skipBlank(source,from,false);

		if (from < maxLen && source[from] == '(') {
			from = CharUtils.parseInt(source,from+1,forIntResult,true);
			prty = forIntResult[0];
			from = CharUtils.skipBlank(source,from,false);

			if (prty < IFProOperator.MIN_PRTY || prty > IFProOperator.MAX_PRTY) {
				throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Operator priority out of range "+IFProOperator.MIN_PRTY+".."+IFProOperator.MAX_PRTY+"!");
			}
			else if (from < maxLen && source[from] == ',') {
				from = CharUtils.skipBlank(source,from+1,false);

				if (from < maxLen && Character.isJavaIdentifierStart(source[from])) {
					from = CharUtils.parseName(source,from,forIntResult);
				}
				else {
					throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Missing xf, fx, yf, fy, xfx, yfx or xfy !");
				}

				if (forIntResult[0] == forIntResult[1]) {
					throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Missing xf, fx, yf, fy, xfx, yfx or xfy !");
				}
				else {
					type = getRepo().operatorType(getRepo().termRepo().placeName(source,forIntResult[0],forIntResult[1]+1,null));
					from = CharUtils.skipBlank(source,from,false);

					if (from < maxLen && source[from] == ',') {
						from = CharUtils.skipBlank(source,from+1,false);

						if (from < maxLen) {
							if (source[from] == '\'') {
								from = CharUtils.parseUnescapedString(source,from+1,'\'',true,forIntResult);
								if (from < maxLen && source[from-1] == '\'') {
									if (forIntResult[0] > forIntResult[1]) {
										throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Empty string can't be used for operator mnemonics!");
									}
									else {
										operatorId = getRepo().termRepo().placeName(source,forIntResult[0]-1,forIntResult[1]+2,null);
									}
								}
								else {
									throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Missing '\'' !");
								}
							}
							else if (Character.isJavaIdentifierStart(source[from])) {
								from = CharUtils.parseName(source,from,forIntResult);
								if (forIntResult[0] == forIntResult[1]) {
									throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Missing operator mnemonics !");
								}
								else {
									operatorId = getRepo().termRepo().placeName(source,forIntResult[0],forIntResult[1]+1,null);
								}
							}
							else if (PUNCTUATIONS.contains(source[from])) {
								forIntResult[0] = from;
								while (PUNCTUATIONS.contains(source[from])) {
									from++;
								}
								forIntResult[1] = from;
								operatorId = getRepo().termRepo().placeName(source,forIntResult[0],forIntResult[1]+1,null);
							}
							else {
								throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Missing operator mnemonics !");
							}
							from = CharUtils.skipBlank(source,from,false);

							if (from < maxLen && source[from] == ')') {
								result[0] = new OperatorDefEntity(prty,type,operatorId);
								from++;
							}
							else {
								throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Missing ')' !");
							}
						}
						else {
							throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Missing operator name!");
						}
					}
					else {
						throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Missing ',' !");
					}
				}
			}
			else {
				throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Missing ',' !");
			}
		}
		else {
			throw new SyntaxException(SyntaxException.toRow(source,from),SyntaxException.toCol(source,from),"Missing '(' !");
		}
		return from;
	}

	private static int skipName(final char[] source, final int from) {
		final ExtendedBitCharSet	letters = VALID_LETTERS;

		for (int index = from, maxIndex = source.length; index < maxIndex; index++) {
			if (!letters.contains(source[index])) {
				return index;
			}
		}
		return source.length;
	}

	private NameClassification classifyName(final char[] source, final int startName, final int endName) {
		return endName - startName == 1 && source[startName] == '_' ? NameClassification.anonymous : NameClassification.term;
	}

	private String blankedName(final String name) {
		if (name == null || name.isEmpty()) {
			return name;
		}
		else {
			if (!Character.isJavaIdentifierStart(name.charAt(0))) {
				return name;
			}
			else {
				for (char item : name.toCharArray()) {
					if (!Character.isJavaIdentifierPart(item)) {
						return name;
					}
				}
				return ' '+name+' ';
			}
		}
	}

	private boolean needBracket(final IFProOperator root, final IFProEntity child) {
		if (child instanceof IFProOperator) {
			return ((IFProOperator)child).getPriority() > root.getPriority();
		}
		else {
			return false;
		}
	}

	private void printBracket(final CharacterTarget target, final IFProOperator root, final IFProEntity child) throws PrintingException, IOException {
		if (needBracket(root,child)) {
			target.put('(');
			putEntity(child,target);
			target.put(')');
		}
		else {
			putEntity(child,target);
		}
	}

	private int printBracket(final char[] target, int from, final IFProOperator root, final IFProEntity child) throws PrintingException, IOException {
		if (needBracket(root,child)) {
			if (from < target.length) {
				target[from] = '(';
			}
			from = putEntity(child,target,from+1);
			if (from < target.length) {
				target[from] = ')';
			}
			from++;
		}
		else {
			from = putEntity(child,target,from);
		}
		return from;
	}

	private int internalPutEntity(final IFProEntity entity, final char[] target, int from) throws IOException, PrintingException, NullPointerException {
		if (entity == null) {
			throw new NullPointerException("Entity to put can't be null!");
		}
		else if (target == null) {
			throw new NullPointerException("Target array can't be null!");
		}
		else {
			int		targetEnd = target.length;

			switch (entity.getEntityType()) {
				case string				:
					final int	stringLength = getRepo().stringRepo().getNameLength(entity.getEntityId());

					if (from + stringLength + 2 < targetEnd) {
						target[from] = '\"';
						getRepo().stringRepo().getName(entity.getEntityId(),target,from+1);
						target[from+stringLength+1] = '\"';
					}
					from += stringLength + 2;
					break;
				case integer			:
					final String	intString = String.valueOf(entity.getEntityId());

					if (from + intString.length() < targetEnd) {
						intString.getChars(0,intString.length(),target,from);
					}
					from += intString.length();
					break;
				case real				:
					final String	realString = String.valueOf(Double.longBitsToDouble(entity.getEntityId()));

					if (from + realString.length() < targetEnd) {
						realString.getChars(0,realString.length(),target,from);
					}
					from += realString.length();
					break;
				case anonymous			:
					if (from < targetEnd) {
						target[from] = '_';
					}
					from++;
					break;
				case variable			:
					final int	varLength = getRepo().termRepo().getNameLength(entity.getEntityId());

					if (from + varLength < targetEnd) {
						getRepo().termRepo().getName(entity.getEntityId(),target,from);
					}
					from += varLength;
					break;
				case list				:
					if (((IFProList)entity).getChild() == null && ((IFProList)entity).getTail() == null) {
						if (from + 2 < targetEnd) {
							target[from] = '[';
							target[from+1] = ']';
						}
						from += 2;
					}
					else {
						char			start = '[';
						IFProEntity		actual = entity;

						while (actual instanceof IFProList) {
							if (from < targetEnd) {
								target[from] = start;
							}
							from++;
							from = putEntity(((IFProList)actual).getChild(),target,from);
							actual = ((IFProList)actual).getTail();
							start = ',';
						}

						if (actual != null) {
							if (from < targetEnd) {
								target[from] = '|';
							}
							from++;
							from = putEntity(((IFProList)entity).getTail(),target,from);
						}
						if (from < targetEnd) {
							target[from] = ']';
						}
						from++;
					}
					break;
				case operator			:
					final String	opName = blankedName(getRepo().termRepo().getName(entity.getEntityId()));

					switch (((IFProOperator)entity).getOperatorType().getSort()) {
						case prefix :
//							final String	prefName = blankedName(getRepo().termRepo().getName(entity.getEntityId()));
//
							from = printBracket(target,from,(IFProOperator)entity,((IFProOperator)entity).getLeft());
//							if (needBracket((IFProOperator)entity,((IFProOperator)entity).getLeft())) {
//								if (from < targetEnd) {
//									target[from] = '(';
//								}
//								from++;
//								from = putEntity(((IFProOperator)entity).getLeft(),target,from);
//								if (from < targetEnd) {
//									target[from] = ')';
//								}
//								from++;
//							}
//							else {
//								from = putEntity(((IFProOperator)entity).getLeft(),target,from);
//							}
							if (from + opName.length() < targetEnd) {
								opName.getChars(0,opName.length(),target,from);
							}
							from += opName.length();
							break;
						case postfix :
//							final String	suffName = blankedName(getRepo().termRepo().getName(entity.getEntityId()));
//
							if (from + opName.length() < targetEnd) {
								opName.getChars(0,opName.length(),target,from);
							}
							from += opName.length();
							from = printBracket(target,from,(IFProOperator)entity,((IFProOperator)entity).getRight());
//							if (needBracket((IFProOperator)entity,((IFProOperator)entity).getRight())) {
//								if (from < targetEnd) {
//									target[from] = '(';
//								}
//								from++;
//								from = putEntity(((IFProOperator)entity).getRight(),target,from);
//								if (from < targetEnd) {
//									target[from] = ')';
//								}
//								from++;
//							}
//							else {
//								from = putEntity(((IFProOperator)entity).getRight(),target,from);
//							}
							break;
						case infix :
//							final String	infName = blankedName(getRepo().termRepo().getName(entity.getEntityId()));

							from = printBracket(target,from,(IFProOperator)entity,((IFProOperator)entity).getLeft());
//							if (needBracket((IFProOperator)entity,((IFProOperator)entity).getLeft())) {
//								if (from < targetEnd) {
//									target[from] = '(';
//								}
//								from++;
//								from = putEntity(((IFProOperator)entity).getLeft(),target,from);
//								if (from < targetEnd) {
//									target[from] = ')';
//								}
//								from++;
//							}
//							else {
//								from = putEntity(((IFProOperator)entity).getLeft(),target,from);
//							}
							if (from + opName.length() < targetEnd) {
								opName.getChars(0,opName.length(),target,from);
							}
							from += opName.length();
							from = printBracket(target,from,(IFProOperator)entity,((IFProOperator)entity).getRight());
//							if (needBracket((IFProOperator)entity,((IFProOperator)entity).getRight())) {
//								if (from < targetEnd) {
//									target[from] = '(';
//								}
//								from++;
//								from = putEntity(((IFProOperator)entity).getRight(),target,from);
//								if (from < targetEnd) {
//									target[from] = ')';
//								}
//								from++;
//							}
//							else {
//								from = putEntity(((IFProOperator)entity).getRight(),target,from);
//							}
							break;
					}
					if (((IFProRuledEntity)entity).getRule() != null) {
						if (from + 1 < targetEnd) {
							target[from] = ':';
							target[from+1] = '-';
						}
						from += 2;
						from = putEntity(((IFProRuledEntity)entity).getRule(),target,from);
					}
					break;
				case predicate			:
					final int	predLength = getRepo().termRepo().getNameLength(entity.getEntityId());

					if (from + predLength < targetEnd) {
						getRepo().termRepo().getName(entity.getEntityId(),target,from);
					}
					from += predLength;

					if (((IFProPredicate)entity).getArity() > 0) {
						char	prefix = '(';

						for (int index = 0; index < ((IFProPredicate)entity).getArity(); index++) {
							if (from < targetEnd) {
								target[from] = prefix;
							}
							from++;
							prefix = ',';
							from = putEntity(((IFProPredicate)entity).getParameters()[index],target,from);
						}
						if (from < targetEnd) {
							target[from] = ')';
						}
						from++;
					}
					if (((IFProRuledEntity)entity).getRule() != null) {
						if (from + 1 < targetEnd) {
							target[from] = ':';
							target[from+1] = '-';
						}
						from += 2;
						from = putEntity(((IFProRuledEntity)entity).getRule(),target,from);
					}
					break;
				case operatordef		:
					final String	opDef = String.format("op(%1$d,%2$s,%3$s)",((IFProOperator)entity).getPriority(),((IFProOperator)entity).getOperatorType(),repo.termRepo().getName(entity.getEntityId()));

					if (from + opDef.length() < targetEnd) {
						opDef.getChars(0,opDef.length(),target,from);
					}
					from += opDef.length();
					break;
				default :
					throw new UnsupportedOperationException("Unknown type ti upload: "+entity.getEntityType());
			}
		}
		return from;
	}

	private IFProEntity convert2Ruled(final IFProEntity entity) {
		final IFProEntity left = ((IFProOperator)entity).getLeft(), right = ((IFProOperator)entity).getRight();

		((IFProPredicate)left).setRule(right);
		right.setParent(left);
		left.setParent(null);

		return left;
	}
}


text:
package lc.hex.mopm.api.common;

import java.net.InetAddress;
import java.util.function.BiPredicate;
import java.util.function.Predicate;

public class ProxyBlacklist implements Predicate<InetAddress> {
    private final BiPredicate<String, InetAddress> matcher;
    private String rootAddress;
    private String name;
    private String defaultCommand;

    public ProxyBlacklist(String rootAddress, String name, BiPredicate<String, InetAddress> matcher, String defaultCommand) {
        this.rootAddress = rootAddress;
        this.name = name;
        this.matcher = matcher;
        this.defaultCommand = defaultCommand;
    }

    public String getRootAddress() {
        return rootAddress;
    }

    public boolean test(InetAddress address) {
        return matcher.test(this.rootAddress, address);
    }

    public String getDefaultCommand() {
        return defaultCommand;
    }

    public String getName() {
        return name;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/watched_popup_menu_watch_again"
        android:title="@string/action_watched" />
    <item
        android:id="@+id/watched_popup_menu_set_not_watched"
        android:title="@string/action_unwatched" />

</menu>


text: {key}: {value}


text:
"""
WMS service handler
"""
from mapproxy.compat import iteritems
from mapproxy.compat.itertools import chain
from functools import partial
from math import sqrt
from mapproxy.cache.tile import CacheInfo
from mapproxy.featureinfo import combine_docs
from mapproxy.request.wms import (wms_request, WMS111LegendGraphicRequest,
    mimetype_from_infotype, infotype_from_mimetype, switch_bbox_epsg_axis_order)
from mapproxy.srs import SRS, TransformationError
from mapproxy.service.base import Server
from mapproxy.response import Response
from mapproxy.source import SourceError
from mapproxy.exception import RequestError
from mapproxy.image import bbox_position_in_image, SubImageSource, BlankImageSource, GeoReference
from mapproxy.image.merge import concat_legends, LayerMerger
from mapproxy.image.opts import ImageOptions
from mapproxy.image.message import attribution_image, message_image
from mapproxy.layer import BlankImage, MapQuery, InfoQuery, LegendQuery, MapError, LimitedLayer
from mapproxy.layer import MapBBOXError, merge_layer_extents, merge_layer_res_ranges
from mapproxy.util import async_
from mapproxy.util.py import cached_property, reraise
from mapproxy.util.coverage import load_limited_to
from mapproxy.util.ext.odict import odict
from mapproxy.template import template_loader, bunch, recursive_bunch
from mapproxy.service import template_helper
from mapproxy.layer import DefaultMapExtent, MapExtent

get_template = template_loader(__name__, 'templates', namespace=template_helper.__dict__)

class PERMIT_ALL_LAYERS(object):
    pass

class WMSServer(Server):
    service = 'wms'
    fi_transformers = None

    def __init__(self, root_layer, md, srs, image_formats,
        request_parser=None, tile_layers=None, attribution=None,
        info_types=None, strict=False, on_error='raise',
        concurrent_layer_renderer=1, max_output_pixels=None,
        srs_extents=None, max_tile_age=None,
        versions=None,
        inspire_md=None,
        ):
        Server.__init__(self)
        self.request_parser = request_parser or partial(wms_request, strict=strict, versions=versions)
        self.root_layer = root_layer
        self.layers = root_layer.child_layers()
        self.tile_layers = tile_layers or {}
        self.strict = strict
        self.attribution = attribution
        self.md = md
        self.on_error = on_error
        self.concurrent_layer_renderer = concurrent_layer_renderer
        self.image_formats = image_formats
        self.info_types = info_types
        self.srs = srs
        self.srs_extents = srs_extents
        self.max_output_pixels = max_output_pixels
        self.max_tile_age = max_tile_age
        self.inspire_md = inspire_md

    def map(self, map_request):
        self.check_map_request(map_request)

        params = map_request.params
        query = MapQuery(params.bbox, params.size, SRS(params.srs), params.format, dimensions=map_request.dimensions)

        if map_request.params.get('tiled', 'false').lower() == 'true':
            query.tiled_only = True
        orig_query = query

        if self.srs_extents and params.srs in self.srs_extents:
            # limit query to srs_extent if query is larger
            query_extent = MapExtent(params.bbox, SRS(params.srs))
            if not self.srs_extents[params.srs].contains(query_extent):
                limited_extent = self.srs_extents[params.srs].intersection(query_extent)
                if not limited_extent:
                    img_opts = self.image_formats[params.format_mime_type].copy()
                    img_opts.bgcolor = params.bgcolor
                    img_opts.transparent = params.transparent
                    img = BlankImageSource(size=params.size, image_opts=img_opts, cacheable=True)
                    return Response(img.as_buffer(), content_type=img_opts.format.mime_type)
                sub_size, offset, sub_bbox = bbox_position_in_image(params.bbox, params.size, limited_extent.bbox)
                query = MapQuery(sub_bbox, sub_size, SRS(params.srs), params.format)

        actual_layers = odict()
        for layer_name in map_request.params.layers:
            layer = self.layers[layer_name]
            # only add if layer renders the query
            if layer.renders_query(query):
                # if layer is not transparent and will be rendered,
                # remove already added (then hidden) layers
                if layer.is_opaque(query):
                    actual_layers = odict()
                for layer_name, map_layers in layer.map_layers_for_query(query):
                    actual_layers[layer_name] = map_layers

        authorized_layers, coverage = self.authorized_layers('map', actual_layers.keys(),
            map_request.http.environ, query_extent=(query.srs.srs_code, query.bbox))

        self.filter_actual_layers(actual_layers, map_request.params.layers, authorized_layers)

        render_layers = []
        for layers in actual_layers.values():
            render_layers.extend(layers)

        self.update_query_with_fwd_params(query, params=params,
            layers=render_layers)

        raise_source_errors =  True if self.on_error == 'raise' else False
        renderer = LayerRenderer(render_layers, query, map_request,
                                 raise_source_errors=raise_source_errors,
                                 concurrent_rendering=self.concurrent_layer_renderer)

        merger = LayerMerger()
        renderer.render(merger)

        if self.attribution and self.attribution.get('text') and not query.tiled_only:
            merger.add(attribution_image(self.attribution['text'], query.size))
        img_opts = self.image_formats[params.format_mime_type].copy()
        img_opts.bgcolor = params.bgcolor
        img_opts.transparent = params.transparent
        result = merger.merge(size=query.size, image_opts=img_opts,
            bbox=query.bbox, bbox_srs=params.srs, coverage=coverage)

        if query != orig_query:
            result = SubImageSource(result, size=orig_query.size, offset=offset, image_opts=img_opts)

        # Provide the wrapping WSGI app or filter the opportunity to process the
        # image before it's wrapped up in a response
        result = self.decorate_img(result, 'wms.map', actual_layers.keys(),
            map_request.http.environ, (query.srs.srs_code, query.bbox))

        try:
            result.georef = GeoReference(bbox=orig_query.bbox, srs=orig_query.srs)
            result_buf = result.as_buffer(img_opts)
        except IOError as ex:
            raise RequestError('error while processing image file: %s' % ex,
                request=map_request)

        resp = Response(result_buf, content_type=img_opts.format.mime_type)

        if query.tiled_only and isinstance(result.cacheable, CacheInfo):
            cache_info = result.cacheable
            resp.cache_headers(cache_info.timestamp, etag_data=(cache_info.timestamp, cache_info.size),
                               max_age=self.max_tile_age)
            resp.make_conditional(map_request.http)

        if not result.cacheable:
            resp.cache_headers(no_cache=True)

        return resp

    def capabilities(self, map_request):
        # TODO: debug layer
        # if '__debug__' in map_request.params:
        #     layers = self.layers.values()
        # else:
        #     layers = [layer for name, layer in iteritems(self.layers)
        #               if name != '__debug__']

        if map_request.params.get('tiled', 'false').lower() == 'true':
            tile_layers = self.tile_layers.values()
        else:
            tile_layers = []

        service = self._service_md(map_request)
        root_layer = self.authorized_capability_layers(map_request.http.environ)

        info_types = ['text', 'html', 'xml'] # defaults
        if self.info_types:
            info_types = self.info_types
        elif self.fi_transformers:
            info_types = self.fi_transformers.keys()
        info_formats = [mimetype_from_infotype(map_request.version, info_type) for info_type in info_types]
        result = Capabilities(service, root_layer, tile_layers,
            self.image_formats, info_formats, srs=self.srs, srs_extents=self.srs_extents,
            inspire_md=self.inspire_md, max_output_pixels=self.max_output_pixels
            ).render(map_request)
        return Response(result, mimetype=map_request.mime_type)

    def featureinfo(self, request):
        infos = []
        self.check_featureinfo_request(request)

        p = request.params
        query = InfoQuery(p.bbox, p.size, SRS(p.srs), p.pos,
              p['info_format'], format=request.params.format or None,
              feature_count=p.get('feature_count'))

        actual_layers = odict()

        for layer_name in request.params.query_layers:
            layer = self.layers[layer_name]
            if not layer.queryable:
                raise RequestError('layer %s is not queryable' % layer_name, request=request)
            for layer_name, info_layers in layer.info_layers_for_query(query):
                actual_layers[layer_name] = info_layers

        authorized_layers, coverage = self.authorized_layers('featureinfo', actual_layers.keys(),
            request.http.environ, query_extent=(query.srs.srs_code, query.bbox))
        self.filter_actual_layers(actual_layers, request.params.layers, authorized_layers)

        # outside of auth-coverage
        if coverage and not coverage.contains(query.coord, query.srs):
            infos = []
        else:
            info_layers = []
            for layers in actual_layers.values():
                info_layers.extend(layers)

            for layer in info_layers:
                info = layer.get_info(query)
                if info is None:
                    continue
                infos.append(info)

        mimetype = None
        if 'info_format' in request.params:
            mimetype = request.params.info_format

        if not infos:
            return Response('', mimetype=mimetype)

        if self.fi_transformers:
            if not mimetype:
                if 'xml' in self.fi_transformers:
                    info_type = 'xml'
                elif 'html' in self.fi_transformers:
                    info_type = 'html'
                else:
                    info_type = 'text'
                mimetype = mimetype_from_infotype(request.version, info_type)
            else:
                info_type = infotype_from_mimetype(request.version, mimetype)
            resp, actual_info_type = combine_docs(infos, self.fi_transformers[info_type])
            if actual_info_type is not None and info_type != actual_info_type:
                mimetype = mimetype_from_infotype(request.version, actual_info_type)
        else:
            resp, info_type = combine_docs(infos)
            mimetype = mimetype_from_infotype(request.version, info_type)

        return Response(resp, mimetype=mimetype)

    def check_map_request(self, request):
        if self.max_output_pixels and \
            (request.params.size[0] * request.params.size[1]) > self.max_output_pixels:
            request.prevent_image_exception = True
            raise RequestError("image size too large", request=request)

        self.validate_layers(request)
        request.validate_format(self.image_formats)
        request.validate_srs(self.srs)

    def update_query_with_fwd_params(self, query, params, layers):
        # forward relevant request params into MapQuery.dimensions
        for layer in layers:
            if not hasattr(layer, 'fwd_req_params'):
                continue
            for p in layer.fwd_req_params:
                if p in params:
                    query.dimensions[p] = params[p]

    def check_featureinfo_request(self, request):
        self.validate_layers(request)
        request.validate_srs(self.srs)

    def validate_layers(self, request):
        query_layers = request.params.query_layers if hasattr(request, 'query_layers') else []
        for layer in chain(request.params.layers, query_layers):
            if layer not in self.layers:
                raise RequestError('unknown layer: ' + str(layer), code='LayerNotDefined',
                                   request=request)

    def check_legend_request(self, request):
        if request.params.layer not in self.layers:
            raise RequestError('unknown layer: ' + request.params.layer,
                               code='LayerNotDefined', request=request)

    #TODO: If layer not in self.layers raise RequestError
    def legendgraphic(self, request):
        legends = []
        self.check_legend_request(request)
        layer = request.params.layer
        if not self.layers[layer].has_legend:
            raise RequestError('layer %s has no legend graphic' % layer, request=request)
        legend = self.layers[layer].legend(request)

        [legends.append(i) for i in legend if i is not None]
        result = concat_legends(legends)
        if 'format' in request.params:
            mimetype = request.params.format_mime_type
        else:
            mimetype = 'image/png'

        if mimetype == 'application/json':
            return Response(legends[0].read(), mimetype='application/json')

        img_opts = self.image_formats[request.params.format_mime_type]
        return Response(result.as_buffer(img_opts), mimetype=mimetype)

    def _service_md(self, map_request):
        md = dict(self.md)
        md['url'] = map_request.url
        md['has_legend'] = self.root_layer.has_legend
        return md

    def authorized_layers(self, feature, layers, env, query_extent):
        if 'mapproxy.authorize' in env:
            result = env['mapproxy.authorize']('wms.' + feature, layers[:],
                environ=env, query_extent=query_extent)
            if result['authorized'] == 'unauthenticated':
                raise RequestError('unauthorized', status=401)
            if result['authorized'] == 'full':
                return PERMIT_ALL_LAYERS, None
            layers = {}
            if result['authorized'] == 'partial':
                for layer_name, permissions in iteritems(result['layers']):
                    if permissions.get(feature, False) == True:
                        layers[layer_name] = permissions.get('limited_to')
            limited_to = result.get('limited_to')
            if limited_to:
                coverage = load_limited_to(limited_to)
            else:
                coverage = None
            return layers, coverage
        else:
            return PERMIT_ALL_LAYERS, None

    def filter_actual_layers(self, actual_layers, requested_layers, authorized_layers):
        if authorized_layers is not PERMIT_ALL_LAYERS:
            requested_layer_names = set(requested_layers)
            for layer_name in actual_layers.keys():
                if layer_name not in authorized_layers:
                    # check whether layer was requested explicit...
                    if layer_name in requested_layer_names:
                        raise RequestError('forbidden', status=403)
                    # or implicit (part of group layer)
                    else:
                        del actual_layers[layer_name]
                elif authorized_layers[layer_name] is not None:
                    limited_to = load_limited_to(authorized_layers[layer_name])
                    actual_layers[layer_name] = [LimitedLayer(lyr, limited_to) for lyr in actual_layers[layer_name]]

    def authorized_capability_layers(self, env):
        if 'mapproxy.authorize' in env:
            result = env['mapproxy.authorize']('wms.capabilities', self.layers.keys(), environ=env)
            if result['authorized'] == 'unauthenticated':
                raise RequestError('unauthorized', status=401)
            if result['authorized'] == 'full':
                return self.root_layer
            if result['authorized'] == 'partial':
                limited_to = result.get('limited_to')
                if limited_to:
                    coverage = load_limited_to(limited_to)
                else:
                    coverage = None
                return FilteredRootLayer(self.root_layer, result['layers'], coverage=coverage)
            raise RequestError('forbidden', status=403)
        else:
            return self.root_layer

class FilteredRootLayer(object):
    def __init__(self, root_layer, permissions, coverage=None):
        self.root_layer = root_layer
        self.permissions = permissions
        self.coverage = coverage

    def __getattr__(self, name):
        return getattr(self.root_layer, name)

    @cached_property
    def extent(self):
        layer_name = self.root_layer.name
        limited_to = self.permissions.get(layer_name, {}).get('limited_to')
        extent = self.root_layer.extent

        if limited_to:
            coverage = load_limited_to(limited_to)
            limited_coverage = coverage.intersection(extent.bbox, extent.srs)
            extent = limited_coverage.extent

        if self.coverage:
            limited_coverage = self.coverage.intersection(extent.bbox, extent.srs)
            extent = limited_coverage.extent
        return extent

    @property
    def queryable(self):
        if not self.root_layer.queryable: return False

        layer_name = self.root_layer.name
        if not layer_name or self.permissions.get(layer_name, {}).get('featureinfo', False):
            return True
        return False

    def layer_permitted(self, layer):
        if not self.permissions.get(layer.name, {}).get('map', False):
            return False
        extent = layer.extent

        limited_to = self.permissions.get(layer.name, {}).get('limited_to')
        if limited_to:
            coverage = load_limited_to(limited_to)
            if not coverage.intersects(extent.bbox, extent.srs):
                return False

        if self.coverage:
            if not self.coverage.intersects(extent.bbox, extent.srs):
                return False
        return True

    @cached_property
    def layers(self):
        layers = []
        for layer in self.root_layer.layers:
            if not layer.name or self.layer_permitted(layer):
                filtered_layer = FilteredRootLayer(layer, self.permissions, self.coverage)
                if filtered_layer.is_active or filtered_layer.layers:
                    # add filtered_layer only if it is active (no grouping layer)
                    # or if it contains other active layers
                    layers.append(filtered_layer)
        return layers

DEFAULT_EXTENTS = {
    'EPSG:3857': DefaultMapExtent(),
    'EPSG:4326': DefaultMapExtent(),
    'EPSG:900913': DefaultMapExtent(),
}

def limit_srs_extents(srs_extents, supported_srs):
    """
    Limit srs_extents to supported_srs.
    """
    if srs_extents:
        srs_extents = srs_extents.copy()
    else:
        srs_extents = DEFAULT_EXTENTS.copy()

    for srs in list(srs_extents.keys()):
        if srs not in supported_srs:
            srs_extents.pop(srs)

    return srs_extents

class Capabilities(object):
    """
    Renders WMS capabilities documents.
    """
    def __init__(self, server_md, layers, tile_layers, image_formats, info_formats,
        srs, srs_extents=None, epsg_axis_order=False,
        inspire_md=None, max_output_pixels=None
        ):
        self.service = server_md
        self.layers = layers
        self.tile_layers = tile_layers
        self.image_formats = image_formats
        self.info_formats = info_formats
        self.srs = srs
        self.srs_extents = limit_srs_extents(srs_extents, srs)
        self.inspire_md = inspire_md
        self.max_output_pixels = max_output_pixels

    def layer_srs_bbox(self, layer, epsg_axis_order=False):
        for srs, extent in iteritems(self.srs_extents):
            if srs not in self.srs:
                continue

            # is_default is True when no explicit bbox is defined for this srs
            # use layer extent
            if extent.is_default:
                bbox = layer.extent.bbox_for(SRS(srs))
            elif layer.extent.is_default:
                bbox = extent.bbox_for(SRS(srs))
            else:
                # Use intersection of srs_extent and layer.extent.
                # Use 4326 extents to avoid transformation errors.
                a = extent.transform(SRS(4326))
                b = layer.extent.transform(SRS(4326))
                bbox = a.intersection(b).bbox_for(SRS(srs))

            if epsg_axis_order:
                bbox = switch_bbox_epsg_axis_order(bbox, srs)

            yield srs, bbox

        # add native srs
        layer_srs_code = layer.extent.srs.srs_code
        if layer_srs_code not in self.srs_extents:
            bbox = layer.extent.bbox
            if epsg_axis_order:
                bbox = switch_bbox_epsg_axis_order(bbox, layer_srs_code)
            if layer_srs_code in self.srs:
                yield layer_srs_code, bbox

    def layer_llbbox(self, layer):
        if 'EPSG:4326' in self.srs_extents:
            intersection = self.srs_extents['EPSG:4326'].intersection(layer.extent)
            if intersection is not None:
                llbbox = intersection.llbbox
                return limit_llbbox(llbbox)
        return limit_llbbox(layer.extent.llbbox)

    def render(self, _map_request):
        return self._render_template(_map_request.capabilities_template)

    def _render_template(self, template):
        template = get_template(template)
        inspire_md = None
        if self.inspire_md:
            inspire_md = recursive_bunch(default='', **self.inspire_md)

        max_output_size = None
        if self.max_output_pixels:
            output_width = output_height = int(sqrt(self.max_output_pixels))
            max_output_size = (output_width, output_height)

        doc = template.substitute(service=bunch(default='', **self.service),
                                   layers=self.layers,
                                   formats=self.image_formats,
                                   info_formats=self.info_formats,
                                   srs=self.srs,
                                   tile_layers=self.tile_layers,
                                   layer_srs_bbox=self.layer_srs_bbox,
                                   layer_llbbox=self.layer_llbbox,
                                   inspire_md=inspire_md,
                                   max_output_size=max_output_size,
        )
        # strip blank lines
        doc = '\n'.join(l for l in doc.split('\n') if l.rstrip())
        return doc

def limit_llbbox(bbox):
    """
    Limit the long/lat bounding box to +-180/89.99999999 degrees.

    Some clients can't handle +-90 north/south, so we subtract a tiny bit.

    >>> ', '.join('%.6f' % x for x in limit_llbbox((-200,-90.0, 180, 90)))
    '-180.000000, -89.999999, 180.000000, 89.999999'
    >>> ', '.join('%.6f' % x for x in limit_llbbox((-20,-9.0, 10, 10)))
    '-20.000000, -9.000000, 10.000000, 10.000000'
    """
    minx, miny, maxx, maxy = bbox

    minx = max(-180, minx)
    miny = max(-89.999999, miny)
    maxx = min(180, maxx)
    maxy = min(89.999999, maxy)

    return minx, miny, maxx, maxy

class LayerRenderer(object):
    def __init__(self, layers, query, request, raise_source_errors=True,
                 concurrent_rendering=1):
        self.layers = layers
        self.query = query
        self.request = request
        self.raise_source_errors = raise_source_errors
        self.concurrent_rendering = concurrent_rendering

    def render(self, layer_merger):
        render_layers = combined_layers(self.layers, self.query)
        if not render_layers: return

        async_pool = async_.Pool(size=min(len(render_layers), self.concurrent_rendering))

        if self.raise_source_errors:
            return self._render_raise_exceptions(async_pool, render_layers, layer_merger)
        else:
            return self._render_capture_source_errors(async_pool, render_layers,
                                                      layer_merger)

    def _render_raise_exceptions(self, async_pool, render_layers, layer_merger):
        # call _render_layer, raise all exceptions
        try:
            for layer_task in async_pool.imap(self._render_layer, render_layers,
                                              use_result_objects=True):
                if layer_task.exception is None:
                    layer, layer_img = layer_task.result
                    if layer_img is not None:
                        layer_merger.add(layer_img, layer.coverage)
                else:
                    ex = layer_task.exception
                    async_pool.shutdown(True)
                    reraise(ex)
        except SourceError as ex:
            raise RequestError(ex.args[0], request=self.request)

    def _render_capture_source_errors(self, async_pool, render_layers, layer_merger):
        # call _render_layer, capture SourceError exceptions
        errors = []
        rendered = 0

        for layer_task in async_pool.imap(self._render_layer, render_layers,
                                          use_result_objects=True):
            if layer_task.exception is None:
                layer, layer_img = layer_task.result
                if layer_img is not None:
                    layer_merger.add(layer_img, layer.coverage)
                rendered += 1
            else:
                layer_merger.cacheable = False
                ex = layer_task.exception
                if isinstance(ex[1], SourceError):
                    errors.append(ex[1].args[0])
                else:
                    async_pool.shutdown(True)
                    reraise(ex)

        if render_layers and not rendered:
            errors = '\n'.join(errors)
            raise RequestError('Could not get any sources:\n'+errors, request=self.request)

        if errors:
            layer_merger.add(message_image('\n'.join(errors), self.query.size,
                image_opts=ImageOptions(transparent=True)))

    def _render_layer(self, layer):
        try:
            layer_img = layer.get_map(self.query)
            if layer_img is not None:
                layer_img.opacity = layer.opacity

            return layer, layer_img
        except SourceError:
            raise
        except MapBBOXError as e:
            raise RequestError('Request too large or invalid BBOX. (%s)' % e, request=self.request)
        except MapError as e:
            raise RequestError('Invalid request: %s' % e.args[0], request=self.request)
        except TransformationError:
            raise RequestError('Could not transform BBOX: Invalid result.',
                request=self.request)
        except BlankImage:
            return layer, None

class WMSLayerBase(object):
    """
    Base class for WMS layer (layer groups and leaf layers).
    """

    "True if layer is an actual layer (not a group only)"
    is_active = True

    "list of sublayers"
    layers = []

    "metadata dictionary with tile, name, etc."
    md = {}

    "True if .info() is supported"
    queryable = False

    "True is .legend() is supported"
    has_legend = False
    legend_url = None
    legend_size = None

    "resolution range (i.e. ScaleHint) of the layer"
    res_range = None
    "MapExtend of the layer"
    extent = None

    def map_layers_for_query(self, query):
        raise NotImplementedError()

    def legend(self, query):
        raise NotImplementedError()

    def info(self, query):
        raise NotImplementedError()

class WMSLayer(WMSLayerBase):
    """
    Class for WMS layers.

    Combines map, info and legend sources with metadata.
    """
    is_active = True
    layers = []
    def __init__(self, name, title, map_layers, info_layers=[], legend_layers=[],
                 res_range=None, md=None,dimensions=None):
        self.name = name
        self.title = title
        self.md = md or {}
        self.map_layers = map_layers
        self.info_layers = info_layers
        self.legend_layers = legend_layers
        self.extent = merge_layer_extents(map_layers)
        self.dimensions = dimensions

        if res_range is None:
            res_range = merge_layer_res_ranges(map_layers)
        self.res_range = res_range
        self.queryable = True if info_layers else False
        self.has_legend = True if legend_layers else False
        self.dimensions = dimensions

    def is_opaque(self, query):
        return any(l.is_opaque(query) for l in self.map_layers)

    def renders_query(self, query):
        if self.res_range and not self.res_range.contains(query.bbox, query.size, query.srs):
            return False
        return True

    def map_layers_for_query(self, query):
        if not self.map_layers:
            return []
        return [(self.name, self.map_layers)]

    def info_layers_for_query(self, query):
        if not self.info_layers:
            return []
        return [(self.name, self.info_layers)]

    def legend(self, request):
        p = request.params
        query = LegendQuery(p.format, p.scale)

        for lyr in self.legend_layers:
            yield lyr.get_legend(query)

    @property
    def legend_size(self):
        width = 0
        height = 0
        for layer in self.legend_layers:
            width = max(layer.size[0], width)
            height += layer.size[1]
        return (width, height)

    @property
    def legend_url(self):
        if self.has_legend:
            req = WMS111LegendGraphicRequest(url='?',
                param=dict(format='image/png', layer=self.name, sld_version='1.1.0'))
            return req.complete_url
        else:
            return None

    def child_layers(self):
        return {self.name: self}

class WMSGroupLayer(WMSLayerBase):
    """
    Class for WMS group layers.

    Groups multiple wms layers, but can also contain a single layer (``this``)
    that represents this layer.
    """
    def __init__(self, name, title, this, layers, md=None):
        self.name = name
        self.title = title
        self.this = this
        self.md = md or {}
        self.is_active = True if this is not None else False
        self.layers = layers
        self.has_legend = True if this and this.has_legend or any(l.has_legend for l in layers) else False
        self.queryable = True if this and this.queryable or any(l.queryable for l in layers) else False
        all_layers = layers + ([self.this] if self.this else [])
        self.extent = merge_layer_extents(all_layers)
        self.res_range = merge_layer_res_ranges(all_layers)

    def is_opaque(self, query):
        return any(l.is_opaque(query) for l in self.layers)

    @property
    def legend_size(self):
        return self.this.legend_size

    @property
    def legend_url(self):
        return self.this.legend_url

    def renders_query(self, query):
        if self.res_range and not self.res_range.contains(query.bbox, query.size, query.srs):
            return False
        return True

    def map_layers_for_query(self, query):
        if self.this:
            return self.this.map_layers_for_query(query)
        else:
            layers = []
            for layer in self.layers:
                layers.extend(layer.map_layers_for_query(query))
            return layers

    def info_layers_for_query(self, query):
        if self.this:
            return self.this.info_layers_for_query(query)
        else:
            layers = []
            for layer in self.layers:
                layers.extend(layer.info_layers_for_query(query))
            return layers

    def child_layers(self):
        layers = odict()
        if self.name:
            layers[self.name] = self
        for lyr in self.layers:
            if hasattr(lyr, 'child_layers'):
                layers.update(lyr.child_layers())
            elif lyr.name:
                layers[lyr.name] = lyr
        return layers

def combined_layers(layers, query):
    """
    Returns a new list of the layers where all adjacent layers are combined
    if possible.
    """
    if len(layers) <= 1:
        return layers
    layers = layers[:]
    combined_layers = [layers.pop(0)]
    while layers:
        current_layer = layers.pop(0)
        combined = combined_layers[-1].combined_layer(current_layer, query)
        if combined:
            # change last layer with combined
            combined_layers[-1] = combined
        else:
            combined_layers.append(current_layer)
    return combined_layers


text:
package com.google.android.glass.eye;

import android.content.Context;

/**
 * Empty stub, only for the code to compile. The implementation in on Glass itself.
 *
 */
public class EyeGestureManager {
    public static final int INFINITE_TIMEOUT = -1;
    public static final String SERVICE_NAME = "eye_gesture";

    public static EyeGestureManager from(Context paramContext) {
        return null;
    }

    public void activateGazeLogging(boolean paramBoolean) {
    }

    public boolean applyAndSaveCalibration(EyeGesture paramEyeGesture) {
        return false;
    }

    public boolean clearCalibration(EyeGesture paramEyeGesture) {
        return false;
    }

    public boolean enableDetectorPersistently(EyeGesture paramEyeGesture, boolean paramBoolean) {
        return false;
    }

    public boolean enableDetectorPersistently(EyeGesture paramEyeGesture, boolean paramBoolean1, boolean paramBoolean2) {
        return false;
    }

    public void enableGazeService(boolean paramBoolean) {
    }

    public boolean endCalibrationInterval(EyeGesture paramEyeGesture) {
        return false;
    }

    public void forceGlasshubResetHack() {
    }

    public boolean isCalibrationComplete(EyeGesture paramEyeGesture) {
        return false;
    }

    public boolean isDetectorPersistentlyEnabled(EyeGesture paramEyeGesture) {
        return false;
    }

    public boolean isDetectorRunning(EyeGesture paramEyeGesture) {
        return false;
    }

    public boolean isGazeLogging() {
        return false;
    }

    public boolean isSupported(EyeGesture paramEyeGesture) {
        return false;
    }

    public boolean loadCalibration(EyeGesture paramEyeGesture) {
        return false;
    }

    public boolean startCalibrationInterval(EyeGesture paramEyeGesture) {
        return false;
    }

    public boolean startDetector(EyeGesture paramEyeGesture, boolean paramBoolean) {
        return false;
    }

    public boolean startDetector(EyeGesture paramEyeGesture, boolean paramBoolean, int paramInt) {
        return false;
    }

    public boolean stopDetector(EyeGesture paramEyeGesture) {
        return false;
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>List Items</title>

List of Items

First

Second

<input type="text" id="newItemText" />
<input type="button" value="Add" onclick="addItem()">


text:
/* @flow */
import Locale from './index'
import * as languages from './languages/en'

export default new Locale('en', languages)


text:
package net.bytebuddy.dynamic.scaffold;

import net.bytebuddy.test.utility.ObjectPropertyAssertion;
import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public class MethodGraphNodeSortTest {

    @Test
    public void testSortVisible() throws Exception {
        assertThat(MethodGraph.Node.Sort.VISIBLE.isResolved(), is(true));
        assertThat(MethodGraph.Node.Sort.VISIBLE.isUnique(), is(true));
        assertThat(MethodGraph.Node.Sort.VISIBLE.isMadeVisible(), is(true));
    }

    @Test
    public void testSortResolved() throws Exception {
        assertThat(MethodGraph.Node.Sort.RESOLVED.isResolved(), is(true));
        assertThat(MethodGraph.Node.Sort.RESOLVED.isUnique(), is(true));
        assertThat(MethodGraph.Node.Sort.RESOLVED.isMadeVisible(), is(false));
    }

    @Test
    public void testAmbiguous() throws Exception {
        assertThat(MethodGraph.Node.Sort.AMBIGUOUS.isResolved(), is(true));
        assertThat(MethodGraph.Node.Sort.AMBIGUOUS.isUnique(), is(false));
        assertThat(MethodGraph.Node.Sort.AMBIGUOUS.isMadeVisible(), is(false));
    }

    @Test
    public void testUnresolved() throws Exception {
        assertThat(MethodGraph.Node.Sort.UNRESOLVED.isResolved(), is(false));
        assertThat(MethodGraph.Node.Sort.UNRESOLVED.isUnique(), is(false));
        assertThat(MethodGraph.Node.Sort.UNRESOLVED.isMadeVisible(), is(false));
    }

    @Test
    public void testObjectProperties() throws Exception {
        ObjectPropertyAssertion.of(MethodGraph.Node.Sort.class).apply();
    }
}


text:
package com.pieframework.model.operations;

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

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.core.Commit;
import org.simpleframework.xml.core.Persist;

import com.pieframework.model.resources.Resource;

@Root(name = "ops")
public class Operations {

	@ElementList(name = "operations", inline = true, required = false)
	private ArrayList<Operation> list;

	private HashMap<String, Operation> ops = new HashMap<String, Operation>();

	@Commit
	private void commit() {
		for (Operation o : list) {
			ops.put(o.getId(), o);
		}
	}

	@Persist
	private void prepare() {
		list = new ArrayList<Operation>(ops.values());
	}

	public HashMap<String, Operation> getOperations() {
		return ops;
	}

	public void setOperations(HashMap<String, Operation> operations) {
		this.ops = operations;
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		ReflectionToStringBuilder
				.setDefaultStyle(ToStringStyle.MULTI_LINE_STYLE);
		return ReflectionToStringBuilder.toStringExclude(this, "list");
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<COLLADA xmlns="http://www.collada.org/2005/11/COLLADASchema" version="1.4.1">
    <library_visual_scenes>
        <visual_scene id="Scene" name="Scene">
        </visual_scene>
    </library_visual_scenes>
    <scene>
        <extra>
            <technique profile="chimera">
                <canvas title="hello2d" width="960" height="540" fullscreen="0"/>
                <view_projection size="1" distance="0.4"/>
            </technique>
        </extra>
        <instance_visual_scene url="#Scene"/>
    </scene>
</COLLADA>


text:
import { TimeInterval, TimeUnit, toDisplayInterval } from '../models';
import { formatNumber } from './formatNumber';

const TimeUnitDescriptions = {
	[TimeUnit.Nanoseconds]: 'nanosecond',
	[TimeUnit.Microseconds]: 'microsecond',
	[TimeUnit.Milliseconds]: 'millisecond',
	[TimeUnit.Seconds]: 'second',
	[TimeUnit.Minutes]: 'minute',
	[TimeUnit.Hours]: 'hour',
	[TimeUnit.Days]: 'day'
};

const TimeUnitAbbreviations = {
	[TimeUnit.Nanoseconds]: 'ns',
	[TimeUnit.Microseconds]: 'µs',
	[TimeUnit.Milliseconds]: 'ms',
	[TimeUnit.Seconds]: 'sec',
	[TimeUnit.Minutes]: 'min',
	[TimeUnit.Hours]: 'hr',
	[TimeUnit.Days]: 'day'
};

const PluralAbbreviations = {
	[TimeUnit.Nanoseconds]: TimeUnitAbbreviations[TimeUnit.Nanoseconds],
	[TimeUnit.Microseconds]: TimeUnitAbbreviations[TimeUnit.Microseconds],
	[TimeUnit.Milliseconds]: TimeUnitAbbreviations[TimeUnit.Milliseconds],
	[TimeUnit.Seconds]: 'secs',
	[TimeUnit.Minutes]: 'mins',
	[TimeUnit.Hours]: 'hrs',
	[TimeUnit.Days]: 'days'
};

export type TimeIntervalFormatOptions = {
	separator?: string;
	abbreviate?: boolean;
};

export const formatTimeInterval = (value: TimeInterval, options?: TimeIntervalFormatOptions): string => {
	const display = toDisplayInterval(value);
	if (!display) {
		return null;
	}

	let unit;
	if (options && options.abbreviate) {
		unit = (display.value > 1 ? PluralAbbreviations : TimeUnitAbbreviations)[display.unit];
	} else {
		unit = TimeUnitDescriptions[display.unit];
		if (display.value > 1) {
			unit += 's';
		}
	}

	return formatNumber(display.value, {unit, separator: options && options.separator});
};