text:
/**
 * Created by: dhayes on 4/15/14.
 * Filename: entity.directives
 */
angular.module('entity.directives', [])

    .directive('formHeader', function() {
        return {
            restrict: 'E',
            scope: {
                formTitle: '@',
                showCancel: '@',
                cancelButtonText: '@',
                onCancel: '&'
            },
            template: "
{{formTitle}}" +
                        "{{cancelButtonText}}"+
                    "
"
        }
    })

    .directive('formFooter', function() {
        return {
            restrict: 'E',
            require: '^form',
            scope: {
                saveButtonText: '@',
                showCancel: '@',
                cancelButtonText: '@',
                onCancel: '&'
            },
            link: function(scope, elem, attrs, formController) {
                scope.form = formController;
            },
            template: "

" +
                "
" +
                "
"+
                "       <button type='submit' class='btn btn-primary' ng-disabled='form.$invalid || form.$pristine || form.attempt'>{{saveButtonText}}</button>"+
                "       {{cancelButtonText}}"+
                "
"+
                "
"

        }
    })

    .directive('submitValid', ['$parse', function($parse) {
        return {
            require: 'form',
            link: function(scope, formElement, attributes, form) {
                form.attempt = false;
                formElement.bind('submit', function (event) {
                    form.attempt = true;
                    if (!scope.$$phase) scope.$apply();

                    var fn = $parse(attributes.submitValid);

                    if (form.$valid) {
                        scope.$apply(function() {
                            fn(scope, {$event:event});
                        });
                    }
                });

                scope.$on('$destroy', function() {
                    formElement.unbind('submit');
                });
            }
        };
    }])

    .directive('field', ['$compile','$interpolate', function($compile, $interpolate) {
        var findInputElement = function(element) {
            return angular.element(element.find('input')[0] || element.find('textarea')[0] || element.find('select')[0]);
        };

        var templateMap = {
            input: '
'+
                ''+
                '<input class="form-control input-sm">'+
                ' {{$validationMessages[key]}}',
            select: '
'+
                ''+
                '<select class="form-control input-sm"></select>'+
                '{{$validationMessages[key]}}'+
                    '
',
            textarea: '
'+
                ''+
                '<textarea class="form-control input-sm"></textarea>'+
                '{{$validationMessages[key]}}'+
                '
',
            checkbox: '
'+
                ''+
                '<input class="checkbox">'+
                ' {{$validationMessages[key]}}'+
                '
'
        };

        return {
            restrict:'E',
            priority: 100,        // We need this directive to happen before ng-model
            terminal: true,       // We are going to deal with this element
            require: '?^form',    // If we are in a form then we can access the ngModelController
            compile:function compile(element, attrs) {

                // Find all the <validator> child elements and extract their validation message info
                var validationMessages = [];
                angular.forEach(element.find('validator'), function(validatorElement) {
                    validatorElement = angular.element(validatorElement);
                    validationMessages.push({
                        key: validatorElement.attr('key'),
                        getMessage: $interpolate(validatorElement.text())
                    });
                });

                // Find the content that will go into the new label
                var labelContent = '';
                if ( element.attr('label') ) {
                    labelContent = element.attr('label');
                    element[0].removeAttribute('label');
                }
                if ( element.find('label')[0] ) {
                    labelContent = element.find('label').html();
                }
                if ( !labelContent ) {
                    throw new Error('No label provided');
                }

                // Load up the template for this kind of field
                var template = attrs.template || 'input';   // Default to the simple input if none given
                var getFieldElement = function() {
                    var newElement = angular.element(templateMap[template]);
                    var inputElement = findInputElement(newElement);

                    // Copy over the attributes to the input element
                    // At least the ng-model attribute must be copied because we can't use interpolation in the template
                    angular.forEach(element[0].attributes, function (attribute) {
                        var value = attribute.value;
                        var key = attribute.name;
                        inputElement.attr(key, value);
                    });

                    // Update the label's contents
                    var labelElement = newElement.find('label');
                    labelElement.html(labelContent);

                    return newElement;
                };

                return function (scope, element, attrs, formController) {
                    // We have to wait for the field element template to be loaded
                    var newElement = getFieldElement();
                    // Our template will have its own child scope
                    var childScope = scope.$new();

                    // Generate an id for the input from the ng-model expression
                    // (we need to replace dots with something to work with browsers and also form scope)
                    // (We couldn't do this in the compile function as we need the scope to
                    // be able to calculate the unique id)
                    childScope.$modelId = attrs.ngModel.replace('.', '_').toLowerCase() + '_' + childScope.$id;

                    // Wire up the input (id and name) and its label (for)
                    // (We need to set the input element's name here before we compile.
                    // If we leave it to interpolation, the formController doesn't pick it up)
                    var inputElement = findInputElement(newElement);
                    inputElement.attr('name', childScope.$modelId);
                    inputElement.attr('id', childScope.$modelId);
                    newElement.find('label').attr('for', childScope.$modelId);

                    childScope.$validationMessages = {};
                    angular.forEach(validationMessages, function(validationMessage) {
                        // We need to watch in-case it has interpolated values that need processing
                        scope.$watch(validationMessage.getMessage, function (message) {
                            childScope.$validationMessages[validationMessage.key] = message;
                        });
                    });

                    // We must compile our new element in the postLink function rather than in the compile function
                    // (i.e. after any parent form element has been linked)
                    // otherwise the new input won't pick up the FormController
                    $compile(newElement)(childScope, function(clone) {
                        // Place our new element after the original element
                        element.after(clone);
                        // Remove our original element
                        element.remove();
                    });

                    // Only after the new element has been compiled do we have access to the ngModelController
                    // (i.e. formController[childScope.name])
                    if ( formController ) {
                        childScope.$form = formController;
                        childScope.$field = formController[childScope.$modelId];
                    }
                };
            }
        };
    }])

    .directive('capitalize', function() {
        return {
            require: 'ngModel',
            link: function (scope, element, attrs, modelCtrl) {
                var capitalize = function (inputValue) {
                    if (angular.isUndefined(inputValue))
                        return;

                    var capitalized = inputValue.toUpperCase();
                    if (capitalized !== inputValue) {
                        modelCtrl.$setViewValue(capitalized);
                        modelCtrl.$render();
                    }
                    return capitalized;
                };
                modelCtrl.$parsers.push(capitalize);
                capitalize(scope[attrs.ngModel]);
            }
        };
    })

    .directive('changeDelay', function() {
        return {
            scope: {
                changeDelay: '&'
            },
            link: function(scope, element, attrs) {
                var timeout;
                element.on('keyup paste search', function() {
                    clearTimeout(timeout);
                    timeout = setTimeout(function() {
                        scope.changeDelay();
                        //scope.$apply();
                    }, attrs.delay || 500);
                });

                scope.$on('$destroy', function() {
                    element.unbind('keyup paste search');
                });
            }
        };
    });


text:
package git4idea.push;

import javax.annotation.Nonnull;
import git4idea.config.UpdateMethod;

// holds settings chosen in GitRejectedPushUpdate dialog to reuse if the next push is rejected again.
class PushUpdateSettings
{

	private final boolean myUpdateAllRoots;
	@Nonnull
	private final UpdateMethod myUpdateMethod;

	PushUpdateSettings(boolean updateAllRoots, @Nonnull UpdateMethod updateMethod)
	{
		myUpdateAllRoots = updateAllRoots;
		myUpdateMethod = updateMethod;
	}

	boolean shouldUpdateAllRoots()
	{
		return myUpdateAllRoots;
	}

	@Nonnull
	UpdateMethod getUpdateMethod()
	{
		return myUpdateMethod;
	}

	@Override
	public String toString()
	{
		return String.format("UpdateSettings{myUpdateAllRoots=%s, myUpdateMethod=%s}", myUpdateAllRoots, myUpdateMethod);
	}
}

redpajama_set_name: RedPajamaGithub


text:
{% load django_backend_tags %}
{% render object %}


text:
package scala
package tools
package nsc
package typechecker

import scala.collection.mutable
import symtab.Flags
import Mode._

 /**
 *
 *  A pattern match such as
 *
 *    x match { case Foo(a, b) => ...}
 *
 *  Might match an instance of any of the following definitions of Foo.
 *  Note the analogous treatment between case classes and unapplies.
 *
 *    case class Foo(xs: Int*)
 *    case class Foo(a: Int, xs: Int*)
 *    case class Foo(a: Int, b: Int)
 *    case class Foo(a: Int, b: Int, xs: Int*)
 *
 *    object Foo { def unapplySeq(x: Any): Option[Seq[Int]] }
 *    object Foo { def unapplySeq(x: Any): Option[(Int, Seq[Int])] }
 *    object Foo { def unapply(x: Any): Option[(Int, Int)] }
 *    object Foo { def unapplySeq(x: Any): Option[(Int, Int, Seq[Int])] }
 */

trait PatternTypers {
  self: Analyzer =>

  import global._
  import definitions._

  private object FixedAndRepeatedTypes {
    def unapply(types: List[Type]) = types match {
      case init :+ last if isRepeatedParamType(last) => Some((init, dropRepeated(last)))
      case _                                         => Some((types, NoType))
    }
  }

  trait PatternTyper {
    self: Typer =>

    import TyperErrorGen._
    import infer._

    private def unit = context.unit

    // If the tree's symbol's type does not define an extractor, maybe the tree's type does.
    // this is the case when we encounter an arbitrary tree as the target of an unapply call
    // (rather than something that looks like a constructor call.) (for now, this only happens
    // due to wrapClassTagUnapply, but when we support parameterized extractors, it will become
    // more common place)
    private def hasUnapplyMember(tpe: Type): Boolean   = reallyExists(unapplyMember(tpe))
    private def hasUnapplyMember(sym: Symbol): Boolean = hasUnapplyMember(sym.tpe_*)
    private def hasUnapplyMember(fun: Tree): Boolean   = hasUnapplyMember(fun.symbol) || hasUnapplyMember(fun.tpe)

    // ad-hoc overloading resolution to deal with unapplies and case class constructors
    // If some but not all alternatives survive filtering the tree's symbol with `p`,
    // then update the tree's symbol and type to exclude the filtered out alternatives.
    private def inPlaceAdHocOverloadingResolution(fun: Tree)(p: Symbol => Boolean): Tree = fun.symbol filter p match {
      case sym if sym.exists && (sym ne fun.symbol) => fun setSymbol sym modifyType (tp => filterOverloadedAlts(tp)(p))
      case _                                        => fun
    }
    private def filterOverloadedAlts(tpe: Type)(p: Symbol => Boolean): Type = tpe match {
      case OverloadedType(pre, alts) => overloadedType(pre, alts filter p)
      case tp                        => tp
    }

