text:
package dotty.tools.dotc
package transform

import core.Phases._
import core.DenotTransformers._
import core.Denotations._
import core.SymDenotations._
import core.Symbols._
import core.Contexts._
import core.Types._
import core.Names._
import core.StdNames._
import core.NameOps._
import core.Decorators._
import core.Constants._
import typer.NoChecking
import typer.ProtoTypes._
import typer.ErrorReporting._
import core.TypeErasure._
import core.Decorators._
import dotty.tools.dotc.ast.{Trees, tpd, untpd}
import ast.Trees._
import scala.collection.mutable.ListBuffer
import dotty.tools.dotc.core.Flags
import ValueClasses._
import TypeUtils._
import ExplicitOuter._
import typer.Mode

class Erasure extends Phase with DenotTransformer { thisTransformer =>

  override def phaseName: String = "erasure"

  /** List of names of phases that should precede this phase */
  override def runsAfter: Set[Class[_ <: Phase]] = Set(classOf[InterceptedMethods], classOf[Splitter], classOf[ElimRepeated])

  def transform(ref: SingleDenotation)(implicit ctx: Context): SingleDenotation = ref match {
    case ref: SymDenotation =>
      assert(ctx.phase == this, s"transforming $ref at ${ctx.phase}")
      if (ref.symbol eq defn.ObjectClass) {
        // Aftre erasure, all former Any members are now Object members
        val ClassInfo(pre, _, ps, decls, selfInfo) = ref.info
        val extendedScope = decls.cloneScope
        defn.AnyClass.classInfo.decls.foreach(extendedScope.enter)
        ref.copySymDenotation(
          info = transformInfo(ref.symbol,
              ClassInfo(pre, defn.ObjectClass, ps, extendedScope, selfInfo))
        )
      }
      else {
        val oldOwner = ref.owner
        val newOwner = if (oldOwner eq defn.AnyClass) defn.ObjectClass else oldOwner
        val oldInfo = ref.info
        val newInfo = transformInfo(ref.symbol, oldInfo)
        val oldFlags = ref.flags
        val newFlags = ref.flags &~ Flags.HasDefaultParams // HasDefaultParams needs to be dropped because overriding might become overloading
        // TODO: define derivedSymDenotation?
        if ((oldOwner eq newOwner) && (oldInfo eq newInfo) && (oldFlags == newFlags)) ref
        else {
          assert(!ref.is(Flags.PackageClass), s"trans $ref @ ${ctx.phase} oldOwner = $oldOwner, newOwner = $newOwner, oldInfo = $oldInfo, newInfo = $newInfo ${oldOwner eq newOwner} ${oldInfo eq newInfo}")
          ref.copySymDenotation(owner = newOwner, initFlags = newFlags, info = newInfo)
        }
      }
    case ref =>
      ref.derivedSingleDenotation(ref.symbol, transformInfo(ref.symbol, ref.info))
  }

  val eraser = new Erasure.Typer

  def run(implicit ctx: Context): Unit = {
    val unit = ctx.compilationUnit
    unit.tpdTree = eraser.typedExpr(unit.tpdTree)(ctx.fresh.setPhase(this.next))
  }

  override def checkPostCondition(tree: tpd.Tree)(implicit ctx: Context) = {
    assertErased(tree)
    tree match {
      case res: tpd.This =>
        assert(!ExplicitOuter.referencesOuter(ctx.owner.enclosingClass, res),
          i"Reference to $res from ${ctx.owner.showLocated}")
      case ret: tpd.Return =>
        // checked only after erasure, as checking before erasure is complicated
        // due presence of type params in returned types
        val from = if (ret.from.isEmpty) ctx.owner.enclosingMethod else ret.from.symbol
        val rType = from.info.finalResultType
        assert(ret.expr.tpe <:< rType,
          i"Returned value:${ret.expr}  does not conform to result type(${ret.expr.tpe.widen} of method $from")
      case _ =>
    }
  }

  /** Assert that tree type and its widened underlying type are erased.
   *  Also assert that term refs have fixed symbols (so we are sure
   *  they need not be reloaded using member; this would likely fail as signatures
   *  may change after erasure).
   */
  def assertErased(tree: tpd.Tree)(implicit ctx: Context): Unit = {
    assertErased(tree.typeOpt, tree)
    if (!defn.isPolymorphicAfterErasure(tree.symbol))
      assertErased(tree.typeOpt.widen, tree)
    if (ctx.mode.isExpr)
      tree.tpe match {
        case ref: TermRef =>
          assert(ref.denot.isInstanceOf[SymDenotation] ||
              ref.denot.isInstanceOf[UniqueRefDenotation],
            i"non-sym type $ref of class ${ref.getClass} with denot of class ${ref.denot.getClass} of $tree")
        case _ =>
      }
  }

  def assertErased(tp: Type, tree: tpd.Tree = tpd.EmptyTree)(implicit ctx: Context): Unit =
    assert(isErasedType(tp), i"The type $tp - ${tp.toString} of class ${tp.getClass} of tree $tree : ${tree.tpe} / ${tree.getClass} is illegal after erasure, phase = ${ctx.phase}")
}

object Erasure extends TypeTestsCasts{

  import tpd._

  object Boxing {

    def isUnbox(sym: Symbol)(implicit ctx: Context) =
      sym.name == nme.unbox && (defn.ScalaValueClasses contains sym.owner.linkedClass)

    def isBox(sym: Symbol)(implicit ctx: Context) =
      sym.name == nme.box && (defn.ScalaValueClasses contains sym.owner.linkedClass)

    def boxMethod(cls: ClassSymbol)(implicit ctx: Context) =
      cls.linkedClass.info.member(nme.box).symbol
    def unboxMethod(cls: ClassSymbol)(implicit ctx: Context) =
      cls.linkedClass.info.member(nme.unbox).symbol

    /** Isf this tree is an unbox operation which can be safely removed
     *  when enclosed in a box, the unboxed argument, otherwise EmptyTree.
     *  Note that one can't always remove a Box(Unbox(x)) combination because the
     *  process of unboxing x may lead to throwing an exception.
     *  This is important for specialization: calls to the super constructor should not box/unbox specialized
     *  fields (see TupleX). (ID)
     */
    private def safelyRemovableUnboxArg(tree: Tree)(implicit ctx: Context): Tree = tree match {
      case Apply(fn, arg :: Nil)
      if isUnbox(fn.symbol) && (defn.ScalaBoxedClasses contains arg.tpe.widen.typeSymbol) =>
        arg
      case _ =>
        EmptyTree
    }

    def constant(tree: Tree, const: Tree)(implicit ctx: Context) =
      if (isPureExpr(tree)) const else Block(tree :: Nil, const)

    final def box(tree: Tree, target: => String = "")(implicit ctx: Context): Tree = ctx.traceIndented(i"boxing ${tree.showSummary}: ${tree.tpe} into $target") {
      tree.tpe.widen match {
        case ErasedValueType(clazz, _) =>
          New(clazz.typeRef, cast(tree, underlyingOfValueClass(clazz)) :: Nil) // todo: use adaptToType?
        case tp =>
          val cls = tp.classSymbol
          if (cls eq defn.UnitClass) constant(tree, ref(defn.BoxedUnit_UNIT))
          else if (cls eq defn.NothingClass) tree // a non-terminating expression doesn't need boxing
          else {
            assert(cls ne defn.ArrayClass)
            val arg = safelyRemovableUnboxArg(tree)
            if (arg.isEmpty) ref(boxMethod(cls.asClass)).appliedTo(tree)
            else {
              ctx.log(s"boxing an unbox: ${tree.symbol} -> ${arg.tpe}")
              arg
            }
          }
      }
    }

    def unbox(tree: Tree, pt: Type)(implicit ctx: Context): Tree = ctx.traceIndented(i"unboxing ${tree.showSummary}: ${tree.tpe} as a $pt") {
      pt match {
        case ErasedValueType(clazz, underlying) =>
          def unboxedTree(t: Tree) =
            adaptToType(t, clazz.typeRef)
            .select(valueClassUnbox(clazz))
            .appliedToNone

          // Null unboxing needs to be treated separately since we cannot call a method on null.
          // "Unboxing" null to underlying is equivalent to doing null.asInstanceOf[underlying]
          // See tests/pos/valueclasses/nullAsInstanceOfVC.scala for cases where this might happen.
          val tree1 =
            if (tree.tpe isRef defn.NullClass)
              adaptToType(tree, underlying)
            else if (!(tree.tpe <:< clazz.typeRef)) {
              assert(!(tree.tpe.typeSymbol.isPrimitiveValueClass))
              val nullTree = Literal(Constant(null))
              val unboxedNull = adaptToType(nullTree, underlying)

              evalOnce(tree) { t =>
                If(t.select(defn.Object_eq).appliedTo(nullTree),
                  unboxedNull,
                  unboxedTree(t))
              }
            } else unboxedTree(tree)

          cast(tree1, pt)
        case _ =>
          val cls = pt.widen.classSymbol
          if (cls eq defn.UnitClass) constant(tree, Literal(Constant(())))
          else {
            assert(cls ne defn.ArrayClass)
            ref(unboxMethod(cls.asClass)).appliedTo(tree)
          }
      }
    }

