text:
// This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0

package org.sosy_lab.java_smt.solvers.z3;

import static com.google.common.base.Preconditions.checkArgument;

import com.google.common.collect.HashBasedTable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Table;
import com.google.common.primitives.Longs;
import com.microsoft.z3.Native;
import com.microsoft.z3.Z3Exception;
import com.microsoft.z3.enumerations.Z3_ast_kind;
import com.microsoft.z3.enumerations.Z3_decl_kind;
import com.microsoft.z3.enumerations.Z3_sort_kind;
import com.microsoft.z3.enumerations.Z3_symbol_kind;
import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.sosy_lab.common.ShutdownNotifier;
import org.sosy_lab.common.configuration.Configuration;
import org.sosy_lab.common.configuration.InvalidConfigurationException;
import org.sosy_lab.common.configuration.Option;
import org.sosy_lab.common.configuration.Options;
import org.sosy_lab.common.rationals.Rational;
import org.sosy_lab.common.time.Timer;
import org.sosy_lab.java_smt.api.ArrayFormula;
import org.sosy_lab.java_smt.api.BitvectorFormula;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.FloatingPointFormula;
import org.sosy_lab.java_smt.api.FloatingPointRoundingMode;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.FormulaType.ArrayFormulaType;
import org.sosy_lab.java_smt.api.FunctionDeclarationKind;
import org.sosy_lab.java_smt.api.QuantifiedFormulaManager.Quantifier;
import org.sosy_lab.java_smt.api.RegexFormula;
import org.sosy_lab.java_smt.api.SolverException;
import org.sosy_lab.java_smt.api.StringFormula;
import org.sosy_lab.java_smt.api.visitors.FormulaVisitor;
import org.sosy_lab.java_smt.basicimpl.FormulaCreator;
import org.sosy_lab.java_smt.basicimpl.FunctionDeclarationImpl;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3ArrayFormula;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3BitvectorFormula;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3BooleanFormula;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3FloatingPointFormula;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3FloatingPointRoundingModeFormula;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3IntegerFormula;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3RationalFormula;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3RegexFormula;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3StringFormula;

@Options(prefix = "solver.z3")
class Z3FormulaCreator extends FormulaCreator<Long, Long, Long, Long> {

  private static final ImmutableMap<Integer, Object> Z3_CONSTANTS =
      ImmutableMap.<Integer, Object>builder()
          .put(Z3_decl_kind.Z3_OP_TRUE.toInt(), true)
          .put(Z3_decl_kind.Z3_OP_FALSE.toInt(), false)
          .put(Z3_decl_kind.Z3_OP_FPA_PLUS_ZERO.toInt(), +0.0)
          .put(Z3_decl_kind.Z3_OP_FPA_MINUS_ZERO.toInt(), -0.0)
          .put(Z3_decl_kind.Z3_OP_FPA_PLUS_INF.toInt(), Double.POSITIVE_INFINITY)
          .put(Z3_decl_kind.Z3_OP_FPA_MINUS_INF.toInt(), Double.NEGATIVE_INFINITY)
          .put(Z3_decl_kind.Z3_OP_FPA_NAN.toInt(), Double.NaN)
          .put(
              Z3_decl_kind.Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN.toInt(),
              FloatingPointRoundingMode.NEAREST_TIES_TO_EVEN)
          .put(
              Z3_decl_kind.Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY.toInt(),
              FloatingPointRoundingMode.NEAREST_TIES_AWAY)
          .put(
              Z3_decl_kind.Z3_OP_FPA_RM_TOWARD_POSITIVE.toInt(),
              FloatingPointRoundingMode.TOWARD_POSITIVE)
          .put(
              Z3_decl_kind.Z3_OP_FPA_RM_TOWARD_NEGATIVE.toInt(),
              FloatingPointRoundingMode.TOWARD_NEGATIVE)
          .put(Z3_decl_kind.Z3_OP_FPA_RM_TOWARD_ZERO.toInt(), FloatingPointRoundingMode.TOWARD_ZERO)
          .buildOrThrow();

  // Set of error messages that might occur if Z3 is interrupted.
  private static final ImmutableSet<String> Z3_INTERRUPT_ERRORS =
      ImmutableSet.of(
          "canceled", // Z3::src/util/common_msgs.cpp
          "Proof error!",
          "interrupted", // Z3::src/solver/check_sat_result.cpp
          "maximization suspended" // Z3::src/opt/opt_solver.cpp
          );

  @Option(secure = true, description = "Whether to use PhantomReferences for discarding Z3 AST")
  private boolean usePhantomReferences = false;

  /**
   * We need to track all created symbols for parsing.
   *
   * <p>This map stores symbols (names) and their declaration (type information).
   */
  private final Map<String, Long> symbolsToDeclarations = new LinkedHashMap<>();

  private final Table<Long, Long, Long> allocatedArraySorts = HashBasedTable.create();

  /** Automatic clean-up of Z3 ASTs. */
  private final ReferenceQueue<Z3Formula> referenceQueue = new ReferenceQueue<>();

  private final IdentityHashMap<PhantomReference<? extends Z3Formula>, Long> referenceMap =
      new IdentityHashMap<>();

  // todo: getters for statistic.
  private final Timer cleanupTimer = new Timer();
  protected final ShutdownNotifier shutdownNotifier;

  @SuppressWarnings("ParameterNumber")
  Z3FormulaCreator(
      long pEnv,
      long pBoolType,
      long pIntegerType,
      long pRealType,
      long pStringType,
      long pRegexType,
      Configuration config,
      ShutdownNotifier pShutdownNotifier)
      throws InvalidConfigurationException {
    super(pEnv, pBoolType, pIntegerType, pRealType, pStringType, pRegexType);
    shutdownNotifier = pShutdownNotifier;
    config.inject(this);
  }

  final Z3Exception handleZ3Exception(Z3Exception e) throws Z3Exception, InterruptedException {
    if (Z3_INTERRUPT_ERRORS.contains(e.getMessage())) {
      shutdownNotifier.shutdownIfNecessary();
    }
    throw e;
  }

  @Override
  public Long makeVariable(Long type, String varName) {
    long z3context = getEnv();
    long symbol = Native.mkStringSymbol(z3context, varName);
    long var = Native.mkConst(z3context, symbol, type);
    symbolsToDeclarations.put(varName, Native.getAppDecl(z3context, var));
    return var;
  }

  @Override
  public Long extractInfo(Formula pT) {
    if (pT instanceof Z3Formula) {
      return ((Z3Formula) pT).getFormulaInfo();
    }
    throw new IllegalArgumentException(
        "Cannot get the formula info of type " + pT.getClass().getSimpleName() + " in the Solver!");
  }

  @SuppressWarnings("unchecked")
  @Override
  public <T extends Formula> FormulaType<T> getFormulaType(T pFormula) {
    Long term = extractInfo(pFormula);
    return (FormulaType<T>) getFormulaType(term);
  }

  public FormulaType<?> getFormulaTypeFromSort(Long pSort) {
    long z3context = getEnv();
    Z3_sort_kind sortKind = Z3_sort_kind.fromInt(Native.getSortKind(z3context, pSort));
    switch (sortKind) {
      case Z3_BOOL_SORT:
        return FormulaType.BooleanType;
      case Z3_INT_SORT:
        return FormulaType.IntegerType;
      case Z3_REAL_SORT:
        return FormulaType.RationalType;
      case Z3_BV_SORT:
        return FormulaType.getBitvectorTypeWithSize(Native.getBvSortSize(z3context, pSort));
      case Z3_ARRAY_SORT:
        long domainSort = Native.getArraySortDomain(z3context, pSort);
        long rangeSort = Native.getArraySortRange(z3context, pSort);
        return FormulaType.getArrayType(
            getFormulaTypeFromSort(domainSort), getFormulaTypeFromSort(rangeSort));
      case Z3_FLOATING_POINT_SORT:
        return FormulaType.getFloatingPointType(
            Native.fpaGetEbits(z3context, pSort), Native.fpaGetSbits(z3context, pSort) - 1);
      case Z3_ROUNDING_MODE_SORT:
        return FormulaType.FloatingPointRoundingModeType;
      case Z3_RE_SORT:
        return FormulaType.RegexType;
      case Z3_DATATYPE_SORT:
      case Z3_RELATION_SORT:
      case Z3_FINITE_DOMAIN_SORT:
      case Z3_SEQ_SORT:
      case Z3_UNKNOWN_SORT:
      case Z3_UNINTERPRETED_SORT:
        if (Native.isStringSort(z3context, pSort)) {
          return FormulaType.StringType;
        } else {
          // TODO: support for remaining sorts.
          throw new IllegalArgumentException(
              "Unknown formula type "
                  + Native.sortToString(z3context, pSort)
                  + " with sort "
                  + sortKind);
        }
      default:
        throw new UnsupportedOperationException("Unexpected state.");
    }
  }

  @Override
  public FormulaType<?> getFormulaType(Long pFormula) {
    long sort = Native.getSort(getEnv(), pFormula);
    return getFormulaTypeFromSort(sort);
  }

  @Override
  @SuppressWarnings("MethodTypeParameterName")
  protected <TD extends Formula, TR extends Formula> FormulaType<TR> getArrayFormulaElementType(
      ArrayFormula<TD, TR> pArray) {
    return ((Z3ArrayFormula<TD, TR>) pArray).getElementType();
  }

  @Override
  @SuppressWarnings("MethodTypeParameterName")
  protected <TD extends Formula, TR extends Formula> FormulaType<TD> getArrayFormulaIndexType(
      ArrayFormula<TD, TR> pArray) {
    return ((Z3ArrayFormula<TD, TR>) pArray).getIndexType();
  }

  @Override
  @SuppressWarnings("MethodTypeParameterName")
  protected <TD extends Formula, TR extends Formula> ArrayFormula<TD, TR> encapsulateArray(
      Long pTerm, FormulaType<TD> pIndexType, FormulaType<TR> pElementType) {
    assert getFormulaType(pTerm).equals(FormulaType.getArrayType(pIndexType, pElementType));
    cleanupReferences();
    return storePhantomReference(
        new Z3ArrayFormula<>(getEnv(), pTerm, pIndexType, pElementType), pTerm);
  }

  private <T extends Z3Formula> T storePhantomReference(T out, Long pTerm) {
    if (usePhantomReferences) {
      PhantomReference<T> ref = new PhantomReference<>(out, referenceQueue);
      referenceMap.put(ref, pTerm);
    }
    return out;
  }

  @SuppressWarnings("unchecked")
  @Override
  public <T extends Formula> T encapsulate(FormulaType<T> pType, Long pTerm) {
    assert pType.equals(getFormulaType(pTerm))
            || (pType.equals(FormulaType.RationalType)
                && getFormulaType(pTerm).equals(FormulaType.IntegerType))
        : String.format(
            "Trying to encapsulate formula of type %s as %s", getFormulaType(pTerm), pType);
    cleanupReferences();
    if (pType.isBooleanType()) {
      return (T) storePhantomReference(new Z3BooleanFormula(getEnv(), pTerm), pTerm);
    } else if (pType.isIntegerType()) {
      return (T) storePhantomReference(new Z3IntegerFormula(getEnv(), pTerm), pTerm);
    } else if (pType.isRationalType()) {
      return (T) storePhantomReference(new Z3RationalFormula(getEnv(), pTerm), pTerm);
    } else if (pType.isStringType()) {
      return (T) storePhantomReference(new Z3StringFormula(getEnv(), pTerm), pTerm);
    } else if (pType.isRegexType()) {
      return (T) storePhantomReference(new Z3RegexFormula(getEnv(), pTerm), pTerm);
    } else if (pType.isBitvectorType()) {
      return (T) storePhantomReference(new Z3BitvectorFormula(getEnv(), pTerm), pTerm);
    } else if (pType.isFloatingPointType()) {
      return (T) storePhantomReference(new Z3FloatingPointFormula(getEnv(), pTerm), pTerm);
    } else if (pType.isFloatingPointRoundingModeType()) {
      return (T)
          storePhantomReference(new Z3FloatingPointRoundingModeFormula(getEnv(), pTerm), pTerm);
    } else if (pType.isArrayType()) {
      ArrayFormulaType<?, ?> arrFt = (ArrayFormulaType<?, ?>) pType;
      return (T)
          storePhantomReference(
              new Z3ArrayFormula<>(getEnv(), pTerm, arrFt.getIndexType(), arrFt.getElementType()),
              pTerm);
    }

    throw new IllegalArgumentException("Cannot create formulas of type " + pType + " in Z3");
  }

