text:
package bixie.translation.soot;

import java.util.LinkedList;

import bixie.boogie.ProgramFactory;
import bixie.boogie.ast.Attribute;
import bixie.boogie.ast.declaration.FunctionDeclaration;
import bixie.boogie.ast.expression.Expression;
import bixie.boogie.ast.expression.IdentifierExpression;
import bixie.boogie.ast.statement.Statement;
import bixie.boogie.enums.BinaryOperator;
import bixie.boogie.enums.UnaryOperator;
import bixie.boogie.type.BoogieType;
import bixie.translation.GlobalsCache;
import bixie.translation.Options;
import bixie.translation.util.CustomNullnessAnalysis;
import bixie.translation.util.MhpInfo;
import bixie.util.Log;
import soot.ArrayType;
import soot.DoubleType;
import soot.FloatType;
import soot.Immediate;
import soot.Local;
import soot.NullType;
import soot.RefType;
import soot.jimple.AddExpr;
import soot.jimple.AndExpr;
import soot.jimple.ArrayRef;
import soot.jimple.BinopExpr;
import soot.jimple.CastExpr;
import soot.jimple.CaughtExceptionRef;
import soot.jimple.ClassConstant;
import soot.jimple.CmpExpr;
import soot.jimple.CmpgExpr;
import soot.jimple.CmplExpr;
import soot.jimple.DivExpr;
import soot.jimple.DoubleConstant;
import soot.jimple.DynamicInvokeExpr;
import soot.jimple.EqExpr;
import soot.jimple.FieldRef;
import soot.jimple.FloatConstant;
import soot.jimple.GeExpr;
import soot.jimple.GtExpr;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceOfExpr;
import soot.jimple.IntConstant;
import soot.jimple.InterfaceInvokeExpr;
import soot.jimple.JimpleValueSwitch;
import soot.jimple.LeExpr;
import soot.jimple.LengthExpr;
import soot.jimple.LongConstant;
import soot.jimple.LtExpr;
import soot.jimple.MethodHandle;
import soot.jimple.MulExpr;
import soot.jimple.NeExpr;
import soot.jimple.NegExpr;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.NullConstant;
import soot.jimple.OrExpr;
import soot.jimple.ParameterRef;
import soot.jimple.RemExpr;
import soot.jimple.ShlExpr;
import soot.jimple.ShrExpr;
import soot.jimple.SpecialInvokeExpr;
import soot.jimple.StaticFieldRef;
import soot.jimple.StaticInvokeExpr;
import soot.jimple.StringConstant;
import soot.jimple.SubExpr;
import soot.jimple.ThisRef;
import soot.jimple.UshrExpr;
import soot.jimple.VirtualInvokeExpr;
import soot.jimple.XorExpr;

/**
 * @author schaef
 */
public class SootValueSwitch implements JimpleValueSwitch {

	public boolean isLeftHandSide = false;

	private SootProcedureInfo procInfo;
	private SootStmtSwitch stmtSwitch;
	private ProgramFactory pf;

	public SootValueSwitch(SootProcedureInfo pinfo, SootStmtSwitch stmtswitch) {
		this.procInfo = pinfo;
		this.pf = GlobalsCache.v().getPf();
		this.stmtSwitch = stmtswitch;
	}

	private LinkedList<Expression> expressionStack = new LinkedList<Expression>();