    def typedConstructorPattern(fun0: Tree, pt: Type): Tree = {
      // Do some ad-hoc overloading resolution and update the tree's symbol and type
      // do not update the symbol if the tree's symbol's type does not define an unapply member
      // (e.g. since it's some method that returns an object with an unapply member)
      val fun         = inPlaceAdHocOverloadingResolution(fun0)(hasUnapplyMember)
      val canElide    = treeInfo.isQualifierSafeToElide(fun)
      val caseClass   = companionSymbolOf(fun.tpe.typeSymbol.sourceModule, context)
      val member      = unapplyMember(fun.tpe)
      def resultType  = (fun.tpe memberType member).finalResultType
      def isEmptyType = resultOfMatchingMethod(resultType, nme.isEmpty)()
      def isOkay      = (
           resultType.isErroneous
        || (resultType <:< BooleanTpe)
        || (isEmptyType <:< BooleanTpe)
        || member.isMacro
        || member.isOverloaded // the whole overloading situation is over the rails
      )

      // Dueling test cases: pos/overloaded-unapply.scala, run/case-class-23.scala, pos/t5022.scala
      // A case class with 23+ params has no unapply method.
      // A case class constructor may be overloaded with unapply methods in the companion.
      if (canElide && caseClass.isCase && !member.isOverloaded)
        logResult(s"convertToCaseConstructor($fun, $caseClass, pt=$pt)")(convertToCaseConstructor(fun, caseClass, pt))
      else if (!reallyExists(member))
        CaseClassConstructorError(fun, s"${fun.symbol} is not a case class, nor does it have an unapply/unapplySeq member")
      else if (isOkay)
        fun
      else if (isEmptyType == NoType)
        CaseClassConstructorError(fun, s"an unapply result must have a member `def isEmpty: Boolean")
      else
        CaseClassConstructorError(fun, s"an unapply result must have a member `def isEmpty: Boolean (found: def isEmpty: $isEmptyType)")
    }

    def typedArgsForFormals(args: List[Tree], formals: List[Type], mode: Mode): List[Tree] = {
      def typedArgWithFormal(arg: Tree, pt: Type) = {
        val newMode = if (isByNameParamType(pt)) mode.onlySticky else mode.onlySticky | BYVALmode
        typedArg(arg, mode, newMode, dropByName(pt))
      }
      val FixedAndRepeatedTypes(fixed, elem) = formals
      val front = (args, fixed).zipped map typedArgWithFormal
      def rest  = context withinStarPatterns (args drop front.length map (typedArgWithFormal(_, elem)))

      elem match {
        case NoType => front
        case _      => front ::: rest
      }
    }

    private def boundedArrayType(bound: Type): Type = {
      val tparam = context.owner freshExistential "" setInfo (TypeBounds upper bound)
      newExistentialType(tparam :: Nil, arrayType(tparam.tpe_*))
    }

    protected def typedStarInPattern(tree: Tree, mode: Mode, pt: Type) = {
      val Typed(expr, tpt) = tree
      val exprTyped = typed(expr, mode)
      val baseClass = exprTyped.tpe.typeSymbol match {
        case ArrayClass => ArrayClass
        case _          => SeqClass
      }
      val starType = baseClass match {
        case ArrayClass if isPrimitiveValueType(pt) || !isFullyDefined(pt) => arrayType(pt)
        case ArrayClass                                                    => boundedArrayType(pt)
        case _                                                             => seqType(pt)
      }
      val exprAdapted = adapt(exprTyped, mode, starType)
      exprAdapted.tpe baseType baseClass match {
        case TypeRef(_, _, elemtp :: Nil) => treeCopy.Typed(tree, exprAdapted, tpt setType elemtp) setType elemtp
        case _                            => setError(tree)
      }
    }

    protected def typedInPattern(tree: Typed, mode: Mode, pt: Type) = {
      val Typed(expr, tpt) = tree
      val tptTyped  = typedType(tpt, mode)
      val tpe       = tptTyped.tpe
      val exprTyped = typed(expr, mode, tpe.deconst)
      val extractor = extractorForUncheckedType(tpt.pos, tpe)

      val canRemedy = tpe match {
        case RefinedType(_, decls) if !decls.isEmpty                 => false
        case RefinedType(parents, _) if parents exists isUncheckable => false
        case _                                                       => extractor.nonEmpty
      }

      val ownType   = inferTypedPattern(tptTyped, tpe, pt, canRemedy)
      val treeTyped = treeCopy.Typed(tree, exprTyped, tptTyped) setType ownType

      extractor match {
        case EmptyTree => treeTyped
        case _         => wrapClassTagUnapply(treeTyped, extractor, tpe)
      }
    }
    private class VariantToSkolemMap extends TypeMap(trackVariance = true) {
      private val skolemBuffer = mutable.ListBuffer[TypeSymbol]()

      // !!! FIXME - skipping this when variance.isInvariant allows unsoundness, see SI-5189
      // Test case which presently requires the exclusion is run/gadts.scala.
      def eligible(tparam: Symbol) = (
           tparam.isTypeParameterOrSkolem
        && tparam.owner.isTerm
        && (settings.strictInference || !variance.isInvariant)
      )

      def skolems = try skolemBuffer.toList finally skolemBuffer.clear()
      def apply(tp: Type): Type = mapOver(tp) match {
        case tp @ TypeRef(NoPrefix, tpSym, Nil) if eligible(tpSym) =>
          val bounds = (
            if (variance.isInvariant) tpSym.tpeHK.bounds
            else if (variance.isPositive) TypeBounds.upper(tpSym.tpeHK)
            else TypeBounds.lower(tpSym.tpeHK)
          )
          // origin must be the type param so we can deskolemize
          val skolem = context.owner.newGADTSkolem(unit.freshTypeName("?" + tpSym.name), tpSym, bounds)
          skolemBuffer += skolem
          logResult(s"Created gadt skolem $skolem: ${skolem.tpe_*} to stand in for $tpSym")(skolem.tpe_*)
        case tp1 => tp1
      }
    }

    /*
     * To deal with the type slack between actual (run-time) types and statically known types, for each abstract type T,
     * reflect its variance as a skolem that is upper-bounded by T (covariant position), or lower-bounded by T (contravariant).
     *
     * Consider the following example:
     *
     *  class AbsWrapperCov[+A]
     *  case class Wrapper[B](x: Wrapped[B]) extends AbsWrapperCov[B]
     *
     *  def unwrap[T](x: AbsWrapperCov[T]): Wrapped[T] = x match {
     *    case Wrapper(wrapped) => // Wrapper's type parameter must not be assumed to be equal to T, it's *upper-bounded* by it
     *      wrapped // : Wrapped[_ <: T]
     *  }
     *
     * this method should type check if and only if Wrapped is covariant in its type parameter
     *
     * when inferring Wrapper's type parameter B from x's type AbsWrapperCov[T],
     * we must take into account that x's actual type is AbsWrapperCov[Tactual] forSome {type Tactual <: T}
     * as AbsWrapperCov is covariant in A -- in other words, we must not assume we know T exactly, all we know is its upper bound
     *
     * since method application is the only way to generate this slack between run-time and compile-time types (TODO: right!?),
     * we can simply replace skolems that represent method type parameters as seen from the method's body
     * by other skolems that are (upper/lower)-bounded by that type-parameter skolem
     * (depending on the variance position of the skolem in the statically assumed type of the scrutinee, pt)
     *
     * see test/files/../t5189*.scala
     */
    private def convertToCaseConstructor(tree: Tree, caseClass: Symbol, ptIn: Type): Tree = {
      // TODO SI-7886 / SI-5900 This is well intentioned but doesn't quite hit the nail on the head.
      //      For now, I've put it completely behind -Xstrict-inference.
      val untrustworthyPt = settings.strictInference && (
           ptIn =:= AnyTpe
        || ptIn =:= NothingTpe
        || ptIn.typeSymbol != caseClass
      )
      val variantToSkolem     = new VariantToSkolemMap
      val caseClassType       = tree.tpe.prefix memberType caseClass
      val caseConstructorType = caseClassType memberType caseClass.primaryConstructor
      val tree1               = TypeTree(caseConstructorType) setOriginal tree
      val pt                  = if (untrustworthyPt) caseClassType else ptIn

      // have to open up the existential and put the skolems in scope
      // can't simply package up pt in an ExistentialType, because that takes us back to square one (List[_ <: T] == List[T] due to covariance)
      val ptSafe   = logResult(s"case constructor from (${tree.summaryString}, $caseClassType, $pt)")(variantToSkolem(pt))
      val freeVars = variantToSkolem.skolems

      // use "tree" for the context, not context.tree: don't make another CaseDef context,
      // as instantiateTypeVar's bounds would end up there
      val ctorContext = context.makeNewScope(tree, context.owner)
      freeVars foreach ctorContext.scope.enter
      newTyper(ctorContext).infer.inferConstructorInstance(tree1, caseClass.typeParams, ptSafe)

      // simplify types without losing safety,
      // so that we get rid of unnecessary type slack, and so that error messages don't unnecessarily refer to skolems
      val extrapolator = new ExistentialExtrapolation(freeVars)
      def extrapolate(tp: Type) = extrapolator extrapolate tp

      // once the containing CaseDef has been type checked (see typedCase),
      // tree1's remaining type-slack skolems will be deskolemized (to the method type parameter skolems)
      tree1 modifyType {
        case MethodType(ctorArgs, restpe) => // ctorArgs are actually in a covariant position, since this is the type of the subpatterns of the pattern represented by this Apply node
          copyMethodType(tree1.tpe, ctorArgs map (_ modifyInfo extrapolate), extrapolate(restpe)) // no need to clone ctorArgs, this is OUR method type
        case tp => tp
      }
    }

    def doTypedUnapply(tree: Tree, fun0: Tree, fun: Tree, args: List[Tree], mode: Mode, pt: Type): Tree = {
      def duplErrTree = setError(treeCopy.Apply(tree, fun0, args))
      def duplErrorTree(err: AbsTypeError) = { context.issue(err); duplErrTree }

      if (args.length > MaxTupleArity)
        return duplErrorTree(TooManyArgsPatternError(fun))

      def freshArgType(tp: Type): Type = tp match {
        case MethodType(param :: _, _) => param.tpe
        case PolyType(tparams, restpe) => createFromClonedSymbols(tparams, freshArgType(restpe))(genPolyType)
        case OverloadedType(_, _)      => OverloadedUnapplyError(fun) ; ErrorType
        case _                         => UnapplyWithSingleArgError(fun) ; ErrorType
      }
      val unapplyMethod    = unapplyMember(fun.tpe)
      val unapplyType      = fun.tpe memberType unapplyMethod
      val unapplyParamType = firstParamType(unapplyType)
      def isSeq            = unapplyMethod.name == nme.unapplySeq

      def extractor     = extractorForUncheckedType(fun.pos, unapplyParamType)
      def canRemedy     = unapplyParamType match {
        case RefinedType(_, decls) if !decls.isEmpty                 => false
        case RefinedType(parents, _) if parents exists isUncheckable => false
        case _                                                       => extractor.nonEmpty
      }

      def freshUnapplyArgType(): Type = {
        val GenPolyType(freeVars, unappFormal) = freshArgType(unapplyType.skolemizeExistential(context.owner, tree))
        val unapplyContext = context.makeNewScope(context.tree, context.owner)
        freeVars foreach unapplyContext.scope.enter
        val pattp = newTyper(unapplyContext).infer.inferTypedPattern(tree, unappFormal, pt, canRemedy)
        // turn any unresolved type variables in freevars into existential skolems
        val skolems = freeVars map (fv => unapplyContext.owner.newExistentialSkolem(fv, fv))
        pattp.substSym(freeVars, skolems)
      }

      val unapplyArg = (
        context.owner.newValue(nme.SELECTOR_DUMMY, fun.pos, Flags.SYNTHETIC) setInfo (
          if (isApplicableSafe(Nil, unapplyType, pt :: Nil, WildcardType)) pt
          else freshUnapplyArgType()
        )
      )
      val unapplyArgTree = Ident(unapplyArg) updateAttachment SubpatternsAttachment(args)

      // clearing the type is necessary so that ref will be stabilized; see bug 881
      val fun1 = typedPos(fun.pos)(Apply(Select(fun.clearType(), unapplyMethod), unapplyArgTree :: Nil))

      def makeTypedUnapply() = {
        // the union of the expected type and the inferred type of the argument to unapply
        val glbType        = glb(ensureFullyDefined(pt) :: unapplyArg.tpe_* :: Nil)
        val wrapInTypeTest = canRemedy && !(fun1.symbol.owner isNonBottomSubClass ClassTagClass)
        val formals        = patmat.alignPatterns(context.asInstanceOf[analyzer.Context], fun1, args).unexpandedFormals
        val args1          = typedArgsForFormals(args, formals, mode)
        val result         = UnApply(fun1, args1) setPos tree.pos setType glbType

        if (wrapInTypeTest)
          wrapClassTagUnapply(result, extractor, glbType)
        else
          result
      }

      if (fun1.tpe.isErroneous)
        duplErrTree
      else if (unapplyMethod.isMacro && !fun1.isInstanceOf[Apply]) {
        if (isBlackbox(unapplyMethod)) duplErrorTree(BlackboxExtractorExpansion(tree))
        else duplErrorTree(WrongShapeExtractorExpansion(tree))
      } else
        makeTypedUnapply()
    }