  @Override
  public BooleanFormula encapsulateBoolean(Long pTerm) {
    assert getFormulaType(pTerm).isBooleanType();
    cleanupReferences();
    return storePhantomReference(new Z3BooleanFormula(getEnv(), pTerm), pTerm);
  }

  @Override
  public BitvectorFormula encapsulateBitvector(Long pTerm) {
    assert getFormulaType(pTerm).isBitvectorType();
    cleanupReferences();
    return storePhantomReference(new Z3BitvectorFormula(getEnv(), pTerm), pTerm);
  }

  @Override
  protected FloatingPointFormula encapsulateFloatingPoint(Long pTerm) {
    assert getFormulaType(pTerm).isFloatingPointType();
    cleanupReferences();
    return storePhantomReference(new Z3FloatingPointFormula(getEnv(), pTerm), pTerm);
  }

  @Override
  protected StringFormula encapsulateString(Long pTerm) {
    assert getFormulaType(pTerm).isStringType()
        : String.format(
            "Term %s has unexpected type %s.",
            Native.astToString(getEnv(), pTerm),
            Native.sortToString(getEnv(), Native.getSort(getEnv(), pTerm)));
    cleanupReferences();
    return storePhantomReference(new Z3StringFormula(getEnv(), pTerm), pTerm);
  }

  @Override
  protected RegexFormula encapsulateRegex(Long pTerm) {
    assert getFormulaType(pTerm).isRegexType()
        : String.format(
            "Term %s has unexpected type %s.",
            Native.astToString(getEnv(), pTerm),
            Native.sortToString(getEnv(), Native.getSort(getEnv(), pTerm)));
    cleanupReferences();
    return storePhantomReference(new Z3RegexFormula(getEnv(), pTerm), pTerm);
  }

  @Override
  public Long getArrayType(Long pIndexType, Long pElementType) {
    Long allocatedArraySort = allocatedArraySorts.get(pIndexType, pElementType);
    if (allocatedArraySort == null) {
      allocatedArraySort = Native.mkArraySort(getEnv(), pIndexType, pElementType);
      Native.incRef(getEnv(), allocatedArraySort);
      allocatedArraySorts.put(pIndexType, pElementType, allocatedArraySort);
    }
    return allocatedArraySort;
  }

  @Override
  public Long getBitvectorType(int pBitwidth) {
    checkArgument(pBitwidth > 0, "Cannot use bitvector type with size %s", pBitwidth);
    long bvSort = Native.mkBvSort(getEnv(), pBitwidth);
    Native.incRef(getEnv(), Native.sortToAst(getEnv(), bvSort));
    return bvSort;
  }

  @Override
  public Long getFloatingPointType(FormulaType.FloatingPointType type) {
    long fpSort = Native.mkFpaSort(getEnv(), type.getExponentSize(), type.getMantissaSize() + 1);
    Native.incRef(getEnv(), Native.sortToAst(getEnv(), fpSort));
    return fpSort;
  }

  private void cleanupReferences() {
    if (!usePhantomReferences) {
      return;
    }
    cleanupTimer.start();
    try {
      Reference<? extends Z3Formula> ref;
      while ((ref = referenceQueue.poll()) != null) {
        long z3ast = referenceMap.remove(ref);
        Native.decRef(environment, z3ast);
      }
    } finally {
      cleanupTimer.stop();
    }
  }

  private String getAppName(long f) {
    long funcDecl = Native.getAppDecl(environment, f);
    long symbol = Native.getDeclName(environment, funcDecl);
    return symbolToString(symbol);
  }

  @Override
  public <R> R visit(FormulaVisitor<R> visitor, final Formula formula, final Long f) {
    switch (Z3_ast_kind.fromInt(Native.getAstKind(environment, f))) {
      case Z3_NUMERAL_AST:
        return visitor.visitConstant(formula, convertValue(f));
      case Z3_APP_AST:
        int arity = Native.getAppNumArgs(environment, f);
        int declKind = Native.getDeclKind(environment, Native.getAppDecl(environment, f));

        if (arity == 0) {
          // constants
          Object value = Z3_CONSTANTS.get(declKind);
          if (value != null) {
            return visitor.visitConstant(formula, value);

            // Rounding mode
          } else if (declKind == Z3_decl_kind.Z3_OP_FPA_NUM.toInt()
              || Native.getSortKind(environment, Native.getSort(environment, f))
                  == Z3_sort_kind.Z3_ROUNDING_MODE_SORT.toInt()) {
            return visitor.visitConstant(formula, convertValue(f));

            // string constant
          } else if (declKind == Z3_decl_kind.Z3_OP_INTERNAL.toInt()
              && Native.getSortKind(environment, Native.getSort(environment, f))
                  == Z3_sort_kind.Z3_SEQ_SORT.toInt()) {
            return visitor.visitConstant(formula, convertValue(f));

            // Free variable
          } else if (declKind == Z3_decl_kind.Z3_OP_UNINTERPRETED.toInt()
              || declKind == Z3_decl_kind.Z3_OP_INTERNAL.toInt()) {
            return visitor.visitFreeVariable(formula, getAppName(f));
          } // else: fall-through with a function application
        }

        // Function application with zero or more parameters
        ImmutableList.Builder<Formula> args = ImmutableList.builder();
        ImmutableList.Builder<FormulaType<?>> argTypes = ImmutableList.builder();
        for (int i = 0; i < arity; i++) {
          long arg = Native.getAppArg(environment, f, i);
          FormulaType<?> argumentType = getFormulaType(arg);
          args.add(encapsulate(argumentType, arg));
          argTypes.add(argumentType);
        }
        return visitor.visitFunction(
            formula,
            args.build(),
            FunctionDeclarationImpl.of(
                getAppName(f),
                getDeclarationKind(f),
                argTypes.build(),
                getFormulaType(f),
                Native.getAppDecl(environment, f)));
      case Z3_VAR_AST:
        int deBruijnIdx = Native.getIndexValue(environment, f);
        return visitor.visitBoundVariable(formula, deBruijnIdx);
      case Z3_QUANTIFIER_AST:
        BooleanFormula body = encapsulateBoolean(Native.getQuantifierBody(environment, f));
        Quantifier q =
            Native.isQuantifierForall(environment, f) ? Quantifier.FORALL : Quantifier.EXISTS;
        return visitor.visitQuantifier((BooleanFormula) formula, q, getBoundVars(f), body);

      case Z3_SORT_AST:
      case Z3_FUNC_DECL_AST:
      case Z3_UNKNOWN_AST:
      default:
        throw new UnsupportedOperationException(
            "Input should be a formula AST, " + "got unexpected type instead");
    }
  }

  protected String symbolToString(long symbol) {
    switch (Z3_symbol_kind.fromInt(Native.getSymbolKind(environment, symbol))) {
      case Z3_STRING_SYMBOL:
        return Native.getSymbolString(environment, symbol);
      case Z3_INT_SYMBOL:

        // Bound variable.
        return "#" + Native.getSymbolInt(environment, symbol);
      default:
        throw new UnsupportedOperationException("Unexpected state");
    }
  }

  private List<Formula> getBoundVars(long f) {
    int numBound = Native.getQuantifierNumBound(environment, f);
    List<Formula> boundVars = new ArrayList<>(numBound);
    for (int i = 0; i < numBound; i++) {
      long varName = Native.getQuantifierBoundName(environment, f, i);
      long varSort = Native.getQuantifierBoundSort(environment, f, i);
      boundVars.add(
          encapsulate(
              getFormulaTypeFromSort(varSort), Native.mkConst(environment, varName, varSort)));
    }
    return boundVars;
  }