    /** Generate a synthetic cast operation from tree.tpe to pt.
     *  Does not do any boxing/unboxing (this is handled upstream).
     *  Casts from and to ErasedValueType are special, see the explanation
     *  in ExtensionMethods#transform.
     */
    def cast(tree: Tree, pt: Type)(implicit ctx: Context): Tree = {
      // TODO: The commented out assertion fails for tailcall/t6574.scala
      //       Fix the problem and enable the assertion.
      // assert(!pt.isInstanceOf[SingletonType], pt)
      if (pt isRef defn.UnitClass) unbox(tree, pt)
      else (tree.tpe, pt) match {
        case (JavaArrayType(treeElem), JavaArrayType(ptElem))
        if treeElem.widen.isPrimitiveValueType && !ptElem.isPrimitiveValueType =>
          // See SI-2386 for one example of when this might be necessary.
          cast(ref(defn.runtimeMethod(nme.toObjectArray)).appliedTo(tree), pt)
        case (_, ErasedValueType(cls, _)) =>
          ref(u2evt(cls)).appliedTo(tree)
        case _ =>
          tree.tpe.widen match {
            case ErasedValueType(cls, _) =>
              ref(evt2u(cls)).appliedTo(tree)
            case _ =>
              if (pt.isPrimitiveValueType)
                primitiveConversion(tree, pt.classSymbol)
              else
                tree.asInstance(pt)
          }
      }
    }

    /** Adaptation of an expression `e` to an expected type `PT`, applying the following
     *  rewritings exhaustively as long as the type of `e` is not a subtype of `PT`.
     *
     *    e -> e()           if `e` appears not as the function part of an application
     *    e -> box(e)        if `e` is of erased value type
     *    e -> unbox(e, PT)  otherwise, if `PT` is an erased value type
     *    e -> box(e)        if `e` is of primitive type and `PT` is not a primitive type
     *    e -> unbox(e, PT)  if `PT` is a primitive type and `e` is not of primitive type
     *    e -> cast(e, PT)   otherwise
     */
    def adaptToType(tree: Tree, pt: Type)(implicit ctx: Context): Tree =
      if (pt.isInstanceOf[FunProto]) tree
      else tree.tpe.widen match {
        case MethodType(Nil, _) if tree.isTerm =>
          adaptToType(tree.appliedToNone, pt)
        case tpw =>
          if (pt.isInstanceOf[ProtoType] || tree.tpe <:< pt)
            tree
          else if (tpw.isErasedValueType)
            adaptToType(box(tree), pt)
          else if (pt.isErasedValueType)
            adaptToType(unbox(tree, pt), pt)
          else if (tpw.isPrimitiveValueType && !pt.isPrimitiveValueType)
            adaptToType(box(tree), pt)
          else if (pt.isPrimitiveValueType && !tpw.isPrimitiveValueType)
            adaptToType(unbox(tree, pt), pt)
          else
            cast(tree, pt)
      }
  }

  class Typer extends typer.ReTyper with NoChecking {
    import Boxing._

    def erasedType(tree: untpd.Tree)(implicit ctx: Context): Type = {
      val tp = tree.typeOpt
      if (tree.isTerm) erasedRef(tp) else valueErasure(tp)
    }

    override def promote(tree: untpd.Tree)(implicit ctx: Context): tree.ThisTree[Type] = {
      assert(tree.hasType)
      val erased = erasedType(tree)
      ctx.log(s"promoting ${tree.show}: ${erased.showWithUnderlying()}")
      tree.withType(erased)
    }

    /** When erasing most TypeTrees we should not semi-erase value types.
     *  This is not the case for [[DefDef#tpt]], [[ValDef#tpt]] and [[Typed#tpt]], they
     *  are handled separately by [[typedDefDef]], [[typedValDef]] and [[typedTyped]].
     */
    override def typedTypeTree(tree: untpd.TypeTree, pt: Type)(implicit ctx: Context): TypeTree =
      tree.withType(erasure(tree.tpe))

    /** This override is only needed to semi-erase type ascriptions */
    override def typedTyped(tree: untpd.Typed, pt: Type)(implicit ctx: Context): Tree = {
      val Typed(expr, tpt) = tree
      val tpt1 = promote(tpt)
      val expr1 = typed(expr, tpt1.tpe)
      assignType(untpd.cpy.Typed(tree)(expr1, tpt1), tpt1)
    }

    override def typedLiteral(tree: untpd.Literal)(implicit ctc: Context): Literal =
      if (tree.typeOpt.isRef(defn.UnitClass)) tree.withType(tree.typeOpt)
      else super.typedLiteral(tree)

    /** Type check select nodes, applying the following rewritings exhaustively
     *  on selections `e.m`, where `OT` is the type of the owner of `m` and `ET`
     *  is the erased type of the selection's original qualifier expression.
     *
     *      e.m1 -> e.m2          if `m1` is a member of Any or AnyVal and `m2` is
     *                            the same-named member in Object.
     *      e.m -> box(e).m       if `e` is primitive and `m` is a member or a reference class
     *                            or `e` has an erased value class type.
     *      e.m -> unbox(e).m     if `e` is not primitive and `m` is a member of a primtive type.
     *      e.m -> cast(e, OT).m  if the type of `e` does not conform to OT and `m`
     *                            is not an array operation.
     *
     *  If `m` is an array operation, i.e. one of the members apply, update, length, clone, and
     *  <init> of class Array, we additionally try the following rewritings:
     *
     *      e.m -> runtime.array_m(e)   if ET is Object
     *      e.m -> cast(e, ET).m        if the type of `e` does not conform to ET
     *      e.clone -> e.clone'         where clone' is Object's clone method
     *      e.m -> e.[]m                if `m` is an array operation other than `clone`.
     */
    override def typedSelect(tree: untpd.Select, pt: Type)(implicit ctx: Context): Tree = {
      val sym = tree.symbol
      assert(sym.exists, tree.show)

      def select(qual: Tree, sym: Symbol): Tree = {
        val name = tree.typeOpt match {
          case tp: NamedType if tp.name.isShadowedName => sym.name.shadowedName
          case _ => sym.name
        }
        untpd.cpy.Select(tree)(qual, sym.name)
          .withType(NamedType.withFixedSym(qual.tpe, sym))
      }

      def selectArrayMember(qual: Tree, erasedPre: Type): Tree =
        if (erasedPre isRef defn.ObjectClass)
          runtimeCallWithProtoArgs(tree.name.genericArrayOp, pt, qual)
        else if (!(qual.tpe <:< erasedPre))
          selectArrayMember(cast(qual, erasedPre), erasedPre)
        else
          assignType(untpd.cpy.Select(tree)(qual, tree.name.primitiveArrayOp), qual)

      def adaptIfSuper(qual: Tree): Tree = qual match {
        case Super(thisQual, tpnme.EMPTY) =>
          val SuperType(thisType, supType) = qual.tpe
          if (sym.owner is Flags.Trait)
            cpy.Super(qual)(thisQual, sym.owner.asClass.name)
              .withType(SuperType(thisType, sym.owner.typeRef))
          else
            qual.withType(SuperType(thisType, thisType.firstParent))
        case _ =>
          qual
      }

      def recur(qual: Tree): Tree = {
        val qualIsPrimitive = qual.tpe.widen.isPrimitiveValueType
        val symIsPrimitive = sym.owner.isPrimitiveValueClass
        if ((sym.owner eq defn.AnyClass) || (sym.owner eq defn.AnyValClass)) {
          assert(sym.isConstructor, s"${sym.showLocated}")
          select(qual, defn.ObjectClass.info.decl(sym.name).symbol)
        }
        else if (qualIsPrimitive && !symIsPrimitive || qual.tpe.widenDealias.isErasedValueType)
          recur(box(qual))
        else if (!qualIsPrimitive && symIsPrimitive)
          recur(unbox(qual, sym.owner.typeRef))
        else if (sym.owner eq defn.ArrayClass)
          selectArrayMember(qual, erasure(tree.qualifier.typeOpt.widen.finalResultType))
        else {
          val qual1 = adaptIfSuper(qual)
          if (qual1.tpe.derivesFrom(sym.owner) || qual1.isInstanceOf[Super])
            select(qual1, sym)
          else
            recur(cast(qual1, sym.owner.typeRef))
        }
      }

      recur(typed(tree.qualifier, AnySelectionProto))
    }

    override def typedSelectFromTypeTree(tree: untpd.SelectFromTypeTree, pt: Type)(implicit ctx: Context) =
      untpd.Ident(tree.name).withPos(tree.pos).withType(erasedType(tree))

    override def typedThis(tree: untpd.This)(implicit ctx: Context): Tree =
      if (tree.symbol == ctx.owner.enclosingClass || tree.symbol.isStaticOwner) promote(tree)
      else {
        ctx.log(i"computing outer path from ${ctx.owner.ownersIterator.toList}%, % to ${tree.symbol}, encl class = ${ctx.owner.enclosingClass}")
        outer.path(tree.symbol)
      }

    private def runtimeCallWithProtoArgs(name: Name, pt: Type, args: Tree*)(implicit ctx: Context): Tree = {
      val meth = defn.runtimeMethod(name)
      val followingParams = meth.info.firstParamTypes.drop(args.length)
      val followingArgs = protoArgs(pt).zipWithConserve(followingParams)(typedExpr).asInstanceOf[List[tpd.Tree]]
      ref(defn.runtimeMethod(name)).appliedToArgs(args.toList ++ followingArgs)
    }

    private def protoArgs(pt: Type): List[untpd.Tree] = pt match {
      case pt: FunProto => pt.args ++ protoArgs(pt.resType)
      case _ => Nil
    }