	public Expression getExpression() {
		return this.expressionStack.pop();
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * soot.jimple.ConstantSwitch#caseClassConstant(soot.jimple.ClassConstant)
	 */
	@Override
	public void caseClassConstant(ClassConstant arg0) {
		this.expressionStack.push(GlobalsCache.v().lookupClassConstant(arg0));
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * soot.jimple.ConstantSwitch#caseDoubleConstant(soot.jimple.DoubleConstant)
	 */
	@Override
	public void caseDoubleConstant(DoubleConstant arg0) {
		this.expressionStack.push(GlobalsCache.v().lookupInternDouble(arg0));
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * soot.jimple.ConstantSwitch#caseFloatConstant(soot.jimple.FloatConstant)
	 */
	@Override
	public void caseFloatConstant(FloatConstant arg0) {
		this.expressionStack.push(GlobalsCache.v().lookupInternFloat(arg0));
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ConstantSwitch#caseIntConstant(soot.jimple.IntConstant)
	 */
	@Override
	public void caseIntConstant(IntConstant arg0) {
		expressionStack.push(this.pf.mkIntLiteral(String.valueOf(arg0.value)));
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * soot.jimple.ConstantSwitch#caseLongConstant(soot.jimple.LongConstant)
	 */
	@Override
	public void caseLongConstant(LongConstant arg0) {
		long value = arg0.value;
		if (value >= Integer.MAX_VALUE || value <= Integer.MIN_VALUE) {
			Log.debug("Used abstract value for long constant that didn't fit in int");
			this.expressionStack.push(GlobalsCache.v().lookupInternLong(arg0));
		} else {
			expressionStack.push(this.pf.mkIntLiteral(String.valueOf(value)));
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * soot.jimple.ConstantSwitch#caseNullConstant(soot.jimple.NullConstant)
	 */
	@Override
	public void caseNullConstant(NullConstant arg0) {
		expressionStack.push(SootPrelude.v().getNullConstant());
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * soot.jimple.ConstantSwitch#caseStringConstant(soot.jimple.StringConstant)
	 */
	@Override
	public void caseStringConstant(StringConstant arg0) {
		this.expressionStack.push(GlobalsCache.v().lookupInternString(arg0));
	}

	private void translateBinOp(BinopExpr arg0) {
		this.isLeftHandSide = false;
		arg0.getOp1().apply(this);
		Expression lhs = this.expressionStack.pop();
		arg0.getOp2().apply(this);
		Expression rhs = this.expressionStack.pop();

		// cast if necessary. This has to be done because soot treats boolean as
		// integers
		if (lhs.getType() != rhs.getType()) {
			rhs = TranslationHelpers.castBoogieTypes(rhs, lhs.getType());
		}

		if (arg0.getType() instanceof FloatType
				|| arg0.getType() instanceof DoubleType) {
			FunctionDeclaration fun = SootPrelude.v().lookupRealOperator(
					arg0.getSymbol());
			Expression[] arguments = { lhs, rhs };
			this.expressionStack.push(this.pf.mkFunctionApplication(fun,
					arguments));
			return;
		}
		// if it is not Float or Double, proceed normally.
		createBinOp(arg0.getSymbol(), lhs, rhs);
	}

	public void createBinOp(String op, Expression left, Expression right) {
		BinaryOperator operator;
		BoogieType rettype;
		op = op.trim();
		if (op.compareTo("+") == 0) {
			rettype = left.getType();
			operator = BinaryOperator.ARITHPLUS;
		} else if (op.compareTo("-") == 0) {
			rettype = left.getType();
			operator = BinaryOperator.ARITHMINUS;
		} else if (op.compareTo("*") == 0) {
			this.expressionStack.push(SootPrelude.v().mulInt(left, right));
			return;
		} else if (op.compareTo("/") == 0) {
			// make sure that "right" is an Integer
			// then assert that it is different from 0
			if (this.stmtSwitch != null)
				this.stmtSwitch.getErrorModel().createDivByZeroGuard(right);
			this.expressionStack.push(SootPrelude.v().divInt(left, right));
			return;
		} else if (op.compareTo("%") == 0) {
			if (this.stmtSwitch != null)
				this.stmtSwitch.getErrorModel().createDivByZeroGuard(right);
			this.expressionStack.push(SootPrelude.v().modInt(left, right));
			return;
		} else if (op.compareTo("cmp") == 0 || op.compareTo("cmpl") == 0
				|| op.compareTo("cmpg") == 0) {
			this.expressionStack.push(SootPrelude.v().compareExpr(left, right));
			return;
		} else if (op.compareTo("==") == 0) {
			rettype = this.pf.getBoolType();
			operator = BinaryOperator.COMPEQ;
		} else if (op.compareTo("<") == 0) {
			rettype = this.pf.getBoolType();
			operator = BinaryOperator.COMPLT;
		} else if (op.compareTo(">") == 0) {
			rettype = this.pf.getBoolType();
			operator = BinaryOperator.COMPGT;
		} else if (op.compareTo("<=") == 0) {
			rettype = this.pf.getBoolType();
			operator = BinaryOperator.COMPLEQ;
		} else if (op.compareTo(">=") == 0) {
			rettype = this.pf.getBoolType();
			operator = BinaryOperator.COMPGEQ;
		} else if (op.compareTo("!=") == 0) {
			rettype = this.pf.getBoolType();
			operator = BinaryOperator.COMPNEQ;
		} else if (op.compareTo("&") == 0) {
			this.expressionStack.push(SootPrelude.v().bitAndExpr(left, right));
			return;
		} else if (op.compareTo("|") == 0) {
			this.expressionStack.push(SootPrelude.v().bitOrExpr(left, right));
			return;
		} else if (op.compareTo("<<") == 0) { // Shiftl
			this.expressionStack.push(SootPrelude.v().shiftLeft(left, right));
			return;
		} else if (op.compareTo(">>") == 0) { // Shiftr
			this.expressionStack.push(SootPrelude.v().shiftRight(left, right));
			return;
		} else if (op.compareTo(">>>") == 0) { // UShiftr
			this.expressionStack.push(SootPrelude.v().uShiftRight(left, right));
			return;
		} else if (op.compareTo("^") == 0) { // XOR
			this.expressionStack.push(SootPrelude.v().xorExpr(left, right));
			return;
		} else {
			throw new RuntimeException("UNKNOWN Jimple operator " + op);
		}
		this.expressionStack.push(this.pf.mkBinaryExpression(rettype, operator,
				left, right));
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ExprSwitch#caseAddExpr(soot.jimple.AddExpr)
	 */
	@Override
	public void caseAddExpr(AddExpr arg0) {
		translateBinOp(arg0);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ExprSwitch#caseAndExpr(soot.jimple.AndExpr)
	 */
	@Override
	public void caseAndExpr(AndExpr arg0) {
		translateBinOp(arg0);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ExprSwitch#caseCastExpr(soot.jimple.CastExpr)
	 */
	@Override
	public void caseCastExpr(CastExpr arg0) {
		this.isLeftHandSide = false;
		arg0.getOp().apply(this);
		Expression exp = this.getExpression();

		// if the jimple types are the same, just return the expression
		if (arg0.getOp().getType() == arg0.getCastType()) {
			this.expressionStack.push(exp);
			return;
		}

		BoogieType boogieTargetType = GlobalsCache.v().getBoogieType(
				arg0.getCastType());

		// //////////////////////////////////////////////////////////////////////
		if (boogieTargetType == this.pf.getIntType()
				|| boogieTargetType == this.pf.getRealType()
				|| boogieTargetType == this.pf.getBoolType()) {
			// in that case, exp is also of primitive type
			// otherwise, java or soot would translate it
			// into a more complex expression that uses the
			// appropriate java methods.
			this.expressionStack.push(TranslationHelpers.castBoogieTypes(exp,
					boogieTargetType));
			return;

			// //////////////////////////////////////////////////////////////////////
		} else if (arg0.getCastType() instanceof RefType) {

			final RefType targetType = (RefType) arg0.getCastType();

			if (targetType.getClassName().equals("java.lang.Object")) {
				// should always be ok, nothing to assert
				this.expressionStack.push(exp);
			} else if (arg0.getOp().getType() instanceof RefType) {
				// Guard that typeof(exp) <: targetType
				if (this.stmtSwitch != null)
					this.stmtSwitch.getErrorModel().createClassCastGuard(
							this.getClassTypeFromExpression(exp, false),
							GlobalsCache.v().lookupClassVariable(
									targetType.getSootClass()));
				this.expressionStack.push(exp);
			} else if (arg0.getOp().getType() instanceof NullType) {
				// should always be ok, nothing to assert
				this.expressionStack.push(exp);
			} else {
				/* Log.error */
				System.out.println("Don't know how to cast from "
						+ arg0.getOp().getType() + " to " + arg0.getCastType());
				this.expressionStack.push(createHavocedExpression(GlobalsCache
						.v().getBoogieType(arg0.getType())));
			}

			return;

			// //////////////////////////////////////////////////////////////////////
		} else if (arg0.getCastType() instanceof ArrayType) {

			final ArrayType targetType = (ArrayType) arg0.getCastType();
			if (this.stmtSwitch != null)
				this.stmtSwitch.getErrorModel().createClassCastGuard(
						this.getClassTypeFromExpression(exp, false),
						GlobalsCache.v().lookupArrayType(targetType));

			this.expressionStack.push(exp);

			return;

			// //////////////////////////////////////////////////////////////////////
			// old, should be removed at some point
		} else if (boogieTargetType == SootPrelude.v().getReferenceType()) {
			// ILocation loc = exp.getLocation();
			if (arg0.getCastType() instanceof RefType) {
				RefType rtype = (RefType) arg0.getCastType();
				// Guard that typeof(exp) <: targetType
				if (this.stmtSwitch != null)
					this.stmtSwitch.getErrorModel().createClassCastGuard(
							this.getClassTypeFromExpression(exp, false),
							GlobalsCache.v().lookupClassVariable(
									rtype.getSootClass()));
				this.expressionStack.push(exp);
				return;
			} else {
				throw new RuntimeException("Cast from "
						+ arg0.getOp().getType() + " to " + arg0.getCastType()
						+ " not implemented");
			}
		}

		throw new RuntimeException("Cast from " + arg0.getOp().getType()
				+ " to " + arg0.getCastType() + " not implemented");
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ExprSwitch#caseCmpExpr(soot.jimple.CmpExpr)
	 */
	@Override
	public void caseCmpExpr(CmpExpr arg0) {
		translateBinOp(arg0);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ExprSwitch#caseCmpgExpr(soot.jimple.CmpgExpr)
	 */
	@Override
	public void caseCmpgExpr(CmpgExpr arg0) {
		translateBinOp(arg0);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ExprSwitch#caseCmplExpr(soot.jimple.CmplExpr)
	 */
	@Override
	public void caseCmplExpr(CmplExpr arg0) {
		translateBinOp(arg0);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ExprSwitch#caseDivExpr(soot.jimple.DivExpr)
	 */
	@Override
	public void caseDivExpr(DivExpr arg0) {
		translateBinOp(arg0);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ExprSwitch#caseEqExpr(soot.jimple.EqExpr)
	 */
	@Override
	public void caseEqExpr(EqExpr arg0) {
		translateBinOp(arg0);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ExprSwitch#caseGeExpr(soot.jimple.GeExpr)
	 */
	@Override
	public void caseGeExpr(GeExpr arg0) {
		translateBinOp(arg0);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ExprSwitch#caseGtExpr(soot.jimple.GtExpr)
	 */
	@Override
	public void caseGtExpr(GtExpr arg0) {
		translateBinOp(arg0);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * soot.jimple.ExprSwitch#caseInstanceOfExpr(soot.jimple.InstanceOfExpr)
	 */
	@Override
	public void caseInstanceOfExpr(InstanceOfExpr arg0) {
		this.isLeftHandSide = false;
		arg0.getOp().apply(this);
		Expression lhs = this.getExpression();
		if (arg0.getCheckType() instanceof RefType) {
			RefType rtype = (RefType) arg0.getCheckType();
			Expression rhs = GlobalsCache.v().lookupClassVariable(
					rtype.getSootClass());

			Expression isNonNull = this.pf.mkBinaryExpression(
					this.pf.getBoolType(), BinaryOperator.COMPNEQ, lhs,
					SootPrelude.v().getNullConstant());

			Expression isSubtype = this.pf.mkBinaryExpression(
					this.pf.getBoolType(), BinaryOperator.COMPPO,
					this.getClassTypeFromExpression(lhs, false), rhs);

			this.expressionStack.push(this.pf.mkBinaryExpression(
					this.pf.getBoolType(), BinaryOperator.LOGICAND, isNonNull,
					isSubtype));
		} else {
			Log.debug("instanceof for arrays not implemented");
			this.expressionStack.push(createHavocedExpression(GlobalsCache.v()
					.getBoogieType(arg0.getType())));
		}
	}

	/**
	 * takes a fake global of appropriate type, adds a havoc statement before it
	 * and returns the identifier expression for it.
	 *
	 * @param t
	 * @return
	 */
	private IdentifierExpression createHavocedExpression(BoogieType t) {
		Attribute[] arrtibutes = {};
		if (this.stmtSwitch != null) {
			arrtibutes = TranslationHelpers
					.javaLocation2Attribute(this.stmtSwitch
							.getCurrentStatement());
		}
		IdentifierExpression ide = GlobalsCache.v().getHavocGlobal(t);
		if (this.stmtSwitch != null) {
			this.stmtSwitch.addStatement(this.pf.mkHavocStatement(arrtibutes,
					ide));
		}
		return ide;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ExprSwitch#caseInterfaceInvokeExpr(soot.jimple.
	 * InterfaceInvokeExpr)
	 */
	@Override
	public void caseInterfaceInvokeExpr(InterfaceInvokeExpr arg0) {
		throw new RuntimeException("This must be handeled by SootStmtSwitch!");
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ExprSwitch#caseLeExpr(soot.jimple.LeExpr)
	 */
	@Override
	public void caseLeExpr(LeExpr arg0) {
		translateBinOp(arg0);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ExprSwitch#caseLengthExpr(soot.jimple.LengthExpr)
	 */
	@Override
	public void caseLengthExpr(LengthExpr arg0) {
		this.isLeftHandSide = false;
		arg0.getOp().apply(this);
		Expression base = this.getExpression();
		this.stmtSwitch.getErrorModel().createNonNullGuard(base);
		this.expressionStack
				.push(GlobalsCache.v().getArraySizeExpression(base));
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ExprSwitch#caseLtExpr(soot.jimple.LtExpr)
	 */
	@Override
	public void caseLtExpr(LtExpr arg0) {
		translateBinOp(arg0);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ExprSwitch#caseMulExpr(soot.jimple.MulExpr)
	 */
	@Override
	public void caseMulExpr(MulExpr arg0) {
		translateBinOp(arg0);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ExprSwitch#caseNeExpr(soot.jimple.NeExpr)
	 */
	@Override
	public void caseNeExpr(NeExpr arg0) {
		translateBinOp(arg0);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ExprSwitch#caseNegExpr(soot.jimple.NegExpr)
	 */
	@Override
	public void caseNegExpr(NegExpr arg0) {
		// this is arithmetic negative!
		// logic neg is already translated by soot
		this.isLeftHandSide = false;
		arg0.getOp().apply(this);
		Expression e = this.expressionStack.pop();
		this.expressionStack.push(this.pf.mkUnaryExpression(e.getType(),
				UnaryOperator.ARITHNEGATIVE, e));
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ExprSwitch#caseNewArrayExpr(soot.jimple.NewArrayExpr)
	 */
	@Override
	public void caseNewArrayExpr(NewArrayExpr arg0) {
		throw new RuntimeException("Must be handeled in SootStmtSwitch");
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ExprSwitch#caseNewExpr(soot.jimple.NewExpr)
	 */
	@Override
	public void caseNewExpr(NewExpr arg0) {
		throw new RuntimeException("Must be handeled in SootStmtSwitch");
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * soot.jimple.ExprSwitch#caseNewMultiArrayExpr(soot.jimple.NewMultiArrayExpr
	 * )
	 */
	@Override
	public void caseNewMultiArrayExpr(NewMultiArrayExpr arg0) {
		throw new RuntimeException("Must be handeled in SootStmtSwitch");
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ExprSwitch#caseOrExpr(soot.jimple.OrExpr)
	 */
	@Override
	public void caseOrExpr(OrExpr arg0) {
		translateBinOp(arg0);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ExprSwitch#caseRemExpr(soot.jimple.RemExpr)
	 */
	@Override
	public void caseRemExpr(RemExpr arg0) {
		translateBinOp(arg0);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ExprSwitch#caseShlExpr(soot.jimple.ShlExpr)
	 */
	@Override
	public void caseShlExpr(ShlExpr arg0) {
		translateBinOp(arg0);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ExprSwitch#caseShrExpr(soot.jimple.ShrExpr)
	 */
	@Override
	public void caseShrExpr(ShrExpr arg0) {
		translateBinOp(arg0);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * soot.jimple.ExprSwitch#caseSpecialInvokeExpr(soot.jimple.SpecialInvokeExpr
	 * )
	 */
	@Override
	public void caseSpecialInvokeExpr(SpecialInvokeExpr arg0) {
		throw new RuntimeException("This must be handeled by SootStmtSwitch!");
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * soot.jimple.ExprSwitch#caseStaticInvokeExpr(soot.jimple.StaticInvokeExpr)
	 */
	@Override
	public void caseStaticInvokeExpr(StaticInvokeExpr arg0) {
		throw new RuntimeException("This must be handeled by SootStmtSwitch!");
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ExprSwitch#caseSubExpr(soot.jimple.SubExpr)
	 */
	@Override
	public void caseSubExpr(SubExpr arg0) {
		translateBinOp(arg0);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ExprSwitch#caseUshrExpr(soot.jimple.UshrExpr)
	 */
	@Override
	public void caseUshrExpr(UshrExpr arg0) {
		translateBinOp(arg0);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * soot.jimple.ExprSwitch#caseVirtualInvokeExpr(soot.jimple.VirtualInvokeExpr
	 * )
	 */
	@Override
	public void caseVirtualInvokeExpr(VirtualInvokeExpr arg0) {
		throw new RuntimeException("This must be handeled by SootStmtSwitch!");
	}

	@Override
	public void caseDynamicInvokeExpr(DynamicInvokeExpr arg0) {
		throw new RuntimeException("This must be handeled by SootStmtSwitch!");
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ExprSwitch#caseXorExpr(soot.jimple.XorExpr)
	 */
	@Override
	public void caseXorExpr(XorExpr arg0) {
		translateBinOp(arg0);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.RefSwitch#caseArrayRef(soot.jimple.ArrayRef)
	 */
	@Override
	public void caseArrayRef(ArrayRef arg0) {
		BoogieType btype = GlobalsCache.v().getBoogieType(arg0.getType());
		Expression arrayvar;
		BoogieType arrtype;
		if (btype == this.pf.getIntType()) {
			arrayvar = SootPrelude.v().getIntArrHeapVariable();
			arrtype = SootPrelude.v().getIntArrType();
		} else if (btype == this.pf.getBoolType()) {
			arrayvar = SootPrelude.v().getBoolArrHeapVariable();
			arrtype = SootPrelude.v().getBoolArrType();
			// } else if (btype == this.pf.getRealType() ) {
			// arrayvar = SootPrelude.v().getRealArrHeapVariable();
			// arrtype= SootPrelude.v().getRealArrType();
		} else if (btype == SootPrelude.v().getReferenceType()) {
			arrayvar = SootPrelude.v().getRefArrHeapVariable();
			arrtype = SootPrelude.v().getRefArrType();
		} else {
			throw new RuntimeException("do not understand array of type: "
					+ btype.toString());
		}
		// tranlate base and index
		this.isLeftHandSide = false;
		arg0.getBase().apply(this);
		Expression baseExpression = this.expressionStack.pop();
		arg0.getIndex().apply(this);
		Expression indexExpression = this.expressionStack.pop();
		// guard out-of-bounds exceptions
		this.stmtSwitch.getErrorModel().createArrayBoundGuard(baseExpression,
				indexExpression);

		// construct the expression
		Expression[] base = { baseExpression };
		Expression array = this.pf.mkArrayAccessExpression(arrtype, arrayvar,
				base);
		Expression[] indices = { indexExpression };
		this.expressionStack.push(this.pf.mkArrayAccessExpression(btype, array,
				indices));
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * soot.jimple.RefSwitch#caseCaughtExceptionRef(soot.jimple.CaughtExceptionRef
	 * )
	 */
	@Override
	public void caseCaughtExceptionRef(CaughtExceptionRef arg0) {
		if (arg0.getType() instanceof RefType) {
			RefType rtype = (RefType) arg0.getType();

			// assume that the exception variable now has the type of the caught
			// exception
			// assume $heap[$exception,$type] <: arg0.getType()

			if (this.stmtSwitch != null) {
				// ensure that $exception is not null.
				//TODO: actually don't! Because this creates
				//a dead else branch in some cases.
				//the non-nullness is ensured by the compiler.
//				this.stmtSwitch.getErrorModel()
//						.createNonNullViolationException(
//								this.procInfo.getExceptionVariable());

				Expression typefield = this.getClassTypeFromExpression(
						this.procInfo.getExceptionVariable(), false);

				this.stmtSwitch.addStatement(pf.mkAssumeStatement(
						new Attribute[] {},
						GlobalsCache.v().compareTypeExpressions(
								typefield,
								GlobalsCache.v().lookupClassVariable(
										rtype.getSootClass()))));
			}
			this.expressionStack.push(this.procInfo.getExceptionVariable());
			return;
		}
		throw new RuntimeException(
				"this case of exception handling has not beend implemented");
	}

	private void checkFieldAnnotations(Expression expr, FieldRef fr) {
		LinkedList<SootAnnotations.Annotation> annot = SootAnnotations
				.parseFieldTags(fr.getField());
		if (annot.contains(SootAnnotations.Annotation.NonNull)) {
			this.stmtSwitch.addStatement(this.stmtSwitch.getErrorModel()
					.createAssumeNonNull(expr));
		}

	}

	private boolean checkSharedField(FieldRef ref, Expression field) {
		if (!Options.v().useSoundThreads()) {
			return false;
		} else {
			if (!this.stmtSwitch.isInMonitor()) {
				if (MhpInfo.v().getSharedFields(this.procInfo.getSootMethod())
						.contains(ref.getField())) {
					// if the field can be modified in another thread, add a
					// havoc statement before it is used.
					return true;
				} else {
					// do nothing
				}

			} else {
				Log.info("Was in monitor ... ");
			}
		}
		return false;
	}

	private void havocField(Expression field, Expression base) {
		if (base == null) {
			// the field is static
			IdentifierExpression identifier = (IdentifierExpression) field;
			if (identifier != null) {
				Statement s = this.pf.mkHavocStatement(TranslationHelpers
						.javaLocation2Attribute(this.stmtSwitch
								.getCurrentStatement()), identifier);
				this.stmtSwitch.addStatement(s);
			} else {
				throw new RuntimeException("Not Implemented");
			}
		} else {
			Expression heapAccess = this.makeHeapAccessExpression(base, field,
					true);
			IdentifierExpression havocval = GlobalsCache.v().getHavocGlobal(
					heapAccess.getType());
			this.stmtSwitch.addStatement(this.pf.mkHavocStatement(
					TranslationHelpers.javaLocation2Attribute(this.stmtSwitch
							.getCurrentStatement()), havocval));
			Expression[] indices = { base, field };
			Expression heapupdate = pf.mkArrayStoreExpression(SootPrelude.v()
					.getHeapVariable().getType(), SootPrelude.v()
					.getHeapVariable(), indices, havocval);
			Statement s = pf.mkAssignmentStatement(SootPrelude.v()
					.getHeapVariable(), heapupdate);
			this.stmtSwitch.addStatement(s);
		}

	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * soot.jimple.RefSwitch#caseInstanceFieldRef(soot.jimple.InstanceFieldRef)
	 */
	@Override
	public void caseInstanceFieldRef(InstanceFieldRef arg0) {
		boolean islhs = this.isLeftHandSide;
		this.isLeftHandSide = false;

		arg0.getBase().apply(this);
		Expression base = this.getExpression();
		Expression field = GlobalsCache.v().lookupSootField(arg0.getField());

		boolean nullCheckNeeded = true;
		// check if the field may be modified by another thread.
		if (!islhs && checkSharedField(arg0, field)) {
			havocField(field, base);
			nullCheckNeeded = false;
		}

		SootProcedureInfo pinfo = this.stmtSwitch.getProcInfo();

		// check if base is trivially non-null
		if (pinfo != null) {
			CustomNullnessAnalysis nna = this.stmtSwitch.getProcInfo()
					.getNullnessAnalysis();
			if (nna != null && arg0.getBase() instanceof Immediate) {
				if (nna.isAlwaysNonNullBefore(
						this.stmtSwitch.getCurrentStatement(),
						(Immediate) arg0.getBase())) {
					nullCheckNeeded = false;
				}
			}

			//TODO: this is a very clumsy way of obtaining thislocal
			// but it is not obvious when it throws an exception.
			Local thislocal = null;
			try {
				thislocal =  pinfo.getSootMethod().getActiveBody().getThisLocal();
			} catch (Exception e) {
				thislocal = null;
			}
			//check if base is "this" or a local variable
			//that is an alias of "this".
			if (arg0.getBase() ==thislocal || arg0.getBase() instanceof ThisRef)  {
				nullCheckNeeded = false; // TODO: check if this is actually needed.
			}

		}

		// We are checking if this is a @NonNull field
		// if so, we add an assume to ensure that it actually is
		// not null here.
		checkFieldAnnotations(
				this.makeHeapAccessExpression(base, field, false), arg0);

		this.expressionStack.push(this.makeHeapAccessExpression(base, field,
				nullCheckNeeded));
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.RefSwitch#caseParameterRef(soot.jimple.ParameterRef)
	 */
	@Override
	public void caseParameterRef(ParameterRef arg0) {
		this.expressionStack.push(this.procInfo.lookupParameterVariable(arg0));
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.RefSwitch#caseStaticFieldRef(soot.jimple.StaticFieldRef)
	 */
	@Override
	public void caseStaticFieldRef(StaticFieldRef arg0) {
		// TODO: we are checking if this is a @NonNull field
		// if so, we add an assume to ensure that it actually is
		// not null here. May be better ways to do this.
		checkFieldAnnotations(
				GlobalsCache.v().lookupSootField(arg0.getField()), arg0);
		Expression field = GlobalsCache.v().lookupSootField(arg0.getField());
		// check if the field may be modified by another thread.
		// (unless it is a lhs expression. In that case we don't care.
		if (!this.isLeftHandSide && checkSharedField(arg0, field)) {
			havocField(field, null);
		}

		this.expressionStack.push(field);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.RefSwitch#caseThisRef(soot.jimple.ThisRef)
	 */
	@Override
	public void caseThisRef(ThisRef arg0) {
		this.expressionStack.push(this.procInfo.getThisReference());
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.JimpleValueSwitch#caseLocal(soot.Local)
	 */
	@Override
	public void caseLocal(Local arg0) {
		this.expressionStack.push(this.procInfo.lookupLocalVariable(arg0));
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see soot.jimple.ConstantSwitch#defaultCase(java.lang.Object)
	 */
	@Override
	public void defaultCase(Object arg0) {
		Log.error("BoogieValueSwitch: case not covered");
		assert (false);
	}

	/**
	 * Make a heap access and the necessary assertion
	 *
	 * @param field
	 * @return
	 */
	public Expression makeHeapAccessExpression(Expression base,
			Expression field, boolean guarded) {
		if (guarded && this.stmtSwitch != null) {
			this.stmtSwitch.getErrorModel().createNonNullGuard(base);
		}
		// Assemble the $heap[base, field] expression
		return SootPrelude.v().heapAccess(base, field);
	}

	/**
	 * gets the field of expr that denotes its Java type E.g., let's say we have
	 * a variable c of type C. The call getExprssionJavaClass(c) returns
	 * $heap[c, $type] which, in this case, would be C.
	 *
	 * @param expr
	 * @param guarded
	 * @return
	 */
	public Expression getExprssionJavaClass(Expression expr) {
		return getClassTypeFromExpression(expr, true);
	}

	/**
	 * gets the field of expr that denotes its Java type E.g., let's say we have
	 * a variable c of type C. The call getExprssionJavaClass(c,false) returns
	 * $heap[c, $type] which, in this case, would be C.
	 *
	 * @param expr
	 * @param guarded
	 * @return
	 */
	public Expression getClassTypeFromExpression(Expression expr,
			boolean guarded) {
		return makeHeapAccessExpression(expr, SootPrelude.v()
				.getFieldClassVariable(), guarded);
	}

	@Override
	public void caseMethodHandle(MethodHandle arg0) {
		throw new RuntimeException("Not implemented "+arg0);
	}

}


text:
package org.anarres.ircd;

import org.apache.mina.core.session.IoSession;
import static org.anarres.ircd.Command.NICK;
import static org.anarres.ircd.Command.PASS;
import static org.anarres.ircd.Command.QUIT;
import static org.anarres.ircd.Command.SERVER;
import static org.anarres.ircd.Command.SQUIT;
import static org.anarres.ircd.Command.USER;

/** A network link. */
public class Link {

    private final Daemon daemon;
    private final IoSession session;

    private String pass;
    private String name;
    private Target target;

    public Link(Daemon d, IoSession s) {
        this.daemon = d;
        this.session = s;
    }

    public Daemon getDaemon() {
        return daemon;
    }

    public IoSession getSession() {
        return session;
    }

    public String getName() {
        Target t = target;	// atomic
        if (t != null)
            return t.getName();
        String n = name;	// atomic
        if (n != null)
            return n;
        return "*";
    }

    /* Output */
    private void send(String msg) {
        if (session.isConnected())
            session.write(msg);
        else
            System.err.println("NOCONN: " + msg);
    }

    public void send(Response response, Object... args) {
        StringBuilder out = new StringBuilder();
        out.append(':').append(daemon.getName());
        out.append(' ');
        String code = String.valueOf(response.getCode());
        for (int i = code.length(); i < 3; i++)
            out.append('0');
        out.append(code);
        out.append(' ').append(getName());
        out.append(' ');
        String msg = response.getMessage();
        for (int i = 0; i < msg.length(); i++) {
            char c = msg.charAt(i);
            if (c == '$') {
                char d = msg.charAt(++i);
                if (d == '$')
                    out.append('$');
                else
                    out.append(args[Character.digit(d, 10) - 1]);
            } else {
                out.append(c);
            }
        }
        send(out.toString());
    }

    public void send(Message m) {
        send(String.valueOf(m));
    }

    /* Input */
    protected boolean isLegal(Message m) {
        if (!m.getCommand().isLegal()) {
            send(Response.ERR_UNKNOWNCOMMAND, m.getCommandText());
            return false;
        }
        if (m.getArgCount() < m.getCommand().getMinArgs()) {
            send(Response.ERR_NEEDMOREPARAMS, m.getCommand().name(),
                    m.getArgCount(),
                    m.getCommand().getMinArgs());
            return false;
        }
        return true;
    }

    public synchronized void messageReceived(Message m) {

        if (!isLegal(m))
            return;

        if (target != null) {
            target.cmd(m);
            return;
        }

        /* Unregistered objects only. */
        switch (m.getCommand()) {

            case USER:
                // <username> <hostname> <servername> <realname>
                Client c = new Client(
                        this,
                        name,
                        m.getArg(0), m.getArg(1),
                        /* m.getArg(2), */ m.getArg(3)
                );
                this.target = c;
                daemon.addClient(c);
                c.helo();
                break;
            case PASS:
                this.pass = m.getArg(0);
                /* XXX Username removes the ~ */
                break;
            case NICK:
                /* XXX Duplicates Client.java */
                String nick = m.getArg(0);
                if (daemon.getClient(nick) != null) {
                    send(Response.ERR_NICKNAMEINUSE, nick);
                    break;
                }
                this.name = nick;
                break;

            case SERVER:
                // <name> <hopcount> <info>
                this.name = m.getArg(0);
                Server s = new Server(
                        this,
                        m.getArg(0), Integer.parseInt(m.getArg(1)),
                        m.getArg(2)
                );
                this.target = s;
                daemon.addServer(s);
                s.helo();
                break;

            case QUIT:
            case SQUIT:
                send("ERROR :Closing Link: YOUR_IP ()");
                close();
                break;
            default:
                send(Response.ERR_NOTREGISTERED);
                break;
        }
    }

    public void close() {
        getSession().close();
    }

}

redpajama_set_name: RedPajamaGithub


text:
import {
  handleActions,
} from 'redux-actions';

const initialState = {
  topics: [],
  isLoading: false,
  detail: null,
};

export default handleActions({
  'fetchHotTopics/start': state => ({
    ...state, isLoading: true,
  }),
  'fetchHotTopics/end': (state, action) => ({
    ...state, topics: action.payload, isLoading: false,
  }),
  'fetchTopicDetail/start': state => ({
    ...state, isLoading: true,
  }),
  'fetchTopicDetail/end': (state, action) => ({
    ...state, detail: action.payload, isLoading: false,
  }),

}, initialState);


text:
package com.amazonaws.services.autoscaling.model.transform;

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

import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.autoscaling.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;

/**
 * DescribeScheduledActionsRequest Marshaller
 */

public class DescribeScheduledActionsRequestMarshaller
        implements
        Marshaller<Request<DescribeScheduledActionsRequest>, DescribeScheduledActionsRequest> {

    public Request<DescribeScheduledActionsRequest> marshall(
            DescribeScheduledActionsRequest describeScheduledActionsRequest) {

        if (describeScheduledActionsRequest == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        Request<DescribeScheduledActionsRequest> request = new DefaultRequest<DescribeScheduledActionsRequest>(
                describeScheduledActionsRequest, "AmazonAutoScaling");
        request.addParameter("Action", "DescribeScheduledActions");
        request.addParameter("Version", "2011-01-01");
        request.setHttpMethod(HttpMethodName.POST);

        if (describeScheduledActionsRequest.getAutoScalingGroupName() != null) {
            request.addParameter("AutoScalingGroupName", StringUtils
                    .fromString(describeScheduledActionsRequest
                            .getAutoScalingGroupName()));
        }

        com.amazonaws.internal.SdkInternalList<String> scheduledActionNamesList = (com.amazonaws.internal.SdkInternalList<String>) describeScheduledActionsRequest
                .getScheduledActionNames();
        if (!scheduledActionNamesList.isEmpty()
                || !scheduledActionNamesList.isAutoConstruct()) {
            int scheduledActionNamesListIndex = 1;

            for (String scheduledActionNamesListValue : scheduledActionNamesList) {
                if (scheduledActionNamesListValue != null) {
                    request.addParameter("ScheduledActionNames.member."
                            + scheduledActionNamesListIndex, StringUtils
                            .fromString(scheduledActionNamesListValue));
                }
                scheduledActionNamesListIndex++;
            }
        }

        if (describeScheduledActionsRequest.getStartTime() != null) {
            request.addParameter("StartTime", StringUtils
                    .fromDate(describeScheduledActionsRequest.getStartTime()));
        }

        if (describeScheduledActionsRequest.getEndTime() != null) {
            request.addParameter("EndTime", StringUtils
                    .fromDate(describeScheduledActionsRequest.getEndTime()));
        }

        if (describeScheduledActionsRequest.getNextToken() != null) {
            request.addParameter("NextToken", StringUtils
                    .fromString(describeScheduledActionsRequest.getNextToken()));
        }

        if (describeScheduledActionsRequest.getMaxRecords() != null) {
            request.addParameter("MaxRecords", StringUtils
                    .fromInteger(describeScheduledActionsRequest
                            .getMaxRecords()));
        }

        return request;
    }

}


text:
using System;
using Avalonia.Platform;

#nullable enable

namespace Avalonia.Controls.Platform
{
    public interface INativeMenuExporter
    {
        void SetNativeMenu(NativeMenu? menu);
    }

    public interface ITopLevelNativeMenuExporter : INativeMenuExporter
    {
        bool IsNativeMenuExported { get; }

        event EventHandler OnIsNativeMenuExportedChanged;
    }

    public interface INativeMenuExporterProvider
    {
        INativeMenuExporter? NativeMenuExporter { get; }
    }

    public interface ITopLevelImplWithNativeMenuExporter : ITopLevelImpl
    {
        ITopLevelNativeMenuExporter NativeMenuExporter { get; }
    }
}


text:
using System;
using System.Linq;

namespace Microsoft.WindowsAzure.Management.Compute.Models
{
    /// <summary>
    /// Specifies the protocol to use when inspecting the virtual machine
    /// availability status.
    /// </summary>
    public enum LoadBalancerProbeTransportProtocol
    {
        Tcp = 0,

        Http = 1,
    }
}


text:
import {Component, PropTypes, h,} from './Component';
import {Motion, spring,} from 'react-motion';
import View from './View';
import {mixins,} from './decorators';
import {} from './mixins';

export default class Writing extends Component {
    title = '';
    text = '';
    stat = {owner: '', date: '',};

    handleSendClick(e) {
        this.title = this.refs.title.value;
        this.text = this.refs.text.value;
        this.stat.owner = this.props.user.username;
        this.stat.date = new Date().toDateString();
        this.props.handleSendClick && this.props.handleSendClick(e, this);
    }

    render({render, style, children, className, handleSendClick, user, ...rest}) {
        return user.authority === 1 ?
            h(View, {
                children: [
                    h('input', {ref: 'title'}),
                    h('textarea', {
                        style: {
                            height: 300,
                        },
                        className: 'whfp',
                        ref: 'text',
                    }),
                    h(View, {
                        children: h('button', {
                            children: 'send',
                            onClick: this.handleSendClick,
                        }),
                        className: 'jcfe whfp',
                    }),
                ],
                className: 'whfp fdcn aicr',
            }) :
            null;
    }
}
Writing.propTypes = {};
Writing.defaultProps = {};


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class org.springframework.aop.support.AbstractPointcutAdvisor (Spring Framework API 2.5)
</TITLE>

<META NAME="date" CONTENT="2007-11-19">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

The Spring Framework

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.springframework.aop.support.AbstractPointcutAdvisor

Packages that use AbstractPointcutAdvisor

org.springframework.aop.aspectj
AspectJ integration package.

org.springframework.aop.aspectj.annotation
Classes enabling AspectJ 5 @Annotated classes to be used in Spring AOP.

org.springframework.aop.support
Convenience classes for using Spring's AOP API.

org.springframework.dao.annotation
Annotation support for DAOs.

org.springframework.transaction.interceptor
AOP-based solution for declarative transaction demarcation.

Uses of AbstractPointcutAdvisor in org.springframework.aop.aspectj

Subclasses of AbstractPointcutAdvisor in org.springframework.aop.aspectj

 class
AspectJExpressionPointcutAdvisor

          Spring AOP Advisor that can be used for any AspectJ pointcut expression.

Uses of AbstractPointcutAdvisor in org.springframework.aop.aspectj.annotation

Subclasses of AbstractPointcutAdvisor in org.springframework.aop.aspectj.annotation

protected static class
ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor

          Synthetic advisor that instantiates the aspect.

Uses of AbstractPointcutAdvisor in org.springframework.aop.support

Subclasses of AbstractPointcutAdvisor in org.springframework.aop.support

 class
AbstractBeanFactoryPointcutAdvisor

          Abstract BeanFactory-based PointcutAdvisor that allows for any Advice
 to be configured as reference to an Advice bean in a BeanFactory.

 class
AbstractGenericPointcutAdvisor

          Abstract generic PointcutAdvisor that allows for any Advice to be configured.

 class
DefaultBeanFactoryPointcutAdvisor

          Concrete BeanFactory-based PointcutAdvisor that allows for any Advice
 to be configured as reference to an Advice bean in the BeanFactory,
 as well as the Pointcut to be configured through a bean property.

 class
DefaultPointcutAdvisor

          Convenient Pointcut-driven Advisor implementation.

 class
NameMatchMethodPointcutAdvisor

          Convenient class for name-match method pointcuts that hold an Advice,
 making them an Advisor.

 class
RegexpMethodPointcutAdvisor

          Convenient class for regexp method pointcuts that hold an Advice,
 making them an Advisor.

Uses of AbstractPointcutAdvisor in org.springframework.dao.annotation

Subclasses of AbstractPointcutAdvisor in org.springframework.dao.annotation

 class
PersistenceExceptionTranslationAdvisor

          Spring AOP exception translation aspect for use at Repository or DAO layer level.

Uses of AbstractPointcutAdvisor in org.springframework.transaction.interceptor

Subclasses of AbstractPointcutAdvisor in org.springframework.transaction.interceptor

 class
TransactionAttributeSourceAdvisor

          Advisor driven by a TransactionAttributeSource, used to exclude
 a TransactionInterceptor from methods that are non-transactional.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

The Spring Framework

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2002-2007 The Spring Framework.


text:
import api from '../../api';

var tag = this;

tag.doLogin = function (e) {
    var email = tag.email.value;
    var password = tag.password.value;
    api.login(email, password, function (err) {
        if (err) {
            console.error(err);
        } else {
            console.log('login attempt');
        }
    });
};


text:
  <empty-state title="Welcome to Redash 👋" description="Connect to any data source, easily visualize and share your data"
    show-dashboard-step="true" show-invite-step="true" onboarding-mode="true" illustration="dashboard" help-link="https://redash.io/help/user-guide/getting-started"></empty-state>

  <home-extra></home-extra>

Favorite Dashboards

            Favorite Dashboards will appear here

              {{dashboard.name}}
              Unpublished

Favorite Queries

            Favorite Queries will appear here

              {{query.name}}
              Unpublished


text:
import sys, socket, os, zipfile, logging
import cProfile as profile
from pprint import pprint

from Kamaelia.Apps.JMB.WSGI import WSGIFactory
from Kamaelia.Chassis.ConnectedServer import ServerCore
from Kamaelia.Support.Protocol.HTTP import HTTPProtocol
from Kamaelia.Protocol.HTTP.Handlers.Minimal import MinimalFactory

#Stuff that's shared between some of the webservers
from Kamaelia.Apps.JMB.Common.Console import info
from Kamaelia.Apps.JMB.Common.ConfigFile import DictFormatter, ParseConfigFile
from Kamaelia.Apps.JMB.Common.autoinstall import autoinstall
from Kamaelia.Apps.JMB.Common.UrlConfig import ParseUrlFile
from Kamaelia.Apps.JMB.Common.ServerSetup import processPyPath, normalizeUrlList, \
    normalizeWsgiVars, initializeLogger

_profile_ = False
_logger_suffix = '.WebServe.main'

def run_program():
    """The main entry point for the application."""
    try:
        zip = zipfile.ZipFile(sys.argv[0], 'r')

        #prompt the user if this executable is corrupt
        corrupt = zip.testzip()
        if corrupt:
            Console.prompt_corrupt(corrupt)

        initializeLogger()
        home_path = os.environ['HOME']

        #prompt the user to install the necessary software if this is the first
        #time to run Kamaelia WebServe
        if not os.path.exists(home_path + '/kp.ini'):
            autoinstall(zip, home_path, 'Kamaelia WebServe')

        zip.close()

        #Extract data from Config Files and organize it into dictionaries
        configs = ParseConfigFile('~/kp.ini', DictFormatter())
        ServerConfig = configs['SERVER']
        WsgiConfig = configs['WSGI']
        StaticConfig = configs['STATIC']

        processPyPath(ServerConfig)
        normalizeWsgiVars(WsgiConfig)

        url_list = ParseUrlFile(WsgiConfig['url_list'])
        normalizeUrlList(url_list)

        StaticConfig['homedirectory'] = os.path.expanduser(StaticConfig['homedirectory'])
        log = os.path.expanduser(ServerConfig['log'])
        routing = [
                      [StaticConfig['url'], MinimalFactory(
                                                           StaticConfig['index'],
                                                           StaticConfig['homedirectory']
                                                           )],
                      ["/", WSGIFactory(WsgiConfig, url_list, log)],
                  ]

        kp = ServerCore(
            protocol=HTTPProtocol(routing),
            port=int(ServerConfig['port']),
            socketOptions=(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1))

        info('Serving on port %s' % (ServerConfig['port']), _logger_suffix)
    except:
        import traceback
        print 'There was an error!  Info is in %s/error.log' % (os.getcwd())
        file = open('error.log', 'a')
        traceback.print_exc(file=file)
        file.write('\n')
        file.close()
        sys.exit(1)
    try:
        kp.run()
    except KeyboardInterrupt:
        print "Halting server!"
    except:
        #Something's gone horribly wrong and the program doesn't know what to do
        #about it.
        import traceback
        traceback.print_exc()
        print "===========FATAL ERROR==========="
    finally:
        kp.stop()
        logging.shutdown()

def profile_main():
    """This is what you want to use if you intend on profiling the application."""
    pr = profile.Profile()  #Note that we've imported cProfile as profile.
    pr.run('main.run_program()')

if _profile_:
    main = profile_main
else:
    main = run_program

if __name__ == '__main__':
    main()


text:
using System;
using CasparCg.AmcpClient.Common;

namespace CasparCg.AmcpClient.Commands.Mixer.Common.Response
{
    public class MixerMipmapGetCommandResponse : AmcpResponse
    {
        public bool IsMipmapEnabled { get; private set; }

        internal override void ProcessData(AmcpParsedData data)
        {
            base.ProcessData(data);

            IsMipmapEnabled = Convert.ToBoolean(Convert.ToInt32(data.Data[1]));;
        }
    }
}


text:
namespace process {

inline void post(const process::UPID& to,
                 const google::protobuf::Message& message)
{
  std::string data;
  if (message.SerializeToString(&data)) {
    post(to, message.GetTypeName(), data.data(), data.size());
  } else {
    LOG(ERROR) << "Failed to post '" << message.GetTypeName() << "' to "
               << to << ": Failed to serialize";
  }
}

inline void post(const process::UPID& from,
                 const process::UPID& to,
                 const google::protobuf::Message& message)
{
  std::string data;
  if (message.SerializeToString(&data)) {
    post(from, to, message.GetTypeName(), data.data(), data.size());
  } else {
    LOG(ERROR) << "Failed to post '" << message.GetTypeName() << "' to "
               << to << ": Failed to serialize";
  }
}

} // namespace process {

// The rest of this file provides libprocess "support" for using
// protocol buffers. In particular, this file defines a subclass of
// Process (ProtobufProcess) that allows you to install protocol
// buffer handlers in addition to normal message and HTTP
// handlers. Install handlers can optionally take the sender's UPID
// as their first argument.
// Note that this header file assumes you will be linking
// against BOTH libprotobuf and libglog.

namespace google {
namespace protobuf {

// Type conversions helpful for changing between protocol buffer types
// and standard C++ types (for parameters).
template <typename T>
const T& convert(const T& t)
{
  return t;
}

template <typename T>
std::vector<T> convert(const google::protobuf::RepeatedPtrField<T>& items)
{
  return std::vector<T>(items.begin(), items.end());
}

template <typename T>
std::vector<T> convert(google::protobuf::RepeatedPtrField<T>&& items)
{
  return std::vector<T>(
      std::make_move_iterator(items.begin()),
      std::make_move_iterator(items.end()));
}

} // namespace protobuf {
} // namespace google {

template <typename T>
class ProtobufProcess : public process::Process<T>
{
public:
  ~ProtobufProcess() override {}

protected:
  void consume(process::MessageEvent&& event) override
  {
    if (protobufHandlers.count(event.message.name) > 0) {
      from = event.message.from; // For 'reply'.
      protobufHandlers[event.message.name](
          event.message.from, event.message.body);
      from = process::UPID();
    } else {
      process::Process<T>::consume(std::move(event));
    }
  }

  void send(const process::UPID& to,
            const google::protobuf::Message& message)
  {
    std::string data;
    if (message.SerializeToString(&data)) {
      process::Process<T>::send(to, message.GetTypeName(), std::move(data));
    } else {
      LOG(ERROR) << "Failed to send '" << message.GetTypeName() << "' to "
                 << to << ": Failed to serialize";
    }
  }

  using process::Process<T>::send;

  void reply(const google::protobuf::Message& message)
  {
    CHECK(from) << "Attempting to reply without a sender";
    send(from, message);
  }

  // Installs that take the sender as the first argument.
  template <typename M>
  void install(void (T::*method)(const process::UPID&, const M&))
  {
    google::protobuf::Message* m = new M();
    T* t = static_cast<T*>(this);
    protobufHandlers[m->GetTypeName()] =
      lambda::bind(&handlerM<M>,
                   t, method,
                   lambda::_1, lambda::_2);
    delete m;
  }

  template <typename M>
  void install(void (T::*method)(const process::UPID&, M&&))
  {
    google::protobuf::Message* m = new M();
    T* t = static_cast<T*>(this);
    protobufHandlers[m->GetTypeName()] =
      lambda::bind(&handlerMutM<M>,
                   t, method,
                   lambda::_1, lambda::_2);
    delete m;
  }

  template <typename M, typename P>
  using MessageProperty = P(M::*)() const;

  template <typename M>
  void install(void (T::*method)(const process::UPID&))
  {
    google::protobuf::Message* m = new M();
    T* t = static_cast<T*>(this);
    protobufHandlers[m->GetTypeName()] =
      lambda::bind(&handler0,
                   t, method,
                   lambda::_1, lambda::_2);
    delete m;
  }

  template <typename M,
            typename ...P, typename ...PC>
  void install(
      void (T::*method)(const process::UPID&, PC...),
      MessageProperty<M, P>... param)
  {
    google::protobuf::Message* m = new M();
    T* t = static_cast<T*>(this);
    protobufHandlers[m->GetTypeName()] =
      lambda::bind(static_cast<void(&)(
                       T*,
                       void (T::*)(const process::UPID&, PC...),
                       const process::UPID&,
                       const std::string&,
                       MessageProperty<M, P>...)>(handlerN),
                   t, method,
                   lambda::_1, lambda::_2, param...);
    delete m;
  }

  // Installs that do not take the sender.
  template <typename M>
  void install(void (T::*method)(const M&))
  {
    google::protobuf::Message* m = new M();
    T* t = static_cast<T*>(this);
    protobufHandlers[m->GetTypeName()] =
      lambda::bind(&_handlerM<M>,
                   t, method,
                   lambda::_1, lambda::_2);
    delete m;
  }

  template <typename M>
  void install(void (T::*method)(M&&))
  {
    google::protobuf::Message* m = new M();
    T* t = static_cast<T*>(this);
    protobufHandlers[m->GetTypeName()] =
      lambda::bind(&_handlerMutM<M>,
                   t, method,
                   lambda::_1, lambda::_2);
    delete m;
  }

  template <typename M>
  void install(void (T::*method)())
  {
    google::protobuf::Message* m = new M();
    T* t = static_cast<T*>(this);
    protobufHandlers[m->GetTypeName()] =
      lambda::bind(&_handler0,
                   t, method,
                   lambda::_1, lambda::_2);
    delete m;
  }

  template <typename M,
            typename ...P, typename ...PC>
  void install(
      void (T::*method)(PC...),
      MessageProperty<M, P>... param)
  {
    google::protobuf::Message* m = new M();
    T* t = static_cast<T*>(this);
    protobufHandlers[m->GetTypeName()] =
      lambda::bind(static_cast<void(&)(
                       T*,
                       void (T::*)(PC...),
                       const process::UPID&,
                       const std::string&,
                       MessageProperty<M, P>...)>(_handlerN),
                   t, method,
                   lambda::_1, lambda::_2, param...);
    delete m;
  }

  using process::Process<T>::install;

private:
  // Handlers that take the sender as the first argument.
  template <typename M>
  static void handlerM(
      T* t,
      void (T::*method)(const process::UPID&, const M&),
      const process::UPID& sender,
      const std::string& data)
  {
    google::protobuf::Arena arena;
    M* m = CHECK_NOTNULL(google::protobuf::Arena::CreateMessage<M>(&arena));

    if (m->ParseFromString(data)) {
      (t->*method)(sender, *m);
    } else {
      LOG(ERROR) << "Failed to deserialize '" << m->GetTypeName()
                 << "' from " << sender;
    }
  }

  template <typename M>
  static void handlerMutM(
      T* t,
      void (T::*method)(const process::UPID&, M&&),
      const process::UPID& sender,
      const std::string& data)
  {
    M m;

    if (m.ParseFromString(data)) {
      (t->*method)(sender, std::move(m));
    } else {
      LOG(ERROR) << "Failed to deserialize '" << m.GetTypeName()
                 << "' from " << sender;
    }
  }

  static void handler0(
      T* t,
      void (T::*method)(const process::UPID&),
      const process::UPID& sender,
      const std::string& data)
  {
    (t->*method)(sender);
  }

  template <typename M,
            typename ...P, typename ...PC>
  static void handlerN(
      T* t,
      void (T::*method)(const process::UPID&, PC...),
      const process::UPID& sender,
      const std::string& data,
      MessageProperty<M, P>... p)
  {
    google::protobuf::Arena arena;
    M* m = CHECK_NOTNULL(google::protobuf::Arena::CreateMessage<M>(&arena));

    if (m->ParseFromString(data)) {
      (t->*method)(sender, google::protobuf::convert((m->*p)())...);
    } else {
      LOG(ERROR) << "Failed to deserialize '" << m->GetTypeName()
                 << "' from " << sender;
    }
  }

  // Handlers that ignore the sender.
  template <typename M>
  static void _handlerM(
      T* t,
      void (T::*method)(const M&),
      const process::UPID& sender,
      const std::string& data)
  {
    google::protobuf::Arena arena;
    M* m = CHECK_NOTNULL(google::protobuf::Arena::CreateMessage<M>(&arena));

    if (m->ParseFromString(data)) {
      (t->*method)(*m);
    } else {
      LOG(ERROR) << "Failed to deserialize '" << m->GetTypeName()
                 << "' from " << sender;
    }
  }

  template <typename M>
  static void _handlerMutM(
      T* t,
      void (T::*method)(M&&),
      const process::UPID& sender,
      const std::string& data)
  {
    M m;

    if (m.ParseFromString(data)) {
      (t->*method)(std::move(m));
    } else {
      LOG(ERROR) << "Failed to deserialize '" << m.GetTypeName()
                 << "' from " << sender;
    }
  }

  static void _handler0(
      T* t,
      void (T::*method)(),
      const process::UPID&,
      const std::string& data)
  {
    (t->*method)();
  }

  template <typename M,
            typename ...P, typename ...PC>
  static void _handlerN(
      T* t,
      void (T::*method)(PC...),
      const process::UPID& sender,
      const std::string& data,
      MessageProperty<M, P>... p)
  {
    google::protobuf::Arena arena;
    M* m = CHECK_NOTNULL(google::protobuf::Arena::CreateMessage<M>(&arena));

    if (m->ParseFromString(data)) {
      (t->*method)(google::protobuf::convert((m->*p)())...);
    } else {
      LOG(ERROR) << "Failed to deserialize '" << m->GetTypeName()
                 << "' from " << sender;
    }
  }

  typedef lambda::function<
      void(const process::UPID&, const std::string&)> handler;
  hashmap<std::string, handler> protobufHandlers;

  // Sender of "current" message, inaccessible by subclasses.
  // This is only used for reply().
  process::UPID from;
};

// Implements a process for sending protobuf "requests" to a process
// and waiting for a protobuf "response", but uses futures so that
// this can be done without needing to implement a process.
template <typename Req, typename Res>
class ReqResProcess : public ProtobufProcess<ReqResProcess<Req, Res>>
{
public:
  ReqResProcess(const process::UPID& _pid, const Req& _req)
    : process::ProcessBase(process::ID::generate("__req_res__")),
      pid(_pid),
      req(_req)
  {
    ProtobufProcess<ReqResProcess<Req, Res>>::template
      install<Res>(&ReqResProcess<Req, Res>::response);
  }

  ~ReqResProcess() override
  {
    // Discard the promise.
    promise.discard();
  }

  process::Future<Res> run()
  {
    promise.future().onDiscard(defer(this, &ReqResProcess::discarded));

    ProtobufProcess<ReqResProcess<Req, Res>>::send(pid, req);

    return promise.future();
  }

private:
  void discarded()
  {
    promise.discard();
    process::terminate(this);
  }

  void response(const Res& res)
  {
    promise.set(res);
    process::terminate(this);
  }

  const process::UPID pid;
  const Req req;
  process::Promise<Res> promise;
};

// Allows you to describe request/response protocols and then use
// those for sending requests and getting back responses.
template <typename Req, typename Res>
struct Protocol
{
  process::Future<Res> operator()(
      const process::UPID& pid,
      const Req& req) const
  {
    // Help debugging by adding some "type constraints".
    { Req* req = nullptr; google::protobuf::Message* m = req; (void)m; }
    { Res* res = nullptr; google::protobuf::Message* m = res; (void)m; }

    ReqResProcess<Req, Res>* process = new ReqResProcess<Req, Res>(pid, req);
    process::spawn(process, true);
    return process::dispatch(process, &ReqResProcess<Req, Res>::run);
  }
};

#endif // __PROCESS_PROTOBUF_HPP__


text:
@class THPinView;

@protocol THPinViewDelegate <NSObject>

@required
- (NSUInteger)pinLengthForPinView:(THPinView *)pinView;
- (BOOL)pinView:(THPinView *)pinView isPinValid:(NSString *)pin;
- (void)cancelButtonTappedInPinView:(THPinView *)pinView;
- (void)correctPinWasEnteredInPinView:(THPinView *)pinView;
- (void)incorrectPinWasEnteredInPinView:(THPinView *)pinView;

@end

@interface THPinView : UIView

@property (nonatomic, weak) id<THPinViewDelegate> delegate;
@property (nonatomic, copy) NSString *promptTitle;
@property (nonatomic, strong) UIColor *promptColor;
@property (nonatomic, assign) BOOL hideLetters;

- (instancetype)initWithDelegate:(id<THPinViewDelegate>)delegate;

@end


text:
package ImpactoExpress;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 *
 * @author joao
 * @version 1.0
 * @since 8nov2016
 *
 */
public class VeiculoDao {
    // a conexão com o banco de dados
    private Connection connection;

    public VeiculoDao() {
        this .connection = new ConnectionFactory().getConnection();
    }

    public void adiciona(Veiculo veiculo) {
        String sql = "insert into veiculo " +
            "(tipoVeiculo,modeloVeiculo,marcaVeiculo,corVeiculo,placaVeiculo,"
                + "renavamVeiculo,vencimentoVeiculo,categoriaVeiculo,observacoesVeiculo)" +
            " values (?,?,?,?,?,?,?,?,?)";
        try {
            // prepared statement para inserção
            PreparedStatement stmt = connection.prepareStatement(sql);

            // seta os valores
            stmt.setString(1,veiculo.getTipoVeiculo());
            stmt.setString(2,veiculo.getModeloVeiculo());
            stmt.setString(3,veiculo.getMarcaVeiculo());
            stmt.setString(4,veiculo.getCorVeiculo());
            stmt.setString(5,veiculo.getPlacaVeiculo());
            stmt.setString(6,veiculo.getRenavamVeiculo());
            stmt.setString(7,veiculo.getVencimentoVeiculo());
            stmt.setString(8,veiculo.getCategoriaVeiculo());
            stmt.setString(9,veiculo.getObservacoesVeiculo());

            // executa
            stmt.execute();
            stmt.close();
        }
        catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}


text:
using Itinero.Optimization.Solvers.CVRP;
using Xunit;

namespace Itinero.Optimization.Tests.Solvers.CVRP
{
    public class CVRPCandidateTests
    {
        [Fact]
        public void CVRPCandidate_AddNewShouldAddNewBasedOnProblem()
        {
            var candidate = new CVRPCandidate()
            {
                Solution = new CVRPSolution(),
                Fitness = 0,
                Problem = new CVRProblem(1, null, new []
                {
                    new [] { 0f, 1f, 2f },
                    new [] { 3f, 4f, 5f },
                    new [] { 6f, 7f, 8f }
                }, null)
            };

            var t = candidate.AddNew();
            Assert.Equal(1, candidate.Count);
            var tour = candidate.Tour(t);
            Assert.NotNull(tour);
            Assert.Equal(1, tour.First);
            Assert.Null(tour.Last);
        }

        [Fact]
        public void CVRPCandidate_AddNewShouldCalculateTourDataWhenArrivalNull()
        {
            var candidate = new CVRPCandidate()
            {
                Solution = new CVRPSolution(),
                Fitness = 0,
                Problem = new CVRProblem(1, null, new []
                {
                    new [] { 0f, 1f, 2f },
                    new [] { 3f, 4f, 5f },
                    new [] { 6f, 7f, 8f }
                }, null)
            };
            var tourData = candidate.TourData(candidate.AddNew());
            Assert.Equal(0, tourData.weight);
            Assert.NotNull(tourData.constraints);
            Assert.Empty(tourData.constraints);

            candidate = new CVRPCandidate()
            {
                Solution = new CVRPSolution(),
                Fitness = 0,
                Problem = new CVRProblem(0, null, new []
                {
                    new [] { 0f, 1f, 2f },
                    new [] { 3f, 4f, 5f },
                    new [] { 6f, 7f, 8f }
                }, null, new []{ 0f, 0f, 0f }, 100, new (string metric, float max, float[] costs)[]
                {
                    ("weight", 100, new [] { 10f, 10f, 10f })
                })
            };
            tourData = candidate.TourData(candidate.AddNew());
            Assert.Equal(0, tourData.weight);
            Assert.NotNull(tourData.constraints);
            Assert.Single(tourData.constraints);
            Assert.Equal("weight", tourData.constraints[0].metric);
            Assert.Equal(10, tourData.constraints[0].value);
        }

        [Fact]
        public void CVRPCandidate_AddNewShouldCalculateTourDataWhenArrivalNotNull()
        {
            var candidate = new CVRPCandidate()
            {
                Solution = new CVRPSolution(),
                Fitness = 0,
                Problem = new CVRProblem(0, 1, new []
                {
                    new [] { 0f, 1f, 2f },
                    new [] { 3f, 4f, 5f },
                    new [] { 6f, 7f, 8f }
                }, null)
            };
            var tourData = candidate.TourData(candidate.AddNew());
            Assert.Equal(1, tourData.weight);
            Assert.NotNull(tourData.constraints);
            Assert.Empty(tourData.constraints);

            candidate = new CVRPCandidate()
            {
                Solution = new CVRPSolution(),
                Fitness = 0,
                Problem = new CVRProblem(1, null, new []
                {
                    new [] { 0f, 1f, 2f },
                    new [] { 3f, 4f, 5f },
                    new [] { 6f, 7f, 8f }
                }, null, new []{ 0f, 0f, 0f }, 100, new (string metric, float max, float[] costs)[]
                {
                    ("weight", 100, new [] { 10f, 10f, 10f })
                })
            };
            tourData = candidate.TourData(candidate.AddNew());
            Assert.Equal(0, tourData.weight);
            Assert.NotNull(tourData.constraints);
            Assert.Single(tourData.constraints);
            Assert.Equal("weight", tourData.constraints[0].metric);
            Assert.Equal(10, tourData.constraints[0].value);
        }

        [Fact]
        public void CVRPCandidate_RemoveShouldRemoveTourAndDecreaseCount()
        {
            var candidate = new CVRPCandidate()
            {
                Solution = new CVRPSolution(),
                Fitness = 0,
                Problem = new CVRProblem(10, null, new []
                {
                    new [] { 0f, 1f, 2f },
                    new [] { 3f, 4f, 5f },
                    new [] { 6f, 7f, 8f }
                }, null)
            };

            var tour = candidate.Tour(candidate.AddNew());
            tour.InsertAfter(tour.First, 0);
            tour = candidate.Tour(candidate.AddNew());
            tour.InsertAfter(tour.First, 1);
            tour = candidate.Tour(candidate.AddNew());
            tour.InsertAfter(tour.First, 2);

            Assert.Equal(3, candidate.Count);
            tour = candidate.Tour(0);
            Assert.Equal(new [] { 10, 0 }, tour);
            tour = candidate.Tour(1);
            Assert.Equal(new [] { 10, 1 }, tour);
            tour = candidate.Tour(2);
            Assert.Equal(new [] { 10, 2 }, tour);

            candidate.Remove(1);
            Assert.Equal(2, candidate.Count);
            tour = candidate.Tour(0);
            Assert.Equal(new [] { 10, 0 }, tour);
            tour = candidate.Tour(1);
            Assert.Equal(new [] { 10, 2 }, tour);

            candidate.Remove(0);
            Assert.Equal(1, candidate.Count);
            tour = candidate.Tour(0);
            Assert.Equal(new [] { 10, 2 }, tour);

            candidate.Remove(0);
            Assert.Equal(0, candidate.Count);
        }

    }
}


text:
#include "config.h"
#include "HeapTimer.h"

#include "APIShims.h"
#include "JSObject.h"
#include "JSString.h"

#include <wtf/MainThread.h>
#include <wtf/Threading.h>

#if PLATFORM(QT)
#include <QCoreApplication>
#include <QMutexLocker>
#include <QThread>
#include <QTimerEvent>
#elif PLATFORM(EFL)
#include <Ecore.h>
#endif

namespace JSC {

#if USE(CF)

const CFTimeInterval HeapTimer::s_decade = 60 * 60 * 24 * 365 * 10;

static const void* retainAPILock(const void* info)
{
    static_cast<JSLock*>(const_cast<void*>(info))->ref();
    return info;
}

static void releaseAPILock(const void* info)
{
    static_cast<JSLock*>(const_cast<void*>(info))->deref();
}

HeapTimer::HeapTimer(VM* vm, CFRunLoopRef runLoop)
    : m_vm(vm)
    , m_runLoop(runLoop)
{
    memset(&m_context, 0, sizeof(CFRunLoopTimerContext));
    m_context.info = &vm->apiLock();
    m_context.retain = retainAPILock;
    m_context.release = releaseAPILock;
    m_timer = adoptCF(CFRunLoopTimerCreate(0, s_decade, s_decade, 0, 0, HeapTimer::timerDidFire, &m_context));
    CFRunLoopAddTimer(m_runLoop.get(), m_timer.get(), kCFRunLoopCommonModes);
}

HeapTimer::~HeapTimer()
{
    CFRunLoopRemoveTimer(m_runLoop.get(), m_timer.get(), kCFRunLoopCommonModes);
    CFRunLoopTimerInvalidate(m_timer.get());
}

void HeapTimer::timerDidFire(CFRunLoopTimerRef timer, void* context)
{
    JSLock* apiLock = static_cast<JSLock*>(context);
    apiLock->lock();

    VM* vm = apiLock->vm();
    // The VM has been destroyed, so we should just give up.
    if (!vm) {
        apiLock->unlock();
        return;
    }

    HeapTimer* heapTimer = 0;
    if (vm->heap.activityCallback()->m_timer.get() == timer)
        heapTimer = vm->heap.activityCallback();
    else if (vm->heap.sweeper()->m_timer.get() == timer)
        heapTimer = vm->heap.sweeper();
    else
        RELEASE_ASSERT_NOT_REACHED();

    {
        APIEntryShim shim(vm);
        heapTimer->doWork();
    }

    apiLock->unlock();
}

#elif PLATFORM(BLACKBERRY)

HeapTimer::HeapTimer(VM* vm)
    : m_vm(vm)
    , m_timer(this, &HeapTimer::timerDidFire)
{
    // FIXME: Implement HeapTimer for other threads.
    if (WTF::isMainThread() && !m_timer.tryCreateClient())
        CRASH();
}

HeapTimer::~HeapTimer()
{
}

void HeapTimer::timerDidFire()
{
    doWork();
}

void HeapTimer::invalidate()
{
}

#elif PLATFORM(QT)

HeapTimer::HeapTimer(VM* vm)
    : m_vm(vm)
    , m_newThread(0)
    , m_mutex(QMutex::NonRecursive)
{
    // The HeapTimer might be created before the runLoop is started,
    // but we need to ensure the thread has an eventDispatcher already.
    QEventLoop fakeLoop(this);
}

HeapTimer::~HeapTimer()
{
    QMutexLocker lock(&m_mutex);
    m_timer.stop();
}

void HeapTimer::timerEvent(QTimerEvent*)
{
    QMutexLocker lock(&m_mutex);
    if (m_newThread) {
        // We need to wait with processing until we are on the right thread.
        return;
    }

    APIEntryShim shim(m_vm);
    doWork();
}

void HeapTimer::customEvent(QEvent*)
{
    ASSERT(m_newThread);
    QMutexLocker lock(&m_mutex);
    moveToThread(m_newThread);
    m_newThread = 0;
}

#elif PLATFORM(EFL)

HeapTimer::HeapTimer(VM* vm)
    : m_vm(vm)
    , m_timer(0)
{
}

HeapTimer::~HeapTimer()
{
    stop();
}

Ecore_Timer* HeapTimer::add(double delay, void* agent)
{
    return ecore_timer_add(delay, reinterpret_cast<Ecore_Task_Cb>(timerEvent), agent);
}

void HeapTimer::stop()
{
    if (!m_timer)
        return;

    ecore_timer_del(m_timer);
    m_timer = 0;
}

bool HeapTimer::timerEvent(void* info)
{
    HeapTimer* agent = static_cast<HeapTimer*>(info);

    APIEntryShim shim(agent->m_vm);
    agent->doWork();
    agent->m_timer = 0;

    return ECORE_CALLBACK_CANCEL;
}

#else
HeapTimer::HeapTimer(VM* vm)
    : m_vm(vm)
{
}

HeapTimer::~HeapTimer()
{
}

void HeapTimer::invalidate()
{
}

#endif

} // namespace JSC


text:
namespace mray {
namespace video {

class GstAppNetAudioStreamerImpl : public GstPipelineHandler {
   protected:
    std::string m_ipAddr;
    uint m_audioPort;

    uint m_appSourceID;
    GstAppSrcCallbacks m_srcCB;
    std::string m_pipeLineString;
    GstAppSrc* m_audioSrc;
    GstElement* m_audioSink;

    IAudioGrabber* m_audioGrabber;

    bool m_rtcp;

   public:
    GstAppNetAudioStreamerImpl() {
        m_appSourceID = 0;
        m_audioSink = 0;
        m_ipAddr = "127.0.0.1";
        m_audioPort = 5005;
        m_rtcp = false;
        m_audioGrabber = 0;
    }
    virtual ~GstAppNetAudioStreamerImpl() {}
#define OPUS_ENC
    void BuildString() {
#ifdef FLAC_ENC

        std::string audioStr =
            "directsoundsrc! "
            "audio/"
            "x-raw,endianness=1234,signed=true,width=16,depth=16,rate=8000,"
            "channels=1 ! audioconvert ! flacenc quality=2 ! rtpgstpay ";
#elif defined OPUS_ENC
        // actual-buffer-time=0 actual-latency-time=0

        std::stringstream ss;

        ss << "appsrc name=src  ";

        ss << " ! audio/x-raw,endianness=1234,format=F32LE,rate="
           << (m_audioGrabber->GetSamplingRate())
           << ",channels=" << (m_audioGrabber->GetChannelsCount())
           << " "
              //" ! audiochebband mode=band-pass lower-frequency=1000
              // upper-frequency=6000 poles=4 "
              "! audioconvert  ! audioresample ! ";
        //	"audiochebband mode=band-pass lower-frequency=1000
        // upper-frequency=4000 type=2 ! "

        ss << "opusenc  bitrate=96000 frame-size=5 ! rtpopuspay  ";
#elif defined VORBIS_ENC
        // actual-buffer-time=0 actual-latency-time=0
        std::string audioStr = "directsoundsrc buffer-time=200 ";

        if (m_interface.deviceGUID != "") {
            audioStr += "device=\"" + m_interface.deviceGUID + "\"";
        }

        audioStr +=
            " ! "
            "audio/"
            "x-raw,endianness=1234,signed=true,width=16,depth=16,rate=32000,"
            "channels=2   ! audioconvert ! ";
        //	"audiochebband mode=band-pass lower-frequency=1000
        // upper-frequency=4000 type=2 ! "

        audioStr += "vorbisenc quality=1 ! rtpvorbispay config-interval=3 ";
#elif defined SPEEX_ENC
        std::string audioStr =
            "directsoundsrc! "
            "audio/"
            "x-raw,endianness=1234,signed=true,width=16,depth=16,rate=22000,"
            "channels=2   ! speexenc ! rtpspeexpay";
#else
        std::string audioStr =
            "directsoundsrc! "
            "audio/"
            "x-raw,endianness=1234,signed=true,width=16,depth=16,rate=8000,"
            "channels=1   ! amrnbenc ! rtpamrpay";
#endif
        ss << +" ! "
				"udpsink name=audioSink port=" << (m_audioPort) << " host=" << m_ipAddr << " sync=false ";
        m_pipeLineString = ss.str();
    }
    void _UpdatePorts() {
        if (!GetPipeline()) return;
#define SET_SRC(name, p)                                                  \
    m_##name =                                                            \
        GST_MyUDPSrc(gst_bin_get_by_name(GST_BIN(GetPipeline()), #name)); \
    if (m_##name) {                                                       \
        m_##name->SetPort(p);                                             \
    }
#define SET_SINK(name, p)                                                  \
    m_##name =                                                             \
        GST_MyUDPSink(gst_bin_get_by_name(GST_BIN(GetPipeline()), #name)); \
    if (m_##name) {                                                        \
        m_##name->SetPort(m_ipAddr, p);                                    \
    }

        m_audioSink = gst_bin_get_by_name(GST_BIN(GetPipeline()), "audioSink");
        g_object_set(m_audioSink, "port", m_audioPort, 0, NULL);
        g_object_set(m_audioSink, "host", m_ipAddr.c_str(), 0, NULL);
        //	SET_SINK(audioSink, m_audioPort);
    }

    void SetAudioGrabber(IAudioGrabber* g) { m_audioGrabber = g; }

    // addr: target address to stream video to
    // audioport: port for the audio stream , audio rtcp is allocated as
    // audioPort+1 and audioPort+2
    void BindPorts(const std::string& addr, uint audioPort, bool rtcp) {
        m_ipAddr = addr;
        m_audioPort = audioPort;
        m_rtcp = rtcp;
        _UpdatePorts();
    }

    GstFlowReturn NeedBuffer(GstBuffer** buffer) {
        if (!IsPlaying()) return GST_FLOW_ERROR;

        if (!m_audioGrabber) {
            LogMessage(
                "GstAppNetAudioStreamer::NeedBuffer() -No audio grabber is "
                "assigned to GstAppNetAudioStreamer",
                ELL_WARNING);
            return GST_FLOW_ERROR;
        }
        if (!m_audioGrabber->GrabFrame()) {
            //	LogMessage("AppSrcVideoSrc::NeedBuffer() - Failed to grab buffer
            //" + std::StringConverter::toString(index), ELL_WARNING);
            return GST_FLOW_ERROR;
        }
        // m_grabber[index]->Lock();

        float* data = m_audioGrabber->GetAudioFrame();
        uint length = m_audioGrabber->GetAudioFrameSize() * sizeof(float);
        *buffer = gst_buffer_new_wrapped_full(GST_MEMORY_FLAG_READONLY, data,
                                              length, 0, length, 0, 0);
        // int len = ifo->imageDataSize;
        // GstMapInfo map;
        // GstBuffer* outbuf = gst_buffer_new_and_alloc(len);
        // gst_buffer_map(outbuf, &map, GST_MAP_WRITE);
        // memcpy(map.data, ifo->imageData, len);

        //	gst_buffer_unmap(outbuf, &map);
        //	m_grabber[index]->Unlock();
        //	*buffer = outbuf;

        // OS::IThreadManager::getInstance().sleep(5);
        return GST_FLOW_OK;
    }

    static gboolean read_data(GstAppNetAudioStreamerImpl* d) {
        GstFlowReturn ret;

        GstBuffer* buffer;
        if (d->NeedBuffer(&buffer) == GST_FLOW_OK) {
            ret = gst_app_src_push_buffer(d->m_audioSrc, buffer);
            //	LogMessage("pushing data to: ",
            // std::StringConverter::toString(d->index),ELL_INFO);
            if (ret != GST_FLOW_OK) {
                LogMessage(
                    "GstAppNetAudioStreamer::read_data() - Failed to push data "
                    "to AppSrc ",
                    ELL_WARNING);
                ret = gst_app_src_end_of_stream(d->m_audioSrc);
                return FALSE;
            }
        }
        return TRUE;
    }
    static void start_feed(GstAppSrc* source, guint size, gpointer data) {
        GstAppNetAudioStreamerImpl* o =
            static_cast<GstAppNetAudioStreamerImpl*>(data);
        if (o->m_appSourceID != 0) {
            g_source_remove(o->m_appSourceID);
            o->m_appSourceID = 0;
        }
        GST_DEBUG("start feeding");
        o->m_appSourceID = g_idle_add((GSourceFunc)read_data, o);
    }

    static void stop_feed(GstAppSrc* source, gpointer data) {
        GstAppNetAudioStreamerImpl* o =
            static_cast<GstAppNetAudioStreamerImpl*>(data);
        if (o->m_appSourceID != 0) {
            GST_DEBUG("stop feeding");
            g_source_remove(o->m_appSourceID);
            o->m_appSourceID = 0;
        }
    }
    static gboolean seek_data(GstAppSrc* src, guint64 offset,
                              gpointer user_data) {
        return TRUE;
    }

    bool CreateStream() {
        if (!m_audioGrabber) return false;
        GError* err = 0;
        BuildString();
        GstElement* p = gst_parse_launch(m_pipeLineString.c_str(), &err);
        LogMessage("GstAppNetAudioStreamer::Starting with pipeline: " +
                       m_pipeLineString,
                   ELL_INFO);
        if (err) {
            LogMessage("GstAppNetAudioStreamer: Pipeline error: " +
                           std::string(err->message),
                       ELL_WARNING);
            gst_object_unref(p);
            p = 0;
        }
        if (!p) return false;
        LogMessage("GstAppNetAudioStreamer::Finished Linking Pipeline",
                   ELL_INFO);

        m_audioSrc =
            GST_APP_SRC(gst_bin_get_by_name(GST_BIN((GstElement*)p), "src"));

        gst_base_src_set_do_timestamp(GST_BASE_SRC(m_audioSrc), true);

        g_object_set(G_OBJECT(m_audioSrc), "stream-type",
                     GST_APP_STREAM_TYPE_STREAM,  // GST_APP_STREAM_TYPE_STREAM
                     "format", GST_FORMAT_TIME, "is-live", TRUE, NULL);

        gst_app_src_set_emit_signals(m_audioSrc, false);

        m_srcCB.need_data = &start_feed;
        m_srcCB.enough_data = &stop_feed;
        m_srcCB.seek_data = &seek_data;
        gst_app_src_set_callbacks(m_audioSrc, &m_srcCB, this, NULL);
        SetPipeline(p);
        _UpdatePorts();

        return CreatePipeline(false);
    }
    void Stream() { SetPaused(false); }
    void Stop() { SetPaused(true); }
    bool IsStreaming() { return IsPlaying(); }
    virtual void Close() {
        GstPipelineHandler::Close();
        if (m_appSourceID != 0) {
            g_source_remove(m_appSourceID);
            m_appSourceID = 0;
        }
    }
};

GstAppNetAudioStreamer::GstAppNetAudioStreamer() {
    m_impl = new GstAppNetAudioStreamerImpl();
}

GstAppNetAudioStreamer::~GstAppNetAudioStreamer() { delete m_impl; }
void GstAppNetAudioStreamer::Stream() { m_impl->Stream(); }
void GstAppNetAudioStreamer::Stop() { m_impl->Stop(); }
GstPipelineHandler* GstAppNetAudioStreamer::GetPipeline() { return m_impl; }

void GstAppNetAudioStreamer::SetAudioGrabber(IAudioGrabber* g) {
    m_impl->SetAudioGrabber(g);
}

void GstAppNetAudioStreamer::BindPorts(const std::string& addr, uint* ports,
                                       uint count, bool rtcp) {
    m_impl->BindPorts(addr, ports[0], rtcp);
}

bool GstAppNetAudioStreamer::CreateStream() { return m_impl->CreateStream(); }

void GstAppNetAudioStreamer::Close() { m_impl->Close(); }
bool GstAppNetAudioStreamer::IsStreaming() { return m_impl->IsStreaming(); }

void GstAppNetAudioStreamer::SetPaused(bool paused) {
    m_impl->SetPaused(paused);
}

bool GstAppNetAudioStreamer::IsPaused() { return !m_impl->IsPlaying(); }

}  // namespace video
}  // namespace mray


text:
This Python project uses LSTM (Long Short-Term Memory) and GRU (Gated Recurrent Unit) based Recurrent Neural Networks to forecast (predict) timeseries using Keras + Theano. We compare the results produced by each of these deep neural networks with those from a linear regression model.

Dataset:  Number of daily births in Quebec, Jan. 01 '77 - Dec. 31 '90 (Hipel & McLeod, 1994)

##Usage
I suggest you install [Virtualenv](https://virtualenv.pypa.io/en/stable/) before trying this out.
```
git clone https://github.com/dhrushilbadani/deeplearning-timeseries.git
cd deeplearning-timeseries
virtualenv ENV
source ENV/bin/activate
pip install --upgrade pip
pip install keras h5py pandas sklearn
python evaluate.py
```

##Architecture & Model Properties
We use Keras' [Sequential](https://keras.io/models/sequential/) model to construct recurrent neural networks. There are 3 layers:

 Layer 1 : Either a LSTM (with output dimension 10,  and statefulness enabled) layer or a GRU (with output dimension 4) layer.

 Layer 2 : A Dropout layer with dropout probability = 0.2, to prevent overfitting.

 Layer 3 : A fully-connected Dense Layer with output dimension 1.

 Default optimizer: rmsprop; Default # of epochs: 150.

 Accuracy Metric: Mean Squared Error.

This architecture can certainly further be optimized - I just haven't had the chance to experiment too much thanks to my laptop's constraints!

##Results & Observations
1. The LSTM-RNN model performed the best with a MSE of 1464.78 (look back = 37).
2. Naively making the RNN "deeper" did not yield immediate results; I didn't fine-tune the parameters (output_dim, for example) though.
3. Making the LSTM network stateful (setting ```stateful=true``` when initializing the LSTM layer) did yield a significant performance improvement though. In stateless LSTM layers, the cell states are reset at each sequence. When ```stateful=true``` however, the states are propagated onto the next batch i.e. the state of the sample located at index ```trainX[i]``` will be used in the computation of the sample ```trainX[i+k]``` in the next batch, where ```k``` is the batch size. You can read more about this at the [Keras docs](https://keras.io/getting-started/faq/#how-can-i-use-stateful-rnns).
4. Using Glorot initializations yielded a performance improvement. However, using He uniform initialization (Gaussian initialization scaled by fan_in) yielded even better results than with Glorot.

##Files

```data/number-of-daily-births-in-quebec.csv``` : Dataset.

 ```lstm_model.py```: Contains the class ```LSTM_RNN``` for LSTM-based Recurrent Neural Networks.

 ```gru_model.py```: Contains the class ```GRU_RNN``` for GRU-based Recurrent Neural Networks.

  ```evaluate.py```: Loads and preprocesses the dataset, creates LSTM-RNN, GRU-RNN and Linear Regression models, and outputs results.

##To-do

K-fold cross validation.

Add plots to aid in visualization.

##References
1. [On the use of 'Long-Short Term Memory' neural networks for time series prediction](https://ccc.inaoep.mx/~pgomez/conferences/PggISCI14.pdf), Gomez-Git et. al, 2014.
2. [Dropout: A Simple Way to Prevent Neural Networks from Overfitting](http://www.cs.toronto.edu/~rsalakhu/papers/srivastava14a.pdf), Srivastava et. al 2014.
4. [Learning to forget](http://www.mitpressjournals.org/doi/pdf/10.1162/089976600300015015), Gers, Schmidhuber & Cummins, 2000.
5. [Empirical Evaluation of Gated Recurrent Neural Networks on Sequence Modeling](http://arxiv.org/pdf/1412.3555v1.pdf), Chung et. al, 2014.


text:
           Zero)] //~ ERROR
enum CantDeriveThose {}

fn main() {
    doesnt_exist!(); //~ ERROR

    asm!(invalid); //~ ERROR

    concat_idents!("not", "idents"); //~ ERROR

    option_env!(invalid); //~ ERROR
    env!(invalid); //~ ERROR
    env!(foo, abr, baz); //~ ERROR
    env!("RUST_HOPEFULLY_THIS_DOESNT_EXIST"); //~ ERROR

    foo::blah!(); //~ ERROR

    format!(); //~ ERROR
    format!(invalid); //~ ERROR

    include!(invalid); //~ ERROR

    include_str!(invalid); //~ ERROR
    include_str!("i'd be quite surprised if a file with this name existed"); //~ ERROR
    include_bytes!(invalid); //~ ERROR
    include_bytes!("i'd be quite surprised if a file with this name existed"); //~ ERROR

    trace_macros!(invalid); //~ ERROR
}


text:
package com.amazonaws.services.elasticache.model;

import com.amazonaws.AmazonServiceException;

/**
 * <p>
 * The requested cache security group name does not refer to an existing
 * cache security group.
 * </p>
 */
public class CacheSecurityGroupNotFoundException extends AmazonServiceException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new CacheSecurityGroupNotFoundException with the specified error
     * message.
     *
     * @param message Describes the error encountered.
     */
    public CacheSecurityGroupNotFoundException(String message) {
        super(message);
    }

}


text:
    <group-box></group-box>

 Create Term

                <form id="CreateUserForm" name="CreateUserForm" class="form-horizontal" role="form"
                      ng-submit="lc.createTerm()">

Term Information

                            Language
                            <input type="text" class="form-control" name="language" id="language" placeholder=""
                                   ng-model="lc.currentTerm.language">

                            Language_Key
                            <input type="text" class="form-control" name="langKey" id="langKey" placeholder=""
                                   ng-model="lc.currentTerm.key">

                            Language_Value
                            <textarea class="form-control" rows="5" name="langValue" id="langValue" placeholder=""
                                   ng-model="lc.currentTerm.value"></textarea>

                        <cancel-submit  cancel="lc.getTerm('system_cancel')"
                                        submit="lc.getTerm('system_create')">
                        </cancel-submit>

                </form>


text:
package com.google.cloud.bqsh

import scopt.OptionParser

object QueryOptionParser extends OptionParser[QueryConfig]("query") with ArgParser[QueryConfig] {
  def parse(args: Seq[String]): Option[QueryConfig] =
    parse(args, QueryConfig())

  head("query", Bqsh.UserAgent)

  help("help")
    .text("prints this usage text")

  // z/OS Options
  opt[Seq[String]]("parameters_from_file")
    .text("Comma-separated query parameters in the form [NAME]:[TYPE]:[DDNAME]. An empty name creates a positional parameter. [TYPE] may be omitted to assume a STRING value in the form: name::ddname or ::ddname. NULL produces a null value.")
    .action((x,c) => c.copy(parametersFromFile = x))

  opt[Unit]("create_if_needed")
    .text("When specified, create destination table. The default value is false.")
    .action((x,c) => c.copy(createIfNeeded = true))

  opt[Unit]('m', "allow_multiple_queries")
    .text("When specified, allow multiple queries. The default value is false.")
    .action((x,c) => c.copy(allowMultipleQueries = true))

  // Standard Options

  opt[Unit]("allow_large_results")
    .text("When specified, enables large destination table sizes for legacy SQL queries.")
    .action((x,c) => c.copy(allowLargeResults = true))

  opt[Unit]("append_table")
    .text("When specified, append data to a destination table. The default value is false.")
    .action((x,c) => c.copy(appendTable = true))

  opt[Unit]("batch")
    .text("When specified, run the query in batch mode. The default value is false.")
    .action((_,c) => c.copy(batch = true))

  opt[Seq[String]]("clustering_fields")
    .text("If specified, a comma-separated list of columns is used to cluster the destination table in a query. This flag must be used with the time partitioning flags to create either an ingestion-time partitioned table or a table partitioned on a DATE or TIMESTAMP column. When specified, the table is first partitioned, and then it is clustered using the supplied columns.")
    .action((x,c) => c.copy(clusteringFields = x))

  opt[String]("destination_kms_key")
    .text("The Cloud KMS key used to encrypt the destination table data.")
    .action((x,c) => c.copy(destinationKmsKey = x))

  opt[String]("destination_schema")
    .text("The path to a local JSON schema file or a comma-separated list of column definitions in the form [FIELD]:[DATA_TYPE],[FIELD]:[DATA_TYPE]. The default value is ''.")
    .action((x,c) => c.copy(destinationSchema = x))

  opt[String]("destination_table")
    .text("The name of the destination table for writing query results. The default value is ''")
    .action((x,c) => c.copy(destinationTable = x))

  opt[Unit]("dry_run")
    .text("When specified, the query is validated but not run.")
    .action((_,c) => c.copy(dryRun = true))

  opt[String]("external_table_definition")
    .text("The table name and schema definition used in an external table query. The schema can be a path to a local JSON schema file or a comma-separated list of column definitions in the form [FIELD]:[DATA_TYPE],[FIELD]:[DATA_TYPE]. The format for supplying the table name and schema is: [TABLE]::[PATH_TO_FILE] or [TABLE]::[SCHEMA]@[SOURCE_FORMAT]=[CLOUD_STORAGE_URI]. Repeat this flag to query multiple tables.")
    .action((x,c) => c.copy(externalTableDefinition = x))

  opt[String]("label")
    .text("A label to apply to a query job in the form [KEY]:[VALUE]. Repeat this flag to specify multiple labels.")
    .action((x,c) => c.copy(label = x))

  opt[Long]("maximum_bytes_billed")
    .text("An integer that limits the bytes billed for the query. If the query goes beyond the limit, it fails (without incurring a charge). If not specified, the bytes billed is set to the project default.")
    .action((x,c) => c.copy(maximumBytesBilled = x))

  opt[Seq[String]]("parameters")
    .text("comma-separated query parameters in the form [NAME]:[TYPE]:[VALUE]. An empty name creates a positional parameter. [TYPE] may be omitted to assume a STRING value in the form: name::value or ::value. NULL produces a null value.")
    .validate{x =>
      if (x.exists(_.split(':').length != 3))
        failure("parameter must be in the form [NAME]:[TYPE]:[VALUE]")
      else
        success
    }
    .action((x,c) => c.copy(parameters = x))

  opt[Unit]("replace")
    .text("If specified, overwrite the destination table with the query results. The default value is false.")
    .action((_,c) => c.copy(replace = true))

  opt[Unit]("require_cache")
    .text("If specified, run the query only if results can be retrieved from the cache.")
    .action((_,c) => c.copy(requireCache = true))

  opt[Boolean]("require_partition_filter")
    .text("If specified, a partition filter is required for queries over the supplied table. This flag can only be used with a partitioned table.")
    .action((x,c) => c.copy(requirePartitionFilter = x))

  opt[Seq[String]]("schema_update_option")
    .text("When appending data to a table (in a load job or a query job), or when overwriting a table partition, specifies how to update the schema of the destination table. Possible values include:\n\n ALLOW_FIELD_ADDITION: Allow\nnew fields to be added\n ALLOW_FIELD_RELAXATION: Allow relaxing REQUIRED fields to NULLABLE")
    .action((x,c) => c.copy(schemaUpdateOption = x))

  opt[Long]("time_partitioning_expiration")
    .text("An integer that specifies (in seconds) when a time-based partition should be deleted. The expiration time evaluates to the partition's UTC date plus the integer value. A negative number indicates no expiration.")
    .action((x,c) => c.copy(timePartitioningExpiration = x))

  opt[String]("time_partitioning_field")
    .text("The field used to determine how to create a time-based partition. If time-based partitioning is enabled without this value, the table is partitioned based on the load time.")
    .action((x,c) => c.copy(timePartitioningField = x))

  opt[String]("time_partitioning_type")
    .text("Enables time-based partitioning on a table and sets the partition type. Currently, the only possible value is DAY which generates one partition per day.")
    .action((x,c) => c.copy(timePartitioningType = x))

  opt[Boolean]("use_cache")
    .text("When specified, caches the query results. The default value is true.")
    .action((x,c) => c.copy(useCache = x))

  opt[Unit]("use_legacy_sql")
    .text("When set to false, runs a standard SQL query. The default value is false (uses Standard SQL).")
    .action((x,c) => c.copy(useLegacySql = true))

  // Global options
  opt[String]("dataset_id")
    .text(GlobalConfig.datasetIdText)
    .action((x,c) => c.copy(datasetId = x))

  opt[Unit]("debug_mode")
    .text(GlobalConfig.debugModeText)
    .action((x,c) => c.copy(debugMode = true))

  opt[String]("job_id")
    .text(GlobalConfig.jobIdText)
    .action((x,c) => c.copy(jobId = x))

  opt[String]("location")
    .text(GlobalConfig.locationText)
    .action((x,c) => c.copy(location = x))

  opt[String]("project_id")
    .text(GlobalConfig.projectIdText)
    .action((x,c) => c.copy(projectId = x))

  opt[Boolean]("synchronous_mode")
    .text(GlobalConfig.synchronousModeText)
    .action((x,c) => c.copy(sync = x))

  opt[Boolean]("sync")
    .text(GlobalConfig.syncText)
    .action((x,c) => c.copy(sync = x))

  // Custom Options
  opt[String]("stats_table")
    .optional()
    .text("tablespec of table to insert stats")
    .action((x,c) => c.copy(statsTable = x))
}