  private FunctionDeclarationKind getDeclarationKind(long f) {
    assert Native.getArity(environment, Native.getAppDecl(environment, f)) > 0
        : "Variables should be handled in other branch.";
    if (getAppName(f).equals("div0")) {
      // Z3 segfaults in getDeclKind for this term (cf. https://github.com/Z3Prover/z3/issues/669)
      return FunctionDeclarationKind.OTHER;
    }
    Z3_decl_kind decl =
        Z3_decl_kind.fromInt(Native.getDeclKind(environment, Native.getAppDecl(environment, f)));
    switch (decl) {
      case Z3_OP_AND:
        return FunctionDeclarationKind.AND;
      case Z3_OP_NOT:
        return FunctionDeclarationKind.NOT;
      case Z3_OP_OR:
        return FunctionDeclarationKind.OR;
      case Z3_OP_IFF:
        return FunctionDeclarationKind.IFF;
      case Z3_OP_ITE:
        return FunctionDeclarationKind.ITE;
      case Z3_OP_XOR:
        return FunctionDeclarationKind.XOR;
      case Z3_OP_DISTINCT:
        return FunctionDeclarationKind.DISTINCT;
      case Z3_OP_IMPLIES:
        return FunctionDeclarationKind.IMPLIES;

      case Z3_OP_SUB:
        return FunctionDeclarationKind.SUB;
      case Z3_OP_ADD:
        return FunctionDeclarationKind.ADD;
      case Z3_OP_DIV:
        return FunctionDeclarationKind.DIV;
      case Z3_OP_MUL:
        return FunctionDeclarationKind.MUL;
      case Z3_OP_MOD:
        return FunctionDeclarationKind.MODULO;
      case Z3_OP_TO_INT:
        return FunctionDeclarationKind.FLOOR;
      case Z3_OP_TO_REAL:
        return FunctionDeclarationKind.TO_REAL;

      case Z3_OP_UNINTERPRETED:
        return FunctionDeclarationKind.UF;

      case Z3_OP_LT:
        return FunctionDeclarationKind.LT;
      case Z3_OP_LE:
        return FunctionDeclarationKind.LTE;
      case Z3_OP_GT:
        return FunctionDeclarationKind.GT;
      case Z3_OP_GE:
        return FunctionDeclarationKind.GTE;
      case Z3_OP_EQ:
        return FunctionDeclarationKind.EQ;

      case Z3_OP_STORE:
        return FunctionDeclarationKind.STORE;
      case Z3_OP_SELECT:
        return FunctionDeclarationKind.SELECT;

      case Z3_OP_TRUE:
      case Z3_OP_FALSE:
      case Z3_OP_ANUM:
      case Z3_OP_AGNUM:
        throw new UnsupportedOperationException("Unexpected state: constants not expected");
      case Z3_OP_OEQ:
        throw new UnsupportedOperationException("Unexpected state: not a proof");
      case Z3_OP_UMINUS:
        return FunctionDeclarationKind.UMINUS;
      case Z3_OP_IDIV:

        // TODO: different handling for integer division?
        return FunctionDeclarationKind.DIV;

      case Z3_OP_EXTRACT:
        return FunctionDeclarationKind.BV_EXTRACT;
      case Z3_OP_CONCAT:
        return FunctionDeclarationKind.BV_CONCAT;
      case Z3_OP_BNOT:
        return FunctionDeclarationKind.BV_NOT;
      case Z3_OP_BNEG:
        return FunctionDeclarationKind.BV_NEG;
      case Z3_OP_BAND:
        return FunctionDeclarationKind.BV_AND;
      case Z3_OP_BOR:
        return FunctionDeclarationKind.BV_OR;
      case Z3_OP_BXOR:
        return FunctionDeclarationKind.BV_XOR;
      case Z3_OP_ULT:
        return FunctionDeclarationKind.BV_ULT;
      case Z3_OP_SLT:
        return FunctionDeclarationKind.BV_SLT;
      case Z3_OP_ULEQ:
        return FunctionDeclarationKind.BV_ULE;
      case Z3_OP_SLEQ:
        return FunctionDeclarationKind.BV_SLE;
      case Z3_OP_UGT:
        return FunctionDeclarationKind.BV_UGT;
      case Z3_OP_SGT:
        return FunctionDeclarationKind.BV_SGT;
      case Z3_OP_UGEQ:
        return FunctionDeclarationKind.BV_UGE;
      case Z3_OP_SGEQ:
        return FunctionDeclarationKind.BV_SGE;
      case Z3_OP_BADD:
        return FunctionDeclarationKind.BV_ADD;
      case Z3_OP_BSUB:
        return FunctionDeclarationKind.BV_SUB;
      case Z3_OP_BMUL:
        return FunctionDeclarationKind.BV_MUL;
      case Z3_OP_BUDIV:
        return FunctionDeclarationKind.BV_UDIV;
      case Z3_OP_BSDIV:
        return FunctionDeclarationKind.BV_SDIV;
      case Z3_OP_BUREM:
        return FunctionDeclarationKind.BV_UREM;
      case Z3_OP_BSREM:
        return FunctionDeclarationKind.BV_SREM;
      case Z3_OP_BSHL:
        return FunctionDeclarationKind.BV_SHL;
      case Z3_OP_BLSHR:
        return FunctionDeclarationKind.BV_LSHR;
      case Z3_OP_BASHR:
        return FunctionDeclarationKind.BV_ASHR;
      case Z3_OP_SIGN_EXT:
        return FunctionDeclarationKind.BV_SIGN_EXTENSION;
      case Z3_OP_ZERO_EXT:
        return FunctionDeclarationKind.BV_ZERO_EXTENSION;

      case Z3_OP_FPA_NEG:
        return FunctionDeclarationKind.FP_NEG;
      case Z3_OP_FPA_ABS:
        return FunctionDeclarationKind.FP_ABS;
      case Z3_OP_FPA_MAX:
        return FunctionDeclarationKind.FP_MAX;
      case Z3_OP_FPA_MIN:
        return FunctionDeclarationKind.FP_MIN;
      case Z3_OP_FPA_SQRT:
        return FunctionDeclarationKind.FP_SQRT;
      case Z3_OP_FPA_SUB:
        return FunctionDeclarationKind.FP_SUB;
      case Z3_OP_FPA_ADD:
        return FunctionDeclarationKind.FP_ADD;
      case Z3_OP_FPA_DIV:
        return FunctionDeclarationKind.FP_DIV;
      case Z3_OP_FPA_MUL:
        return FunctionDeclarationKind.FP_MUL;
      case Z3_OP_FPA_LT:
        return FunctionDeclarationKind.FP_LT;
      case Z3_OP_FPA_LE:
        return FunctionDeclarationKind.FP_LE;
      case Z3_OP_FPA_GE:
        return FunctionDeclarationKind.FP_GE;
      case Z3_OP_FPA_GT:
        return FunctionDeclarationKind.FP_GT;
      case Z3_OP_FPA_EQ:
        return FunctionDeclarationKind.FP_EQ;
      case Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN:
        return FunctionDeclarationKind.FP_ROUND_EVEN;
      case Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY:
        return FunctionDeclarationKind.FP_ROUND_AWAY;
      case Z3_OP_FPA_RM_TOWARD_POSITIVE:
        return FunctionDeclarationKind.FP_ROUND_POSITIVE;
      case Z3_OP_FPA_RM_TOWARD_NEGATIVE:
        return FunctionDeclarationKind.FP_ROUND_NEGATIVE;
      case Z3_OP_FPA_RM_TOWARD_ZERO:
        return FunctionDeclarationKind.FP_ROUND_ZERO;
      case Z3_OP_FPA_ROUND_TO_INTEGRAL:
        return FunctionDeclarationKind.FP_ROUND_TO_INTEGRAL;
      case Z3_OP_FPA_TO_FP_UNSIGNED:
        return FunctionDeclarationKind.BV_UCASTTO_FP;
      case Z3_OP_FPA_TO_SBV:
        return FunctionDeclarationKind.FP_CASTTO_SBV;
      case Z3_OP_FPA_TO_UBV:
        return FunctionDeclarationKind.FP_CASTTO_UBV;
      case Z3_OP_FPA_TO_IEEE_BV:
        return FunctionDeclarationKind.FP_AS_IEEEBV;
      case Z3_OP_FPA_TO_FP:
        Z3_sort_kind sortKind =
            Z3_sort_kind.fromInt(
                Native.getSortKind(
                    environment, Native.getSort(environment, Native.getAppArg(environment, f, 1))));
        if (Z3_sort_kind.Z3_BV_SORT == sortKind) {
          return FunctionDeclarationKind.BV_SCASTTO_FP;
        } else {
          return FunctionDeclarationKind.FP_CASTTO_FP;
        }
      case Z3_OP_FPA_IS_NAN:
        return FunctionDeclarationKind.FP_IS_NAN;
      case Z3_OP_FPA_IS_INF:
        return FunctionDeclarationKind.FP_IS_INF;
      case Z3_OP_FPA_IS_ZERO:
        return FunctionDeclarationKind.FP_IS_ZERO;
      case Z3_OP_FPA_IS_NEGATIVE:
        return FunctionDeclarationKind.FP_IS_NEGATIVE;
      case Z3_OP_FPA_IS_SUBNORMAL:
        return FunctionDeclarationKind.FP_IS_SUBNORMAL;
      case Z3_OP_FPA_IS_NORMAL:
        return FunctionDeclarationKind.FP_IS_NORMAL;

      case Z3_OP_SEQ_CONCAT:
        return FunctionDeclarationKind.STR_CONCAT;
      case Z3_OP_SEQ_PREFIX:
        return FunctionDeclarationKind.STR_PREFIX;
      case Z3_OP_SEQ_SUFFIX:
        return FunctionDeclarationKind.STR_SUFFIX;
      case Z3_OP_SEQ_CONTAINS:
        return FunctionDeclarationKind.STR_CONTAINS;
      case Z3_OP_SEQ_EXTRACT:
        return FunctionDeclarationKind.STR_SUBSTRING;
      case Z3_OP_SEQ_REPLACE:
        return FunctionDeclarationKind.STR_REPLACE;
      case Z3_OP_SEQ_AT:
        return FunctionDeclarationKind.STR_CHAR_AT;
      case Z3_OP_SEQ_LENGTH:
        return FunctionDeclarationKind.STR_LENGTH;
      case Z3_OP_SEQ_INDEX:
        return FunctionDeclarationKind.STR_INDEX_OF;
      case Z3_OP_SEQ_TO_RE:
        return FunctionDeclarationKind.STR_TO_RE;
      case Z3_OP_SEQ_IN_RE:
        return FunctionDeclarationKind.STR_IN_RE;
      case Z3_OP_STR_TO_INT:
        return FunctionDeclarationKind.STR_TO_INT;
      case Z3_OP_INT_TO_STR:
        return FunctionDeclarationKind.INT_TO_STR;
      case Z3_OP_STRING_LT:
        return FunctionDeclarationKind.STR_LT;
      case Z3_OP_STRING_LE:
        return FunctionDeclarationKind.STR_LE;
      case Z3_OP_RE_PLUS:
        return FunctionDeclarationKind.RE_PLUS;
      case Z3_OP_RE_STAR:
        return FunctionDeclarationKind.RE_STAR;
      case Z3_OP_RE_OPTION:
        return FunctionDeclarationKind.RE_OPTIONAL;
      case Z3_OP_RE_CONCAT:
        return FunctionDeclarationKind.RE_CONCAT;
      case Z3_OP_RE_UNION:
        return FunctionDeclarationKind.RE_UNION;
      case Z3_OP_RE_RANGE:
        return FunctionDeclarationKind.RE_RANGE;
      case Z3_OP_RE_INTERSECT:
        return FunctionDeclarationKind.RE_INTERSECT;
      case Z3_OP_RE_COMPLEMENT:
        return FunctionDeclarationKind.RE_COMPLEMENT;

      default:
        return FunctionDeclarationKind.OTHER;
    }
  }

  /**
   * @param value Z3_ast
   * @return Whether the value is a constant and can be passed to {@link #convertValue(Long)}.
   */
  public boolean isConstant(long value) {
    return Native.isNumeralAst(environment, value)
        || Native.isAlgebraicNumber(environment, value)
        || Native.isString(environment, value)
        || isOP(environment, value, Z3_decl_kind.Z3_OP_TRUE.toInt())
        || isOP(environment, value, Z3_decl_kind.Z3_OP_FALSE.toInt());
  }

  /**
   * @param value Z3_ast representing a constant value.
   * @return {@link BigInteger} or {@link Double} or {@link Rational} or {@link Boolean} or {@link
   *     FloatingPointRoundingMode} or {@link String}.
   */
  @Override
  public Object convertValue(Long value) {
    if (!isConstant(value)) {
      return null;
    }

    Native.incRef(environment, value);

    Object constantValue =
        Z3_CONSTANTS.get(Native.getDeclKind(environment, Native.getAppDecl(environment, value)));
    if (constantValue != null) {
      return constantValue;
    }

    try {
      FormulaType<?> type = getFormulaType(value);
      if (type.isBooleanType()) {
        return isOP(environment, value, Z3_decl_kind.Z3_OP_TRUE.toInt());
      } else if (type.isIntegerType()) {
        return new BigInteger(Native.getNumeralString(environment, value));
      } else if (type.isRationalType()) {
        return Rational.ofString(Native.getNumeralString(environment, value));
      } else if (type.isStringType()) {
        return Native.getString(environment, value);
      } else if (type.isBitvectorType()) {
        return new BigInteger(Native.getNumeralString(environment, value));
      } else if (type.isFloatingPointType()) {

        // Converting to Rational first.
        return convertValue(Native.simplify(environment, Native.mkFpaToReal(environment, value)));
      } else {

        // Explicitly crash on unknown type.
        throw new IllegalArgumentException("Unexpected type encountered: " + type);
      }

    } finally {
      Native.decRef(environment, value);
    }
  }

  @Override
  public Long declareUFImpl(String pName, Long returnType, List<Long> pArgTypes) {
    long symbol = Native.mkStringSymbol(environment, pName);
    long[] sorts = Longs.toArray(pArgTypes);
    long func = Native.mkFuncDecl(environment, symbol, sorts.length, sorts, returnType);
    Native.incRef(environment, func);
    symbolsToDeclarations.put(pName, func);
    return func;
  }