    override def typedTypeApply(tree: untpd.TypeApply, pt: Type)(implicit ctx: Context) = {
      val ntree = interceptTypeApply(tree.asInstanceOf[TypeApply])

      ntree match {
        case TypeApply(fun, args) =>
          val fun1 = typedExpr(fun, WildcardType)
          fun1.tpe.widen match {
            case funTpe: PolyType =>
              val args1 = args.mapconserve(typedType(_))
              untpd.cpy.TypeApply(tree)(fun1, args1).withType(funTpe.instantiate(args1.tpes))
            case _ => fun1
          }
        case _ => typedExpr(ntree, pt)
      }
    }

    override def typedApply(tree: untpd.Apply, pt: Type)(implicit ctx: Context): Tree = {
      val Apply(fun, args) = tree
      if (fun.symbol == defn.dummyApply)
        typedUnadapted(args.head, pt)
      else typedExpr(fun, FunProto(args, pt, this)) match {
        case fun1: Apply => // arguments passed in prototype were already passed
          fun1
        case fun1 =>
          fun1.tpe.widen match {
            case mt: MethodType =>
              val outers = outer.args(fun.asInstanceOf[tpd.Tree]) // can't use fun1 here because its type is already erased
              val args1 = (outers ::: args ++ protoArgs(pt)).zipWithConserve(mt.paramTypes)(typedExpr)
              untpd.cpy.Apply(tree)(fun1, args1) withType mt.resultType
            case _ =>
              throw new MatchError(i"tree $tree has unexpected type of function ${fun1.tpe.widen}, was ${fun.typeOpt.widen}")
          }
      }
    }

    // The following four methods take as the proto-type the erasure of the pre-existing type,
    // if the original proto-type is not a value type.
    // This makes all branches be adapted to the correct type.
    override def typedSeqLiteral(tree: untpd.SeqLiteral, pt: Type)(implicit ctx: Context) =
      super.typedSeqLiteral(tree, erasure(tree.typeOpt))
        // proto type of typed seq literal is original type;

    override def typedIf(tree: untpd.If, pt: Type)(implicit ctx: Context) =
      super.typedIf(tree, adaptProto(tree, pt))

    override def typedMatch(tree: untpd.Match, pt: Type)(implicit ctx: Context) =
      super.typedMatch(tree, adaptProto(tree, pt))

    override def typedTry(tree: untpd.Try, pt: Type)(implicit ctx: Context) =
      super.typedTry(tree, adaptProto(tree, pt))

    private def adaptProto(tree: untpd.Tree, pt: Type)(implicit ctx: Context) = {
      if (pt.isValueType) pt else {
        if (tree.typeOpt.derivesFrom(ctx.definitions.UnitClass))
          tree.typeOpt
        else valueErasure(tree.typeOpt)
      }
    }

    override def typedValDef(vdef: untpd.ValDef, sym: Symbol)(implicit ctx: Context): ValDef =
      super.typedValDef(untpd.cpy.ValDef(vdef)(
        tpt = untpd.TypedSplice(TypeTree(sym.info).withPos(vdef.tpt.pos))), sym)

    override def typedDefDef(ddef: untpd.DefDef, sym: Symbol)(implicit ctx: Context) = {
      var effectiveSym = sym
      if (sym == defn.newRefArrayMethod) {
        // newRefArray is treated specially: It's the only source-defined method
        // that has a polymorphic type after erasure. But treating its (dummy) definition
        // with a polymorphic type at and after erasure is an awkward special case.
        // We therefore rewrite the method definition with a new Symbol of type
        // (length: Int)Object
        val MethodType(pnames, ptypes) = sym.info.resultType
        effectiveSym = sym.copy(info = MethodType(pnames, ptypes, defn.ObjectType))
      }
      val restpe =
        if (effectiveSym.isConstructor) defn.UnitType
        else effectiveSym.info.resultType
      val ddef1 = untpd.cpy.DefDef(ddef)(
        tparams = Nil,
        vparamss = (outer.paramDefs(effectiveSym) ::: ddef.vparamss.flatten) :: Nil,
        tpt = untpd.TypedSplice(TypeTree(restpe).withPos(ddef.tpt.pos)),
        rhs = ddef.rhs match {
          case id @ Ident(nme.WILDCARD) => untpd.TypedSplice(id.withType(restpe))
          case _ => ddef.rhs
        })
      super.typedDefDef(ddef1, effectiveSym)
    }

    /** After erasure, we may have to replace the closure method by a bridge.
     *  LambdaMetaFactory handles this automatically for most types, but we have
     *  to deal with boxing and unboxing of value classes ourselves.
     */
    override def typedClosure(tree: untpd.Closure, pt: Type)(implicit ctx: Context) = {
      val implClosure @ Closure(_, meth, _) = super.typedClosure(tree, pt)
      implClosure.tpe match {
        case SAMType(sam) =>
          val implType = meth.tpe.widen

          val List(implParamTypes) = implType.paramTypess
          val List(samParamTypes) = sam.info.paramTypess
          val implResultType = implType.resultType
          val samResultType = sam.info.resultType

          // Given a value class V with an underlying type U, the following code:
          //   val f: Function1[V, V] = x => ...
          // results in the creation of a closure and a method:
          //   def $anonfun(v1: V): V = ...
          //   val f: Function1[V, V] = closure($anonfun)
          // After [[Erasure]] this method will look like:
          //   def $anonfun(v1: ErasedValueType(V, U)): ErasedValueType(V, U) = ...
          // And after [[ElimErasedValueType]] it will look like:
          //   def $anonfun(v1: U): U = ...
          // This method does not implement the SAM of Function1[V, V] anymore and
          // needs to be replaced by a bridge:
          //   def $anonfun$2(v1: V): V = new V($anonfun(v1.underlying))
          //   val f: Function1 = closure($anonfun$2)
          // In general, a bridge is needed when the signature of the closure method after
          // Erasure contains an ErasedValueType but the corresponding type in the functional
          // interface is not an ErasedValueType.
          val bridgeNeeded =
            (implResultType :: implParamTypes, samResultType :: samParamTypes).zipped.exists(
              (implType, samType) => implType.isErasedValueType && !samType.isErasedValueType
            )

          if (bridgeNeeded) {
            val bridge = ctx.newSymbol(ctx.owner, nme.ANON_FUN, Flags.Synthetic | Flags.Method, sam.info)
            val bridgeCtx = ctx.withOwner(bridge)
            Closure(bridge, bridgeParamss => {
              implicit val ctx: Context = bridgeCtx

              val List(bridgeParams) = bridgeParamss
              val rhs = Apply(meth, (bridgeParams, implParamTypes).zipped.map(adapt(_, _)))
              adapt(rhs, sam.info.resultType)
            })
          } else implClosure
        case _ =>
          implClosure
      }
    }

    override def typedTypeDef(tdef: untpd.TypeDef, sym: Symbol)(implicit ctx: Context) =
      EmptyTree

    override def typedStats(stats: List[untpd.Tree], exprOwner: Symbol)(implicit ctx: Context): List[Tree] = {
      val stats1 = Trees.flatten(super.typedStats(stats, exprOwner))
      if (ctx.owner.isClass) stats1 ::: addBridges(stats, stats1)(ctx) else stats1
    }

    // this implementation doesn't check for bridge clashes with value types!
    def addBridges(oldStats: List[untpd.Tree], newStats: List[tpd.Tree])(implicit ctx: Context): List[tpd.Tree] = {
      val beforeCtx = ctx.withPhase(ctx.erasurePhase)
      def traverse(after: List[Tree], before: List[untpd.Tree],
                   emittedBridges: ListBuffer[tpd.DefDef] = ListBuffer[tpd.DefDef]()): List[tpd.DefDef] = {
        after match {
          case Nil => emittedBridges.toList
          case (member: DefDef) :: newTail =>
            before match {
              case Nil => emittedBridges.toList
              case (oldMember: untpd.DefDef) :: oldTail =>
                val oldSymbol = oldMember.symbol(beforeCtx)
                val newSymbol = member.symbol(ctx)
                assert(oldSymbol.name(beforeCtx) == newSymbol.name,
                  s"${oldSymbol.name(beforeCtx)} bridging with ${newSymbol.name}")
                val newOverridden = oldSymbol.denot.allOverriddenSymbols.toSet // TODO: clarify new <-> old in a comment; symbols are swapped here
                val oldOverridden = newSymbol.allOverriddenSymbols(beforeCtx).toSet // TODO: can we find a more efficient impl? newOverridden does not have to be a set!
                def stillInBaseClass(sym: Symbol) = ctx.owner derivesFrom sym.owner
                val neededBridges = (oldOverridden -- newOverridden).filter(stillInBaseClass)

                var minimalSet = Set[Symbol]()
                // compute minimal set of bridges that are needed:
                for (bridge <- neededBridges) {
                  val isRequired = minimalSet.forall(nxtBridge => !(bridge.info =:= nxtBridge.info))

                  if (isRequired) {
                    // check for clashes
                    val clash: Option[Symbol] = oldSymbol.owner.info.decls.lookupAll(bridge.name).find {
                      sym =>
                        (sym.name eq bridge.name) && sym.info.widen =:= bridge.info.widen
                    }.orElse(
                        emittedBridges.find(stat => (stat.name == bridge.name) && stat.tpe.widen =:= bridge.info.widen)
                          .map(_.symbol)
                      )
                    clash match {
                      case Some(cl) =>
                        ctx.error(i"bridge for method ${newSymbol.showLocated(beforeCtx)} of type ${newSymbol.info(beforeCtx)}\n" +
                          i"clashes with ${cl.symbol.showLocated(beforeCtx)} of type ${cl.symbol.info(beforeCtx)}\n" +
                          i"both have same type after erasure: ${bridge.symbol.info}")
                      case None => minimalSet += bridge
                    }
                  }
                }

                val bridgeImplementations = minimalSet.map {
                  sym => makeBridgeDef(member, sym)(ctx)
                }
                emittedBridges ++= bridgeImplementations
                traverse(newTail, oldTail, emittedBridges)
              case notADefDef :: oldTail =>
                traverse(after, oldTail, emittedBridges)
            }
          case notADefDef :: newTail =>
            traverse(newTail, before, emittedBridges)
        }
      }

      traverse(newStats, oldStats)
    }