    def wrapClassTagUnapply(uncheckedPattern: Tree, classTagExtractor: Tree, pt: Type): Tree = {
      // TODO: disable when in unchecked match
      // we don't create a new Context for a Match, so find the CaseDef,
      // then go out one level and navigate back to the match that has this case
      val args = List(uncheckedPattern)
      val app  = atPos(uncheckedPattern.pos)(Apply(classTagExtractor, args))
      // must call doTypedUnapply directly, as otherwise we get undesirable rewrites
      // and re-typechecks of the target of the unapply call in PATTERNmode,
      // this breaks down when the classTagExtractor (which defines the unapply member) is not a simple reference to an object,
      // but an arbitrary tree as is the case here
      val res = doTypedUnapply(app, classTagExtractor, classTagExtractor, args, PATTERNmode, pt)

      log(sm"""
        |wrapClassTagUnapply {
        |  pattern: $uncheckedPattern
        |  extract: $classTagExtractor
        |       pt: $pt
        |      res: $res
        |}""".trim)

      res
    }

    // if there's a ClassTag that allows us to turn the unchecked type test for `pt` into a checked type test
    // return the corresponding extractor (an instance of ClassTag[`pt`])
    def extractorForUncheckedType(pos: Position, pt: Type): Tree = {
      if (isPastTyper || (pt eq NoType)) EmptyTree else {
        pt match {
          case RefinedType(parents, decls) if !decls.isEmpty || (parents exists isUncheckable) => return EmptyTree
          case _                                                                               =>
        }
        // only look at top-level type, can't (reliably) do anything about unchecked type args (in general)
        // but at least make a proper type before passing it elsewhere
        val pt1 = pt.dealiasWiden match {
          case tr @ TypeRef(pre, sym, args) if args.nonEmpty => copyTypeRef(tr, pre, sym, sym.typeParams map (_.tpeHK)) // replace actual type args with dummies
          case pt1                                           => pt1
        }
        if (isCheckable(pt1)) EmptyTree
        else resolveClassTag(pos, pt1) match {
          case tree if unapplyMember(tree.tpe).exists => tree
          case _                                      => devWarning(s"Cannot create runtime type test for $pt1") ; EmptyTree
        }
      }
    }
  }
}


text:
<?php

namespace Media;

use Kenarkose\Nuclear\Html\MediaBuilder as MB;

/**
 * ----------------------------------------
 * Media builder
 * ----------------------------------------
 */
class MediaBuilder extends MB {
	/**
	 * Returns the display path for image
	 *
	 * @return string
	 */
	protected function getFigureDisplayPath($media) {
		return $media->sizePath('site-view');
	}
}


text:
<?php
declare(strict_types=1);

namespace tests\Happyr\DoctrineSpecification\Filter;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Query\Expr;
use Doctrine\ORM\Query\Expr\Comparison;
use Doctrine\ORM\QueryBuilder;
use Happyr\DoctrineSpecification\Filter\Filter;
use Happyr\DoctrineSpecification\Filter\MemberOfX;
use PhpSpec\ObjectBehavior;

/**
 * @mixin MemberOfX
 */
final class MemberOfXSpec extends ObjectBehavior
{
    public function let(): void
    {
        $this->beConstructedWith(18, 'age', null);
    }

    public function it_is_initializable(): void
    {
        $this->shouldHaveType(MemberOfX::class);
    }

    public function it_is_an_expression(): void
    {
        $this->shouldBeAnInstanceOf(Filter::class);
    }

    public function it_returns_expression_func_object(QueryBuilder $qb, ArrayCollection $parameters, Expr $exp): void
    {
        $exp_comparison = new Comparison(':comparison_10', 'MEMBER OF', 'a.age');
        $qb->expr()->willReturn($exp);
        $qb->getParameters()->willReturn($parameters);
        $parameters->count()->willReturn(10);

        $qb->setParameter('comparison_10', 18, null)->shouldBeCalled();
        $exp->isMemberOf(':comparison_10', 'a.age')->willReturn($exp_comparison);

        $this->getFilter($qb, 'a')->shouldReturn(':comparison_10 MEMBER OF a.age');
    }

    public function it_returns_expression_func_object_in_context(
        QueryBuilder $qb,
        ArrayCollection $parameters,
        Expr $exp
    ): void {
        $this->beConstructedWith(18, 'age', 'user');

        $exp_comparison = new Comparison(':comparison_10', 'MEMBER OF', 'user.age');
        $qb->expr()->willReturn($exp);
        $qb->getParameters()->willReturn($parameters);
        $parameters->count()->willReturn(10);

        $qb->setParameter('comparison_10', 18, null)->shouldBeCalled();
        $exp->isMemberOf(':comparison_10', 'user.age')->willReturn($exp_comparison);

        $qb->getDQLPart('join')->willReturn([]);
        $qb->getAllAliases()->willReturn([]);
        $qb->join('root.user', 'user')->willReturn($qb);

        $this->getFilter($qb, 'root')->shouldReturn(':comparison_10 MEMBER OF user.age');
    }
}


text:
import os
import sys

# Pull in regular tests' utilities
mod = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'tests'))
sys.path.insert(0, mod)
# Clean up
del sys.path[0]

class Integration(object):
    def setup(self):
        # Just so subclasses can super() us w/o fear. Meh.
        pass

    def teardown(self):
        # Just so subclasses can super() us w/o fear. Meh.
        pass


text:
using UnityEngine;
using UnityEditor;
using System.IO;

public static class ScriptableObjectUtility
{
    /// <summary>
    //	This makes it easy to create, name and place unique new ScriptableObject asset files.
    /// </summary>
    public static void CreateAsset<T>() where T : ScriptableObject
    {
        T asset = ScriptableObject.CreateInstance<T>();

        string path = AssetDatabase.GetAssetPath(Selection.activeObject);
        if (path == "")
        {
            path = "Assets";
        }
        else if (Path.GetExtension(path) != "")
        {
            path = path.Replace(Path.GetFileName(AssetDatabase.GetAssetPath(Selection.activeObject)), "");
        }

        string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath(path + "/New " + typeof(T).ToString() + ".asset");

        AssetDatabase.CreateAsset(asset, assetPathAndName);

        AssetDatabase.SaveAssets();
        EditorUtility.FocusProjectWindow();
        Selection.activeObject = asset;
    }
}


text:
<?php
/**
 * CakePHP New Relic plugin.
 *
 * @author https://github.com/brunitto
 * @author https://github.com/voycey
 * @author https://github.com/rodrigorm
 * @link https://github.com/brunitto/cakephp-new-relic
 */
namespace NewRelic\Middleware;

use Cake\Utility\Inflector;
use Cake\Http\ServerRequest;
use Cake\Http\Response;

/**
 * New Relic name transaction middleware.
 */
class NameTransactionMiddleware
{
    /**
     * __invoke() method.
     *
     * Call the newrelic_name_transaction function when the newrelic extension
     * is loaded.
     *
     * @param Cake\Http\ServerRequest $request The request.
     * @param Cake\Http\Client\Response $response The response.
     * @param callable $next The next middleware to call.
     * @return Cake\Http\Client\Response A response.
     */
    public function __invoke(ServerRequest $request, Response $response, $next)
    {
        if (extension_loaded('newrelic')) {
            newrelic_name_transaction($this->nameTransaction($request));
        }

        return $next($request, $response);
    }

    /**
     * nameTransaction() method.
     *
     * Name the transaction using request data.
     *
     * @param Cake\Http\ServerRequest $request The request.
     * @return string
     */
    public function nameTransaction(ServerRequest $request)
    {
        $prefix = $request->getParam('prefix', null);
        $plugin = $request->getParam('plugin', null);
        $controller = $request->getParam('controller');
        $action = $request->getParam('action');

        $transaction = Inflector::dasherize($controller) . '/' . $action;

        if ($prefix !== null) {
            $transaction = Inflector::dasherize($prefix) . '/' . $transaction;
        }

        if ($plugin !== null) {
            $transaction = Inflector::dasherize($plugin) . '/' . $transaction;
        }

        return $transaction;
    }
}


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

import javax.annotation.Generated;

/**
 * <p>
 * The definition you submitted is not supported.
 * </p>
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ScheduleDefinitionTypeUnsupportedException extends com.amazonaws.services.redshift.model.AmazonRedshiftException {
    private static final long serialVersionUID = 1L;

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

}


text:
对于一个非web项目,转换为Spring Boot应用很容易(抛弃创建`ApplicationContext`的代码,取而代之的是调用`SpringApplication`或`SpringApplicationBuilder`)。Spring MVC web应用通常先创建一个可部署的war应用,然后将它迁移为一个可执行的war或jar,建议阅读[Getting Started Guide on Converting a jar to a war.](http://spring.io/guides/gs/convert-jar-to-war/)。

通过继承`SpringBootServletInitializer`创建一个可执行war(比如,在一个名为`Application`的类中),然后添加Spring Boot的`@EnableAutoConfiguration`注解,示例:
```java
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        // Customize the application or call application.sources(...) to add sources
        // Since our example is itself a @Configuration class we actually don't
        // need to override this method.
        return application;
    }

}
```
记住不管你往`sources`放什么东西,它仅是一个Spring `ApplicationContext`,正常情况下,任何生效的在这里也会起作用。有一些beans你可以先移除,然后让Spring Boot提供它的默认实现,不过有可能需要先完成一些事情。

静态资源可以移到classpath根目录下的`/public`(或`/static`,`/resources`,`/META-INF/resources`)。同样的方式也适合于`messages.properties`(Spring Boot在classpath根目录下自动发现这些配置)。

美妙的(Vanilla usage of)Spring `DispatcherServlet`和Spring Security不需要改变。如果你的应用有其他特性,比如使用其他servlets或filters,那你可能需要添加一些配置到你的`Application`上下文中,按以下操作替换`web.xml`的那些元素:

- 在容器中安装一个`Servlet`或`ServletRegistrationBean`类型的`@Bean`,就好像`web.xml`中的`<servlet/>`和`<servlet-mapping/>`。
- 同样的添加一个`Filter`或`FilterRegistrationBean`类型的`@Bean`(类似于`<filter/>`和`<filter-mapping/>`)。
- 在XML文件中的`ApplicationContext`可以通过`@Import`添加到你的`Application`中。简单的情况下,大量使用注解配置可以在几行内定义`@Bean`定义。

一旦war可以使用,我们就通过添加一个main方法到`Application`来让它可以执行,比如:
```java
public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}
```
应用可以划分为多个类别:

- 没有web.xml的Servlet 3.0+应用
- 有web.xml的应用
- 有上下文层次的应用
- 没有上下文层次的应用

所有这些都可以进行适当的转化,但每个可能需要稍微不同的技巧。

Servlet 3.0+的应用转化的相当简单,如果它们已经使用Spring Servlet 3.0+初始化器辅助类。通常所有来自一个存在的`WebApplicationInitializer`的代码可以移到一个`SpringBootServletInitializer`中。如果一个存在的应用有多个`ApplicationContext`(比如,如果它使用`AbstractDispatcherServletInitializer`),那你可以将所有上下文源放进一个单一的`SpringApplication`。你遇到的主要难题可能是如果那样不能工作,那你就要维护上下文层次。参考示例[entry on building a hierarchy](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-build-an-application-context-hierarchy)。一个存在的包含web相关特性的父上下文通常需要分解,这样所有的`ServletContextAware`组件都处于子上下文中。

对于还不是Spring应用的应用来说,上面的指南有助于你把应用转换为一个Spring Boot应用,但你也可以选择其他方式。


text:
package com.spectralogic.dsbrowser.gui.util;

import org.junit.Test;

import java.util.Date;

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

/**
 * Created by linchpin on 30/1/17.
 */