  @Override
  public Long callFunctionImpl(Long declaration, List<Long> args) {
    return Native.mkApp(environment, declaration, args.size(), Longs.toArray(args));
  }

  @Override
  protected Long getBooleanVarDeclarationImpl(Long pLong) {
    return Native.getAppDecl(getEnv(), pLong);
  }

  /** returns, if the function of the expression is the given operation. */
  static boolean isOP(long z3context, long expr, int op) {
    if (!Native.isApp(z3context, expr)) {
      return false;
    }

    long decl = Native.getAppDecl(z3context, expr);
    return Native.getDeclKind(z3context, decl) == op;
  }

  /**
   * Apply multiple tactics in sequence.
   *
   * @throws InterruptedException thrown by JNI code in case of termination request
   * @throws SolverException thrown by JNI code in case of error
   */
  public long applyTactics(long z3context, final Long pF, String... pTactics)
      throws InterruptedException, SolverException {
    long overallResult = pF;
    for (String tactic : pTactics) {
      overallResult = applyTactic(z3context, overallResult, tactic);
    }
    return overallResult;
  }

  /**
   * Apply tactic on a Z3_ast object, convert the result back to Z3_ast.
   *
   * @param z3context Z3_context
   * @param tactic Z3 Tactic Name
   * @param pF Z3_ast
   * @return Z3_ast
   * @throws InterruptedException If execution gets interrupted.
   */
  public long applyTactic(long z3context, long pF, String tactic) throws InterruptedException {
    long tacticObject = Native.mkTactic(z3context, tactic);
    Native.tacticIncRef(z3context, tacticObject);

    long goal = Native.mkGoal(z3context, true, false, false);
    Native.goalIncRef(z3context, goal);
    Native.goalAssert(z3context, goal, pF);

    long result;
    try {
      result = Native.tacticApply(z3context, tacticObject, goal);
    } catch (Z3Exception exp) {
      throw handleZ3Exception(exp);
    }

    try {
      return applyResultToAST(z3context, result);
    } finally {
      Native.goalDecRef(z3context, goal);
      Native.tacticDecRef(z3context, tacticObject);
    }
  }

  private long applyResultToAST(long z3context, long applyResult) {
    int subgoalsCount = Native.applyResultGetNumSubgoals(z3context, applyResult);
    long[] goalFormulas = new long[subgoalsCount];
    for (int i = 0; i < subgoalsCount; i++) {
      long subgoal = Native.applyResultGetSubgoal(z3context, applyResult, i);
      goalFormulas[i] = goalToAST(z3context, subgoal);
    }
    return goalFormulas.length == 1
        ? goalFormulas[0]
        : Native.mkOr(z3context, goalFormulas.length, goalFormulas);
  }

  private long goalToAST(long z3context, long goal) {
    int subgoalFormulasCount = Native.goalSize(z3context, goal);
    long[] subgoalFormulas = new long[subgoalFormulasCount];
    for (int k = 0; k < subgoalFormulasCount; k++) {
      subgoalFormulas[k] = Native.goalFormula(z3context, goal, k);
    }
    return subgoalFormulas.length == 1
        ? subgoalFormulas[0]
        : Native.mkAnd(z3context, subgoalFormulas.length, subgoalFormulas);
  }

  /** Closing the context. */
  public void forceClose() {
    cleanupReferences();

    // Force clean all ASTs, even those which were not GC'd yet.
    // Is a no-op if phantom reference handling is not enabled.
    for (long ast : referenceMap.values()) {
      Native.decRef(getEnv(), ast);
    }
  }

  /**
   * get a previously created application declaration, or <code>NULL</code> if the symbol is
   * unknown.
   */
  @Nullable Long getKnownDeclaration(String symbolName) {
    return symbolsToDeclarations.get(symbolName);
  }
}


text:
namespace bindings {

inline v8::Isolate* GetIsolate() {
  return v8::Isolate::GetCurrent();
}

// Defined in runtime.cc to avoid a circular dependency.
v8::Local<v8::Context> GetContext();

inline int64_t GetInt64(v8::Local<v8::Context> context, v8::Local<v8::Value> source) {
  return source->ToNumber(context).ToLocalChecked()->IntegerValue(context).ToChecked();
}

inline v8::Local<v8::String> v8String(const char* string, int length) {
  return v8::String::NewFromUtf8(GetIsolate(), string, v8::NewStringType::kNormal, length).ToLocalChecked();
}

inline v8::Local<v8::String> v8String(const char* string) {
  return v8String(string, strlen(string));
}

inline v8::Local<v8::String> v8String(const std::string& string) {
  return v8::String::NewFromUtf8(GetIsolate(), string.c_str(), v8::NewStringType::kNormal, string.size()).ToLocalChecked();
}

inline v8::Local<v8::Primitive> v8Null() {
  return v8::Null(GetIsolate());
}

template<typename T>
inline v8::Local<v8::Number> v8Number(T number) {
  return v8::Number::New(GetIsolate(), static_cast<double>(number));
}

inline std::string toString(v8::Local<v8::Value> string) {
  v8::String::Utf8Value value(GetIsolate(), string);
  if (value.length())
    return std::string(*value, value.length());

  return std::string();
}

inline void ThrowException(const std::string& message) {
  v8::Local<v8::Value> error = v8::Exception::TypeError(v8String(message));
  if (ScopedExceptionAttribution::HasAttribution())
    RegisterError(error);

  v8::Isolate::GetCurrent()->ThrowException(error);
}

}  // namespace bindings

#endif  // PLAYGROUND_BINDINGS_UTILITIES_H_

redpajama_set_name: RedPajamaGithub


text:
package com.charlie.wheather.pojo;

/**
 * Created by Administrator on 2017/3/2.
 */
public class DrsgBean {
    public String brf;
    public String txt;
}


text: An alarmclock built with Electron


text:
A Terraria 1.3 tModLoader mod that makes bosses behave like in Expert Mode even in Normal Mode. Also adds an */expert* command that toggles Expert Mode in worlds.

Download either from "[Releases](https://github.com/goldenapple3/BossExpertise/releases)" on this website or from the Mod Browser.
**Link to TCF forum thread**: http://forums.terraria.org/index.php?threads/boss-expertise.41243/


text:
package exps.sn;

import java.util.*;

public class Graph {

    private final Map<String,Vertex> vertexMap=new HashMap<>();
    private final Set<Edge> edges=new HashSet<>();

    public Iterator<Vertex> getVertexes(){
        return vertexMap.values().iterator();
    }

    public Iterator<Edge> getEdges(){
        return edges.iterator();
    }

    void createVertex(String id){
        vertexMap.put(id, new Vertex(id));
    }

    Vertex getVertexById(String id){
        return vertexMap.get(id);
    }

    void createEdge(String id1, String id2, String type){
        Vertex v1=getVertexById(id1);
        Vertex v2=getVertexById(id2);
        createEdge(v1,v2,type);
    }

    void weight(){
        for (Edge edge:edges){
            long forwardCount=edge.source.outgoingEdges.stream().map(Edge::getTarget).count();
            long backwardCount=edge.target.incomingEdges.stream().map(Edge::getSource).count();
            edge.weight=1.0/forwardCount/backwardCount;
        }
    }

    private void createEdge(Vertex v1, Vertex v2, String type){
        if (v1==null||v2==null)
            return;
        if (v1.equals(v2))
            return;
        Edge e=new Edge(v1,v2,type,0);
        v1.outgoingEdges.add(e);
        v2.incomingEdges.add(e);
        edges.add(e);
    }

    public class Vertex{

        private String id;
        private Set<Edge> outgoingEdges=new HashSet<>();
        private Set<Edge> incomingEdges=new HashSet<>();
        private Vertex(String id) {
            this.id = id;
        }
        public String getId(){
            return id;
        }
        public Set<Vertex> getNeighbors(boolean outgoing, boolean incoming){
            Set<Vertex> r=new HashSet<>();
            if (outgoing)
                outgoingEdges.stream().map(Edge::getTarget).forEach(n->r.add(n));
            if (incoming)
                incomingEdges.stream().map(Edge::getSource).forEach(n->r.add(n));
            return r;
        }
        public double weightTo(Vertex v, boolean outgoing, boolean incoming){
            double r=0;
            if (outgoing)
                for (Edge e:outgoingEdges)
                    if (e.target==v)
                        r+=e.weight;
            if (incoming)
                for (Edge e:incomingEdges)
                    if (e.source==v)
                        r+=e.weight;
            return r;
        }
        @Override
        public boolean equals(Object v){
            if (v instanceof Vertex)
                return id.equals(((Vertex) v).id);
            else
                return false;
        }
        @Override
        public int hashCode(){
            return id.hashCode();
        }
    }

    public class Edge{
        private Vertex source,target;
        private String type;
        private double weight;
        private Edge(Vertex source, Vertex target, String type, double weight){
            this.source=source;
            this.target=target;
            this.type=type;
            this.weight=weight;
        }

        public Vertex getSource() {
            return source;
        }

        public Vertex getTarget() {
            return target;
        }

        public String getType() {
            return type;
        }

        public double getWeight() {
            return weight;
        }

        @Override
        public boolean equals(Object e){
            if (e instanceof Edge)
                return hashCode()==e.hashCode();
            else
                return false;
        }
        @Override
        public int hashCode(){
            return (""+source.hashCode()+" "+target.hashCode()+" "+type.hashCode()).hashCode();
        }
    }

}


text:
package com.ibm.uk.hursley.perfharness.amqp;

import java.util.logging.Level;

import com.ibm.uk.hursley.perfharness.Config;
import com.ibm.uk.hursley.perfharness.WorkerThread;

/**
 * @author ElliotGregory
 *
 * This class is designed to read as many message from the subscribed topic.
 */
public final class FloodSubscriber extends AMQPWorkerThread implements WorkerThread.Paceable {

	@SuppressWarnings("unused")
	private static final String c = com.ibm.uk.hursley.perfharness.Copyright.COPYRIGHT; // IGNORE compiler warning

	/** force failure if connection lost. **/
	private final boolean failureOnLostConnection = Config.parms.getBoolean("fl");
	/** Topic to read the messages from **/
	private final String  inboundTopicBase = Config.parms.getString("it");
	/** Topic index per thread id **/
	private final boolean topicIndexByThread = Config.parms.getBoolean("tpt");

	/** Inbound topic to subscribe and receive messages from **/
	private final String inboundtopic;

	/**
	 * @param name
	 */
	public FloodSubscriber(String name) {
		super(name);
		inboundtopic = topicIndexByThread ? inboundTopicBase + getThreadNum() : inboundTopicBase;
	}

	/**
	 *
	 */
	public static void registerConfig() {
		Config.registerSelf(FloodSubscriber.class);
		if (!Config.isInvalid())
			Config.registerAnother(Config.parms.getClazz("df"));
	}

	/* (non-Javadoc)
	 * @see java.lang.Thread#run()
	 */
	public void run() {
		run(this);
	}

	/* (non-Javadoc)
	 * @see com.ibm.uk.hursley.perfharness.amqp.MQJavaWorkerThread#buildMQJavaResources()
	 */
	protected void buildAMQPResources() throws Exception {
		super.buildAMQPResources();

		client.subscribe(inboundtopic);
	}

	/* (non-Javadoc)
	 * @see com.ibm.uk.hursley.perfharness.WorkerThread.Paceable#oneIteration()
	 */
	public boolean oneIteration() throws Exception {

		if (failureOnLostConnection && client.connectionLost()) {
			log(Level.SEVERE, "({0}) has lost its connection.", getName());
			throw new AMQPException("Connection to AMQP Server has been lost.");
		}

		client.receiveMessage();
		incIterations();
		return true;
	}