    private final val NoBridgeFlags = Flags.Accessor | Flags.Deferred | Flags.Lazy

    /** Create a bridge DefDef which overrides a parent method.
     *
     *  @param newDef     The DefDef which needs bridging because its signature
     *                    does not match the parent method signature
     *  @param parentSym  A symbol corresponding to the parent method to override
     *  @return           A new DefDef whose signature matches the parent method
     *                    and whose body only contains a call to newDef
     */
    def makeBridgeDef(newDef: tpd.DefDef, parentSym: Symbol)(implicit ctx: Context): tpd.DefDef = {
      val newDefSym = newDef.symbol
      val currentClass = newDefSym.owner.asClass

      def error(reason: String) = {
        assert(false, s"failure creating bridge from ${newDefSym} to ${parentSym}, reason: $reason")
        ???
      }
      var excluded = NoBridgeFlags
      if (!newDefSym.is(Flags.Protected)) excluded |= Flags.Protected // needed to avoid "weaker access" assertion failures in expandPrivate
      val bridge = ctx.newSymbol(currentClass,
        parentSym.name, parentSym.flags &~ excluded | Flags.Bridge, parentSym.info, coord = newDefSym.owner.coord).asTerm
      bridge.enteredAfter(ctx.phase.prev.asInstanceOf[DenotTransformer]) // this should be safe, as we're executing in context of next phase
      ctx.debuglog(s"generating bridge from ${newDefSym} to $bridge")

      val sel: Tree = This(currentClass).select(newDefSym.termRef)

      val resultType = parentSym.info.widen.resultType

      val bridgeCtx = ctx.withOwner(bridge)

      tpd.DefDef(bridge, { paramss: List[List[tpd.Tree]] =>
          implicit val ctx: Context = bridgeCtx

          val rhs = paramss.foldLeft(sel)((fun, vparams) =>
            fun.tpe.widen match {
              case MethodType(names, types) => Apply(fun, (vparams, types).zipped.map(adapt(_, _, untpd.EmptyTree)))
              case a => error(s"can not resolve apply type $a")

            })
          adapt(rhs, resultType)
      })
    }

    override def adapt(tree: Tree, pt: Type, original: untpd.Tree)(implicit ctx: Context): Tree =
      ctx.traceIndented(i"adapting ${tree.showSummary}: ${tree.tpe} to $pt", show = true) {
        assert(ctx.phase == ctx.erasurePhase.next, ctx.phase)
        if (tree.isEmpty) tree
        else if (ctx.mode is Mode.Pattern) tree // TODO: replace with assertion once pattern matcher is active
        else adaptToType(tree, pt)
      }
  }
}


text:
package silhouette.authenticator

import cats.effect.{ Async, Sync }
import com.typesafe.scalalogging.LazyLogging
import javax.inject.Inject
import silhouette._
import silhouette.authenticator.AuthenticatorProvider._
import silhouette.http.{ RequestPipeline, ResponsePipeline }
import silhouette.provider.RequestProvider

/**
 * A request provider implementation that supports authentication with an [[Authenticator]].
 *
 * @param authenticationPipeline The authentication pipeline which transforms a request into an [[AuthState]].
 * @param targetPipeline         The target pipeline which writes an [[Authenticator]] to the [[http.ResponsePipeline]].
 * @tparam F The type of the IO monad.
 * @tparam R The type of the request.
 * @tparam P The type of the response.
 * @tparam I The type of the identity.
 */
class AuthenticatorProvider[F[_]: Async, R, P, I <: Identity] @Inject() (
  authenticationPipeline: AuthenticationPipeline[F, RequestPipeline[R], I],
  targetPipeline: TargetPipeline[F, ResponsePipeline[P]]
) extends RequestProvider[F, R, P, I]
    with LazyLogging {

  /**
   * The type of the credentials.
   */
  override type C = Authenticator

  /**
   * Gets the provider ID.
   *
   * @return The provider ID.
   */
  override def id: String = ID

  /**
   * Authenticates an identity based on an [[Authenticator]] sent in a request.
   *
   * @param request The request pipeline.
   * @param handler A function that returns a [[http.ResponsePipeline]] for the given [[AuthState]].
   * @return The [[http.ResponsePipeline]].
   */
  override def authenticate(request: RequestPipeline[R])(handler: AuthStateHandler): F[ResponsePipeline[P]] =
    Async[F].flatMap(authenticationPipeline(request)) {
      case authState @ Authenticated(_, authenticator, _) =>
        Sync[F].flatMap(handler(authState))(targetPipeline(authenticator, _))
      case authState =>
        handler(authState)
    }
}

/**
 * The companion object.
 */
object AuthenticatorProvider {

  /**
   * The provider constants.
   */
  val ID = "authenticator"
}

redpajama_set_name: RedPajamaGithub


text:
require_relative '../../version2_0'
require_relative '../../relationship'

module BELParser
  module Language
    module Version2_0
      module Relationships
        # Analogous:  +A analogous B+ -  For terms A and B, +A analogousTo
        # B+ indicates that A and B represent abundances or molecular
        # activities in different species which function in a similar
        # manner.
        class Analogous
          extend Relationship

          SHORT       = :analogous
          LONG        = :analogous
          DESCRIPTION = ' +A analogous B+ -  For terms A and B, +A
          nalogousTo B+ indicates that A and B represent
          bundances or molecular activities in different
          pecies which function in a similar manner.'.freeze

          def self.short
            SHORT
          end

          def self.long
            LONG
          end

          def self.description
            DESCRIPTION
          end

          def self.deprecated?
            true
          end

          def self.genomic?
            true
          end
        end
      end
    end
  end
end


text:
This is the content and builder for the Piazza documentation in both HTML and PDF.

## Conventions for doc writers

Linking:

- For hyperlinks within the pz-docs system, always use relative links. Do not include "spaces" or domain names.
- For links within "our" deployment domains, e.g. to pz-swagger, use venicegeo.io (the prod deployment).

## Building & Installing

The delivery method for this documentation is a static html site. We use mkdocs to generate the HTML from the markdown documents contained in this repo.

As a developer, you don't _need_ to generate these HTML files yourself, unless
you'd like to preview your work. Here's how to do it:

#### HOWTO for Unixy (GNU is not UNIX!) people:

Mkdocs is a Python based HTML generator that takes markdown syntax formatted text-files and creates the "site" that displays the documentation.

If you're using a posix compliant operating system, you likely already have Python
installed. For more detailed installation instructions.

*MacOS*
Either use pip:

`$ pip install mkdocs`

or use homebrew: `$ brew install mkdocs`

*Linux*

It's highly recommended to use a virtualenv. This helps isolate your Python install and modules from your system. Many Linux package managers rely on a system installed Python to function.

Use your package manager to install virtualenv:

`$ sudo dnf -y install python-virtualenv`

Create a new virtualenv:

`$ virtualenv ~/.venv/mkdocs`

Activate the new virtualenv:

`$ source ~/.venv/mkdocs/bin/activate`

Use pip to install mkdocs:

`$ pip install mkdocs`

*Use Anaconda*

You can avoid pip issues, and the need to install *anything* as root as well as
 the virtualenv steps and just use anaconda.

Install Anaconda for your
operating system.

Create a new environment:

`$ conda create --name pz-docs`

Activate the environment:

`$ source activate pz-docs`

Add the conda-forge channel because that's where mkdocs is:

`$ conda config --add channels conda-forge`

Install mkdocs:

`$ conda install mkdocs`

#### HOWTO for Windows people:

Install anaconda for windows.

Just like the linux instructions, create and activate a new environment:

`$ conda create --name pz-docs`

Activate the environment:

`$ source activate pz-docs`

Add the conda-forge channel because that's where mkdocs is:

`$ conda config --add channels conda-forge`

Install mkdocs:

`$ conda install mkdocs`

### Building with mkdocs

Once you've got mkdocs installed, you can build the static site from the source
markdown documentation:

From within this `pz-docs` directory:

`$ mkdocs build`

You can view your created site under `site/`

####Using standalone VM with Vagrant to generate static pages:
For this download and install Oracle VM VirtualBox Manager, and VAGRANT.
Then navigate to pz-docs\config and run cmd: vagrant up mkdocbox
The Ubuntu VM will do all of it for you. You can putty to the box at: 192.168.44.44:22 to see the pages.


text:
'use strict';

import { isNumber } from '@emmetio/stream-reader-utils';

const ASTERISK = 42; // *

/**
 * Consumes node repeat token from current stream position and returns its
 * parsed value
 * @param  {StringReader} stream
 * @return {Object}
 */