public class DateFormatTest {
    @Test
    public void formatDate() throws Exception {
        final Date d = new Date(1485757788120l);
        final String formatedDate = DateFormat.formatDate(d);
        assertThat(formatedDate,is("1/30/2017 11:59:48"));
    }

}


text:
class ThingsController < ApplicationController
  before_action :set_thing, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!
  respond_to :html

  def index
    @things = Thing.all
    respond_with(@things)
  end

  def show
    respond_with(@thing)
  end

  def new
    @thing = Thing.new
    respond_with(@thing)
  end

  def edit
  end

  def create
    @thing = Thing.new(thing_params)
    @thing.save
    respond_with(@thing)
  end

  def update
    @thing.update(thing_params)
    respond_with(@thing)
  end

  def destroy
    @thing.destroy
    respond_with(@thing)
  end

  private
    def set_thing
      @thing = Thing.find(params[:id])
    end

    def thing_params
      params.require(:thing).permit(:name, :private, :user_id)
    end
end


text:
module Azure::ApiManagement::Mgmt::V2019_01_01
  module Models
    #
    # Email Template update Parameters.
    #
    class EmailTemplateUpdateParameters

      include MsRestAzure

      # @return [String] Subject of the Template.
      attr_accessor :subject

      # @return [String] Title of the Template.
      attr_accessor :title

      # @return [String] Description of the Email Template.
      attr_accessor :description

      # @return [String] Email Template Body. This should be a valid XDocument
      attr_accessor :body

      # @return [Array<EmailTemplateParametersContractProperties>] Email
      # Template Parameter values.
      attr_accessor :parameters

      #
      # Mapper for EmailTemplateUpdateParameters class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'EmailTemplateUpdateParameters',
          type: {
            name: 'Composite',
            class_name: 'EmailTemplateUpdateParameters',
            model_properties: {
              subject: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.subject',
                constraints: {
                  MaxLength: 1000,
                  MinLength: 1
                },
                type: {
                  name: 'String'
                }
              },
              title: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.title',
                type: {
                  name: 'String'
                }
              },
              description: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.description',
                type: {
                  name: 'String'
                }
              },
              body: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.body',
                constraints: {
                  MinLength: 1
                },
                type: {
                  name: 'String'
                }
              },
              parameters: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.parameters',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'EmailTemplateParametersContractPropertiesElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'EmailTemplateParametersContractProperties'
                      }
                  }
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
ON_DAED['3D'].Orbitas = function (scene, url) {

    var wrapper = new THREE.Object3D();

    var fatorEscala = 5;

    var tamanhoBaseGalaxia = 40 * fatorEscala;
    var raioDistanciaSol = 8 * fatorEscala;

    var umMilhaoDeAnosJD = 366963559.5;
    var correcaoData = 1; // ?? KPC ?

    var esferaReferencia = new THREE.Mesh(new THREE.SphereGeometry(0.6, 16, 8), new THREE.MeshBasicMaterial({
        color: 0x0000FF
    }));

    wrapper.add(esferaReferencia);

    var lastLine = null;
    var lastData = null;

    var sol = new THREE.Mesh(
            new THREE.SphereGeometry(0.6, 16, 8),
            new THREE.MeshBasicMaterial({
                color: 0xFFFF00
            })
        );

    wrapper.add(sol);

    var galaxia = new THREE.Mesh(new THREE.PlaneGeometry(tamanhoBaseGalaxia, tamanhoBaseGalaxia, 2, 2), new THREE.MeshBasicMaterial({
        map: THREE.ImageUtils.loadTexture("imgs/texturas/galaxias/vialactea.jpg"),
        side: THREE.DoubleSide,
        depthTest: false
    }));

    galaxia.renderOrder = -1;

    wrapper.add(galaxia);

    scene.add(wrapper);

    var o = {};

    o.loadData = function (url) {

        document.body.style.cursor = 'wait';

        $('#select-orbitas').attr("disabled", true);

        $.getJSON("lib/on-daed-js/orbitas/" + url, {}, function (dataSelecionada) {

            $.getJSON(dataSelecionada[1],
                    function (data) {

                        for(var pageId in data.query.pages) {

                            var page = data.query.pages[pageId];
                            var parentTitle = $('#informacao-texto-modal .modal-title')[0];

                            $('#wiki-orbita-titulo').html(page.title);
                            $('#wiki-orbita-conteudo').html(page.extract);

                            parentTitle.innerHTML = page.title;

                        }

                    });

            delete lastData;

            lastData = dataSelecionada;

            var sliderDataJuliana = $('#data-juliana-slider').data('bootstrapSlider');

            sliderDataJuliana.setAttribute("max", dataSelecionada.length - 4);
            sliderDataJuliana.setAttribute("min", 2);
            sliderDataJuliana.setAttribute("value", 2);
            sliderDataJuliana.refresh();

            $('#data-juliana-slider').trigger('slide');

            if (lastLine !== null) {
                lastLine.parent.remove(lastLine);
                ThreeHelper.dispose(lastLine);
            }

            var geo = new THREE.Geometry();
            var mat;

            mat = new THREE.LineDashedMaterial({linewidth: 1, color: 0xFF0000, dashSize: 0.2, gapSize: 0.2, depthTest: false});

            for (var i = 2; i < dataSelecionada.length; i = i + 4) {
                geo.vertices.push(new THREE.Vector3((dataSelecionada[i + 1] * fatorEscala) * correcaoData, (dataSelecionada[i + 2] * fatorEscala) * correcaoData, (dataSelecionada[i + 3] * fatorEscala) * correcaoData));
            }

            geo.computeLineDistances();

            lastLine = new THREE.Line(geo, mat, THREE.LineStrip);
            wrapper.add(lastLine);

            $('#select-orbitas').attr("disabled", false);

            window.history.pushState({}, "", "orbitas-" + url.replace(".json", "").replace(/ /g, "-").replace(/[^a-zA-Z0-9-]/g, "").toLowerCase());

            document.body.style.cursor = 'auto';

        });
    };

    o.setGalaxia = function (bool) {
        galaxia.visible = bool;
    };

    o.setRaioGalaxia = function (raio) {
        galaxia.scale.x = galaxia.scale.y = galaxia.scale.z = raio / (tamanhoBaseGalaxia / (2 * fatorEscala));
    };

    o.update = function (value) {

        var periodoSol = 250000000 * 365.25;
        var argumentoSol = (value / periodoSol) * Math.PI * 2;

        sol.position.set(raioDistanciaSol * Math.cos(argumentoSol), raioDistanciaSol * Math.sin(argumentoSol), 0);

        esferaReferencia.position.set((lastData[value + 1] * fatorEscala) * correcaoData, (lastData[value + 2] * fatorEscala) * correcaoData, (lastData[value + 3] * fatorEscala) * correcaoData);

        $('#distancia-centro-galaxia').html(Math.round((esferaReferencia.position.length() / fatorEscala) * 1000) / 1000);

        return Math.round(lastData[value] * umMilhaoDeAnosJD * 1000) / 1000;

    };

    o.loadData(url);

    return o;

};


text:
package org.apache.ignite.ml.preprocessing.maxabsscaling;

import org.apache.ignite.ml.dataset.Dataset;
import org.apache.ignite.ml.dataset.DatasetBuilder;
import org.apache.ignite.ml.dataset.UpstreamEntry;
import org.apache.ignite.ml.dataset.primitive.context.EmptyContext;
import org.apache.ignite.ml.environment.LearningEnvironmentBuilder;
import org.apache.ignite.ml.preprocessing.PreprocessingTrainer;
import org.apache.ignite.ml.preprocessing.Preprocessor;
import org.apache.ignite.ml.structures.LabeledVector;

/**
 * Trainer of the maxabsscaling preprocessor.
 *
 * @param <K> Type of a key in {@code upstream} data.
 * @param <V> Type of a value in {@code upstream} data.
 */