	/* (non-Javadoc)
	 * @see com.ibm.uk.hursley.perfharness.amqp.AMQPWorkerThread#close()
	 */
	@Override
	protected void close () {
		if (client != null) client.close(getName());
	}
}


text:
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
import collections
import inspect
import gevent
import functools
import copy
import sys

if sys.version_info.major == 2:
    str = unicode  # noqa

class EasyDecorator(object):
    """An attempt to make Decorating stuff easier"""
    _instance = None
    _thing = _othing = None

    def __init__(self, *args, **kwargs):
        """Figure how we are being called for decoration"""
        #Default to empty
        self.args = []
        self.kwargs = {}

        if len(args) == 1 and not kwargs \
           and (inspect.isclass(args[0]) or isinstance(args[0],
                                                       collections.Callable)):
            self._thing = args[0]
            self._mimic()
        else:
            # Save args so wrappers could use them
            self.args = args
            self.kwargs = kwargs

    def _mimic(self):
        """Mimic the base object so we have the same props"""
        for n in set(dir(self._thing)) - set(dir(self)):
            setattr(self, n, getattr(self._thing, n))
        #These have to happen
        self.__name__ = self._thing.__name__
        self.__doc__ = self._thing.__doc__

    def wrapper(self, *args, **kwargs):
        """Empty Wrapper: Overwride me"""
        return self.call(*args, **kwargs)

    def call(self, *args, **kwargs):
        """Call the decorated object"""
        return self._thing(*args, **kwargs)

    #Instance Methods
    def __get__(self, instance, klass):
        self._instance = instance

        #Before we bind the method lets capture the original
        if self._othing is None:
            self._othing = self._thing

        #Get a bound method from the original
        self._thing = self._othing.__get__(instance, klass)

        #Return a copy of self, for instance safety
        return copy.copy(self)

    #Functions / With args this gets the thing
    def __call__(self, *args, **kwargs):
        if self._thing:
            return self.wrapper(*args, **kwargs)
        else:
            self._thing = args[0]
            self._mimic()
            return self

def filterintree(adict, block, stype=str, history=None):
    """Execute block filter for all strings in a dict/list recusive"""
    if not adict:  # Don't go through the proccess for empty containers
        return adict
    if history is None:
        history = set()
    if id(adict) in history:
        return
    else:
        history.add(id(adict))

    if isinstance(adict, list):
        for i in range(len(adict)):
            if isinstance(adict[i], stype):
                adict[i] = block(adict[i])
            elif isinstance(adict[i], (set, tuple)):
                adict[i] = filterintree(adict[i], block, stype, history)
            elif isinstance(adict[i], (list, dict)):
                filterintree(adict[i], block, stype, history)
    elif isinstance(adict, (set, tuple)):
        c = list(adict)
        filterintree(c, block, stype, history)
        return type(adict)(c)
    elif isinstance(adict, dict):
        for k, v in adict.items():
            if isinstance(v, stype):
                adict[k] = block(v)
            elif isinstance(v, (dict, list)):
                filterintree(v, block, stype, history)
            elif isinstance(v, (set, tuple)):
                adict[k] = filterintree(v, block, stype, history)

class utf8Decode(EasyDecorator):
    """decode all arguments to unicode strings"""
    def wrapper(self, *args, **kwargs):
        def decode(s):
            return s.decode('utf-8', 'ignore')

        args = filterintree(args, decode, stype=bytes)
        filterintree(kwargs, decode, stype=bytes)
        #Call Method with converted args
        return self.call(*args, **kwargs)

    class returnValue(EasyDecorator):
        """decode the return value only"""
        def wrapper(self, *args, **kwargs):
            def decode(s):
                return s.decode('utf-8', 'ignore')

            value = [self.call(*args, **kwargs)]
            filterintree(value, decode, stype=bytes)
            return value[0]

class utf8Encode(EasyDecorator):
    """encode all unicode arguments to byte strings"""
    def wrapper(self, *args, **kwargs):
        def encode(s):
            return s.encode('utf-8', 'backslashreplace')

        args = filterintree(args, encode, stype=str)
        filterintree(kwargs, encode, stype=str)
        #Call Method with converted args
        return self.call(*args, **kwargs)

    class returnValue(EasyDecorator):
        """encode the return value"""
        def wrapper(self, *args, **kwargs):
            def encode(s):
                return s.encode('utf-8', 'backslashreplace')

            value = [self.call(*args, **kwargs)]
            filterintree(value, encode, stype=str)
            return value[0]

def raise_exceptions(func):
    """Wrap around for spawn to raise exceptions in current context"""
    caller = gevent.getcurrent()

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as ex:
            caller.throw(ex)

    return wrapper


text:
'use strict';

import config from '../../config';
import {output as pagespeed} from 'psi';

export default function (options = {}, url = config.pagespeed.url) {
  options = Object.assign({
    nokey: 'true',

    // By default we use the PageSpeed Insights free (no API key) tier.
    // Use a Google Developer API key if you have one: http://goo.gl/RkN0vE
    // key: 'YOUR_API_KEY'
  }, options);

  return function(done){
    return pagespeed(url, options, done);
  };
}


text:
const assert = require("assert");
const path = require("path");
const _ = require("underscore");
const semver = require("semver");
const lowerFirstLetter = require("node-opcua-utils").lowerFirstLetter;

const expected_version = "0.7.1";