export default function(stream) {
	if (stream.eat(ASTERISK)) {
		stream.start = stream.pos;

		// XXX think about extending repeat syntax with through numbering
		return { count: stream.eatWhile(isNumber) ? +stream.current() : null };
	}
}


text:
{-# LANGUAGE FlexibleContexts #-}

module Propellor.Property.Postfix where

import Propellor.Base
import qualified Propellor.Property.Apt as Apt
import qualified Propellor.Property.File as File
import qualified Propellor.Property.Service as Service
import qualified Propellor.Property.User as User

import qualified Data.Map as M
import Data.List
import Data.Char

installed :: Property NoInfo
installed = Apt.serviceInstalledRunning "postfix"

restarted :: Property NoInfo
restarted = Service.restarted "postfix"

reloaded :: Property NoInfo
reloaded = Service.reloaded "postfix"

-- | Configures postfix as a satellite system, which
-- relays all mail through a relay host, which defaults to smtp.domain,
-- but can be changed by @mainCf "relayhost"@.
--
-- The smarthost may refuse to relay mail on to other domains, without
-- further configuration/keys. But this should be enough to get cron job
-- mail flowing to a place where it will be seen.
satellite :: Property NoInfo
satellite = check (not <$> mainCfIsSet "relayhost") setup
	`requires` installed
  where
	setup = trivial $ property "postfix satellite system" $ do
		hn <- asks hostName
		let (_, domain) = separate (== '.') hn
		ensureProperties
			[ Apt.reConfigure "postfix"
				[ ("postfix/main_mailer_type", "select", "Satellite system")
				, ("postfix/root_address", "string", "root")
				, ("postfix/destinations", "string", "localhost")
				, ("postfix/mailname", "string", hn)
				]
			, mainCf ("relayhost", "smtp." ++ domain)
				`onChange` reloaded
			]

-- | Sets up a file by running a property (which the filename is passed
-- to). If the setup property makes a change, postmap will be run on the
-- file, and postfix will be reloaded.
mappedFile
	:: Combines (Property x) (Property NoInfo)
	=> FilePath
	-> (FilePath -> Property x)
	-> Property (CInfo x NoInfo)
mappedFile f setup = setup f
	`onChange` cmdProperty "postmap" [f]

-- | Run newaliases command, which should be done after changing
-- @/etc/aliases@.
newaliases :: Property NoInfo
newaliases = trivial $ cmdProperty "newaliases" []

-- | The main config file for postfix.
mainCfFile :: FilePath
mainCfFile = "/etc/postfix/main.cf"

-- | Sets a main.cf @name=value@ pair. Does not reload postfix immediately.
mainCf :: (String, String) -> Property NoInfo
mainCf (name, value) = check notset set
		`describe` ("postfix main.cf " ++ setting)
  where
	setting = name ++ "=" ++ value
	notset = (/= Just value) <$> getMainCf name
	set = cmdProperty "postconf" ["-e", setting]

-- | Gets a main.cf setting.
getMainCf :: String -> IO (Maybe String)
getMainCf name = parse . lines <$> readProcess "postconf" [name]
  where
	parse (l:_) = Just $
		case separate (== '=') l of
			(_, (' ':v)) -> v
			(_, v) -> v
	parse [] = Nothing

-- | Checks if a main.cf field is set. A field that is set to
-- the empty string is considered not set.
mainCfIsSet :: String -> IO Bool
mainCfIsSet name = do
	v <- getMainCf name
	return $ v /= Nothing && v /= Just ""

-- | Parses main.cf, and removes any initial configuration lines that are
-- overridden to other values later in the file.
--
-- For example, to add some settings, removing any old settings:
--
-- > mainCf `File.containsLines`
-- >	[ "# I like bars."
-- >	, "foo = bar"
-- >	] `onChange` dedupMainCf
--
-- Note that multiline configurations that continue onto the next line
-- are not currently supported.
dedupMainCf :: Property NoInfo
dedupMainCf = File.fileProperty "postfix main.cf dedupped" dedupCf mainCfFile

dedupCf :: [String] -> [String]
dedupCf ls =
	let parsed = map parse ls
	in dedup [] (keycounts $ rights parsed) parsed
  where
	parse l
		| "#" `isPrefixOf` l = Left l
		| "=" `isInfixOf` l =
			let (k, v) = separate (== '=') l
			in Right ((filter (not . isSpace) k), v)
		| otherwise = Left l
	fmt k v = k ++ " =" ++ v

	keycounts = M.fromListWith (+) . map (\(k, _v) -> (k, (1 :: Integer)))

	dedup c _ [] = reverse c
	dedup c kc ((Left v):rest) = dedup (v:c) kc rest
	dedup c kc ((Right (k, v)):rest) = case M.lookup k kc of
		Just n | n > 1 -> dedup c (M.insert k (n - 1) kc) rest
		_ -> dedup (fmt k v:c) kc rest

-- | Installs saslauthd and configures it for postfix, authenticating
-- against PAM.
--
-- Does not configure postfix to use it; eg @smtpd_sasl_auth_enable = yes@
-- needs to be set to enable use. See
-- <https://wiki.debian.org/PostfixAndSASL>.
saslAuthdInstalled :: Property NoInfo
saslAuthdInstalled = setupdaemon
	`requires` Service.running "saslauthd"
	`requires` postfixgroup
	`requires` dirperm
	`requires` Apt.installed ["sasl2-bin"]
	`requires` smtpdconf
  where
	setupdaemon = "/etc/default/saslauthd" `File.containsLines`
		[ "START=yes"
		, "OPTIONS=\"-c -m " ++ dir ++ "\""
		]
		`onChange` Service.restarted "saslauthd"
	smtpdconf = "/etc/postfix/sasl/smtpd.conf" `File.containsLines`
		[ "pwcheck_method: saslauthd"
		, "mech_list: PLAIN LOGIN"
		]
	dirperm = check (not <$> doesDirectoryExist dir) $
		cmdProperty "dpkg-statoverride"
			[ "--add", "root", "sasl", "710", dir ]
	postfixgroup = (User "postfix") `User.hasGroup` (Group "sasl")
		`onChange` restarted
	dir = "/var/spool/postfix/var/run/saslauthd"


text:
@interface PodsDummy_ALNetwork : NSObject
@end
@implementation PodsDummy_ALNetwork
@end


text:
import os

from fabric.api import env, local, prefix, put, run

CSIL_USERNAME = os.getenv('CSIL_USERNAME', '')
if not CSIL_USERNAME:
    CSIL_USERNAME = raw_input('CSIL USERNAME: ')

base_path = os.path.dirname(os.path.abspath(__file__))
env.gateway = '{}@cmpt470.csil.sfu.ca'.format(CSIL_USERNAME)
env.hosts = ['feeder@mx4']
env.password = 'qwerty123'

def deploy():
    local('py.test')
    put(base_path, '~/')
    with prefix('source .virtualenvs/feeder/bin/activate'):
        run('pip install --upgrade -r project/requirements.txt')

def restart():
    put(os.path.join(base_path, 'deploy'), '~/project')
    with prefix('[ ! -e /tmp/supervisor.sock ] || exit 0'):
        run('supervisord -c ~/project/deploy/feeder_supervisor.conf')
    run('supervisorctl -c ~/project/deploy/feeder_supervisor.conf reload')


text:
<?php

namespace Paymill\Models\Response;

/**
 * Subscription Model
 * Subscriptions allow you to charge recurring payments on a client's credit card / to a client's direct debit.
 * A subscription connects a client to the offers-object. A client can have several subscriptions to different offers,
 * but only one subscription to the same offer.
 * @tutorial https://paymill.com/de-de/dokumentation/referenz/api-referenz/#document-subscriptions
 */
class Subscription extends Base
{
    /**
     * @var \Paymill\Models\Response\Offer
     */
    private $_offer;

    /**
     * @var boolean
     */
    private $_livemode;

    /**
     * @var integer
     */
    private $_trialStart;

    /**
     * @var integer
     */
    private $_trialEnd;

    /**
     * @var integer
     */
    private $_nextCaptureAt;

    /**
     * @var integer
     */
    private $_canceledAt;

    /**
     * @var \Paymill\Models\Response\Payment
     */
    private $_payment;

    /**
     * @var \Paymill\Models\Response\Client
     */
    private $_client;

    /**
     * @var integer
     */
    private $_startAt;

    /**
     * @var boolean
     */
    private $_isCanceled;

    /**
     * @var boolean
     */
    private $_isDeleted;

    /**
     * @var string
     */
    private $_status;

    /**
     * @var string
     */
    private $_periodOfValidity;

    /**
     * @var int
     */
    private $_amountChangeType;

    /**
     * @var int
     */
    private $_offerChangeType;

    /**
     * Returns the model of the offer the subscription is based on
     * @return \Paymill\Models\Response\Offer
     */
    public function getOffer()
    {
        return $this->_offer;
    }

    /**
     * Sets the model of the offer the subscription is based on
     * @param \Paymill\Models\Response\Offer $offer
     * @return \Paymill\Models\Response\Subscription
     */
    public function setOffer($offer)
    {
        $this->_offer = $offer;
        return $this;
    }

    /**
     * Returns the flag determining whether this subscription was issued while being in live mode or not.
     * @return boolean
     */
    public function getLivemode()
    {
        return $this->_livemode;
    }

    /**
     * Sets the flag determining whether this subscription was issued while being in live mode or not.
     * @param string $livemode
     * @return \Paymill\Models\Response\Subscription
     */
    public function setLivemode($livemode)
    {
        $this->_livemode = $livemode;
        return $this;
    }

    /**
     * Returns the Unix-Timestamp for the trial period start
     * @return integer
     */
    public function getTrialStart()
    {
        return $this->_trialStart;
    }

    /**
     * Sets the Unix-Timestamp for the trial period start
     * @param integer $trialStart
     * @return \Paymill\Models\Response\Subscription
     */
    public function setTrialStart($trialStart)
    {
        $this->_trialStart = $trialStart;
        return $this;
    }

    /**
     * Returns the Unix-Timestamp for the trial period end.
     * @return integer
     */
    public function getTrialEnd()
    {
        return $this->_trialEnd;
    }

    /**
     * Sets the Unix-Timestamp for the trial period end.
     * @param integer $trialEnd
     * @return \Paymill\Models\Response\Subscription
     */
    public function setTrialEnd($trialEnd)
    {
        $this->_trialEnd = $trialEnd;
        return $this;
    }

    /**
     * Returns the Unix-Timestamp for the next charge.
     * @return integer
     */
    public function getNextCaptureAt()
    {
        return $this->_nextCaptureAt;
    }

    /**
     * Sets the Unix-Timestamp for the next charge.
     * @param integer $nextCaptureAt
     * @return \Paymill\Models\Response\Subscription
     */
    public function setNextCaptureAt($nextCaptureAt)
    {
        $this->_nextCaptureAt = $nextCaptureAt;
        return $this;
    }

    /**
     * Returns the Unix-Timestamp for the cancel date.
     * @return integer
     */
    public function getCanceledAt()
    {
        return $this->_canceledAt;
    }

    /**
     * Sets the Unix-Timestamp for the cancel date.
     * @param integer $canceledAt
     * @return \Paymill\Models\Response\Subscription
     */
    public function setCanceledAt($canceledAt)
    {
        $this->_canceledAt = $canceledAt;
        return $this;
    }

    /**
     * Returns the payment object registered with this subscription
     * @return \Paymill\Models\Response\Payment
     */
    public function getPayment()
    {
        return $this->_payment;
    }

    /**
     * Sets the payment object registered with this subscription
     * @param \Paymill\Models\Response\Payment $payment
     * @return \Paymill\Models\Response\Subscription
     */
    public function setPayment($payment)
    {
        $this->_payment = $payment;
        return $this;
    }

    /**
     * Returns the client associated with this subscription
     * @return \Paymill\Models\Response\Client
     */
    public function getClient()
    {
        return $this->_client;
    }

    /**
     * Sets the client associated with this subscription
     * @param \Paymill\Models\Response\Client $client
     * @return \Paymill\Models\Response\Subscription
     */
    public function setClient($client)
    {
        $this->_client = $client;
        return $this;
    }

    /**
     * Returns the Unix-Timestamp for the trial period start
     * @return integer
     */
    public function getStartAt()
    {
        return $this->_startAt;
    }

    /**
     * Sets the Unix-Timestamp for the trial period start
     * @param integer $startAt
     * @return \Paymill\Models\Response\Subscription
     */
    public function setStartAt($startAt)
    {
        $this->_startAt = $startAt;
        return $this;
    }

    /**
     * (un)cancel subscription
     * @param boolean $canceled
     * @return \Paymill\Models\Response\Subscription
     */
    public function setIsCanceled($canceled)
    {
        $this->_isCanceled = $canceled;
        return $this;
    }

    /**
     * Returns whether subscription is canceled or not
     * @return boolean
     */
    public function getIsCanceled()
    {
        return $this->_isCanceled;

    }

    /**
     * (un)delete subscription
     * @param boolean $deleted
     * @return \Paymill\Models\Response\Subscription
     */
    public function setIsDeleted($deleted)
    {
        $this->_isDeleted = $deleted;
        return $this;
    }

    /**
     * Returns whether subscription is deleted or not
     * @return boolean
     */
    public function getIsDeleted()
    {
        return $this->_isDeleted;
    }

    /**
     * Sets the status of subscription
     * @param string $status
     * @return \Paymill\Models\Response\Subscription
     */
    public function setStatus($status)
    {
        $this->_status = $status;
        return $this;
    }

    /**
     * Returns subscription status
     * @return string
     */
    public function getStatus()
    {
        return $this->_status;
    }

    /**
     * Set the period of time the subscription shall be active/valid (starting creation date)
     * @param $perdiodOfValidity
     * @return \Paymill\Models\Response\Subscription
     */
    public function setPeriodOfValidity($periodOfValidity)
    {
        $this->_periodOfValidity = $periodOfValidity;
        return $this;
    }

    /**
     * Returns the period of time the subscriptions is valid (starting creation date)
     * @return string
     */
    public function getPeriodOfValidity()
    {
        return $this->_periodOfValidity;
    }

    /**
     * Set amount change type
     *
     * @param $amountChangeType
     * @return $this
     */
    public function setAmountChangeType($amountChangeType)
    {
        $this->_amountChangeType = $amountChangeType;
        return $this;
    }

    /**
     * Return amount change type
     * @return int
     */
    public function getAmountChangeType()
    {
        return $this->_amountChangeType;
    }

    /**
     * Set offer change type
     * @param $offerChangeType
     *
     * @return $this
     */
    public function setOfferChangeType($offerChangeType)
    {
        $this->_offerChangeType;
        return $this;
    }

    /**
     * Return offer change type
     * @return int
     */
    public function getOfferChangeType()
    {
        return $this->_offerChangeType;
    }

}


text:
package me.androidbox.busbybaking.recipieslist;

import android.content.Context;

import me.androidbox.busbybaking.model.Recipe;

/**
 * Created by steve on 6/10/17.
 */

public interface RecipeItemClickListener {
    void onRecipeItemClick(Recipe recipe, Context context);
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.1
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace XamlGeneratedNamespace {

    /// <summary>
    /// GeneratedInternalTypeHelper
    /// </summary>
    [System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
    public sealed class GeneratedInternalTypeHelper : System.Windows.Markup.InternalTypeHelper {

        /// <summary>
        /// CreateInstance
        /// </summary>
        protected override object CreateInstance(System.Type type, System.Globalization.CultureInfo culture) {
            return System.Activator.CreateInstance(type, ((System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic)
                            | (System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.CreateInstance)), null, null, culture);
        }

        /// <summary>
        /// GetPropertyValue
        /// </summary>
        protected override object GetPropertyValue(System.Reflection.PropertyInfo propertyInfo, object target, System.Globalization.CultureInfo culture) {
            return propertyInfo.GetValue(target, System.Reflection.BindingFlags.Default, null, null, culture);
        }

        /// <summary>
        /// SetPropertyValue
        /// </summary>
        protected override void SetPropertyValue(System.Reflection.PropertyInfo propertyInfo, object target, object value, System.Globalization.CultureInfo culture) {
            propertyInfo.SetValue(target, value, System.Reflection.BindingFlags.Default, null, null, culture);
        }

        /// <summary>
        /// CreateDelegate
        /// </summary>
        protected override System.Delegate CreateDelegate(System.Type delegateType, object target, string handler) {
            return ((System.Delegate)(target.GetType().InvokeMember("_CreateDelegate", (System.Reflection.BindingFlags.InvokeMethod
                            | (System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)), null, target, new object[] {
                        delegateType,
                        handler}, null)));
        }

        /// <summary>
        /// AddEventHandler
        /// </summary>
        protected override void AddEventHandler(System.Reflection.EventInfo eventInfo, object target, System.Delegate handler) {
            eventInfo.AddEventHandler(target, handler);
        }
    }
}


text:
import provide from 'autotrack/lib/provide';
import {
  parseUrl
} from 'dom-utils';

class TrackThisOpenExternalInTab {
  constructor() {
    const links = document.querySelectorAll('a[href]');
    links.forEach((link) => {
      const linkUrl = parseUrl(link.getAttribute('href'));
      if (linkUrl.host !== location.host) {
        link.setAttribute('rel', 'external');
        link.setAttribute('target', '_blank');
      }
    });
  }
}

provide('trackThisOpenExternalInTab', TrackThisOpenExternalInTab);


text:
export const simple = `
class myComponent extends React.Component {

    state = {
      open: true
    };

    render() {
        const { open } = this.state;
        return (
            <>

                    <ToggleSwitch checked={open} onChange={() => this.setState({ open: !open})} size={'small'}/>
                    Toggle collapse

                <Collapse open={open}>
                    <FormField label="Some collapsible content">
                        <Input />
                    </FormField>
                </Collapse>
            </>
      );
    }
  }
`;


text:
'use strict';

const electron = require('electron');
// Module to control application life.
const app = electron.app;
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow;

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;

// Define global reference to the python server (which we'll start next).
let server;

function createWindow() {
    // Start python server.
    if (process.platform === 'win32') {
        // If on Windows, use the batch command (py -3 ./server.py).
        // Change the X's in the IP below to your robot's IP, according to the guide in the README.
        server = require('child_process').spawn('py', ['-3', '-m', 'pynetworktables2js', '--robot', '10.XX.XX.2']);
    } else {
        // If on unix-like/other OSes, use bash command (python3 ./server.py).
        server = require('child_process').spawn('python3', ['-m', 'pynetworktables2js']);
    }

	// Create the browser window.
	mainWindow = new BrowserWindow({
		width: 1366,
		height: 570,
		// 1366x570 is a good standard height, but you may want to change this to fit your DriverStation's screen better.
		// It's best if the dashboard takes up as much space as possible without covering the DriverStation application.
		// The window is closed until the python server is ready
		show: false
	});

	// Move window to top (left) of screen.
	mainWindow.setPosition(0, 0);

	// Load window.
	mainWindow.loadURL('http://localhost:8888');

	// Once the python server is ready, load window contents.
    // TODO: fix this abnomination
	mainWindow.once('ready-to-show', function() {
		mainWindow.loadURL('http://localhost:8888');
		mainWindow.once('ready-to-show', function() {
			// Once it has reloaded, show the window
			mainWindow.show();
		});
	});

    // Remove menu
    //mainWindow.setMenu(null);

	// Emitted when the window is closed.
	mainWindow.on('closed', function() {
		// Dereference the window object, usually you would store windows
		// in an array if your app supports multi windows, this is the time
		// when you should delete the corresponding element.
		mainWindow = null;
	});
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', createWindow);

// Quit when all windows are closed.
app.on('window-all-closed', function() {
	// On OS X it is common for applications and their menu bar
	// to stay active until the user quits explicitly with Cmd + Q.
    // Not like we're creating a consumer application though.
    // Let's just kill it anyway.

    // If you want to restore the standard behavior, uncomment the next line.
    // if (process.platform !== 'darwin')

    app.quit();
});

app.on('quit', function() {
    console.log('Application quit. Killing tornado server.');

    // Kill tornado server child process.
    server.kill('SIGINT');
});

app.on('activate', function() {
	// On OS X it's common to re-create a window in the app when the
	// dock icon is clicked and there are no other windows open.
	if (mainWindow === null) {
		createWindow();
	}
});


text:
const modules = [
  'replacer',
  'identifiers'
]

function invokeModule (name) {
  require(`./${name}.js`)
}

modules.forEach(invokeModule)


text:
package fr.vidal.oss.jax_rs_linker.model;

import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class QueryParameterTest {

    @Test
    public void equals_should_return_true_if_objects_are_identical() {
        QueryParameter queryParameter = new QueryParameter("Foo");
        QueryParameter queryParameter1 = queryParameter;

        assertThat(queryParameter).isEqualTo(queryParameter1);
    }

    @Test
    public void equals_should_return_false_if_object_is_null() {
        QueryParameter queryParameter = new QueryParameter("Foo");
        QueryParameter queryParameter1 = null;

        assertThat(queryParameter).isNotEqualTo(queryParameter1);
    }

    @Test
    public void equals_should_return_false_Objects_have_not_the_same_class() {
        QueryParameter queryParameter = new QueryParameter("Foo");
        String queryParameter1 = "baz";

        assertThat(queryParameter).isNotEqualTo(queryParameter1);
    }

    @Test
    public void toString_should_return_a_valid_string() {
        QueryParameter queryParameter = new QueryParameter("Foo");

        assertThat(queryParameter.toString()).isEqualTo("QueryParameter{name='Foo'}");
    }

    @Test
    public void equals_contract() {
        EqualsVerifier.forClass(QueryParameter.class).verify();
    }
}


text:
package com.csforge.sstable;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Host;
import com.google.common.collect.Maps;
import org.apache.cassandra.db.Mutation;
import org.apache.cassandra.db.partitions.PartitionUpdate;

import java.io.IOException;
import java.net.InetAddress;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;

public class MutationReplayer {
    private final Cluster cluster;
    private ConcurrentMap<InetAddress, StorageConnection> connections = Maps.newConcurrentMap();
    private static final AtomicInteger idGen = new AtomicInteger(0);

    public MutationReplayer(Cluster cluster) {
        this.cluster = cluster;
    }

    public void sendMutation(Mutation mutation) {
        for (PartitionUpdate partition : mutation.getPartitionUpdates()) {
            Set<Host> replicas = cluster.getMetadata().getReplicas(mutation.getKeyspaceName(),
                    partition.partitionKey().getKey());
            // in case theres multiple partitions in this mutation, with topology changes we cant assume can send
            // them in batches so break them up.
            Mutation toSend = new Mutation(mutation.getKeyspaceName(), partition.partitionKey());
            toSend.add(partition);
            for(Host h : replicas) {
                InetAddress target = h.getBroadcastAddress();
                StorageConnection conn = connections.get(target);
                if(conn == null) {
                    conn = connections.computeIfAbsent(target, host -> {
                        StorageConnection c = new StorageConnection(host);
                        c.connect();
                        return c;
                    });
                }
                try {
                    conn.enqueue(toSend.createMessage(), idGen.incrementAndGet());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


text:
/**Problem 2: Each new term in the Fibonacci sequence is
generated by adding the previous two terms.

By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the even-valued terms.
Solved By: Shengyuan Guo in 2013
**/

#include <iostream>
#include <vector>

int main()
{

    cout="Sum of even valued terms of Fibonacci Seq <4 million:" << natural35(1000));
}

int evenfib()
{
    int sum=0;
    // Use an arr to memoize the process
    // improve efficency
for int
    int fibArr[4000000]

}

int fib(int n, int fibArr[])
{
    if(fibArr[n])
return fibArr[n]
    if(n==0)
        return 0;
    else if(n==1)
        return 1;
    else
        return fib(n-1)+fib(n-2);

}
int fibHelper(int n, int arr[])


text:
module Resque
  module Rollbar
    VERSION = "0.0.1"
  end
end


text:
#include "exodusII.h"
#include "exodusII_int.h"
#include <string.h>

/*!

The function ex_put_prop() stores an integer object property value to
a single element block, node set, or side set. Although it is not
necessary to invoke ex_put_prop_names(), since ex_put_prop() will
allocate space within the data file if it hasn't been previously
allocated, it is more efficient to use ex_put_prop_names() if there is
more than one property to store. \see Efficiency for a discussion of
efficiency issues.

It should be noted that the interpretation of the values of the
integers stored as properties is left to the application code. In
general, a zero (0) means the object does not have the specified
property (or is not in the specified group); a nonzero value means the
object does have the specified property. When space is allocated for
the properties using ex_put_prop_names() or ex_put_prop(), the
properties are initialized to zero (0).

Because the ID of an element block, node set, or side set is just
another property (named \b ID), this routine can be used to change
the value of an ID. This feature must be used with caution, though,
because changing the ID of an object to the ID of another object of
the same type (element block, node set, or side set) would cause two
objects to have the same ID, and thus only the first would be
accessible. Therefore, ex_put_prop() issues a warning if a user
attempts to give two objects the same ID.

\return In case of an error, ex_put_prop() returns a negative number;
a warning will return a positive number.  Possible causes of errors
include:
  -  data file not properly opened with call to ex_create() or ex_open()
  -  data file opened for read only.
  -  data file not initialized properly with call to ex_put_init().
  -  invalid object type specified.
  -  a warning is issued if a user attempts to change the ID of an
     object to the ID of an existing object of the same type.

\param[in] exoid      exodus file ID returned from a previous call to ex_create() or ex_open().
\param[in] obj_type   Type of object; use one of the options in the table below.
\param[in] obj_id     The element block, node set, or side set ID.
\param[in]  prop_name The name of the property for which the value will be stored.
                      Maximum length of this string is \p MAX_STR_LENGTH .
\param[in] value      The value of the property.

 \c EX_NODE_SET   	  Node Set entity type

 \c EX_EDGE_BLOCK 	  Edge Block entity type

 \c EX_EDGE_SET   	  Edge Set entity type

 \c EX_FACE_BLOCK 	  Face Block entity type

 \c EX_FACE_SET   	  Face Set entity type

 \c EX_ELEM_BLOCK 	  Element Block entity type

 \c EX_ELEM_SET   	  Element Set entity type

 \c EX_SIDE_SET   	  Side Set entity type

 \c EX_ELEM_MAP   	  Element Map entity type

 \c EX_NODE_MAP   	  Node Map entity type

 \c EX_EDGE_MAP   	  Edge Map entity type

 \c EX_FACE_MAP   	  Face Map entity type

For an example of code to write out an object property, refer to the
description for ex_put_prop_names().
*/

int ex_put_prop (int   exoid,
                 ex_entity_type obj_type,
                 int   obj_id,
                 const char *prop_name,
                 int   value)
{
  int status;
  int oldfill, temp;
  int found = FALSE;
  int num_props, i, dimid, propid, dims[1];
  size_t start[1];
  size_t prop_name_len, name_length;
  int ldum;
  char name[MAX_VAR_NAME_LENGTH+1];
  char tmpstr[MAX_STR_LENGTH+1];
  char dim_name[MAX_VAR_NAME_LENGTH+1];
  int vals[1];

  char errmsg[MAX_ERR_LENGTH];

  exerrval  = 0; /* clear error code */

  /* check if property has already been created */

  num_props = ex_get_num_props(exoid, obj_type);

  if (num_props > 1) {  /* any properties other than the default 1? */

    for (i=1; i<=num_props; i++) {
      switch (obj_type) {
      case EX_ELEM_BLOCK:
  strcpy (name, VAR_EB_PROP(i));
  break;
      case EX_EDGE_BLOCK:
  strcpy (name, VAR_ED_PROP(i));
  break;
      case EX_FACE_BLOCK:
  strcpy (name, VAR_FA_PROP(i));
  break;
      case EX_NODE_SET:
  strcpy (name, VAR_NS_PROP(i));
  break;
      case EX_EDGE_SET:
  strcpy (name, VAR_ES_PROP(i));
  break;
      case EX_FACE_SET:
  strcpy (name, VAR_FS_PROP(i));
  break;
      case EX_ELEM_SET:
  strcpy (name, VAR_ELS_PROP(i));
  break;
      case EX_SIDE_SET:
  strcpy (name, VAR_SS_PROP(i));
  break;
      case EX_ELEM_MAP:
  strcpy (name, VAR_EM_PROP(i));
  break;
      case EX_FACE_MAP:
  strcpy (name, VAR_FAM_PROP(i));
  break;
      case EX_EDGE_MAP:
  strcpy (name, VAR_EDM_PROP(i));
  break;
      case EX_NODE_MAP:
  strcpy (name, VAR_NM_PROP(i));
  break;
      default:
  exerrval = EX_BADPARAM;
  sprintf(errmsg, "Error: object type %d not supported; file id %d",
    obj_type, exoid);
  ex_err("ex_put_prop",errmsg,exerrval);
  return(EX_FATAL);
      }

      if ((status = nc_inq_varid(exoid, name, &propid)) != NC_NOERR) {
  exerrval = status;
  sprintf(errmsg,
    "Error: failed to get property array id in file id %d",
    exoid);
  ex_err("ex_put_prop",errmsg,exerrval);
  return (EX_FATAL);
      }

      /*   compare stored attribute name with passed property name   */
      memset(tmpstr, 0, MAX_STR_LENGTH+1);
      if ((status = nc_get_att_text(exoid, propid, ATT_PROP_NAME, tmpstr)) != NC_NOERR) {
  exerrval = status;
  sprintf(errmsg,
    "Error: failed to get property name in file id %d", exoid);
  ex_err("ex_put_prop",errmsg,exerrval);
  return (EX_FATAL);
      }

      if (strcmp(tmpstr, prop_name) == 0) {
  found = TRUE;
  break;
      }
    }
  }

  /* if property array has not been created, create it */
  if (!found) {

    name_length = ex_inquire_int(exoid, EX_INQ_DB_MAX_ALLOWED_NAME_LENGTH)+1;

    /* put netcdf file into define mode  */
    if ((status = nc_redef (exoid)) != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,"Error: failed to place file id %d into define mode",exoid);
      ex_err("ex_put_prop",errmsg,exerrval);
      return (EX_FATAL);
    }

    /*   create a variable with a name xx_prop#, where # is the new number   */
    /*   of the property                                                     */

    switch (obj_type){
    case EX_ELEM_BLOCK:
      strcpy (name, VAR_EB_PROP(num_props+1));
      strcpy (dim_name, DIM_NUM_EL_BLK);
      break;
    case EX_FACE_BLOCK:
      strcpy (name, VAR_FA_PROP(num_props+1));
      strcpy (dim_name, DIM_NUM_FA_BLK);
      break;
    case EX_EDGE_BLOCK:
      strcpy (name, VAR_ED_PROP(num_props+1));
      strcpy (dim_name, DIM_NUM_ED_BLK);
      break;
    case EX_NODE_SET:
      strcpy (name, VAR_NS_PROP(num_props+1));
      strcpy (dim_name, DIM_NUM_NS);
      break;
    case EX_EDGE_SET:
      strcpy (name, VAR_ES_PROP(num_props+1));
      strcpy (dim_name, DIM_NUM_ES);
      break;
    case EX_FACE_SET:
      strcpy (name, VAR_FS_PROP(num_props+1));
      strcpy (dim_name, DIM_NUM_FS);
      break;
    case EX_ELEM_SET:
      strcpy (name, VAR_ELS_PROP(num_props+1));
      strcpy (dim_name, DIM_NUM_ELS);
      break;
    case EX_SIDE_SET:
      strcpy (name, VAR_SS_PROP(num_props+1));
      strcpy (dim_name, DIM_NUM_SS);
      break;
    case EX_ELEM_MAP:
      strcpy (name, VAR_EM_PROP(num_props+1));
      strcpy (dim_name, DIM_NUM_EM);
      break;
    case EX_FACE_MAP:
      strcpy (name, VAR_FAM_PROP(num_props+1));
      strcpy (dim_name, DIM_NUM_FAM);
      break;
    case EX_EDGE_MAP:
      strcpy (name, VAR_EDM_PROP(num_props+1));
      strcpy (dim_name, DIM_NUM_EDM);
      break;
    case EX_NODE_MAP:
      strcpy (name, VAR_NM_PROP(num_props+1));
      strcpy (dim_name, DIM_NUM_NM);
      break;
    default:
      exerrval = EX_BADPARAM;
      sprintf(errmsg, "Error: object type %d not supported; file id %d",
        obj_type, exoid);
      ex_err("ex_put_prop",errmsg,exerrval);
      goto error_ret;        /* Exit define mode and return */
    }

    /*   inquire id of previously defined dimension (number of objects) */
    if ((status = nc_inq_dimid(exoid, dim_name, &dimid)) != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
        "Error: failed to locate number of objects in file id %d",
        exoid);
      ex_err("ex_put_prop",errmsg, exerrval);
      goto error_ret;  /* Exit define mode and return */
    }

    dims[0] = dimid;
    nc_set_fill(exoid, NC_FILL, &oldfill); /* fill with zeros per routine spec */

    if ((status = nc_def_var(exoid, name, NC_INT, 1, dims, &propid)) != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
        "Error: failed to create property array variable in file id %d",
        exoid);
      ex_err("ex_put_prop",errmsg,exerrval);
      goto error_ret;  /* Exit define mode and return */
    }

    vals[0] = 0; /* fill value */
    /*   create attribute to cause variable to fill with zeros per routine spec */
    if ((status = nc_put_att_int(exoid, propid, _FillValue, NC_INT, 1, vals)) != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
        "Error: failed to create property name fill attribute in file id %d",
        exoid);
      ex_err("ex_put_prop",errmsg,exerrval);
      goto error_ret;  /* Exit define mode and return */
    }

    /*   Check that the property name length is less than MAX_NAME_LENGTH */
    prop_name_len = strlen(prop_name)+1;
    if (prop_name_len > name_length) {
      fprintf(stderr,
        "Warning: The property name '%s' is too long.\n\tIt will be truncated from %d to %d characters\n",
        prop_name, (int)prop_name_len-1, (int)name_length-1);
      prop_name_len = name_length;
    }

    /*   store property name as attribute of property array variable */
    if ((status = nc_put_att_text(exoid, propid, ATT_PROP_NAME,
          prop_name_len, (void*)prop_name)) != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
        "Error: failed to store property name %s in file id %d",
        prop_name,exoid);
      ex_err("ex_put_prop",errmsg,exerrval);
      goto error_ret;  /* Exit define mode and return */
    }

    ex_update_max_name_length(exoid, prop_name_len-1);

    /* leave define mode  */
    if ((status = nc_enddef (exoid)) != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
        "Error: failed to leave define mode in file id %d",
        exoid);
      ex_err("ex_put_prop",errmsg,exerrval);
      return (EX_FATAL);
    }

    nc_set_fill(exoid, oldfill, &temp); /* default: nofill */
  }

  /* find index into property array using obj_id; put value in property */
  /* array at proper index; ex_id_lkup returns an index that is 1-based,*/
  /* but netcdf expects 0-based arrays so subtract 1                    */

  /* special case: property name ID - check for duplicate ID assignment */
  if (strcmp("ID",prop_name) == 0) {
    start[0] = ex_id_lkup (exoid, obj_type, value);
    if (exerrval != EX_LOOKUPFAIL)   /* found the id */
      {
  exerrval = EX_BADPARAM;
  sprintf(errmsg,
    "Warning: attempt to assign duplicate %s ID %d in file id %d",
    ex_name_of_object(obj_type), value, exoid);
  ex_err("ex_put_prop",errmsg,exerrval);
  return (EX_WARN);
      }
  }

  start[0] = ex_id_lkup (exoid, obj_type, obj_id);
  if (exerrval != 0) {
    if (exerrval == EX_NULLENTITY) {
      sprintf(errmsg,
        "Warning: no properties allowed for NULL %s id %d in file id %d",
        ex_name_of_object(obj_type), obj_id,exoid);
      ex_err("ex_put_prop",errmsg,EX_MSG);
      return (EX_WARN);
    } else {
      sprintf(errmsg,
        "Error: failed to find value %d in %s property array in file id %d",
        obj_id, ex_name_of_object(obj_type), exoid);
      ex_err("ex_put_prop",errmsg,exerrval);
      return (EX_FATAL);
    }
  }

  start[0] = start[0] - 1;

  ldum = (int)value;
  if ((status = nc_put_var1_int(exoid, propid, start, &ldum)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
      "Error: failed to store property value in file id %d",
      exoid);
    ex_err("ex_put_prop",errmsg,exerrval);
    return (EX_FATAL);
  }

  return (EX_NOERR);

  /* Fatal error: exit definition mode and return */
 error_ret:
  nc_set_fill(exoid, oldfill, &temp); /* default: nofill */

  if (nc_enddef (exoid) != NC_NOERR) {    /* exit define mode */
    sprintf(errmsg,
      "Error: failed to complete definition for file id %d",
      exoid);
    ex_err("ex_put_prop",errmsg,exerrval);
  }
  return (EX_FATAL);
}