public class MaxAbsScalerTrainer<K, V> implements PreprocessingTrainer<K, V> {
    /** {@inheritDoc} */
    @Override public MaxAbsScalerPreprocessor<K, V> fit(
        LearningEnvironmentBuilder envBuilder,
        DatasetBuilder<K, V> datasetBuilder,
        Preprocessor<K, V> basePreprocessor) {
        try (Dataset<EmptyContext, MaxAbsScalerPartitionData> dataset = datasetBuilder.build(
            envBuilder,
            (env, upstream, upstreamSize) -> new EmptyContext(),
            (env, upstream, upstreamSize, ctx) -> {
                double[] maxAbs = null;

                while (upstream.hasNext()) {
                    UpstreamEntry<K, V> entity = upstream.next();
                    LabeledVector row = basePreprocessor.apply(entity.getKey(), entity.getValue());

                    if (maxAbs == null) {
                        maxAbs = new double[row.size()];
                        for (int i = 0; i < maxAbs.length; i++)
                            maxAbs[i] = .0;
                    }
                    else
                        assert maxAbs.length == row.size() : "Base preprocessor must return exactly " + maxAbs.length
                            + " features";

                    for (int i = 0; i < row.size(); i++) {
                        if (Math.abs(row.get(i)) > Math.abs(maxAbs[i]))
                            maxAbs[i] = Math.abs(row.get(i));
                    }
                }
                return new MaxAbsScalerPartitionData(maxAbs);
            }, learningEnvironment(basePreprocessor)
        )) {
            double[] maxAbs = dataset.compute(MaxAbsScalerPartitionData::getMaxAbs,
                (a, b) -> {
                    if (a == null)
                        return b;

                    if (b == null)
                        return a;

                    double[] res = new double[a.length];

                    for (int i = 0; i < res.length; i++)
                        res[i] = Math.max(Math.abs(a[i]), Math.abs(b[i]));

                    return res;
                });
            return new MaxAbsScalerPreprocessor<>(maxAbs, basePreprocessor);
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}


text:
<?php

namespace Symfony\Bridge\PhpUnit\DeprecationErrorHandler;

/**
 * @internal
 */
class Configuration
{
    /**
     * @var int[]
     */
    private $thresholds;

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

    /**
     * @var bool
     */
    private $enabled = true;

    /**
     * @var bool[]
     */
    private $verboseOutput;

    /**
     * @param int[]  $thresholds    A hash associating groups to thresholds
     * @param string $regex         Will be matched against messages, to decide
     *                              whether to display a stack trace
     * @param bool[] $verboseOutput Keyed by groups
     */
    private function __construct(array $thresholds = [], $regex = '', $verboseOutput = [])
    {
        $groups = ['total', 'indirect', 'direct', 'self'];

        foreach ($thresholds as $group => $threshold) {
            if (!\in_array($group, $groups, true)) {
                throw new \InvalidArgumentException(sprintf('Unrecognized threshold "%s", expected one of "%s"', $group, implode('", "', $groups)));
            }
            if (!is_numeric($threshold)) {
                throw new \InvalidArgumentException(sprintf('Threshold for group "%s" has invalid value "%s"', $group, $threshold));
            }
            $this->thresholds[$group] = (int) $threshold;
        }
        if (isset($this->thresholds['direct'])) {
            $this->thresholds += [
                'self' => $this->thresholds['direct'],
            ];
        }
        if (isset($this->thresholds['indirect'])) {
            $this->thresholds += [
                'direct' => $this->thresholds['indirect'],
                'self' => $this->thresholds['indirect'],
            ];
        }
        foreach ($groups as $group) {
            if (!isset($this->thresholds[$group])) {
                $this->thresholds[$group] = 999999;
            }
        }
        $this->regex = $regex;

        $this->verboseOutput = [
            'unsilenced' => true,
            'direct' => true,
            'indirect' => true,
            'self' => true,
            'other' => true,
        ];

        foreach ($verboseOutput as $group => $status) {
            if (!isset($this->verboseOutput[$group])) {
                throw new \InvalidArgumentException(sprintf('Unsupported verbosity group "%s", expected one of "%s"', $group, implode('", "', array_keys($this->verboseOutput))));
            }
            $this->verboseOutput[$group] = (bool) $status;
        }
    }

    /**
     * @return bool
     */
    public function isEnabled()
    {
        return $this->enabled;
    }

    /**
     * @param DeprecationGroup[] $deprecationGroups
     *
     * @return bool
     */
    public function tolerates(array $deprecationGroups)
    {
        $grandTotal = 0;

        foreach ($deprecationGroups as $name => $group) {
            if ('legacy' !== $name) {
                $grandTotal += $group->count();
            }
        }

        if ($grandTotal > $this->thresholds['total']) {
            return false;
        }

        foreach (['self', 'direct', 'indirect'] as $deprecationType) {
            if ($deprecationGroups[$deprecationType]->count() > $this->thresholds[$deprecationType]) {
                return false;
            }
        }

        return true;
    }

    /**
     * @param string $message
     *
     * @return bool
     */
    public function shouldDisplayStackTrace($message)
    {
        return '' !== $this->regex && preg_match($this->regex, $message);
    }

    /**
     * @return bool
     */
    public function isInRegexMode()
    {
        return '' !== $this->regex;
    }

    /**
     * @return bool
     */
    public function verboseOutput($group)
    {
        return $this->verboseOutput[$group];
    }

    /**
     * @param string $serializedConfiguration an encoded string, for instance
     *                                        max[total]=1234&max[indirect]=42
     *
     * @return self
     */
    public static function fromUrlEncodedString($serializedConfiguration)
    {
        parse_str($serializedConfiguration, $normalizedConfiguration);
        foreach (array_keys($normalizedConfiguration) as $key) {
            if (!\in_array($key, ['max', 'disabled', 'verbose', 'quiet'], true)) {
                throw new \InvalidArgumentException(sprintf('Unknown configuration option "%s"', $key));
            }
        }

        if (isset($normalizedConfiguration['disabled'])) {
            return self::inDisabledMode();
        }

        $verboseOutput = [];
        if (!isset($normalizedConfiguration['verbose'])) {
            $normalizedConfiguration['verbose'] = true;
        }

        foreach (['unsilenced', 'direct', 'indirect', 'self', 'other'] as $group) {
            $verboseOutput[$group] = (bool) $normalizedConfiguration['verbose'];
        }

        if (isset($normalizedConfiguration['quiet']) && \is_array($normalizedConfiguration['quiet'])) {
            foreach ($normalizedConfiguration['quiet'] as $shushedGroup) {
                $verboseOutput[$shushedGroup] = false;
            }
        }

        return new self(
            isset($normalizedConfiguration['max']) ? $normalizedConfiguration['max'] : [],
            '',
            $verboseOutput
        );
    }

    /**
     * @return self
     */
    public static function inDisabledMode()
    {
        $configuration = new self();
        $configuration->enabled = false;

        return $configuration;
    }

    /**
     * @return self
     */
    public static function inStrictMode()
    {
        return new self(['total' => 0]);
    }

    /**
     * @return self
     */
    public static function inWeakMode()
    {
        $verboseOutput = [];
        foreach (['unsilenced', 'direct', 'indirect', 'self', 'other'] as $group) {
            $verboseOutput[$group] = false;
        }

        return new self([], '', $verboseOutput);
    }

    /**
     * @return self
     */
    public static function fromNumber($upperBound)
    {
        return new self(['total' => $upperBound]);
    }

    /**
     * @return self
     */
    public static function fromRegex($regex)
    {
        return new self([], $regex);
    }
}


text:
//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// value_integrity_test.cpp
//
// Identification: test/codegen/value_integrity_test.cpp
//
// Copyright (c) 2015-2018, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "codegen/testing_codegen_util.h"

#include <random>

#include "codegen/function_builder.h"
#include "codegen/type/tinyint_type.h"
#include "codegen/type/smallint_type.h"
#include "codegen/type/integer_type.h"
#include "codegen/type/bigint_type.h"
#include "function/numeric_functions.h"

namespace peloton {
namespace test {

class ValueIntegrityTest : public PelotonCodeGenTest {};

// This test sets up a function taking a single argument. The body of the
// function divides a constant value with the value of the argument. After
// JITing the function, we test the division by passing in a zero value divisor.
template <typename CType>
void DivideByZeroTest(const codegen::type::Type &data_type, ExpressionType op) {
  codegen::CodeContext code_context;
  codegen::CodeGen codegen{code_context};

  const auto &sql_type = data_type.GetSqlType();

  llvm::Type *llvm_type = nullptr, *llvm_len_type = nullptr;
  sql_type.GetTypeForMaterialization(codegen, llvm_type, llvm_len_type);

  codegen::FunctionBuilder function{
      code_context, "test", codegen.VoidType(), {{"arg", llvm_type}}};
  {
    codegen::Value a = sql_type.GetMaxValue(codegen);
    codegen::Value divisor{data_type, function.GetArgumentByPosition(0)};
    codegen::Value res;
    switch (op) {
      case ExpressionType::OPERATOR_DIVIDE: {
        // a / 0
        res = a.Div(codegen, divisor);
        break;
      }
      case ExpressionType::OPERATOR_MOD: {
        // a % 0
        res = a.Mod(codegen, divisor);
        break;
      }
      default: {
        throw Exception{"Invalid expression type for divide-by-zero test"};
      }
    }

    codegen.Printf("%lu\n", {res.GetValue()});

    function.ReturnAndFinish();
  }

  // Should be able to compile
  EXPECT_TRUE(code_context.Compile());

  typedef void (*func)(CType);
  func f = (func)code_context.GetRawFunctionPointer(function.GetFunction());
  EXPECT_THROW(f(0), DivideByZeroException);
}

template <typename CType>
void OverflowTest(const codegen::type::Type &data_type, ExpressionType op) {
  codegen::CodeContext code_context;
  codegen::CodeGen codegen{code_context};

  const auto &sql_type = data_type.GetSqlType();

  llvm::Type *llvm_type = nullptr, *llvm_len_type = nullptr;
  sql_type.GetTypeForMaterialization(codegen, llvm_type, llvm_len_type);

  codegen::FunctionBuilder function{
      code_context, "test", codegen.VoidType(), {{"arg", llvm_type}}};
  {
    codegen::Value initial{data_type, function.GetArgumentByPosition(0)};
    codegen::Value res;
    switch (op) {
      case ExpressionType::OPERATOR_PLUS: {
        // initial + MAX_FOR_TYPE
        codegen::Value next = sql_type.GetMaxValue(codegen);
        res = next.Add(codegen, initial);
        break;
      }
      case ExpressionType::OPERATOR_MINUS: {
        // a - MIN_FOR_TYPE
        codegen::Value next = sql_type.GetMinValue(codegen);
        res = initial.Sub(codegen, next);
        break;
      }
      case ExpressionType::OPERATOR_MULTIPLY: {
        // a * INT32_MAX
        codegen::Value next = sql_type.GetMaxValue(codegen);
        res = initial.Mul(codegen, next);
        break;
      }
      /*
      case ExpressionType::OPERATOR_DIVIDE: {
        // Overflow when: lhs == INT_MIN && rhs == -1
        // (a - 1) --> this makes a[0] = -1
        // INT64_MIN / (a - 1)
        auto *const_min_exp = ConstIntExpr(INT32_MIN).release();
        auto *const_one_exp = ConstIntExpr(1).release();
        auto *a_sub_one = new expression::OperatorExpression(
            ExpressionType::OPERATOR_MINUS, type::TypeId::INTEGER,
            a_col_exp, const_one_exp);
        a_op_lim = new expression::OperatorExpression(
            exp_type, type::TypeId::INTEGER, const_min_exp, a_sub_one);
        break;
      }
      */
      default: {
        throw Exception{"Invalid expression type for overflow check"};
      }
    }

    codegen.Printf("%lu\n", {res.GetValue()});

    function.ReturnAndFinish();
  }

  // Should be able to compile
  EXPECT_TRUE(code_context.Compile());

  typedef void (*func)(CType);
  func f = (func)code_context.GetRawFunctionPointer(function.GetFunction());
  EXPECT_THROW(f(2), std::overflow_error);
}

TEST_F(ValueIntegrityTest, IntegerOverflow) {
  auto overflowable_ops = {ExpressionType::OPERATOR_MINUS,
                           ExpressionType::OPERATOR_PLUS,
                           ExpressionType::OPERATOR_MULTIPLY};
  for (auto op : overflowable_ops) {
    OverflowTest<int8_t>(codegen::type::TinyInt::Instance(), op);
    OverflowTest<int16_t>(codegen::type::SmallInt::Instance(), op);
    OverflowTest<int32_t>(codegen::type::Integer::Instance(), op);
    OverflowTest<int64_t>(codegen::type::BigInt::Instance(), op);
  }
}

TEST_F(ValueIntegrityTest, IntegerDivideByZero) {
  auto div0_ops = {ExpressionType::OPERATOR_DIVIDE,
                   ExpressionType::OPERATOR_MOD};
  for (auto op : div0_ops) {
    DivideByZeroTest<int8_t>(codegen::type::TinyInt::Instance(), op);
    DivideByZeroTest<int16_t>(codegen::type::SmallInt::Instance(), op);
    DivideByZeroTest<int32_t>(codegen::type::Integer::Instance(), op);
    DivideByZeroTest<int64_t>(codegen::type::BigInt::Instance(), op);
  }
}

namespace {

template <typename T>
using InputFunc = T (*)(const codegen::type::Type &, const char *, uint32_t);

template <typename T>
void TestInputIntegral(
    const codegen::type::Type &type, InputFunc<T> TestFunc,
    std::vector<std::pair<std::string, int64_t>> extra_valid_tests = {},
    std::vector<std::string> extra_invalid_tests = {},
    std::vector<std::string> extra_overflow_tests = {}) {
  // Default valid tests - these are valid for all integral types
  std::vector<std::pair<std::string, int64_t>> valid_tests = {{"0", 0},
                                                              {"-1", -1},
                                                              {"2", 2},
                                                              {"+3", 3},
                                                              {"  4", 4},
                                                              {"  -5", -5},
                                                              {"  +6", 6},
                                                              {"7  ", 7},
                                                              {"-8  ", -8},
                                                              {"  9  ", 9},
                                                              {"  -10  ", -10},
                                                              {"  +11  ", 11}};
  valid_tests.insert(valid_tests.end(), extra_valid_tests.begin(),
                     extra_valid_tests.end());

  // Default invalid tests
  std::vector<std::string> invalid_tests = {"a",       "-b",    "+c",   " 1c",
                                            "2d ",     "3 3",   "-4 4", "-5 a ",
                                            "  -6  a", "  c 7 "};
  invalid_tests.insert(invalid_tests.end(), extra_invalid_tests.begin(),
                       extra_invalid_tests.end());

  // Default overflow tests
  std::vector<std::string> overflow_tests = {
      std::to_string(std::numeric_limits<T>::min()) + "1",
      std::to_string(std::numeric_limits<T>::max()) + "1",
      "123456789123456789123456789"};
  overflow_tests.insert(overflow_tests.end(), extra_overflow_tests.begin(),
                        extra_overflow_tests.end());

  for (const auto &test : valid_tests) {
    auto *ptr = test.first.data();
    auto len = static_cast<uint32_t>(test.first.length());
    try {
      EXPECT_EQ(test.second, TestFunc(type, ptr, len));
    } catch (std::exception &e) {
      EXPECT_TRUE(false) << "Valid input '" << test.first << "' threw an error";
    }
  }

  for (const auto &test : invalid_tests) {
    auto *ptr = test.data();
    auto len = static_cast<uint32_t>(test.length());
    EXPECT_THROW(TestFunc(type, ptr, len), std::runtime_error)
        << "Input '" << test << "' was expected to throw an error, but did not";
  }

  for (const auto &test : overflow_tests) {
    auto *ptr = test.data();
    auto len = static_cast<uint32_t>(test.length());
    EXPECT_THROW(TestFunc(type, ptr, len), std::overflow_error)
        << "Input '" << test << "' expected to overflow, but did not";
  }
}
}  // namespace

TEST_F(ValueIntegrityTest, InputIntegralTypesTest) {
  codegen::type::Type tinyint{type::TypeId::TINYINT, false};
  TestInputIntegral<int8_t>(tinyint, function::NumericFunctions::InputTinyInt,
                            {{"-126", -126}, {"126", 126}});

  codegen::type::Type smallint{type::TypeId::SMALLINT, false};
  TestInputIntegral<int16_t>(smallint,
                             function::NumericFunctions::InputSmallInt);

  codegen::type::Type integer{type::TypeId::INTEGER, false};
  TestInputIntegral<int32_t>(integer, function::NumericFunctions::InputInteger);

  codegen::type::Type bigint{type::TypeId::BIGINT, false};
  TestInputIntegral<int64_t>(bigint, function::NumericFunctions::InputBigInt);
}

TEST_F(ValueIntegrityTest, InputDecimalTypesTest) {
  codegen::type::Type decimal{type::TypeId::DECIMAL, false};

  // First check some valid cases
  std::vector<std::pair<std::string, double>> valid_tests = {
      {"0.0", 0.0},
      {"-1.0", -1.0},
      {"2.0", 2.0},
      {"+3.0", 3.0},
      {"  4.0", 4.0},
      {"  -5.0", -5.0},
      {"  +6.0", 6.0},
      {"7.0  ", 7.0},
      {"-8.0  ", -8.0},
      {"  9.0  ", 9.0},
      {"  -10.0  ", -10.0},
      {"  +11.0  ", 11.0}};

  for (const auto &test_case : valid_tests) {
    auto *ptr = test_case.first.data();
    auto len = static_cast<uint32_t>(test_case.first.length());
    EXPECT_EQ(test_case.second,
              function::NumericFunctions::InputDecimal(decimal, ptr, len));
  }

  // Now let's try some invalid ones. Take each valid test and randomly insert
  // a character somewhere.
  std::vector<std::string> invalid_tests;

  std::random_device rd;
  std::mt19937 rng(rd());

  for (const auto &valid_test : valid_tests) {
    auto orig = valid_test.first;

    std::uniform_int_distribution<> dist(0, orig.length());
    auto pos = dist(rng);

    auto invalid_num = orig.substr(0, pos) + "aa" + orig.substr(pos);

    invalid_tests.push_back(invalid_num);
  }

  // Now check that each test throws an invalid string error
  for (const auto &invalid_test : invalid_tests) {
    auto *ptr = invalid_test.data();
    auto len = static_cast<uint32_t>(invalid_test.length());
    EXPECT_THROW(function::NumericFunctions::InputDecimal(decimal, ptr, len),
                 std::runtime_error)
        << "Input '" << invalid_test
        << "' expected to throw error, but passed parsing logic";
  }
}

}  // namespace test
}  // namespace peloton


text:
<?php
namespace TestApp\Shell;

use Cake\Console\Shell;

class MyShell extends Shell {

	/**
	 * @var string
	 */
	protected $modelClass = 'Cars';

	/**
	 * @var array
	 */
	public $tasks = [
		'Command',
	];

	/**
	 * @return void
	 */
	public function main() {
		$this->loadModel('Wheels');
	}

}


text:
class UsersController < ApplicationController
  before_action :set_user, only: [:show, :edit, :update, :destroy]
  skip_before_filter :require_login, only: [:index, :new, :create]

  # GET /users
  # GET /users.json
  def index
    @users = User.all
  end

  # GET /users/1
  # GET /users/1.json
  def show
  end

  # GET /users/new
  def new
    @user = User.new
  end

  # GET /users/1/edit
  def edit
  end

  # POST /users
  # POST /users.json
  def create
    @user = User.new(user_params)

    respond_to do |format|
      if @user.save
        format.html { redirect_to login_path, notice: 'User was successfully created.' }
        format.json { render :show, status: :created, location: @user }
      else
        format.html { render :new }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /users/1
  # PATCH/PUT /users/1.json
  def update
    respond_to do |format|
      if @user.update(user_params)
        format.html { redirect_to :users, notice: 'User was successfully updated.' }
        format.json { render :show, status: :ok, location: @user }
      else
        flash[:alert] = @user.errors
        format.html { render :edit }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /users/1
  # DELETE /users/1.json
  def destroy
    @user.destroy
    respond_to do |format|
      format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_user
      @user = User.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def user_params
      params.require(:user).permit(:email, :password, :password_confirmation)
    end
end


text:
import os
import glob
import time

from .. import irc, var, ini
from ..tools import is_identified
from ..tools import prefix, time_format

#####################################
#                                   #
#           COMMAND LIST            #
#                                   #
#####################################

def ins_command ():

	var.commands["seen"] = type("command", (object,), {})()
	var.commands["seen"].method = seen
	var.commands["seen"].tags = ["other"]
	var.commands["seen"].aliases = [".seen"]
	var.commands["seen"].usage = [
		"{} user - Check when user was last seen in this channel."
	]

#####################################
#                                   #
#           DATABASE INIT           #
#                                   #
#####################################

def ins_db ():
	flist  = glob.glob("seen/{}/*.ini".format(irc.server))
	chlist = [ os.path.basename(f)[:-4] for f in flist ]
	var.data["seen"] = {}

	for channel in chlist:

		var.data["seen"][channel.replace("-", "/")] = ini.fill_dict(
			filename = "seen/{}/{}.ini".format(irc.server, channel),
			section  = "Seen",
			raw_path = True
		)

		channel = channel.replace("-", "/")

		var.data["seen"][channel] = {
			key : tuple([
				var.data["seen"][channel][key][0],
				float(var.data["seen"][channel][key][1])
			])

			for key in var.data["seen"][channel]
		}

#####################################
#                                   #
#          IDENT FUNCTION           #
#                                   #
#####################################

def ident (f):

	def seen (user, channel, word):
		if (
			(user == irc.admin and is_identified(user)) or
			word[0] in [".seen"]
		):
			f(user, channel, word)
		elif word[0] in [".untrack", ".track"] and is_identified(user):
			if prefix(user, channel) in [
				var.settings["op.prefix"],
				var.settings["ircop.prefix"],
				var.settings["owner.prefix"],
				var.settings["admin.prefix"],
				var.settings["halfop.prefix"]
			]:
				f(user, channel, word)
			else:
				irc.msg(channel, "{}: You need at least hop to do that.".format(user))
		else:
			irc.msg(channel, "{}: You don't have admin rights.".format(user))

	return seen

#####################################
#                                   #
#          MONITOR FUNCTION         #
#                                   #
#####################################

def ins_monitor (line_obj):
	# We're tracking users, so...
	if not hasattr(line_obj, "user"):
		return

	user	  = line_obj.user
	channel   = line_obj.channel if hasattr(line_obj, "channel") \
								 else line_obj.target if hasattr(line_obj,
											"target") else ""
	new_nick  = line_obj.new_nick if hasattr(line_obj, "new_nick") else ""
	timestamp = time.time()

	# Create entry in dictionary if not present.
	if channel not in var.data["seen"]:
		var.data["seen"][channel] = {}

	# The user joins a channel.
	if line_obj.event == "JOIN":

		last_seen = ("joining {}".format(channel), timestamp)
		var.data["seen"][channel][user] = last_seen
		channel = channel.replace("/", "-")
		ini.add_to_ini (
			filename = "seen/{}/{}.ini".format(irc.server, channel),
			section  = "Seen",
			option   = user,
			data	 = "\n".join(map(str, last_seen)),
			raw_path = True
		)

	# The user leaves a channel.
	if line_obj.event == "PART":

		last_seen = ("parting {}".format(channel), timestamp)
		var.data["seen"][channel][user] = last_seen
		channel = channel.replace("/", "-")
		ini.add_to_ini (
			filename = "seen/{}/{}.ini".format(irc.server, channel),
			section  = "Seen",
			option   = user,
			data	 = "\n".join(map(str, last_seen)),
			raw_path = True
		)

	# A channel message is received.
	elif line_obj.event == "PRIVMSG":

		last_seen = ("saying: \"{}\"".format(line_obj.message), timestamp)
		var.data["seen"][channel][user] = last_seen
		channel = channel.replace("/", "-")
		ini.add_to_ini (
			filename = "seen/{}/{}.ini".format(irc.server, channel),
			section  = "Seen",
			option   = user,
			data	 = "\n".join(map(str, last_seen)),
			raw_path = True
		)

	# The user changes nicknames.
	elif line_obj.event == "NICK":

		last_seen = ("changing nickname to {}".format(new_nick), timestamp)
		var.data["seen"][channel][user] = last_seen
		channel = channel.replace("/", "-")
		ini.add_to_ini (
			filename = "seen/{}/{}.ini".format(irc.server, channel),
			section  = "Seen",
			option   = user,
			data	 = "\n".join(map(str, last_seen)),
			raw_path = True
		)

#####################################
#                                   #
#           COMMAND METHOD          #
#                                   #
#####################################

def seen (user, channel, word):

	if len(word) == 1:
		irc.msg(channel, "{}: Gimme a name!".format(user))
	elif channel not in var.data["seen"]:
		irc.msg(channel, "{}: There are no activity records for this channel yet.".format(user))
	else:
		target = word[1]

		# Has to be case insensitive.
		for nick in var.data["seen"][channel]:
			if target.lower() == nick.lower():
				target = nick

		if target not in var.data["seen"][channel]:
			irc.msg(channel, "I have not seen {}.".format(target))

		else:
			line = var.data["seen"][channel][target][0]
			elapsed_time = time.time() - var.data["seen"][channel][target][1]

			if elapsed_time <= 300:
				line += " just now."
			else:
				line += " {} ago.".format(time_format(elapsed_time))

			irc.msg(channel, "{} was last seen {}".format(target, line))


text:
======
Models
======

.. module:: macaron

A model corresponds to a table of your database.
It contains relationships and behaviors of the data.

The basics:

- Each model is a Python class which subclasses :class:`macaron.Model`.
- Each database field is represented as an attribute of the model.
- Macaron defines attributes of the model from the table information
  automatically.
- Macaron's model is similar to the one in Django.

Model definition
================

Basic usage
-----------

This example model defines a ``Member``,
which has a ``first_name`` and ``last_name``:

::

    import macaron
    class Member(macaron.Model): pass

The above ``Member`` model corresponds to a database table like this:

::

    CREATE TABLE member (
        id          INTEGER PRIMARY KEY,
        first_name  TEXT DEFAULT 'unknown',
        last_name   TEXT,
        joined      TIMESTAMP
    );

In order to keep Macaron simple, it does not contain functionality for
creating tables.
But attributes of the model are inferred from the table definition.
In general, you don't need to modify the class definition of the model
when the database table is modified.

.. note::

   - The name of the table, ``member``, is automatically derived
    from the class name, ``Member``, but it can be specified
    with ``_table_name`` property.
   - You need to ``CREATE TABLE`` manually.
   - Any DEFAULT property is auto-detected.

Field definition
----------------

In the most simple case, you do not define your :class:`Model` classes,
you just declare their existence.
But if you define fields on your :class:`Model`\ s,
you can specify validation and conversion mechanisms for each field.
A field definition example is below.

::

    class Member(macaron.Model):
        name = macaron.CharField(max_length=20)
        joined = macaon.TimestampAtCreate()
        modified = macaron.TimestampAtSave()
        point = macaron.IntegerField(min=0, max=20)

In the code, notice the :class:`TimestampAtCreate`,
:class:`TimestampAtSave`, `IntegerField`, and `CharField`.
The former two classes differs from the latter two ones.
Built-in classes are described below.

.. class:: TimestampAtCreate()

   This sets time created when ``INSERT`` is conducted.

.. class:: TimestampAtSave()

   This sets time modified when ``UPDATE`` is conducted.

.. class:: FloatField([min, max])

   :param min: minimum value
   :param max: maximum value

   This is for number fields.
   The minimum and maximum values can be specified.

.. class:: IntegerField([min, max])

   This is for integer fields.

.. class:: CharField([min_length, max_length])

   :param min_length: minimum length
   :param max_length: maximum length

   This is for text fields.
   If you want to check the text length,
   you can specify ``min_length`` and ``max_length``.

Relationships
-------------

If you use a single table which has no relationships,
this is very simple.
This is described above.
However, it is possible to describe relationships if you need to.
Macaron supports "Many-to-One" relationships
and needs the field information in the class definition.
See below.

::

    class Team(macaron.Model): pass

    class Member(macaron.Model):
        team = macaron.ManyToOne(Team, related_name="members", fkey="team_id", key="id")

These Team and Member classes are defined as database tables in SQL.

::

    CREATE TABLE team (
        id          INTEGER PRIMARY KEY,
        name        TEXT
    );

    CREATE TABLE member (
        id          INTEGER PRIMARY KEY,
        team_id     INTEGER NOT NULL,
        first_name  TEXT,
        last_name   TEXT,
        age         INT
    );

.. note::

   - The parameters ``related_name``, ``fkey`` (foreign key),
     and ``key`` of :class:`macaron.ManyToOne` can be omitted.
     Then, parameters are specified as below.

     - The ``related_name`` is derived from ``Team``
       and '_set', i.e. 'team_set'.
     - The ``fkey`` is specified as ``Team``'s table name
       and '_id', i.e. 'team_id'.
     - The ``key`` is specified as ``Team``'s primary key name, i.e. 'id'.

In this example, a Many-to-One relationship is defined as above.
It represents that a ``Member`` has a ``Team``
-- means a ``Member`` belongs to a ``Team``
but each ``Member`` only belongs to one ``Team``.

The attribute ``team`` of ``Member`` class
relates the ``Member`` to the ``Team``.
This definition also create *recursive relationships*
(an object with a Many-to-One relationship to itself)
automatically.
If you want to use another name for the field, that is possible, too.

::

    class Member(macaron.Model):
        belongs_to = macaron.ManyToOne(Team, fkey="team_id", key="id", related_name="members")

Using models
============

Customizing fields and behaviors of models
==========================================

Macaron's model class is designed to be flexible.
You can customize field types and actions to perform
before and after ``INSERT`` and ``UPDATE``.

Field types
-----------

The field definition section describes how to use field classes.
This section describes how to customize fields.
Field type classes are derived from the base class :class:`Field`
or subclasses of :class:`Field`.
Now there are :class:`AtCreate` and :class:`AtSave` subclasses
derived from :class:`Field`.
For example, :class:`TimestampAtCreate` is a subclass of :class:`AtCreate`
(i.e. it is a subclass of :class:`Field`, too).

For example, :class:`TimestampAtCreate` is implemented as below.::

    class TimestampAtCreate(AtCreate):
        def set(self, obj, value):
            return datetime.datetime.now()

The :meth:`TimestampAtCreate.set` is called
when an object is inserted into the database.
In this way, you can control behaviors of model objects
by implementing some callback methods.

These methods are called in the following sequence.

- In ``INSERT`` and ``UPDATE``

  1. The :meth:`Field.set` is called at ``INSERT`` or ``UPDATE``.
  2. The :meth:`Field.validate` is called for validation.
  3. The :meth:`Model.before_create` or :meth:`Model.before_save` is called
     (see next section).
  4. The :meth:`Field.to_database` is called.
  5. SQL is executed.
  6. The :meth:`Field.to_object` is called with a new record from the database.
  7. The :meth:`Model.after_create` or :meth:`Model.after_save` is called
     (see next section).

- In ``SELECT``

  1. SQL is executed.
  2. The :meth:`Field.to_object` is called with the selected record.

Hooks in the model
--------------

- :meth:`Model.before_create()`
- :meth:`Model.before_save()`
- :meth:`Model.after_create()`
- :meth:`Model.after_save()`


text:
import {MessageType} from '../../../src/3p-frame-messaging';
import {WindowInterface} from '#core/window/interface';
import {getMode} from '../../../src/mode';
import {iframeMessagingClientFor} from '#inabox/inabox-iframe-messaging-client';
import {layoutRectLtwh} from '#core/dom/layout/rect';

/**
 * Setup cross-origin iframe polyfill for AMP iframes, such as inabox.
 *
 * @param {!Window} win
 */
export function maybeSetupCrossOriginObserver(win) {
  if (win == WindowInterface.getTop(win) || getMode(win).runtime != 'inabox') {
    // Not an iframe at all.
    return;
  }

  // Check if there is an iframe client connected and if it's indeed a polyfill.
  const iframeClient = iframeMessagingClientFor(win);
  const setupPolyfillUpdater =
    win.IntersectionObserver['_setupCrossOriginUpdater'];
  if (!iframeClient || !setupPolyfillUpdater) {
    return;
  }

  const updater = setupPolyfillUpdater();
  iframeClient.makeRequest(
    MessageType.SEND_POSITIONS,
    MessageType.POSITION,
    (data) => {
      const boundingClientRect =
        /** @type {!../../../src/layout-rect.LayoutRectDef} */ (
          data['targetRect']
        );
      const viewportRect =
        /** @type {!../../../src/layout-rect.LayoutRectDef} */ (
          data['viewportRect']
        );
      const intersectionRect = calculateIntersectionRect(
        viewportRect,
        boundingClientRect
      );
      updater(boundingClientRect, intersectionRect);
    }
  );
}

/**
 * @param {!../../../src/layout-rect.LayoutRectDef} viewportRect
 * @param {!../../../src/layout-rect.LayoutRectDef} targetRect
 * @return {!../../../src/layout-rect.LayoutRectDef}
 * @visibleForTesting
 */
export function calculateIntersectionRect(viewportRect, targetRect) {
  const top = Math.max(targetRect.top, 0);
  const left = Math.max(targetRect.left, 0);
  const bottom = Math.min(targetRect.bottom, viewportRect.height);
  const right = Math.min(targetRect.right, viewportRect.width);
  if (top > bottom || left > right) {
    return layoutRectLtwh(0, 0, 0, 0);
  }
  return layoutRectLtwh(left, top, right - left, bottom - top);
}


text:
package com.diamondq.common.model.persistence;

import com.diamondq.common.context.ContextFactory;
import com.diamondq.common.errors.Verify;
import com.diamondq.common.model.generic.AbstractDocumentPersistenceLayer;
import com.diamondq.common.model.generic.GenericToolkit;
import com.diamondq.common.model.interfaces.Property;
import com.diamondq.common.model.interfaces.PropertyDefinition;
import com.diamondq.common.model.interfaces.PropertyType;
import com.diamondq.common.model.interfaces.Scope;
import com.diamondq.common.model.interfaces.Structure;
import com.diamondq.common.model.interfaces.StructureDefinition;
import com.diamondq.common.model.interfaces.StructureDefinitionRef;
import com.diamondq.common.model.interfaces.StructureRef;
import com.diamondq.common.model.interfaces.Toolkit;
import com.diamondq.common.storage.kv.IKVStore;
import com.diamondq.common.storage.kv.IKVTableDefinitionSupport;
import com.diamondq.common.storage.kv.IKVTransaction;
import com.diamondq.common.storage.kv.KVColumnType;
import com.diamondq.common.storage.kv.KVTableDefinitionBuilder;
import com.google.common.cache.Cache;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;

import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;

import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * A Persistence Layer that stores the information in a Storage KV store
 */
public class StorageStructureKVPersistenceLayer extends AbstractDocumentPersistenceLayer<Map<String, Object>, String> {

  private final IKVStore mStore;

  private boolean        mSetupTables = false;

  /**
   * Default constructor
   *
   * @param pContextFactory the context factory
   * @param pStore the KV store for structures
   */
  public StorageStructureKVPersistenceLayer(ContextFactory pContextFactory, IKVStore pStore) {
    super(pContextFactory, false, false, -1, true, true, -1, false, false, -1, false, false, -1);
    ContextFactory.staticReportTrace(StorageStructureKVPersistenceLayer.class, this, pStore);
    mStore = pStore;
  }

  private void setupTables() {
    synchronized (this) {
      if (mSetupTables == false) {
        IKVTableDefinitionSupport<?, ?> tableDefinitionSupport = Verify.notNull(mStore.getTableDefinitionSupport());

        KVTableDefinitionBuilder<?> tableBuilder = tableDefinitionSupport.createTableDefinitionBuilder();
        tableBuilder = tableBuilder.tableName("structures");
        tableBuilder.addColumn(tableDefinitionSupport.createColumnDefinitionBuilder().name("definition")
          .type(KVColumnType.Binary).maxLength(1024 * 1024 * 10).build());

        tableDefinitionSupport.addTableDefinition(tableBuilder.build());

        mSetupTables = true;
      }
    }
  }

  /**
   * @see com.diamondq.common.model.generic.AbstractDocumentPersistenceLayer#internalLookupStructureDefinitionByNameAndRevision(com.diamondq.common.model.interfaces.Toolkit,
   *      com.diamondq.common.model.interfaces.Scope, java.lang.String, int)
   */
  @Override
  protected @Nullable StructureDefinition internalLookupStructureDefinitionByNameAndRevision(Toolkit pToolkit,
    Scope pScope, String pName, int pRevision) {
    setupTables();
    IKVTransaction transaction = mStore.startTransaction();
    boolean commit = false;
    try {
      @SuppressWarnings("unchecked")
      Map<String, Object> result = transaction.getByKey("structures", pName, String.valueOf(pRevision), Map.class);
      if (result == null)
        return null;
      byte[] data = Verify.notNull((byte[]) result.get("definition"));

      /* Now convert the data into a StructureDefinition */

      StructureDefinition sd = pToolkit.populateStructureDefinition(pScope, data);
      commit = true;
      return sd;
    }
    finally {
      if (commit == true)
        transaction.commit();
      else
        transaction.rollback();
    }
  }

  /**
   * @see com.diamondq.common.model.generic.AbstractCachingPersistenceLayer#internalGetAllMissingStructureDefinitionRefs(com.diamondq.common.model.interfaces.Toolkit,
   *      com.diamondq.common.model.interfaces.Scope, com.google.common.cache.Cache)
   */
  @Override
  protected Collection<StructureDefinitionRef> internalGetAllMissingStructureDefinitionRefs(Toolkit pToolkit,
    Scope pScope, @Nullable Cache<String, StructureDefinition> pStructureDefinitionCache) {
    setupTables();
    IKVTransaction transaction = mStore.startTransaction();
    boolean commit = false;
    try {
      ImmutableList.Builder<StructureDefinitionRef> resultBuilder = ImmutableList.builder();
      for (Iterator<String> i = transaction.keyIterator("structures"); i.hasNext();) {
        String name = i.next();
        for (Iterator<String> i2 = transaction.keyIterator2("structures", name); i2.hasNext();) {
          String revStr = i2.next();
          int rev = Integer.valueOf(revStr);
          if (pStructureDefinitionCache != null) {
            String cacheKey = new StringBuilder(name).append('-').append(rev).toString();
            if (pStructureDefinitionCache.getIfPresent(cacheKey) != null)
              continue;
          }
          resultBuilder.add(pToolkit.createStructureDefinitionRefFromSerialized(pScope,
            new StringBuilder(name).append(':').append(rev).toString()));
        }
      }
      commit = true;
      return resultBuilder.build();
    }
    finally {
      if (commit == true)
        transaction.commit();
      else
        transaction.rollback();
    }
  }

  /**
   * @see com.diamondq.common.model.generic.AbstractCachingPersistenceLayer#internalWriteStructureDefinition(com.diamondq.common.model.interfaces.Toolkit,
   *      com.diamondq.common.model.interfaces.Scope, com.diamondq.common.model.interfaces.StructureDefinition)
   */
  @Override
  protected StructureDefinition internalWriteStructureDefinition(Toolkit pToolkit, Scope pScope,
    StructureDefinition pValue) {
    setupTables();
    IKVTransaction transaction = mStore.startTransaction();
    boolean commit = false;
    try {
      byte[] bytes = pValue.saveToByteArray();
      transaction.putByKey("structures", pValue.getName(), String.valueOf(pValue.getRevision()),
        Collections.singletonMap("definition", bytes));
      commit = true;
      return pValue;
    }
    finally {
      if (commit == true)
        transaction.commit();
      else
        transaction.rollback();
    }

  }

  /**
   * @see com.diamondq.common.model.generic.AbstractCachingPersistenceLayer#internalDeleteStructureDefinition(com.diamondq.common.model.interfaces.Toolkit,
   *      com.diamondq.common.model.interfaces.Scope, com.diamondq.common.model.interfaces.StructureDefinition)
   */
  @Override
  protected void internalDeleteStructureDefinition(Toolkit pToolkit, Scope pScope, StructureDefinition pValue) {
    setupTables();
    IKVTransaction transaction = mStore.startTransaction();
    boolean commit = false;
    try {
      transaction.removeByKey("structures", pValue.getName(), String.valueOf(pValue.getRevision()));
      commit = true;
    }
    finally {
      if (commit == true)
        transaction.commit();
      else
        transaction.rollback();
    }
  }

  /**
   * @see com.diamondq.common.model.generic.PersistenceLayer#inferStructureDefinitions(com.diamondq.common.model.generic.GenericToolkit,
   *      com.diamondq.common.model.interfaces.Scope)
   */
  @Override
  public boolean inferStructureDefinitions(GenericToolkit pGenericToolkit, Scope pScope) {
    throw new UnsupportedOperationException();
  }

  /**
   * @see com.diamondq.common.model.generic.AbstractDocumentPersistenceLayer#loadStructureConfigObject(com.diamondq.common.model.interfaces.Toolkit,
   *      com.diamondq.common.model.interfaces.Scope, java.lang.String, java.lang.String, boolean)
   */
  @Override
  protected @Nullable Map<String, Object> loadStructureConfigObject(Toolkit pToolkit, Scope pScope, String pDefName,
    String pKey, boolean pCreateIfMissing) {
    throw new UnsupportedOperationException();
  }

  /**
   * @see com.diamondq.common.model.generic.AbstractDocumentPersistenceLayer#constructOptimisticObj(com.diamondq.common.model.interfaces.Toolkit,
   *      com.diamondq.common.model.interfaces.Scope, java.lang.String, java.lang.String,
   *      com.diamondq.common.model.interfaces.Structure)
   */
  @Override
  protected @Nullable String constructOptimisticObj(Toolkit pToolkit, Scope pScope, String pDefName, String pKey,
    @Nullable Structure pStructure) {
    throw new UnsupportedOperationException();
  }

  /**
   * @see com.diamondq.common.model.generic.AbstractDocumentPersistenceLayer#setStructureConfigObjectProp(com.diamondq.common.model.interfaces.Toolkit,
   *      com.diamondq.common.model.interfaces.Scope, java.lang.Object, boolean, java.lang.String,
   *      com.diamondq.common.model.interfaces.PropertyType, java.lang.Object)
   */
  @Override
  protected <@NonNull R> void setStructureConfigObjectProp(Toolkit pToolkit, Scope pScope, Map<String, Object> pConfig,
    boolean pIsMeta, String pKey, PropertyType pType, @NonNull R pValue) {
    throw new UnsupportedOperationException();
  }

  /**
   * @see com.diamondq.common.model.generic.AbstractDocumentPersistenceLayer#getStructureConfigObjectProp(com.diamondq.common.model.interfaces.Toolkit,
   *      com.diamondq.common.model.interfaces.Scope, java.lang.Object, boolean, java.lang.String,
   *      com.diamondq.common.model.interfaces.PropertyType)
   */
  @Override
  protected <R> R getStructureConfigObjectProp(Toolkit pToolkit, Scope pScope, Map<String, Object> pConfig,
    boolean pIsMeta, String pKey, PropertyType pType) {
    throw new UnsupportedOperationException();
  }

  /**
   * @see com.diamondq.common.model.generic.AbstractDocumentPersistenceLayer#hasStructureConfigObjectProp(com.diamondq.common.model.interfaces.Toolkit,
   *      com.diamondq.common.model.interfaces.Scope, java.lang.Object, boolean, java.lang.String)
   */
  @Override
  protected boolean hasStructureConfigObjectProp(Toolkit pToolkit, Scope pScope, Map<String, Object> pConfig,
    boolean pIsMeta, String pKey) {
    throw new UnsupportedOperationException();
  }

  /**
   * @see com.diamondq.common.model.generic.AbstractDocumentPersistenceLayer#removeStructureConfigObjectProp(com.diamondq.common.model.interfaces.Toolkit,
   *      com.diamondq.common.model.interfaces.Scope, java.lang.Object, boolean, java.lang.String,
   *      com.diamondq.common.model.interfaces.PropertyType)
   */
  @Override
  protected boolean removeStructureConfigObjectProp(Toolkit pToolkit, Scope pScope, Map<String, Object> pConfig,
    boolean pIsMeta, String pKey, PropertyType pType) {
    throw new UnsupportedOperationException();
  }

  /**
   * @see com.diamondq.common.model.generic.AbstractDocumentPersistenceLayer#saveStructureConfigObject(com.diamondq.common.model.interfaces.Toolkit,
   *      com.diamondq.common.model.interfaces.Scope, java.lang.String, java.lang.String, java.lang.Object, boolean,
   *      java.lang.Object)
   */
  @Override
  protected boolean saveStructureConfigObject(Toolkit pToolkit, Scope pScope, String pDefName, String pKey,
    Map<String, Object> pConfig, boolean pMustMatchOptimisticObj, @Nullable String pOptimisticObj) {
    throw new UnsupportedOperationException();
  }

  /**
   * @see com.diamondq.common.model.generic.AbstractDocumentPersistenceLayer#isStructureConfigChanged(com.diamondq.common.model.interfaces.Toolkit,
   *      com.diamondq.common.model.interfaces.Scope, java.lang.Object)
   */
  @Override
  protected boolean isStructureConfigChanged(Toolkit pToolkit, Scope pScope, Map<String, Object> pConfig) {
    throw new UnsupportedOperationException();
  }

  /**
   * @see com.diamondq.common.model.generic.AbstractDocumentPersistenceLayer#internalPopulateChildStructureList(com.diamondq.common.model.interfaces.Toolkit,
   *      com.diamondq.common.model.interfaces.Scope, java.lang.Object,
   *      com.diamondq.common.model.interfaces.StructureDefinition, java.lang.String, java.lang.String,
   *      com.diamondq.common.model.interfaces.PropertyDefinition, com.google.common.collect.ImmutableList.Builder)
   */
  @Override
  protected void internalPopulateChildStructureList(Toolkit pToolkit, Scope pScope,
    @Nullable Map<String, Object> pConfig, StructureDefinition pStructureDefinition, String pStructureDefName,
    @Nullable String pKey, @Nullable PropertyDefinition pPropDef, Builder<StructureRef> pStructureRefListBuilder) {
    throw new UnsupportedOperationException();
  }

  /**
   * @see com.diamondq.common.model.generic.AbstractDocumentPersistenceLayer#persistContainerProp(com.diamondq.common.model.interfaces.Toolkit,
   *      com.diamondq.common.model.interfaces.Scope, com.diamondq.common.model.interfaces.Structure,
   *      com.diamondq.common.model.interfaces.Property)
   */
  @Override
  protected boolean persistContainerProp(Toolkit pToolkit, Scope pScope, Structure pStructure, Property<?> pProp) {
    throw new UnsupportedOperationException();
  }

  /**
   * @see com.diamondq.common.model.generic.AbstractCachingPersistenceLayer#internalDeleteStructure(com.diamondq.common.model.interfaces.Toolkit,
   *      com.diamondq.common.model.interfaces.Scope, java.lang.String, java.lang.String,
   *      com.diamondq.common.model.interfaces.Structure)
   */
  @Override
  protected boolean internalDeleteStructure(Toolkit pToolkit, Scope pScope, String pDefName, String pKey,
    Structure pStructure) {
    throw new UnsupportedOperationException();
  }

  /**
   * @see com.diamondq.common.model.generic.PersistenceLayer#clearStructures(com.diamondq.common.model.interfaces.Toolkit,
   *      com.diamondq.common.model.interfaces.Scope, com.diamondq.common.model.interfaces.StructureDefinition)
   */
  @Override
  public void clearStructures(Toolkit pToolkit, Scope pScope, StructureDefinition pStructureDef) {
    throw new UnsupportedOperationException();
  }
}