exports.install = function(opcua) {

    if (opcua.hasOwnProperty("ISA95")){
        return false; // already installed
    }

    // verify that node-opcua version is compatible
    if (semver.lt(opcua.version, expected_version)) {
        throw new Error("node-opcua-isa95 need node-opcua version to be greater" +
            " or equal than " + expected_version + ". Currently your version of node-opcua is " + opcua.version+ "" +
            " Please update node-opcua");
    }

    if (semver.gt(opcua.version, expected_version)) {
        console.log("warning : the expected version of node-opcua is less than " + expected_version + " - actual version is " + opcua.version);
        console.log("Please, check if there is a newer version of node-opcua-isa95!")
    }

    const Enum = opcua.Enum;//require("enum");

    const EquipmentLevel = new Enum({
        // ISA95EquipmentElementLevelEnum
        //
        // This DataType is an enumeration that defines the equipment element levels defined in ISA-95. Its values are
        // defined in a below table.
        // Note:  for enumeration DataTypes it is recommended that variables that use the enumeration also expose the EnumStrings
        //        property. This property allows a client to easily translate the enumeration (integer value) to a string for
        //        display (see OPC Part 3).
        // Table 36 – ISA95EquipmentElementLevelEnum Values
        //
        // Value              Description
        // ENTERPRISE_0       An enterprise is a collection of sites and areas and represents the top level of a role based
        //                    equipment hierarchy.
        Enterprise: 0,

        // SITE_1             A site is a physical, geographical, or logical grouping determined by the enterprise. It may contain
        //                    areas, production lines, process cells, and production units.
        Site: 1,

        // AREA_2             An area is a physical, geographical, or logical grouping determined by the site. It may contain work
        //                    centres such as process cells, production units, production lines, and storage zones.
        Area: 2,

        // PROCESSCELL_3      Process cells are the low level of equipment typically scheduled by the Level 4 and Level 3
        //                    functions for batch manufacturing processes. The definitions for process cells are
        //                    contained in IEC 61512-1.
        ProcessCell: 3,

        // UNIT_4             Units are low level of equipment typically scheduled by the Level 4 and Level 3 functions for batch
        //                    manufacturing processes and continuous manufacturing processes. The definition of the unit for batch
        //                    manufacturing processes is contained in IEC 61512-1.
        Unit: 4,

        // PRODUCTIONLINE_5   Production lines are low levels of equipment typically scheduled by the Level 4 or Level 3
        //                    functions for discrete manufacturing processes.
        ProductionLine: 5,

        // WORKCELL_6         Work cells are low levels of equipment typically scheduled by the Level 4 or Level 3 functions for
        //                    discrete manufacturing processes.
        WorkCell: 6,

        // PRODUCTIONUINT_7   Production units are the lowest level of equipment typically scheduled by the Level 4 or Level
        //                    functions for continuous manufacturing processes.
        ProductionUnit: 7,

        // STORAGEZONE_8      Storage zones are low level of material movement equipment typically scheduled by the Level 4 and
        //                    Level 3 functions for discrete, batch and continuous manufacturing processes.
        StorageZone: 8,

        // STORAGEUNIT_9      Storage units are low level of material movement equipment typically scheduled by the  Level 4 and
        //                    Level 3 functions for discrete, batch and continuous manufacturing processes.
        //                    WORKCENTER_10 Work centres are typically the grouping of equipment scheduled by the Level 4 or
        //                    Level 3 functions.
        StorageUnit: 9,
        // WORKUNIT_11        A work unit is any element of the equipment hierarchy under a work centre. Work units are the lowest
        //                    form of elements in an equipment hierarchy that are typically scheduled by Level 3 functions.
        WorkUnit: 11,

        // EQUIPMENTMODULE_12 An equipment module entity is an engineered subdivision of a process cell, a unit, or another
        //                    equipment module. The definition of the equipment module is contained in IEC61512-1.
        EquipmentModule: 12,

        // CONTROLMODULE_13   A control module entity is an engineered subdivision of a process cell, a unit, an equipment module,
        //                    or another control module. The definition of the equipment module is contained in IEC 61512-1.
        ControlModule: 13,
        // OTHER_14           The types of work centres may be extended when required for application specific role based
        //                    equipment hierarchies where the defined types do not apply. In that case, the equipment element
        //                    level shall be specified as this value, and actual value that identifies the level shall be
        //                    specified by OtherValue Property of ISAHierarchyScopeType defined in 7.4.1.
        Other: 14
        // When a new type is added it shall maintain the same relationship within the hierarchy as the defined work centre
        // types (within an area and contains work units).
    });

    const registerBasicType = require("node-opcua-factory").registerBasicType;
    registerBasicType({ name: "CDTIdentifier",  subtype: "String",  defaultValue: null});

    assert(!opcua.hasOwnProperty('ISA95'),"already initialized ?");

    opcua.ISA95= {};
    opcua.ISA95.EquipmentLevel = EquipmentLevel;

    const isa95_xml_file = path.join(__dirname, "../nodesets/Opc.ISA95.NodeSet2.xml");
    opcua.ISA95.nodeset_file = isa95_xml_file;

    function coerceISA95TypeDefinition(addressSpace,typeDefinition,baseType) {

        baseType = addressSpace.findISA95VariableType(baseType);
        assert(baseType,baseType + " must exists ");
        if (typeof typeDefinition === "string") {
            const _typeDefinition = addressSpace.findISA95VariableType(typeDefinition);
            assert(_typeDefinition,typeDefinition + " must exists ");
            typeDefinition = _typeDefinition;
        }
        if (typeDefinition instanceof opcua.NodeId) {
            typeDefinition = addressSpace.findNode(typeDefinition);
        }
        assert(typeDefinition.nodeId instanceof opcua.NodeId);

        // istanbul ignore next
        if (!baseType.isSupertypeOf(typeDefinition)) {
            //xx throw new Error(typeDefinition.browseName.toString() + " must be a subtype of " + baseType.browseName.toString());
        }
        return typeDefinition;
    }

    /**
     *
     * @param options
     * @param options.browseName
     * @param options.ISA95ClassPropertyOf
     * @param options.typeDefinition
     * @param options.dataType
     * @param options.value
     */
    opcua.AddressSpace.prototype.addISA95ClassProperty = function(options) {

        assert(options.dataType,"expecting a dataType here");
        assert(!options.componentOf && !options.organizedBy && !options.propertyOf);
        assert(options.typeDefinition, "expecting a typeDefinition");
        assert(options.ISA95ClassPropertyOf,"expecting a parent object");
        // todo ; check that nodeISA95 is a ...ClassType
        const nodeISA95 = options.ISA95ClassPropertyOf;
        const addressSpace = nodeISA95.addressSpace;
        const namespace = addressSpace.getOwnNamespace();

        function coerceISA95ClassPropertyTypeDefinition(typeDefinition) {
            return coerceISA95TypeDefinition(addressSpace,typeDefinition,"ISA95ClassPropertyType");
        }
        const typeDefinition = coerceISA95ClassPropertyTypeDefinition(options.typeDefinition);

        const ns = addressSpace.getISA95Namespace();

        // placeHolder  => HasISA95ClassProperty => <PropertyName>
        //              => TestedByEquipmentTest => <TestSpecification>
        //
        const property = namespace.addVariable({
            typeDefinition: typeDefinition,
            browseName: options.browseName,
            dataType: options.dataType,
            value: options.value
        });

        // not : the hasISA95ClassProperty reference will be turned into a  hasISA95Property in the instantiated object
        const hasISA95ClassProperty = addressSpace.findReferenceType("HasISA95ClassProperty",ns);

        nodeISA95.addReference({
            referenceType: hasISA95ClassProperty.nodeId,
                nodeId: property
        });
        return property;
    };

    /**
     *
     * @param options
     * @param options.browseName
     * @param options.typeDefinition
     * @param options.ISA95PropertyOf
     * @param [options.modellingRule]
     * @returns {UAVariable}
     */
    opcua.AddressSpace.prototype.addISA95Property = function(options) {

        assert(options.browseName,"expecting a browseName");
        assert(options.dataType,"expecting a dataType here");
        assert(!options.componentOf && !options.organizedBy && !options.propertyOf);
        assert(options.typeDefinition, "expecting a typeDefinition");
        assert(options.ISA95PropertyOf,"expecting a parent object");

        // todo ; check that nodeISA95 is a ...ClassType
        const nodeISA95 = options.ISA95PropertyOf;
        const addressSpace = nodeISA95.addressSpace;
        const namespace = addressSpace.getOwnNamespace();

        const ns = addressSpace.getISA95Namespace();
        const hasISA95Property = addressSpace.findReferenceType("HasISA95Property",ns);

        function coerceISA95PropertyTypeDefinition(typeDefinition) {
            return coerceISA95TypeDefinition(addressSpace,typeDefinition,"ISA95PropertyType");
        }
        const typeDefinition = coerceISA95PropertyTypeDefinition(options.typeDefinition);

        const property = namespace.addVariable({
            browseName: options.browseName,
            typeDefinition: typeDefinition,
            modellingRule: options.modellingRule,
            dataType: options.dataType,
            value: options.value

        });
        nodeISA95.addReference({
            referenceType: hasISA95Property.nodeId,
            nodeId: property
        });
        return property;

    };

    /**
     *
     * @param options
     * @param options.browseName
     * @param options.dataType
     * @param options.value
     * @param [options.typeDefinition]
     * @param [options.modellingRule]
     * @param options.ISA95AttributeOf
     */
    opcua.AddressSpace.prototype.addISA95Attribute = function(options) {

        assert(options.ISA95AttributeOf," ISA95AttributeOf options is expected");
        const nodeISA95 = options.ISA95AttributeOf;

        // modelling rule must be specified if nodeISA95 is a UAVariableType of UAObjectType;
        if (!options.modellingRule &&
            ( nodeISA95.constructor.name === "UAVariableType" ||
              nodeISA95.constructor.name === "UAObjectType")) {
            throw new Error("Expecting options.modellingRule to be specified")
        }
        const addressSpace = nodeISA95.addressSpace;
        const namespace = addressSpace.getOwnNamespace();

        const ns = addressSpace.getNamespaceIndex("http://www.OPCFoundation.org/UA/2013/01/ISA95");

        const hasISA95Attribute = addressSpace.findReferenceType("HasISA95Attribute",ns);

        let dataType =  options.dataType;
        if (typeof dataType === "string") {
            let dataTypeNode = addressSpace.findDataType(dataType,ns);
            if (!dataTypeNode) {
                dataTypeNode = addressSpace.findDataType(dataType);
                if (!dataTypeNode) {
                    dataTypeNode = opcua.DataType[dataType];
                }
            }
            dataType = dataTypeNode;
        }
        if(!dataType ){
            console.log("opcua.",opcua.DataType);
            throw new Error(" cannot find dataType " + options.dataType + " " + typeof options.dataType );
        }

        const typeDefinition = options.typeDefinition || addressSpace.findVariableType("BaseDataVariableType");

        const property = namespace.addVariable({
            typeDefinition: typeDefinition,
            modellingRule: options.modellingRule,
            browseName: options.browseName,
            dataType: dataType,
            value: options.value,
        });
        nodeISA95.addReference({
            referenceType: hasISA95Attribute.nodeId,
            nodeId: property
        });

        const name = lowerFirstLetter(property.browseName.name.toString());
        nodeISA95[name] = property;

        return property;
    };

    /**
     * find a ReferenceType in the ISA95 namespace
     * @param name {String}
     * @return {opcua.ReferenceType}
     */
    opcua.AddressSpace.prototype.getISA95Namespace = function() {
        const addressSpace  = this;
        return addressSpace.getNamespaceIndex("http://www.OPCFoundation.org/UA/2013/01/ISA95");
    };

    opcua.AddressSpace.prototype.findISA95ReferenceType = function(name) {
        const addressSpace  = this;
        return addressSpace.findReferenceType(name,addressSpace.getISA95Namespace());
    };

    opcua.AddressSpace.prototype.findISA95ObjectType = function(name) {
        const addressSpace  = this;
        return addressSpace.findObjectType(name,addressSpace.getISA95Namespace());
    };

    opcua.AddressSpace.prototype.findISA95VariableType = function(name) {
        const addressSpace  = this;
        return addressSpace.findVariableType(name,addressSpace.getISA95Namespace());
    };

    opcua.AddressSpace.prototype.findISA95DataType = function(name) {
        const addressSpace  = this;
        return addressSpace.findDataType(name,addressSpace.getISA95Namespace());
    };

    require("./isa95_address_space_extension_utils")(opcua);
    require("./isa95_address_space_extension_equipment")(opcua);
    require("./isa95_address_space_extension_physical_asset")(opcua);
};


text:
package view.toolbar;

import view.UtilityFactory;
import view.ViewData;

public class ResetEvent implements ToolBarButtonEvent{

	private ViewData myData;

	public ResetEvent(UtilityFactory utilF, ViewData dataIn){
		myData = dataIn;
	}

	@Override
	public void event() {
		myData.removePlacedEntities(myData.getCurrentLevel());
	}
}


text:
/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM ../../../dist/idl\nsIDOMDOMCursor.idl
 */

#ifndef __gen_nsIDOMDOMCursor_h__
#define __gen_nsIDOMDOMCursor_h__

#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif

/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif

/* starting interface:    nsICursorContinueCallback */
#define NS_ICURSORCONTINUECALLBACK_IID_STR "3a75d80a-9258-4ab8-95fd-ec0b5f634df1"

#define NS_ICURSORCONTINUECALLBACK_IID \
  {0x3a75d80a, 0x9258, 0x4ab8, \
    { 0x95, 0xfd, 0xec, 0x0b, 0x5f, 0x63, 0x4d, 0xf1 }}

class NS_NO_VTABLE nsICursorContinueCallback : public nsISupports {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_ICURSORCONTINUECALLBACK_IID)

  /* void handleContinue (); */
  NS_IMETHOD HandleContinue(void) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsICursorContinueCallback, NS_ICURSORCONTINUECALLBACK_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSICURSORCONTINUECALLBACK \
  NS_IMETHOD HandleContinue(void) override;

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSICURSORCONTINUECALLBACK(_to) \
  NS_IMETHOD HandleContinue(void) override { return _to HandleContinue(); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSICURSORCONTINUECALLBACK(_to) \
  NS_IMETHOD HandleContinue(void) override { return !_to ? NS_ERROR_NULL_POINTER : _to->HandleContinue(); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsCursorContinueCallback : public nsICursorContinueCallback
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSICURSORCONTINUECALLBACK

  nsCursorContinueCallback();

private:
  ~nsCursorContinueCallback();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS(nsCursorContinueCallback, nsICursorContinueCallback)

nsCursorContinueCallback::nsCursorContinueCallback()
{
  /* member initializers and constructor code */
}

nsCursorContinueCallback::~nsCursorContinueCallback()
{
  /* destructor code */
}

/* void handleContinue (); */
NS_IMETHODIMP nsCursorContinueCallback::HandleContinue()
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

/* starting interface:    nsIDOMDOMCursor */
#define NS_IDOMDOMCURSOR_IID_STR "062ea35a-5158-425a-b7bc-3ae9daa84398"

#define NS_IDOMDOMCURSOR_IID \
  {0x062ea35a, 0x5158, 0x425a, \
    { 0xb7, 0xbc, 0x3a, 0xe9, 0xda, 0xa8, 0x43, 0x98 }}

class NS_NO_VTABLE nsIDOMDOMCursor : public nsISupports {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMDOMCURSOR_IID)

  /* readonly attribute boolean done; */
  NS_IMETHOD GetDone(bool *aDone) = 0;

  /* void continue (); */
  NS_IMETHOD Continue(void) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMDOMCursor, NS_IDOMDOMCURSOR_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIDOMDOMCURSOR \
  NS_IMETHOD GetDone(bool *aDone) override; \
  NS_IMETHOD Continue(void) override;

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIDOMDOMCURSOR(_to) \
  NS_IMETHOD GetDone(bool *aDone) override { return _to GetDone(aDone); } \
  NS_IMETHOD Continue(void) override { return _to Continue(); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIDOMDOMCURSOR(_to) \
  NS_IMETHOD GetDone(bool *aDone) override { return !_to ? NS_ERROR_NULL_POINTER : _to->GetDone(aDone); } \
  NS_IMETHOD Continue(void) override { return !_to ? NS_ERROR_NULL_POINTER : _to->Continue(); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsDOMDOMCursor : public nsIDOMDOMCursor
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIDOMDOMCURSOR

  nsDOMDOMCursor();

private:
  ~nsDOMDOMCursor();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS(nsDOMDOMCursor, nsIDOMDOMCursor)

nsDOMDOMCursor::nsDOMDOMCursor()
{
  /* member initializers and constructor code */
}

nsDOMDOMCursor::~nsDOMDOMCursor()
{
  /* destructor code */
}

/* readonly attribute boolean done; */
NS_IMETHODIMP nsDOMDOMCursor::GetDone(bool *aDone)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void continue (); */
NS_IMETHODIMP nsDOMDOMCursor::Continue()
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

#endif /* __gen_nsIDOMDOMCursor_h__ */


text:
import asyncore
import base64
import cherrypy
import email
import errno
import json
import os
import six
import smtpd
import socket
import threading
import time

from six import BytesIO
from six.moves import queue, range, urllib

_startPort = 31000
_maxTries = 100

class MockSmtpServer(smtpd.SMTPServer):
    mailQueue = queue.Queue()

    def __init__(self, localaddr, remoteaddr, decode_data=False):
        kwargs = {}
        if six.PY3:
            # Python 3.5+ prints a warning if 'decode_data' isn't explicitly
            # specified, but earlier versions don't accept the argument at all
            kwargs['decode_data'] = decode_data
        # smtpd.SMTPServer is an old-style class in Python2,
        # so super() can't be used
        smtpd.SMTPServer.__init__(self, localaddr, remoteaddr, **kwargs)

    def process_message(self, peer, mailfrom, rcpttos, data, **kwargs):
        self.mailQueue.put(data)

class MockSmtpReceiver(object):
    def __init__(self):
        self.address = None
        self.smtp = None
        self.thread = None

    def start(self):
        """
        Start the mock SMTP server. Attempt to bind to any port within the
        range specified by _startPort and _maxTries.  Bias it with the pid of
        the current process so as to reduce potential conflicts with parallel
        tests that are started nearly simultaneously.
        """
        for porttry in range(_maxTries):
            port = _startPort + ((porttry + os.getpid()) % _maxTries)
            try:
                self.address = ('localhost', port)
                self.smtp = MockSmtpServer(self.address, None)
                break
            except (OSError if six.PY3 else socket.error) as e:
                if e.errno != errno.EADDRINUSE:
                    raise
        else:
            raise Exception('Could not bind to any port for Mock SMTP server')

        self.thread = threading.Thread(target=self.loop)
        self.thread.start()

    def loop(self):
        """
        Instead of calling asyncore.loop directly, wrap it with a small
        timeout.  This prevents using 100% cpu and still allows a graceful exit.
        """
        while len(asyncore.socket_map):
            asyncore.loop(timeout=0.5, use_poll=True)

    def stop(self):
        """Stop the mock STMP server"""
        self.smtp.close()
        self.thread.join()

    def getMail(self, parse=False):
        """
        Return the message at the front of the queue.
        Raises Queue.Empty exception if there are no messages.

        :param parse: Whether to parse the email into an email.message.Message
            object. If False, just returns the raw email string.
        :type parse: bool
        """
        msg = self.smtp.mailQueue.get(block=False)

        if parse:
            if six.PY3 and isinstance(msg, six.binary_type):
                return email.message_from_bytes(msg)
            else:
                return email.message_from_string(msg)
        else:
            return msg

    def isMailQueueEmpty(self):
        """Return whether or not the mail queue is empty"""
        return self.smtp.mailQueue.empty()

    def waitForMail(self, timeout=10):
        """
        Waits for mail to appear on the queue. Returns "True" as soon as the
        queue is not empty, or "False" if the timeout was reached before any
        mail appears.

        :param timeout: Timeout in seconds.
        :type timeout: float
        """
        startTime = time.time()
        while True:
            if not self.isMailQueueEmpty():
                return True
            if time.time() > startTime + timeout:
                return False
            time.sleep(0.1)

def getResponseBody(response, text=True):
    """
    Returns the response body as a text type or binary string.

    :param response: The response object from the server.
    :param text: If true, treat the data as a text string, otherwise, treat
                 as binary.
    """
    data = '' if text else b''

    for chunk in response.body:
        if text and isinstance(chunk, six.binary_type):
            chunk = chunk.decode('utf8')
        elif not text and not isinstance(chunk, six.binary_type):
            chunk = chunk.encode('utf8')
        data += chunk

    return data

def request(path='/', method='GET', params=None, user=None,
            prefix='/api/v1', isJson=True, basicAuth=None, body=None,
            type=None, exception=False, cookie=None, token=None,
            additionalHeaders=None, useHttps=False,
            authHeader='Girder-Authorization', appPrefix=''):
    """
    Make an HTTP request.

    :param path: The path part of the URI.
    :type path: str
    :param method: The HTTP method.
    :type method: str
    :param params: The HTTP parameters.
    :type params: dict
    :param prefix: The prefix to use before the path.
    :param isJson: Whether the response is a JSON object.
    :param basicAuth: A string to pass with the Authorization: Basic header
                      of the form 'login:password'
    :param exception: Set this to True if a 500 is expected from this call.
    :param cookie: A custom cookie value to set.
    :param token: If you want to use an existing token to login, pass
        the token ID.
    :type token: str
    :param additionalHeaders: A list of headers to add to the
                              request.  Each item is a tuple of the form
                              (header-name, header-value).
    :param useHttps: If True, pretend to use HTTPS.
    :param authHeader: The HTTP request header to use for authentication.
    :type authHeader: str
    :param appPrefix: The CherryPy application prefix (mounted location without trailing slash)
    :type appPrefix: str
    :returns: The cherrypy response object from the request.
    """
    local = cherrypy.lib.httputil.Host('127.0.0.1', 30000)
    remote = cherrypy.lib.httputil.Host('127.0.0.1', 30001)
    headers = [('Host', '127.0.0.1'), ('Accept', 'application/json')]
    qs = fd = None

    if additionalHeaders:
        headers.extend(additionalHeaders)

    if isinstance(body, six.text_type):
        body = body.encode('utf8')

    if params:
        qs = urllib.parse.urlencode(params)

    if params and body:
        # In this case, we are forced to send params in query string
        fd = BytesIO(body)
        headers.append(('Content-Type', type))
        headers.append(('Content-Length', '%d' % len(body)))
    elif method in ['POST', 'PUT', 'PATCH'] or body:
        if type:
            qs = body
        elif params:
            qs = qs.encode('utf8')

        headers.append(('Content-Type', type or 'application/x-www-form-urlencoded'))
        headers.append(('Content-Length', '%d' % len(qs or b'')))
        fd = BytesIO(qs or b'')
        qs = None

    app = cherrypy.tree.apps[appPrefix]
    request, response = app.get_serving(
        local, remote, 'http' if not useHttps else 'https', 'HTTP/1.1')
    request.show_tracebacks = True

    headers = buildHeaders(headers, cookie, user, token, basicAuth, authHeader)

    # Python2 will not match Unicode URLs
    url = str(prefix + path)
    try:
        response = request.run(method, url, qs, 'HTTP/1.1', headers, fd)
    finally:
        if fd:
            fd.close()

    if isJson:
        body = getResponseBody(response)
        try:
            response.json = json.loads(body)
        except ValueError:
            raise AssertionError('Did not receive JSON response')

    if not exception and response.output_status.startswith(b'500'):
        raise AssertionError("Internal server error: %s" %
                             getResponseBody(response))

    return response

def buildHeaders(headers, cookie, user, token, basicAuth, authHeader):
    from girder.models.token import Token

    headers = headers[:]
    if cookie is not None:
        headers.append(('Cookie', cookie))

    if user is not None:
        token = Token().createToken(user)
        headers.append(('Girder-Token', str(token['_id'])))
    elif token is not None:
        if isinstance(token, dict):
            headers.append(('Girder-Token', token['_id']))
        else:
            headers.append(('Girder-Token', token))

    if basicAuth is not None:
        auth = base64.b64encode(basicAuth.encode('utf8'))
        headers.append((authHeader, 'Basic %s' % auth.decode()))

    return headers

def uploadFile(name, contents, user, parent, parentType='folder',
               mimeType=None):
    """
    Upload a file.

    :param name: The name of the file.
    :type name: str
    :param contents: The file contents
    :type contents: str
    :param user: The user performing the upload.
    :type user: dict
    :param parent: The parent document.
    :type parent: dict
    :param parentType: The type of the parent ("folder" or "item")
    :type parentType: str
    :param mimeType: Explicit MIME type to set on the file.
    :type mimeType: str
    :returns: The file that was created.
    :rtype: dict
    """
    mimeType = mimeType or 'application/octet-stream'
    upload = request(path='/file', method='POST', user=user,
                     params={
                         'parentType': parentType,
                         'parentId': str(parent['_id']),
                         'name': name,
                         'size': len(contents),
                         'mimeType': mimeType
                     })

    resp = request(path='/file/chunk', method='POST', user=user,
                   body=contents,
                   params={
                       'uploadId': upload.json['_id'],
                       'offset': 0
                   },
                   type='text/plain')

    return resp.json


text:
Contacts can be accessed from any application that includes the [$.fn.blockstrap.contacts](../../../framework/modules/contacts/) module.

By utilizing this module, the wallet is able to create and manage contacts.

When first creating a new contacts called ___Blockstrap Donations___, information such as the following is added to [localStorage](http://en.wikipedia.org/wiki/Web_storage):

<!--pre-javascript-->
```
{
    id: "blockstrap_donations",
    name: "Blockstrap Donations",
    blockchains: [
        {
            code: "btc",
            blockchain: "Bitcoin",
            addresses: [
                {
                    key: "13uXA8zfLjsnrg69f6FcHVRfwBGobYU3bc"
                }
            ]
        }
    ],
    data: {
        contacts_dnk: false
    },
    tx_to: 0,
    tx_from: 0
}
```
---

Please note that the `id` field is auto-generated base dupon the `name`.

The `blockchain` selection is a parameter of the function and should only allow those supported via configuration. Verified `addresses` can be added to each blockchain. Although the Blockstrap data structure is set-up for multiple addresses within multiple blockchains, the current UX implementation with the default wallet only allows each contact to use a single blockchain / address, unless you are importing contact addresses using the [DNKey](http://dnkey.me) specifications as supported by the Blockstrap API.

The `data` field allows you to assign arbitary information to contacts, such as email addresses or DNKs.

The `tx_to` and `tx_from` fields are not yet supported.

---

1. Related Articles
2. [Back to Wallet](../../wallet/)
3. [Installation](../installation/)
4. [Security](../security/)
5. [Accounts](../accounts/)
6. [Contacts](../contacts/)
7. [Table of Contents](../../../)


text:
Invoke `rbenv alias <name> <version>` to make a symbolic link from `<name>` to
`<version>` in the [rbenv][] versions directory, effectively creating an
alias.  The cool part is that if you pass in a point release as the name, you
can give `--auto` to link to the latest installed patch level.  For example,
`rbenv alias 1.8.7 --auto` will automatically create an alias from `1.8.7` to
`1.8.7-p371` (or whatever the most recent version you have installed is).

Plus, if you're using [ruby-build][], `rbenv install A.B.C-pXXX` automatically
invokes `rbenv alias A.B.C --auto`, so you'll always have up to date aliases
for point releases.

Whether it's a good idea to use these aliases in a `.ruby-version` file, I
cannot say.  I created this plugin to find out.  If your only concern is
having to reinstall gems every time you install a new patch release, check out
[rbenv-communal-gems][].

## Installation

    mkdir -p "$(rbenv root)/plugins"
    git clone git://github.com/tpope/rbenv-aliases.git \
      "$(rbenv root)/plugins/rbenv-aliases"
    rbenv alias --auto

[rbenv]: https://github.com/sstephenson/rbenv
[ruby-build]: https://github.com/sstephenson/ruby-build
[rbenv-communal-gems]: https://github.com/tpope/rbenv-communal-gems


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

@ECHO OFF
IF "%1"=="" Goto Usage
IF "%2"=="" Goto Usage
IF "%3"=="" Goto Usage
IF "%4"=="" Goto Usage
IF "%5"=="" Goto Usage

SET HOST_NAME=%1
SET PORT_NUM=%2
SET DB_NAME=%3
SET _GEOPORTALSCHEMA=%4
SET _USERTOCONNECT=%5
SET _GEOPORTALUSER=%6

:Run

date /t > grants_pg.txt
echo  Running grants_pg.sql ...   >> grants_pg.txt
createuser  -P -R -S -D -h %HOST_NAME% -p %PORT_NUM% -U %_USERTOCONNECT% %_GEOPORTALUSER%   >> grants_pg.txt
psql  -e -h %HOST_NAME% -p %PORT_NUM% -d %DB_NAME% -U %_USERTOCONNECT% -v geoportalschema=%_GEOPORTALSCHEMA% -v geoportaluser=%_GEOPORTALUSER% -v geoportaluserpwd=%_GEOP0RTALUSERPWD% -f grants_pg.sql >> grants_pg.txt
echo  ... All done.   >> grants_pg.txt
start notepad grants_pg.txt

if errorlevel 1 goto Failed

goto END

:Failed
ECHO "Setting grants failed"
ECHO.

:Usage
rem ------------------------------------------
rem Basic Explanation on what this does ...
rem ------------------------------------------
ECHO.
ECHO Usage : grants_pg.cmd [host] [port] [database] [geoportal schema] [database user] [geoportal user]
ECHO Where [host] is the machine name hosting PostgreSQL
ECHO       [port] is the port number of postgreSQL
ECHO       [database] is the database name for the geoportal tables
ECHO       [geoportal schema] is the geoportal schema name
ECHO       [database user] is the user to connect to the database as
ECHO       [geoportal user] is the geoportal user name
ECHO e.g. grants_pg localhost 5432 postgres geoportal postgres geoportal
goto END

:END


text:
Pattern: Use of ternary operator to call `void`

Issue: _

## Description

Ternary operator should be used just on right side of assignment or in return statement and should not be used as an alternative for `if`/`else`.

Examples of **correct** code:
```swift
let result = success ? "Success" : "Fail"

if success {
    askQuestion()
} else {
    exit()
}

var price: Double {
    return hasDiscount ? initialPrice _ discount : initialPrice
}

```
Examples of **incorrect** code:
```swift
success ? askQuestion() : exit()
```


text:
package poisondog.string;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
 * @author Adam Huang <poisondog@gmail.com>
 */
public class URLDecodePath implements StringProcessor {
	private URLDecode mEncode;

	public URLDecodePath() {
		this("utf8");
	}

	public URLDecodePath(String charset) {
		mEncode = new URLDecode(charset);
	}

	@Override
	public String process(String input) throws UnsupportedEncodingException {
		ExtractPath task = new ExtractPath();
		String path = task.process(input);
		StringBuilder builder = new StringBuilder();
		builder.append(input.replace(path, ""));
		for (String str: path.split("/")) {
			builder.append(mEncode.process(str));
			builder.append("/");
		}
		if(!input.endsWith("/"))
			return builder.substring(0, builder.length() - 1);
		return builder.toString();
	}
}


text:
"""
    extensions.py
    ~~~~~~~~~~~
    finance summary crawler
    :copyright: (c) 2015 by Lu Tianchao.
    :license: Apache, see LICENSE for more details.
"""

from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.cache import Cache

db = SQLAlchemy()
cache = Cache(config={'CACHE_TYPE': 'simple'})


text:
class ReloadsController < ApplicationController
  include Equipe::ContentRefresher
  refresh :show, :every => 5.seconds, :check => false

  def show
    @reload = Reload.find(params[:id])
    render :text => '<body></body>'
  end
end


text:
import React from 'react'
import Login from '../containers/Login'
import {Link} from 'react-router-dom'

const Home = (props) =>

        Welcome! Log in below to view your newsfeed, or <Link className="link" to="/signup">click here</Link> to sign up.

      <Login history={props.history}/>

export default Home


text:
import React from 'react'
import sinon from 'sinon'
import {expect} from 'chai'
import {act} from 'react-dom/test-utils'
import {mount} from 'enzyme'
import {Clock} from '../Clock'
const moment = require('moment')

describe('<Clock/>', () => {

  let clock
  let props
  let wrapper
  beforeEach(() => {
    const now = moment()
    props = {
      startedAt: moment(now).valueOf(),
    }
    clock = sinon.useFakeTimers({now: now.valueOf()})
  })

  afterEach(() => {
    clock.restore()
    props = null
    wrapper = null
  })

  it('renders', () => {
    wrapper = mount(<Clock {...props}/>)
    expect(wrapper.find('.wkr-duration__hours').text()).to.be.equal('00')
    expect(wrapper.find('.wkr-duration__minutes').text()).to.be.equal('00')
    expect(wrapper.find('.wkr-duration__seconds').text()).to.be.equal('00')
  })

  it('updates timer', () => {
    wrapper = mount(<Clock {...props}/>)

    // Assume 1.5 seconds have passed
    act(() => { clock.tick(1.5 * 1000) })
    expect(wrapper.find('.wkr-duration__hours').text()).to.be.equal('00')
    expect(wrapper.find('.wkr-duration__minutes').text()).to.be.equal('00')
    expect(wrapper.find('.wkr-duration__seconds').text()).to.be.equal('01')

    // Assume ~2 min have passed
    act(() => { clock.tick(119 * 1000) })
    expect(wrapper.find('.wkr-duration__hours').text()).to.be.equal('00')
    expect(wrapper.find('.wkr-duration__minutes').text()).to.be.equal('02')
    expect(wrapper.find('.wkr-duration__seconds').text()).to.be.equal('00')
  })
})


text:
package btn

import (
	"fmt"

	"github.com/oakmound/oak/v4/render"
)

//Text sets the text of the button to be generated
func Text(s string) Option {
	return func(g Generator) Generator {
		g.TextPtr = nil
		g.TextStringer = nil
		g.Text = s
		return g
	}
}

// TextPtr sets the text of the button to be generated
// to a string pointer.
func TextPtr(s *string) Option {
	return func(g Generator) Generator {
		g.Text = ""
		g.TextStringer = nil
		g.TextPtr = s
		return g
	}
}

// TextStringer sets the text of the generated button to
// use a fmt.Stringer String call
func TextStringer(s fmt.Stringer) Option {
	return func(g Generator) Generator {
		g.Text = ""
		g.TextPtr = nil
		g.TextStringer = s
		return g
	}
}

//Font sets the font for the text of the button to be generated
func Font(f *render.Font) Option {
	return func(g Generator) Generator {
		g.Font = f
		return g
	}
}

//TxtOff sets the text offset  of the button generator from the bottom left
func TxtOff(x, y float64) Option {
	return func(g Generator) Generator {
		g.TxtX = x
		g.TxtY = y
		return g
	}
}

// FitText adjusts a btn's width, given it has text and font defined, to
// be large enough for the given text plus the provided buffer
func FitText(buffer int) Option {
	return func(g Generator) Generator {
		if g.Font != nil && (g.Text != "" || g.TextPtr != nil) {
			measure := g.Text
			if g.TextPtr != nil {
				measure = *g.TextPtr
			}
			w := g.Font.MeasureString(measure)
			wf := float64(w.Ceil() + buffer)
			if g.W < wf {
				g.W = wf
			}
		}
		return g
	}
}


text:
package es.shyri.swagger.android.volley.petstore.full;

import android.app.Application;
import android.test.ApplicationTestCase;

/**
 * Testing Fundamentals
 */
public class ApplicationTest extends ApplicationTestCase<Application> {
    public ApplicationTest() {
        super(Application.class);
    }
}


text:
namespace content {
class WebContents;
}  // namespace content

namespace pdf {

// Delegate for obtaining information from the `extensions::StreamContainer` for
// the PDF viewer. This avoids a dependency on `//extensions/browser`, which
// would be a layering violation.
class PdfStreamDelegate {
 public:
  struct StreamInfo {
    StreamInfo();
    StreamInfo(const StreamInfo&);
    StreamInfo(StreamInfo&&);
    StreamInfo& operator=(const StreamInfo&);
    StreamInfo& operator=(StreamInfo&&);
    ~StreamInfo();

    GURL stream_url;
    GURL original_url;

    // Script to be injected into the internal plugin frame. This should point
    // at an immutable string with static storage duration.
    const std::string* injected_script = nullptr;

    SkColor background_color = SK_ColorTRANSPARENT;
    bool full_frame = false;
    bool allow_javascript = false;
  };

  PdfStreamDelegate();
  PdfStreamDelegate(const PdfStreamDelegate&) = delete;
  PdfStreamDelegate& operator=(const PdfStreamDelegate&) = delete;
  virtual ~PdfStreamDelegate();

  // Maps the incoming stream URL to the original URL. This method should
  // associate a `StreamInfo` with the given `WebContents`, for later retrieval
  // by `GetStreamInfo()`.
  virtual absl::optional<GURL> MapToOriginalUrl(content::WebContents* contents,
                                                const GURL& stream_url);

  // Gets the stream information associated with the given `WebContents`.
  // Returns null if there is no associated stream.
  virtual absl::optional<StreamInfo> GetStreamInfo(
      content::WebContents* contents);
};

}  // namespace pdf

#endif  // COMPONENTS_PDF_BROWSER_PDF_STREAM_DELEGATE_H_


text:
This feature is language-specific.
It occurs with 2 different values: `Bound`, `Short`.

3917 tokens (3%) have a non-empty value of `Variant`.
57 types (0%) occur at least once with a non-empty value of `Variant`.
15 lemmas (0%) occur at least once with a non-empty value of `Variant`.
The feature is used with 1 part-of-speech tags: [sl-pos/PRON]() (3917; 3% instances).

### `PRON`

3917 [sl-pos/PRON]() tokens (56% of all `PRON` tokens) have a non-empty value of `Variant`.

The most frequent other feature values with which `PRON` and `Variant` co-occurred: <tt>PronType=Prs</tt> (3917; 100%), <tt>Gender=EMPTY</tt> (2575; 66%), <tt>Reflex=Yes</tt> (2328; 59%), <tt>Number=EMPTY</tt> (2328; 59%), <tt>Person=EMPTY</tt> (2328; 59%), <tt>Case=EMPTY</tt> (2062; 53%).

`PRON` tokens may have the following values of `Variant`:

* `Bound` (118; 3% of non-empty `Variant`): zanj, zame, zase, nanjo, zanjo, nanj, vanjo, vanj, zanje, name
* `Short` (3799; 97% of non-empty `Variant`): se, ga, jih, si, jo, mu, mi, ji, me, jim

`Variant` seems to be **lexical feature** of `PRON`. 100% lemmas (15) occur only with one value of `Variant`.

--------------------------------------------------------------------------------

## Treebank Statistics (UD_Slovenian-SST)

This feature is language-specific.
It occurs with 2 different values: `Bound`, `Short`.

806 tokens (3%) have a non-empty value of `Variant`.
19 types (0%) occur at least once with a non-empty value of `Variant`.
7 lemmas (0%) occur at least once with a non-empty value of `Variant`.
The feature is used with 1 part-of-speech tags: [sl-pos/PRON]() (806; 3% instances).

### `PRON`

806 [sl-pos/PRON]() tokens (31% of all `PRON` tokens) have a non-empty value of `Variant`.

The most frequent other feature values with which `PRON` and `Variant` co-occurred: <tt>PronType=Prs</tt> (806; 100%), <tt>Gender=EMPTY</tt> (596; 74%), <tt>Number=EMPTY</tt> (447; 55%), <tt>Person=EMPTY</tt> (447; 55%).

`PRON` tokens may have the following values of `Variant`:

* `Bound` (7; 1% of non-empty `Variant`): zanjo, vanj, zame, zanj, zase, zate
* `Short` (799; 99% of non-empty `Variant`): se, mi, ga, jih, si, ti, jo, me, jim, mu