text:
//===--- TypeCheckCaptures.cpp - Capture Analysis -------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements computing capture info for closure expressions and named
// local functions.
//
//===----------------------------------------------------------------------===//

#include "TypeChecker.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/Decl.h"
#include "swift/AST/TypeWalker.h"
#include "swift/Basic/Defer.h"
#include "llvm/ADT/SmallPtrSet.h"
using namespace swift;

namespace {

class FindCapturedVars : public ASTWalker {
  TypeChecker &TC;
  SmallVectorImpl<CapturedValue> &Captures;
  llvm::SmallDenseMap<ValueDecl*, unsigned, 4> captureEntryNumber;
  SourceLoc CaptureLoc;
  SourceLoc &GenericParamCaptureLoc;
  SourceLoc &DynamicSelfCaptureLoc;
  DynamicSelfType *&DynamicSelf;
  llvm::SmallPtrSet<ValueDecl *, 2> Diagnosed;
  /// The AbstractClosureExpr or AbstractFunctionDecl being analyzed.
  AnyFunctionRef AFR;
public:
  FindCapturedVars(TypeChecker &tc,
                   SmallVectorImpl<CapturedValue> &Captures,
                   SourceLoc &GenericParamCaptureLoc,
                   SourceLoc &DynamicSelfCaptureLoc,
                   DynamicSelfType *&DynamicSelf,
                   AnyFunctionRef AFR)
      : TC(tc), Captures(Captures),
        GenericParamCaptureLoc(GenericParamCaptureLoc),
        DynamicSelfCaptureLoc(DynamicSelfCaptureLoc),
        DynamicSelf(DynamicSelf),
        AFR(AFR) {
    if (auto AFD = AFR.getAbstractFunctionDecl())
      CaptureLoc = AFD->getLoc();
    else {
      auto ACE = AFR.getAbstractClosureExpr();
      if (auto closure = dyn_cast<ClosureExpr>(ACE))
        CaptureLoc = closure->getInLoc();

      if (CaptureLoc.isInvalid())
        CaptureLoc = ACE->getLoc();
    }
  }

  /// \brief Check if the type of an expression references any generic
  /// type parameters, or the dynamic Self type.
  ///
  /// Note that we do not need to distinguish inner from outer generic
  /// parameters here -- if a local function has its own inner parameter
  /// list, it also implicitly captures outer parameters, even if they're
  /// not used anywhere inside the body.
  void checkType(Type type, SourceLoc loc) {

    if (!type)
      return;

    // We want to look through type aliases here.
    type = type->getCanonicalType();

    class TypeCaptureWalker : public TypeWalker {
      AnyFunctionRef AFR;
      llvm::function_ref<void(Type)> Callback;
    public:
      explicit TypeCaptureWalker(AnyFunctionRef AFR,
                                 llvm::function_ref<void(Type)> callback)
        : AFR(AFR), Callback(callback) {}

      Action walkToTypePre(Type ty) override {
        Callback(ty);
        // Pseudogeneric classes don't use their generic parameters so we
        // don't need to visit them.
        if (AFR.isObjC()) {
          if (auto clas = dyn_cast_or_null<ClassDecl>(ty->getAnyNominal())) {
            if (clas->usesObjCGenericsModel()) {
              return Action::SkipChildren;
            }
          }
        }
        return Action::Continue;
      }
    };
    // If the type contains dynamic 'Self', conservatively assume we will
    // need 'Self' metadata at runtime. We could generalize the analysis
    // used below for usages of generic parameters in Objective-C
    // extensions, and re-use it here.
    //
    // For example, forming an existential from a value of type 'Self'
    // does not need the dynamic 'Self' type -- the static type will
    // suffice. Also, just passing around a value of type 'Self' does
    // not need metadata either, since it is represented as a single
    // retainable pointer. Similarly stored property access does not
    // need it, etc.
    if (type->hasDynamicSelfType()) {
      type.walk(TypeCaptureWalker(AFR, [&](Type t) {
        if (auto *dynamicSelf = t->getAs<DynamicSelfType>()) {
          if (DynamicSelfCaptureLoc.isInvalid()) {
            DynamicSelfCaptureLoc = loc;
            DynamicSelf = dynamicSelf;
          }
        }
      }));
    }

    // Similar to dynamic 'Self', IRGen doesn't really need type metadata
    // for class-bound archetypes in nearly as many cases as with opaque
    // archetypes.
    //
    // Perhaps this entire analysis should happen at the SILGen level,
    // instead, but even there we don't really have enough information to
    // perform it accurately.
    if (type->hasArchetype()) {
      type.walk(TypeCaptureWalker(AFR, [&](Type t) {
        if (t->is<ArchetypeType>() &&
            !t->isOpenedExistential() &&
          GenericParamCaptureLoc.isInvalid()) {
          GenericParamCaptureLoc = loc;
        }
      }));
    }
  }

  /// Add the specified capture to the closure's capture list, diagnosing it
  /// if invalid.
  void addCapture(CapturedValue capture, SourceLoc Loc) {
    auto VD = capture.getDecl();

    // Check to see if we already have an entry for this decl.
    unsigned &entryNumber = captureEntryNumber[VD];
    if (entryNumber == 0) {
      Captures.push_back(capture);
      entryNumber = Captures.size();
    } else {
      // If this already had an entry in the capture list, make sure to merge
      // the information together.  If one is noescape but the other isn't,
      // then the result is escaping.
      unsigned Flags =
        Captures[entryNumber-1].getFlags() & capture.getFlags();
      capture = CapturedValue(VD, Flags);
      Captures[entryNumber-1] = capture;
    }

    // Visit the type of the capture, if it isn't a class reference, since
    // we'd need the metadata to do so.
    if (VD->hasType()
        && (!AFR.isObjC()
            || !VD->getType()->hasRetainablePointerRepresentation()))
      checkType(VD->getType(), VD->getLoc());

    // If VD is a noescape decl, then the closure we're computing this for
    // must also be noescape.
    if (VD->hasType() && VD->getType()->is<AnyFunctionType>() &&
        VD->getType()->castTo<AnyFunctionType>()->isNoEscape() &&
        !capture.isNoEscape() &&
        // Don't repeatedly diagnose the same thing.
        Diagnosed.insert(VD).second) {

      // Otherwise, diagnose this as an invalid capture.
      bool isDecl = AFR.getAbstractFunctionDecl() != nullptr;

      TC.diagnose(Loc, isDecl ? diag::decl_closure_noescape_use
                              : diag::closure_noescape_use,
                  VD->getName());

      // If we're a parameter, emit a helpful fixit to add @escaping
      auto paramDecl = dyn_cast<ParamDecl>(VD);
      bool isAutoClosure =
          VD->getType()->castTo<AnyFunctionType>()->isAutoClosure();
      if (paramDecl && !isAutoClosure) {
        TC.diagnose(paramDecl->getStartLoc(), diag::noescape_parameter,
                    paramDecl->getName())
            .fixItInsert(paramDecl->getTypeLoc().getSourceRange().Start,
                         "@escaping ");
      } else if (isAutoClosure) {
        // TODO: add in a fixit for autoclosure
        TC.diagnose(VD->getLoc(), diag::noescape_autoclosure, VD->getName());
      }
    }
  }

  std::pair<bool, Expr *> walkToDeclRefExpr(DeclRefExpr *DRE) {
    auto *D = DRE->getDecl();

    // Capture the generic parameters of the decl.
    if (!AFR.isObjC() || !D->isObjC() || isa<ConstructorDecl>(D)) {
      for (auto sub : DRE->getDeclRef().getSubstitutions()) {
        checkType(sub.getReplacement(), DRE->getLoc());
      }
    }

    // DC is the DeclContext where D was defined
    // CurDC is the DeclContext where D was referenced
    auto DC = D->getDeclContext();
    auto CurDC = AFR.getAsDeclContext();

    // A local reference is not a capture.
    if (CurDC == DC)
      return { false, DRE };

    auto TmpDC = CurDC;

    if (!isa<TopLevelCodeDecl>(DC)) {
      while (TmpDC != nullptr) {
        if (TmpDC == DC)
          break;

        // We have an intervening nominal type context that is not the
        // declaration context, and the declaration context is not global.
        // This is not supported since nominal types cannot capture values.
        if (auto NTD = dyn_cast<NominalTypeDecl>(TmpDC)) {
          if (DC->isLocalContext()) {
            TC.diagnose(DRE->getLoc(), diag::capture_across_type_decl,
                        NTD->getDescriptiveKind(),
                        D->getName());

            TC.diagnose(NTD->getLoc(), diag::type_declared_here);

            TC.diagnose(D, diag::decl_declared_here, D->getFullName());
            return { false, DRE };
          }
        }

        TmpDC = TmpDC->getParent();
      }

      // We walked all the way up to the root without finding the declaration,
      // so this is not a capture.
      if (TmpDC == nullptr)
        return { false, DRE };
    }

    // Only capture var decls at global scope.  Other things can be captured
    // if they are local.
    if (!isa<VarDecl>(D) && !DC->isLocalContext())
      return { false, DRE };

    // Can only capture a variable that is declared before the capturing
    // entity.
    llvm::DenseSet<ValueDecl *> checkedCaptures;
    llvm::SmallVector<FuncDecl *, 2> capturePath;

    std::function<bool (ValueDecl *)>
    validateForwardCapture = [&](ValueDecl *capturedDecl) -> bool {
      if (!checkedCaptures.insert(capturedDecl).second)
        return true;

      // Captures at nonlocal scope are order-invariant.
      if (!capturedDecl->getDeclContext()->isLocalContext())
        return true;

      // Assume implicit decl captures are OK.
      if (!CaptureLoc.isValid() || !capturedDecl->getLoc().isValid())
        return true;

      // Check the order of the declarations.
      if (!TC.Context.SourceMgr.isBeforeInBuffer(CaptureLoc,
                                                 capturedDecl->getLoc()))
        return true;

      // Forward captures of functions are OK, if the function doesn't
      // transitively capture variables ahead of the original function.
      if (auto func = dyn_cast<FuncDecl>(capturedDecl)) {
        if (!func->getCaptureInfo().hasBeenComputed()) {
          // Check later.
          TC.ForwardCapturedFuncs[func].push_back(AFR);
          return true;
        }
        // Recursively check the transitive captures.
        capturePath.push_back(func);
        SWIFT_DEFER { capturePath.pop_back(); };
        for (auto capture : func->getCaptureInfo().getCaptures())
          if (!validateForwardCapture(capture.getDecl()))
            return false;
        return true;
      }

      // Diagnose the improper forward capture.
      if (Diagnosed.insert(capturedDecl).second) {
        if (capturedDecl == DRE->getDecl()) {
          TC.diagnose(DRE->getLoc(), diag::capture_before_declaration,
                      capturedDecl->getName());
        } else {
          TC.diagnose(DRE->getLoc(),
                      diag::transitive_capture_before_declaration,
                      DRE->getDecl()->getName(),
                      capturedDecl->getName());
          ValueDecl *prevDecl = capturedDecl;
          for (auto path : reversed(capturePath)) {
            TC.diagnose(path->getLoc(),
                        diag::transitive_capture_through_here,
                        path->getName(),
                        prevDecl->getName());
            prevDecl = path;
          }
        }
        TC.diagnose(capturedDecl, diag::decl_declared_here,
                    capturedDecl->getFullName());
      }
      return false;
    };

    if (!validateForwardCapture(DRE->getDecl()))
      return { false, DRE };

    bool isInOut = D->hasType() && D->getInterfaceType()->is<InOutType>();
    bool isNested = false;
    if (auto f = AFR.getAbstractFunctionDecl())
      isNested = f->getDeclContext()->isLocalContext();

    if (isInOut && !AFR.isKnownNoEscape() && !isNested) {
      if (D->getNameStr() == "self") {
        TC.diagnose(DRE->getLoc(),
          diag::closure_implicit_capture_mutating_self);
      } else {
        TC.diagnose(DRE->getLoc(),
          diag::closure_implicit_capture_without_noescape);
      }
      return { false, DRE };
    }

    // We're going to capture this, compute flags for the capture.
    unsigned Flags = 0;

    // If this is a direct reference to underlying storage, then this is a
    // capture of the storage address - not a capture of the getter/setter.
    if (DRE->getAccessSemantics() == AccessSemantics::DirectToStorage)
      Flags |= CapturedValue::IsDirect;

    // If the closure is noescape, then we can capture the decl as noescape.
    if (AFR.isKnownNoEscape())
      Flags |= CapturedValue::IsNoEscape;

    addCapture(CapturedValue(D, Flags), DRE->getStartLoc());
    return { false, DRE };
  }

  void propagateCaptures(AnyFunctionRef innerClosure, SourceLoc captureLoc) {
    TC.computeCaptures(innerClosure);

    auto CurDC = AFR.getAsDeclContext();
    bool isNoEscapeClosure = AFR.isKnownNoEscape();

    auto &captureInfo = innerClosure.getCaptureInfo();

    for (auto capture : captureInfo.getCaptures()) {
      // If the decl was captured from us, it isn't captured *by* us.
      if (capture.getDecl()->getDeclContext() == CurDC)
        continue;

      // Compute adjusted flags.
      unsigned Flags = capture.getFlags();

      // The decl is captured normally, even if it was captured directly
      // in the subclosure.
      Flags &= ~CapturedValue::IsDirect;

      // If this is an escaping closure, then any captured decls are also
      // escaping, even if they are coming from an inner noescape closure.
      if (!isNoEscapeClosure)
        Flags &= ~CapturedValue::IsNoEscape;

      addCapture(CapturedValue(capture.getDecl(), Flags), captureLoc);
    }

    if (GenericParamCaptureLoc.isInvalid())
      if (captureInfo.hasGenericParamCaptures())
        GenericParamCaptureLoc = innerClosure.getLoc();

    if (DynamicSelfCaptureLoc.isInvalid())
      if (captureInfo.hasDynamicSelfCapture()) {
        DynamicSelfCaptureLoc = innerClosure.getLoc();
        DynamicSelf = captureInfo.getDynamicSelfType();
      }
  }

  bool walkToDeclPre(Decl *D) override {
    if (auto *AFD = dyn_cast<AbstractFunctionDecl>(D)) {
      propagateCaptures(AFD, AFD->getLoc());

      // Can default parameter initializers capture state?  That seems like
      // a really bad idea.
      for (auto *paramList : AFD->getParameterLists())
        for (auto param : *paramList) {
          if (auto E = param->getDefaultValue())
            E->walk(*this);
        }
      return false;
    }

    return true;
  }

  bool usesTypeMetadataOfFormalType(Expr *E) {
    // For non-ObjC closures, assume the type metadata is always used.
    if (!AFR.isObjC())
      return true;

    if (!E->getType() || E->getType()->hasError())
      return false;

    // We can use Objective-C generics in limited ways without reifying
    // their type metadata, meaning we don't need to capture their generic
    // params.

    // Look through one layer of optionality when considering the class-

    // Referring to a class-constrained generic or metatype
    // doesn't require its type metadata.
    if (auto declRef = dyn_cast<DeclRefExpr>(E))
      return (!declRef->getDecl()->isObjC()
              && !E->getType()->getLValueOrInOutObjectType()
                              ->hasRetainablePointerRepresentation()
              && !E->getType()->getLValueOrInOutObjectType()
                              ->is<AnyMetatypeType>());

    // Loading classes or metatypes doesn't require their metadata.
    if (isa<LoadExpr>(E))
      return (!E->getType()->hasRetainablePointerRepresentation()
              && !E->getType()->is<AnyMetatypeType>());

    // Accessing @objc members doesn't require type metadata.
    // rdar://problem/27796375 -- allocating init entry points for ObjC
    // initializers are generated as true Swift generics, so reify type
    // parameters.
    if (auto memberRef = dyn_cast<MemberRefExpr>(E))
      return !memberRef->getMember().getDecl()->hasClangNode();

    if (auto applyExpr = dyn_cast<ApplyExpr>(E)) {
      if (auto methodApply = dyn_cast<ApplyExpr>(applyExpr->getFn())) {
        if (auto callee = dyn_cast<DeclRefExpr>(methodApply->getFn())) {
          return !callee->getDecl()->isObjC()
            || isa<ConstructorDecl>(callee->getDecl());
        }
      }
      if (auto callee = dyn_cast<DeclRefExpr>(applyExpr->getFn())) {
        return !callee->getDecl()->isObjC()
          || isa<ConstructorDecl>(callee->getDecl());
      }
    }

    if (auto subscriptExpr = dyn_cast<SubscriptExpr>(E)) {
      return (subscriptExpr->hasDecl() &&
              !subscriptExpr->getDecl().getDecl()->isObjC());
    }

    // Getting the dynamic type of a class doesn't require type metadata.
    if (isa<DynamicTypeExpr>(E))
      return (!E->getType()->castTo<AnyMetatypeType>()->getInstanceType()
                  ->hasRetainablePointerRepresentation());

    // Building a fixed-size tuple doesn't require type metadata.
    // Approximate this for the purposes of being able to invoke @objc methods
    // by considering tuples of ObjC-representable types to not use metadata.
    if (auto tuple = dyn_cast<TupleExpr>(E)) {
      for (auto elt : tuple->getType()->castTo<TupleType>()->getElements()) {
        if (!elt.getType()->isRepresentableIn(ForeignLanguage::ObjectiveC,
                                              AFR.getAsDeclContext()))
          return true;
      }
      return false;
    }

    // Coercion by itself is a no-op.
    if (isa<CoerceExpr>(E))
      return false;

    // Upcasting doesn't require type metadata.
    if (isa<DerivedToBaseExpr>(E))
      return false;
    if (isa<ArchetypeToSuperExpr>(E))
      return false;
    if (isa<CovariantReturnConversionExpr>(E))
      return false;
    if (isa<MetatypeConversionExpr>(E))
      return false;

    // Identity expressions are no-ops.
    if (isa<IdentityExpr>(E))
      return false;

    // Discarding an assignment is a no-op.
    if (isa<DiscardAssignmentExpr>(E))
      return false;

    // Opening an @objc existential or metatype is a no-op.
    if (auto open = dyn_cast<OpenExistentialExpr>(E))
      return (!open->getSubExpr()->getType()->isObjCExistentialType()
              && !open->getSubExpr()->getType()->is<AnyMetatypeType>());

    // Erasure to an ObjC existential or between metatypes doesn't require
    // type metadata.
    if (auto erasure = dyn_cast<ErasureExpr>(E)) {
      if (E->getType()->isObjCExistentialType()
          || E->getType()->is<AnyMetatypeType>())
        return false;

      // We also special case Any erasure in pseudogeneric contexts
      // not to rely on concrete type metadata by erasing from AnyObject
      // as a waypoint.
      if (E->getType()->isAny()
          && erasure->getSubExpr()->getType()->is<ArchetypeType>())
        return false;

      // Erasure to a Swift protocol always captures the type metadata from
      // its subexpression.
      checkType(erasure->getSubExpr()->getType(),
                erasure->getSubExpr()->getLoc());
      return true;
    }

    // Converting an @objc metatype to AnyObject doesn't require type
    // metadata.
    if (isa<ClassMetatypeToObjectExpr>(E)
        || isa<ExistentialMetatypeToObjectExpr>(E))
      return false;

    // Casting to an ObjC class doesn't require the metadata of its type
    // parameters, if any.
    if (auto cast = dyn_cast<CheckedCastExpr>(E)) {
      // If we failed to resolve the written type, we've emitted an
      // earlier diagnostic and should bail.
      auto toTy = cast->getCastTypeLoc().getType();
      if (!toTy || toTy->hasError())
        return false;

      if (auto clas = dyn_cast_or_null<ClassDecl>(
                         cast->getCastTypeLoc().getType()->getAnyNominal())) {
        if (clas->usesObjCGenericsModel()) {
          return false;
        }
      }
    }

    // Assigning an object doesn't require type metadata.
    if (auto assignment = dyn_cast<AssignExpr>(E))
      return !assignment->getSrc()->getType()
        ->hasRetainablePointerRepresentation();

    return true;
  }

  std::pair<bool, Expr *> walkToExprPre(Expr *E) override {
    if (usesTypeMetadataOfFormalType(E)) {
      checkType(E->getType(), E->getLoc());
    }

    // Some kinds of expression don't really evaluate their subexpression,
    // so we don't need to traverse.
    if (isa<ObjCSelectorExpr>(E)) {
      return { false, E };
    }

    if (auto *ECE = dyn_cast<ExplicitCastExpr>(E)) {
      checkType(ECE->getCastTypeLoc().getType(), ECE->getLoc());
      return { true, E };
    }

    if (auto *DRE = dyn_cast<DeclRefExpr>(E))
      return walkToDeclRefExpr(DRE);

    // When we see a reference to the 'super' expression, capture 'self' decl.
    if (auto *superE = dyn_cast<SuperRefExpr>(E)) {
      auto CurDC = AFR.getAsDeclContext();
      if (CurDC->isChildContextOf(superE->getSelf()->getDeclContext()))
        addCapture(CapturedValue(superE->getSelf(), 0), superE->getLoc());
      return { false, superE };
    }

    // Don't recur into child closures. They should already have a capture
    // list computed; we just propagate it, filtering out stuff that they
    // capture from us.
    if (auto *SubCE = dyn_cast<AbstractClosureExpr>(E)) {
      propagateCaptures(SubCE, SubCE->getStartLoc());
      return { false, E };
    }

    return { true, E };
  }
};

}  // namespace

void TypeChecker::maybeDiagnoseCaptures(Expr *E, AnyFunctionRef AFR) {
  if (!AFR.getCaptureInfo().hasBeenComputed()) {
    // The capture list is not always initialized by the point we reference
    // it. Remember we formed a C function pointer so we can diagnose later
    // if necessary.
    LocalCFunctionPointers[AFR].push_back(E);
    return;
  }

  if (AFR.getCaptureInfo().hasGenericParamCaptures() ||
      AFR.getCaptureInfo().hasDynamicSelfCapture() ||
      AFR.getCaptureInfo().hasLocalCaptures()) {
    unsigned kind;
    if (AFR.getCaptureInfo().hasLocalCaptures())
      kind = 0;
    else if (AFR.getCaptureInfo().hasGenericParamCaptures())
      kind = 1;
    else
      kind = 2;
    diagnose(E->getLoc(),
             diag::c_function_pointer_from_function_with_context,
             /*closure*/ AFR.getAbstractClosureExpr() != nullptr,
             kind);
  }
}

void TypeChecker::computeCaptures(AnyFunctionRef AFR) {
  if (AFR.getCaptureInfo().hasBeenComputed())
    return;

  SmallVector<CapturedValue, 4> Captures;
  SourceLoc GenericParamCaptureLoc;
  SourceLoc DynamicSelfCaptureLoc;
  DynamicSelfType *DynamicSelf = nullptr;
  FindCapturedVars finder(*this, Captures,
                          GenericParamCaptureLoc,
                          DynamicSelfCaptureLoc,
                          DynamicSelf,
                          AFR);
  AFR.getBody()->walk(finder);

  unsigned inoutCount = 0;
  for (auto C: Captures) {
    if (auto type = C.getDecl()->getInterfaceType())
      if (isa<InOutType>(type.getPointer()))
        inoutCount++;
  }

  if (inoutCount > 0) {
    if (auto e = AFR.getAbstractFunctionDecl()) {
      for (auto returnOccurrence: getEscapingFunctionAsReturnValue(e)) {
        diagnose(returnOccurrence->getReturnLoc(),
          diag::nested_function_escaping_inout_capture);
      }
      auto occurrences = getEscapingFunctionAsArgument(e);
      for (auto occurrence: occurrences) {
        diagnose(occurrence->getLoc(),
          diag::nested_function_with_implicit_capture_argument,
          inoutCount > 1);
      }
    }
  }

  if (AFR.hasType() && !AFR.isObjC()) {
    finder.checkType(AFR.getType(), AFR.getLoc());
  }

  // If this is an init(), explicitly walk the initializer values for members of
  // the type.  They will be implicitly emitted by SILGen into the generated
  // initializer.
  if (auto CD =
        dyn_cast_or_null<ConstructorDecl>(AFR.getAbstractFunctionDecl())) {
    auto *typeDecl = dyn_cast<NominalTypeDecl>(CD->getDeclContext());
    if (typeDecl && CD->isDesignatedInit()) {
      for (auto member : typeDecl->getMembers()) {
        // Ignore everything other than PBDs.
        auto *PBD = dyn_cast<PatternBindingDecl>(member);
        if (!PBD) continue;
        // Walk the initializers for all properties declared in the type with
        // an initializer.
        for (auto &elt : PBD->getPatternList())
          if (auto *init = elt.getInit())
            init->walk(finder);
      }
    }
  }

  // A generic function always captures outer generic parameters.
  auto *AFD = AFR.getAbstractFunctionDecl();
  if (AFD) {
    if (AFD->getGenericParams())
      AFR.getCaptureInfo().setGenericParamCaptures(true);
  }

  // Only local functions capture dynamic 'Self'.
  if (AFR.getAsDeclContext()->getParent()->isLocalContext()) {
    if (GenericParamCaptureLoc.isValid())
      AFR.getCaptureInfo().setGenericParamCaptures(true);

    if (DynamicSelfCaptureLoc.isValid())
      AFR.getCaptureInfo().setDynamicSelfType(DynamicSelf);
  }

  if (Captures.empty())
    AFR.getCaptureInfo().setCaptures(None);
  else
    AFR.getCaptureInfo().setCaptures(Context.AllocateCopy(Captures));

  // Extensions of generic ObjC functions can't use generic parameters from
  // their context.
  if (AFD && GenericParamCaptureLoc.isValid()) {
    if (auto Clas = AFD->getParent()->getAsClassOrClassExtensionContext()) {
      if (Clas->isGenericContext() && Clas->hasClangNode()) {
        diagnose(AFD->getLoc(),
                 diag::objc_generic_extension_using_type_parameter);
        diagnose(GenericParamCaptureLoc,
                 diag::objc_generic_extension_using_type_parameter_here);
      }
    }
  }

  // Diagnose if we have local captures and there were C pointers formed to
  // this function before we computed captures.
  auto cFunctionPointers = LocalCFunctionPointers.find(AFR);
  if (cFunctionPointers != LocalCFunctionPointers.end())
    for (auto *expr : cFunctionPointers->second)
      maybeDiagnoseCaptures(expr, AFR);
}


text:
using namespace std;

namespace ycsbc {

int RedisDB::Read(const string &table, const string &key,
         const vector<string> *fields,
         vector<KVPair> &result) {
  if (fields) {
    int argc = fields->size() + 2;
    const char *argv[argc];
    size_t argvlen[argc];
    int i = 0;
    argv[i] = "HMGET"; argvlen[i] = strlen(argv[i]);
    argv[++i] = key.c_str(); argvlen[i] = key.length();
    for (const string &f : *fields) {
      argv[++i] = f.data(); argvlen[i] = f.size();
    }
    assert(i == argc - 1);
    redisReply *reply = (redisReply *)redisCommandArgv(
        redis_.context(), argc, argv, argvlen);
    if (!reply) return DB::kOK;
    assert(reply->type == REDIS_REPLY_ARRAY);
    assert(fields->size() == reply->elements);
    for (size_t i = 0; i < reply->elements; ++i) {
      const char *value = reply->element[i]->str;
      result.push_back(make_pair(fields->at(i), string(value ? value : "")));
    }
    freeReplyObject(reply);
  } else {
    redisReply *reply = (redisReply *)redisCommand(redis_.context(),
        "HGETALL %s", key.c_str());
    if (!reply) return DB::kOK;
    assert(reply->type == REDIS_REPLY_ARRAY);
    for (size_t i = 0; i < reply->elements / 2; ++i) {
      result.push_back(make_pair(
          string(reply->element[2 * i]->str),
          string(reply->element[2 * i + 1]->str)));
    }
    freeReplyObject(reply);
  }
  return DB::kOK;
}

int RedisDB::Update(const string &table, const string &key,
           vector<KVPair> &values) {
  string cmd("HMSET");
  size_t len = cmd.length() + key.length() + 1;
  for (KVPair &p : values) {
    len += p.first.length() + p.second.length() + 2;
  }
  cmd.reserve(len);

  cmd.append(" ").append(key);
  for (KVPair &p : values) {
    assert(p.first.find(' ') == string::npos);
    cmd.append(" ").append(p.first);
    assert(p.second.find(' ') == string::npos);
    cmd.append(" ").append(p.second);
  }
  assert(cmd.length() == len);
  redis_.Command(cmd);
  return DB::kOK;
}

} // namespace ycsbc

redpajama_set_name: RedPajamaGithub


text:
'use strict';

/**
 * @class
 * Initializes a new instance of the SubjectAlternativeNames class.
 * @constructor
 * The subject alternate names of a X509 object.
 *
 * @member {array} [emails] Email addresses.
 *
 * @member {array} [dnsNames] Domain names.
 *
 * @member {array} [upns] User principal names.
 *
 */
class SubjectAlternativeNames {
  constructor() {
  }

  /**
   * Defines the metadata of SubjectAlternativeNames
   *
   * @returns {object} metadata of SubjectAlternativeNames
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'SubjectAlternativeNames',
      type: {
        name: 'Composite',
        className: 'SubjectAlternativeNames',
        modelProperties: {
          emails: {
            required: false,
            serializedName: 'emails',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'StringElementType',
                  type: {
                    name: 'String'
                  }
              }
            }
          },
          dnsNames: {
            required: false,
            serializedName: 'dns_names',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'StringElementType',
                  type: {
                    name: 'String'
                  }
              }
            }
          },
          upns: {
            required: false,
            serializedName: 'upns',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'StringElementType',
                  type: {
                    name: 'String'
                  }
              }
            }
          }
        }
      }
    };
  }
}

module.exports = SubjectAlternativeNames;


text:
CREATE TABLE list (id VARCHAR(10) NOT NULL, value VARCHAR(64) NOT NULL, PRIMARY KEY(id));

INSERT INTO "list" ("id", "value") VALUES (E'ARM', E'Argentine Peso (1881–1970)');
INSERT INTO "list" ("id", "value") VALUES (E'ARL', E'Argentine Peso Ley (1970–1983)');
INSERT INTO "list" ("id", "value") VALUES (E'BOL', E'Bolivian Boliviano (1863–1963)');
INSERT INTO "list" ("id", "value") VALUES (E'BAN', E'Bosnia-Herzegovina New Dinar (1994–1997)');
INSERT INTO "list" ("id", "value") VALUES (E'BRZ', E'Brazilian Cruzeiro (1942–1967)');
INSERT INTO "list" ("id", "value") VALUES (E'BGO', E'Bulgarian Lev (1879–1952)');
INSERT INTO "list" ("id", "value") VALUES (E'BGM', E'Bulgarian Socialist Lev');
INSERT INTO "list" ("id", "value") VALUES (E'CLE', E'Chilean Escudo');
INSERT INTO "list" ("id", "value") VALUES (E'CNX', E'Chinese People's Bank Dollar');
INSERT INTO "list" ("id", "value") VALUES (E'ISJ', E'Icelandic Króna (1918–1981)');
INSERT INTO "list" ("id", "value") VALUES (E'ILR', E'Israeli Shekel (1980–1985)');
INSERT INTO "list" ("id", "value") VALUES (E'MKN', E'Macedonian Denar (1992–1993)');
INSERT INTO "list" ("id", "value") VALUES (E'MVP', E'Maldivian Rupee (1947–1981)');
INSERT INTO "list" ("id", "value") VALUES (E'MDC', E'Moldovan Cupon');
INSERT INTO "list" ("id", "value") VALUES (E'MCF', E'Monegasque Franc');
INSERT INTO "list" ("id", "value") VALUES (E'KRH', E'South Korean Hwan (1953–1962)');
INSERT INTO "list" ("id", "value") VALUES (E'KRO', E'South Korean Won (1945–1953)');
INSERT INTO "list" ("id", "value") VALUES (E'VNN', E'Vietnamese Dong (1978–1985)');
INSERT INTO "list" ("id", "value") VALUES (E'YUR', E'Yugoslavian Reformed Dinar (1992–1993)');
INSERT INTO "list" ("id", "value") VALUES (E'AFA', E'afghani (1927–2002)');
INSERT INTO "list" ("id", "value") VALUES (E'AFN', E'afghani afghan');
INSERT INTO "list" ("id", "value") VALUES (E'ROL', E'ancien leu roumain');
INSERT INTO "list" ("id", "value") VALUES (E'MGA', E'ariary malgache');
INSERT INTO "list" ("id", "value") VALUES (E'ARA', E'austral argentin');
INSERT INTO "list" ("id", "value") VALUES (E'THB', E'baht thaïlandais');
INSERT INTO "list" ("id", "value") VALUES (E'PAB', E'balboa panaméen');
INSERT INTO "list" ("id", "value") VALUES (E'ETB', E'birr éthiopien');
INSERT INTO "list" ("id", "value") VALUES (E'VEF', E'bolivar vénézuélien');
INSERT INTO "list" ("id", "value") VALUES (E'VEB', E'bolivar vénézuélien (1871–2008)');
INSERT INTO "list" ("id", "value") VALUES (E'BOB', E'boliviano bolivien');
INSERT INTO "list" ("id", "value") VALUES (E'CRC', E'colón costaricain');
INSERT INTO "list" ("id", "value") VALUES (E'SVC', E'colón salvadorien');
INSERT INTO "list" ("id", "value") VALUES (E'NIC', E'cordoba');
INSERT INTO "list" ("id", "value") VALUES (E'GEK', E'coupon de lari géorgien');
INSERT INTO "list" ("id", "value") VALUES (E'DKK', E'couronne danoise');
INSERT INTO "list" ("id", "value") VALUES (E'EEK', E'couronne estonienne');
INSERT INTO "list" ("id", "value") VALUES (E'CSK', E'couronne forte tchécoslovaque');
INSERT INTO "list" ("id", "value") VALUES (E'ISK', E'couronne islandaise');
INSERT INTO "list" ("id", "value") VALUES (E'NOK', E'couronne norvégienne');
INSERT INTO "list" ("id", "value") VALUES (E'SKK', E'couronne slovaque');
INSERT INTO "list" ("id", "value") VALUES (E'SEK', E'couronne suédoise');
INSERT INTO "list" ("id", "value") VALUES (E'CZK', E'couronne tchèque');
INSERT INTO "list" ("id", "value") VALUES (E'BRC', E'cruzado brésilien (1986–1989)');
INSERT INTO "list" ("id", "value") VALUES (E'BRR', E'cruzeiro');
INSERT INTO "list" ("id", "value") VALUES (E'BRE', E'cruzeiro brésilien (1990–1993)');
INSERT INTO "list" ("id", "value") VALUES (E'GHC', E'cédi');
INSERT INTO "list" ("id", "value") VALUES (E'GHS', E'cédi ghanéen');
INSERT INTO "list" ("id", "value") VALUES (E'NIO', E'córdoba oro nicaraguayen');
INSERT INTO "list" ("id", "value") VALUES (E'GMD', E'dalasi gambien');
INSERT INTO "list" ("id", "value") VALUES (E'MKD', E'denar macédonien');
INSERT INTO "list" ("id", "value") VALUES (E'DZD', E'dinar algérien');
INSERT INTO "list" ("id", "value") VALUES (E'BHD', E'dinar bahreïni');
INSERT INTO "list" ("id", "value") VALUES (E'BAD', E'dinar bosniaque');
INSERT INTO "list" ("id", "value") VALUES (E'HRD', E'dinar croate');
INSERT INTO "list" ("id", "value") VALUES (E'YDD', E'dinar du Yémen');
INSERT INTO "list" ("id", "value") VALUES (E'IQD', E'dinar irakien');
INSERT INTO "list" ("id", "value") VALUES (E'JOD', E'dinar jordanien');
INSERT INTO "list" ("id", "value") VALUES (E'KWD', E'dinar koweïtien');
INSERT INTO "list" ("id", "value") VALUES (E'LYD', E'dinar libyen');
INSERT INTO "list" ("id", "value") VALUES (E'RSD', E'dinar serbe');
INSERT INTO "list" ("id", "value") VALUES (E'CSD', E'dinar serbo-monténégrin');
INSERT INTO "list" ("id", "value") VALUES (E'SDD', E'dinar soudanais');
INSERT INTO "list" ("id", "value") VALUES (E'TND', E'dinar tunisien');
INSERT INTO "list" ("id", "value") VALUES (E'YUM', E'dinar yougoslave Noviy');
INSERT INTO "list" ("id", "value") VALUES (E'YUN', E'dinar yougoslave convertible');
INSERT INTO "list" ("id", "value") VALUES (E'AED', E'dirham des Émirats arabes unis');
INSERT INTO "list" ("id", "value") VALUES (E'MAD', E'dirham marocain');
INSERT INTO "list" ("id", "value") VALUES (E'STD', E'dobra santoméen');
INSERT INTO "list" ("id", "value") VALUES (E'AUD', E'dollar australien');
INSERT INTO "list" ("id", "value") VALUES (E'BSD', E'dollar bahaméen');
INSERT INTO "list" ("id", "value") VALUES (E'BBD', E'dollar barbadien');
INSERT INTO "list" ("id", "value") VALUES (E'BMD', E'dollar bermudien');
INSERT INTO "list" ("id", "value") VALUES (E'BND', E'dollar brunéien');
INSERT INTO "list" ("id", "value") VALUES (E'BZD', E'dollar bélizéen');
INSERT INTO "list" ("id", "value") VALUES (E'CAD', E'dollar canadien');
INSERT INTO "list" ("id", "value") VALUES (E'HKD', E'dollar de Hong Kong');
INSERT INTO "list" ("id", "value") VALUES (E'SGD', E'dollar de Singapour');
INSERT INTO "list" ("id", "value") VALUES (E'TTD', E'dollar de Trinité-et-Tobago');
INSERT INTO "list" ("id", "value") VALUES (E'XCD', E'dollar des Caraïbes orientales');
INSERT INTO "list" ("id", "value") VALUES (E'USS', E'dollar des Etats-Unis (jour même)');
INSERT INTO "list" ("id", "value") VALUES (E'USN', E'dollar des Etats-Unis (jour suivant)');
INSERT INTO "list" ("id", "value") VALUES (E'USD', E'dollar des États-Unis');
INSERT INTO "list" ("id", "value") VALUES (E'KYD', E'dollar des îles Caïmans');
INSERT INTO "list" ("id", "value") VALUES (E'SBD', E'dollar des îles Salomon');
INSERT INTO "list" ("id", "value") VALUES (E'GYD', E'dollar du Guyana');
INSERT INTO "list" ("id", "value") VALUES (E'FJD', E'dollar fidjien');
INSERT INTO "list" ("id", "value") VALUES (E'JMD', E'dollar jamaïcain');
INSERT INTO "list" ("id", "value") VALUES (E'LRD', E'dollar libérien');
INSERT INTO "list" ("id", "value") VALUES (E'NAD', E'dollar namibien');
INSERT INTO "list" ("id", "value") VALUES (E'NZD', E'dollar néo-zélandais');
INSERT INTO "list" ("id", "value") VALUES (E'RHD', E'dollar rhodésien');
INSERT INTO "list" ("id", "value") VALUES (E'SRD', E'dollar surinamais');
INSERT INTO "list" ("id", "value") VALUES (E'ZWD', E'dollar zimbabwéen');
INSERT INTO "list" ("id", "value") VALUES (E'ZWR', E'dollar zimbabwéen (2008)');
INSERT INTO "list" ("id", "value") VALUES (E'ZWL', E'dollar zimbabwéen (2009)');
INSERT INTO "list" ("id", "value") VALUES (E'GRD', E'drachme grecque');
INSERT INTO "list" ("id", "value") VALUES (E'AMD', E'dram arménien');
INSERT INTO "list" ("id", "value") VALUES (E'VND', E'dông vietnamien');
INSERT INTO "list" ("id", "value") VALUES (E'GQE', E'ekwélé équatoguinéen');
INSERT INTO "list" ("id", "value") VALUES (E'CVE', E'escudo capverdien');
INSERT INTO "list" ("id", "value") VALUES (E'GWE', E'escudo de Guinée portugaise');
INSERT INTO "list" ("id", "value") VALUES (E'MZE', E'escudo mozambicain');
INSERT INTO "list" ("id", "value") VALUES (E'PTE', E'escudo portugais');
INSERT INTO "list" ("id", "value") VALUES (E'TPE', E'escudo timorais');
INSERT INTO "list" ("id", "value") VALUES (E'EUR', E'euro');
INSERT INTO "list" ("id", "value") VALUES (E'CHE', E'euro WIR');
INSERT INTO "list" ("id", "value") VALUES (E'ANG', E'florin antillais');
INSERT INTO "list" ("id", "value") VALUES (E'AWG', E'florin arubais');
INSERT INTO "list" ("id", "value") VALUES (E'NLG', E'florin néerlandais');
INSERT INTO "list" ("id", "value") VALUES (E'SRG', E'florin surinamais');
INSERT INTO "list" ("id", "value") VALUES (E'HUF', E'forint hongrois');
INSERT INTO "list" ("id", "value") VALUES (E'XOF', E'franc CFA (BCEAO)');
INSERT INTO "list" ("id", "value") VALUES (E'XAF', E'franc CFA (BEAC)');
INSERT INTO "list" ("id", "value") VALUES (E'XPF', E'franc CFP');
INSERT INTO "list" ("id", "value") VALUES (E'XFU', E'franc UIC');
INSERT INTO "list" ("id", "value") VALUES (E'CHW', E'franc WIR');
INSERT INTO "list" ("id", "value") VALUES (E'BEF', E'franc belge');
INSERT INTO "list" ("id", "value") VALUES (E'BEC', E'franc belge (convertible)');
INSERT INTO "list" ("id", "value") VALUES (E'BEL', E'franc belge (financier)');
INSERT INTO "list" ("id", "value") VALUES (E'BIF', E'franc burundais');
INSERT INTO "list" ("id", "value") VALUES (E'KMF', E'franc comorien');
INSERT INTO "list" ("id", "value") VALUES (E'CDF', E'franc congolais');
INSERT INTO "list" ("id", "value") VALUES (E'LUC', E'franc convertible luxembourgeois');
INSERT INTO "list" ("id", "value") VALUES (E'DJF', E'franc djiboutien');
INSERT INTO "list" ("id", "value") VALUES (E'LUL', E'franc financier luxembourgeois');
INSERT INTO "list" ("id", "value") VALUES (E'FRF', E'franc français');
INSERT INTO "list" ("id", "value") VALUES (E'GNF', E'franc guinéen');
INSERT INTO "list" ("id", "value") VALUES (E'LUF', E'franc luxembourgeois');
INSERT INTO "list" ("id", "value") VALUES (E'MGF', E'franc malgache');
INSERT INTO "list" ("id", "value") VALUES (E'MLF', E'franc malien');
INSERT INTO "list" ("id", "value") VALUES (E'MAF', E'franc marocain');
INSERT INTO "list" ("id", "value") VALUES (E'XFO', E'franc or');
INSERT INTO "list" ("id", "value") VALUES (E'RWF', E'franc rwandais');
INSERT INTO "list" ("id", "value") VALUES (E'CHF', E'franc suisse');
INSERT INTO "list" ("id", "value") VALUES (E'HTG', E'gourde haïtienne');
INSERT INTO "list" ("id", "value") VALUES (E'PYG', E'guaraní paraguayen');
INSERT INTO "list" ("id", "value") VALUES (E'UAH', E'hryvnia ukrainienne');
INSERT INTO "list" ("id", "value") VALUES (E'PEI', E'inti péruvien');
INSERT INTO "list" ("id", "value") VALUES (E'UAK', E'karbovanetz');
INSERT INTO "list" ("id", "value") VALUES (E'PGK', E'kina papouan-néo-guinéen');
INSERT INTO "list" ("id", "value") VALUES (E'LAK', E'kip loatien');
INSERT INTO "list" ("id", "value") VALUES (E'HRK', E'kuna croate');
INSERT INTO "list" ("id", "value") VALUES (E'MWK', E'kwacha malawite');
INSERT INTO "list" ("id", "value") VALUES (E'ZMW', E'kwacha zambien');
INSERT INTO "list" ("id", "value") VALUES (E'ZMK', E'kwacha zambien (1968–2012)');
INSERT INTO "list" ("id", "value") VALUES (E'AOA', E'kwanza angolais');
INSERT INTO "list" ("id", "value") VALUES (E'AOK', E'kwanza angolais (1977–1990)');
INSERT INTO "list" ("id", "value") VALUES (E'AOR', E'kwanza angolais réajusté (1995–1999)');
INSERT INTO "list" ("id", "value") VALUES (E'BUK', E'kyat birman');
INSERT INTO "list" ("id", "value") VALUES (E'MMK', E'kyat myanmarais');
INSERT INTO "list" ("id", "value") VALUES (E'GEL', E'lari géorgien');
INSERT INTO "list" ("id", "value") VALUES (E'LVL', E'lats letton');
INSERT INTO "list" ("id", "value") VALUES (E'ALL', E'lek albanais');
INSERT INTO "list" ("id", "value") VALUES (E'ALK', E'lek albanais (1947–1961)');
INSERT INTO "list" ("id", "value") VALUES (E'HNL', E'lempira hondurien');
INSERT INTO "list" ("id", "value") VALUES (E'SLL', E'leone sierra-léonais');
INSERT INTO "list" ("id", "value") VALUES (E'MDL', E'leu moldave');
INSERT INTO "list" ("id", "value") VALUES (E'RON', E'leu roumain');
INSERT INTO "list" ("id", "value") VALUES (E'BGN', E'lev bulgare');
INSERT INTO "list" ("id", "value") VALUES (E'BGL', E'lev bulgare (1962–1999)');
INSERT INTO "list" ("id", "value") VALUES (E'SZL', E'lilangeni swazi');
INSERT INTO "list" ("id", "value") VALUES (E'ITL', E'lire italienne');
INSERT INTO "list" ("id", "value") VALUES (E'MTL', E'lire maltaise');
INSERT INTO "list" ("id", "value") VALUES (E'LTL', E'litas lituanien');
INSERT INTO "list" ("id", "value") VALUES (E'CYP', E'livre chypriote');
INSERT INTO "list" ("id", "value") VALUES (E'GIP', E'livre de Gibraltar');
INSERT INTO "list" ("id", "value") VALUES (E'SHP', E'livre de Sainte-Hélène');
INSERT INTO "list" ("id", "value") VALUES (E'FKP', E'livre des Îles Malouines');
INSERT INTO "list" ("id", "value") VALUES (E'IEP', E'livre irlandaise');
INSERT INTO "list" ("id", "value") VALUES (E'ILP', E'livre israélienne');
INSERT INTO "list" ("id", "value") VALUES (E'LBP', E'livre libanaise');
INSERT INTO "list" ("id", "value") VALUES (E'MTP', E'livre maltaise');
INSERT INTO "list" ("id", "value") VALUES (E'SDG', E'livre soudanaise');
INSERT INTO "list" ("id", "value") VALUES (E'SDP', E'livre soudanaise (1956–2007)');
INSERT INTO "list" ("id", "value") VALUES (E'GBP', E'livre sterling');
INSERT INTO "list" ("id", "value") VALUES (E'SSP', E'livre sud-soudanaise');
INSERT INTO "list" ("id", "value") VALUES (E'SYP', E'livre syrienne');
INSERT INTO "list" ("id", "value") VALUES (E'TRY', E'livre turque');
INSERT INTO "list" ("id", "value") VALUES (E'TRL', E'livre turque (1844–2005)');
INSERT INTO "list" ("id", "value") VALUES (E'EGP', E'livre égyptienne');
INSERT INTO "list" ("id", "value") VALUES (E'LSL', E'loti lesothan');
INSERT INTO "list" ("id", "value") VALUES (E'AZN', E'manat azéri');
INSERT INTO "list" ("id", "value") VALUES (E'AZM', E'manat azéri (1993–2006)');
INSERT INTO "list" ("id", "value") VALUES (E'TMM', E'manat turkmène');
INSERT INTO "list" ("id", "value") VALUES (E'DEM', E'mark allemand');
INSERT INTO "list" ("id", "value") VALUES (E'BAM', E'mark convertible bosniaque');
INSERT INTO "list" ("id", "value") VALUES (E'DDM', E'mark est-allemand');
INSERT INTO "list" ("id", "value") VALUES (E'FIM', E'mark finlandais');
INSERT INTO "list" ("id", "value") VALUES (E'MZN', E'metical mozambicain');
INSERT INTO "list" ("id", "value") VALUES (E'BOV', E'mvdol bolivien');
INSERT INTO "list" ("id", "value") VALUES (E'MZM', E'métical');
INSERT INTO "list" ("id", "value") VALUES (E'ERN', E'nafka érythréen');
INSERT INTO "list" ("id", "value") VALUES (E'NGN', E'naira nigérian');
INSERT INTO "list" ("id", "value") VALUES (E'BTN', E'ngultrum bouthanais');
INSERT INTO "list" ("id", "value") VALUES (E'BRN', E'nouveau cruzado');
INSERT INTO "list" ("id", "value") VALUES (E'BRB', E'nouveau cruzeiro brésilien (1967–1986)');
INSERT INTO "list" ("id", "value") VALUES (E'YUD', E'nouveau dinar yougoslave');
INSERT INTO "list" ("id", "value") VALUES (E'TWD', E'nouveau dollar taïwanais');
INSERT INTO "list" ("id", "value") VALUES (E'AON', E'nouveau kwanza angolais (1990–2000)');
INSERT INTO "list" ("id", "value") VALUES (E'TMT', E'nouveau manat turkmène');
INSERT INTO "list" ("id", "value") VALUES (E'BYB', E'nouveau rouble biélorusse (1994–1999)');
INSERT INTO "list" ("id", "value") VALUES (E'ILS', E'nouveau shekel israélien');
INSERT INTO "list" ("id", "value") VALUES (E'ZRN', E'nouveau zaïre zaïrien');
INSERT INTO "list" ("id", "value") VALUES (E'MRO', E'ouguiya mauritanien');
INSERT INTO "list" ("id", "value") VALUES (E'MOP', E'pataca macanaise');
INSERT INTO "list" ("id", "value") VALUES (E'TOP', E'pa'anga');
INSERT INTO "list" ("id", "value") VALUES (E'ADP', E'peseta andorrane');
INSERT INTO "list" ("id", "value") VALUES (E'ESP', E'peseta espagnole');
INSERT INTO "list" ("id", "value") VALUES (E'ESA', E'peseta espagnole (compte A)');
INSERT INTO "list" ("id", "value") VALUES (E'ESB', E'peseta espagnole (compte convertible)');
INSERT INTO "list" ("id", "value") VALUES (E'ARS', E'peso argentin');
INSERT INTO "list" ("id", "value") VALUES (E'ARP', E'peso argentin (1983–1985)');
INSERT INTO "list" ("id", "value") VALUES (E'GWP', E'peso bissau-guinéen');
INSERT INTO "list" ("id", "value") VALUES (E'BOP', E'peso bolivien');
INSERT INTO "list" ("id", "value") VALUES (E'CLP', E'peso chilien');
INSERT INTO "list" ("id", "value") VALUES (E'COP', E'peso colombien');
INSERT INTO "list" ("id", "value") VALUES (E'CUP', E'peso cubain');
INSERT INTO "list" ("id", "value") VALUES (E'CUC', E'peso cubain convertible');
INSERT INTO "list" ("id", "value") VALUES (E'DOP', E'peso dominicain');
INSERT INTO "list" ("id", "value") VALUES (E'MXP', E'peso d'argent mexicain (1861–1992)');
INSERT INTO "list" ("id", "value") VALUES (E'MXN', E'peso mexicain');
INSERT INTO "list" ("id", "value") VALUES (E'PHP', E'peso philippin');
INSERT INTO "list" ("id", "value") VALUES (E'UYU', E'peso uruguayen');
INSERT INTO "list" ("id", "value") VALUES (E'UYP', E'peso uruguayen (1975–1993)');
INSERT INTO "list" ("id", "value") VALUES (E'UYI', E'peso uruguayen (unités indexées)');
INSERT INTO "list" ("id", "value") VALUES (E'BWP', E'pula botswanais');
INSERT INTO "list" ("id", "value") VALUES (E'GTQ', E'quetzal guatémaltèque');
INSERT INTO "list" ("id", "value") VALUES (E'ZAR', E'rand sud-africain');
INSERT INTO "list" ("id", "value") VALUES (E'ZAL', E'rand sud-africain (financier)');
INSERT INTO "list" ("id", "value") VALUES (E'IRR', E'rial iranien');
INSERT INTO "list" ("id", "value") VALUES (E'OMR', E'rial omanais');
INSERT INTO "list" ("id", "value") VALUES (E'QAR', E'rial qatari');
INSERT INTO "list" ("id", "value") VALUES (E'SAR', E'rial saoudien');
INSERT INTO "list" ("id", "value") VALUES (E'YER', E'rial yéménite');
INSERT INTO "list" ("id", "value") VALUES (E'KHR', E'riel cambodgien');
INSERT INTO "list" ("id", "value") VALUES (E'MYR', E'ringgit malais');
INSERT INTO "list" ("id", "value") VALUES (E'BYN', E'rouble biélorusse');
INSERT INTO "list" ("id", "value") VALUES (E'BYR', E'rouble biélorusse (2000–2016)');
INSERT INTO "list" ("id", "value") VALUES (E'LVR', E'rouble letton');
INSERT INTO "list" ("id", "value") VALUES (E'RUB', E'rouble russe');
INSERT INTO "list" ("id", "value") VALUES (E'RUR', E'rouble russe (1991–1998)');
INSERT INTO "list" ("id", "value") VALUES (E'SUR', E'rouble soviétique');
INSERT INTO "list" ("id", "value") VALUES (E'TJR', E'rouble tadjik');
INSERT INTO "list" ("id", "value") VALUES (E'SCR', E'roupie des Seychelles');
INSERT INTO "list" ("id", "value") VALUES (E'INR', E'roupie indienne');
INSERT INTO "list" ("id", "value") VALUES (E'IDR', E'roupie indonésienne');
INSERT INTO "list" ("id", "value") VALUES (E'MUR', E'roupie mauricienne');
INSERT INTO "list" ("id", "value") VALUES (E'NPR', E'roupie népalaise');
INSERT INTO "list" ("id", "value") VALUES (E'PKR', E'roupie pakistanaise');
INSERT INTO "list" ("id", "value") VALUES (E'LKR', E'roupie srilankaise');
INSERT INTO "list" ("id", "value") VALUES (E'MVR', E'rufiyaa maldivien');
INSERT INTO "list" ("id", "value") VALUES (E'BRL', E'réal brésilien');
INSERT INTO "list" ("id", "value") VALUES (E'ATS', E'schilling autrichien');
INSERT INTO "list" ("id", "value") VALUES (E'KES', E'shilling kényan');
INSERT INTO "list" ("id", "value") VALUES (E'UGX', E'shilling ougandais');
INSERT INTO "list" ("id", "value") VALUES (E'UGS', E'shilling ougandais (1966–1987)');
INSERT INTO "list" ("id", "value") VALUES (E'SOS', E'shilling somalien');
INSERT INTO "list" ("id", "value") VALUES (E'TZS', E'shilling tanzanien');
INSERT INTO "list" ("id", "value") VALUES (E'PEN', E'sol péruvien');
INSERT INTO "list" ("id", "value") VALUES (E'PES', E'sol péruvien (1863–1985)');
INSERT INTO "list" ("id", "value") VALUES (E'KGS', E'som kirghize');
INSERT INTO "list" ("id", "value") VALUES (E'TJS', E'somoni tadjik');
INSERT INTO "list" ("id", "value") VALUES (E'ECS', E'sucre équatorien');
INSERT INTO "list" ("id", "value") VALUES (E'UZS', E'sum ouzbek');
INSERT INTO "list" ("id", "value") VALUES (E'GNS', E'syli guinéen');
INSERT INTO "list" ("id", "value") VALUES (E'BDT', E'taka bangladeshi');
INSERT INTO "list" ("id", "value") VALUES (E'WST', E'tala samoan');
INSERT INTO "list" ("id", "value") VALUES (E'LTT', E'talonas lituanien');
INSERT INTO "list" ("id", "value") VALUES (E'KZT', E'tenge kazakh');
INSERT INTO "list" ("id", "value") VALUES (E'SIT', E'tolar slovène');
INSERT INTO "list" ("id", "value") VALUES (E'MNT', E'tugrik mongol');
INSERT INTO "list" ("id", "value") VALUES (E'XRE', E'type de fonds RINET');
INSERT INTO "list" ("id", "value") VALUES (E'XEU', E'unité de compte européenne (ECU)');
INSERT INTO "list" ("id", "value") VALUES (E'MXV', E'unité de conversion mexicaine (UDI)');
INSERT INTO "list" ("id", "value") VALUES (E'ECV', E'unité de valeur constante équatoriale (UVC)');
INSERT INTO "list" ("id", "value") VALUES (E'COU', E'unité de valeur réelle colombienne');
INSERT INTO "list" ("id", "value") VALUES (E'CLF', E'unité d'investissement chilienne');
INSERT INTO "list" ("id", "value") VALUES (E'VUV', E'vatu vanuatuan');
INSERT INTO "list" ("id", "value") VALUES (E'KPW', E'won nord-coréen');
INSERT INTO "list" ("id", "value") VALUES (E'KRW', E'won sud-coréen');
INSERT INTO "list" ("id", "value") VALUES (E'JPY', E'yen japonais');
INSERT INTO "list" ("id", "value") VALUES (E'CNY', E'yuan renminbi chinois');
INSERT INTO "list" ("id", "value") VALUES (E'ZRZ', E'zaïre zaïrois');
INSERT INTO "list" ("id", "value") VALUES (E'PLZ', E'zloty (1950–1995)');
INSERT INTO "list" ("id", "value") VALUES (E'PLN', E'zloty polonais');


text:
       <if condition="$busines['type'] eq 'fitness'">
                    <include file="Business:fitness_menu"/>
                    <elseif condition="$busines['type'] eq 'gover'"/>
                        <include file="Business:gover_menu"/>
                    <elseif condition="$busines['type'] eq 'food'"/>
                        <include file="Business:food_menu"/>
                    <elseif condition="$busines['type'] eq 'travel'"/>
                        <include file="Business:travel_menu"/>
                    <elseif condition="$busines['type'] eq 'flower'"/>
                        <include file="Business:flower_menu"/>
                    <elseif condition="$busines['type'] eq 'property'"/>
                        <include file="Business:property_menu"/>
                    <elseif condition="$busines['type'] eq 'ktv'"/>
                        <include file="Business:ktv_menu"/>
                    <elseif condition="$busines['type'] eq 'bar'"/>
                        <include file="Business:bar_menu"/>
                    <elseif condition="$busines['type'] eq 'fitment'"/>
                        <include file="Business:fitment_menu"/>
                    <elseif condition="$busines['type'] eq 'wedding'"/>
                        <include file="Business:wedding_menu"/>
                    <elseif condition="$busines['type'] eq 'affections'"/>
                        <include file="Business:affections_menu"/>
                    <elseif condition="$busines['type'] eq 'housekeeper'"/>
                        <include file="Business:housekeeper_menu"/>
                    <elseif condition="$busines['type'] eq 'lease'"/>
                        <include file="Business:lease_menu"/>
                    </if>


text: setup for starting react app with redux


text:
package org.apache.usergrid.persistence.collection.serialization.impl;

import java.util.UUID;

import org.apache.usergrid.persistence.model.field.Field;

/**
 * Class that encapsulates a unique field with the entity and version that own it
 */
public class UniqueFieldEntry {

    private final UUID version;
    private final Field field;

    /**
     * Create a unique field with the specified version and field
     * @param version
     * @param field
     */
    public UniqueFieldEntry( final UUID version, final Field field ) {
        this.version = version;
        this.field = field;
    }

    public UUID getVersion() {
        return version;
    }

    public Field getField() {
        return field;
    }
}


text:
<?php

// Variable setup and checking
if(!isset($remove))
{
    $remove = false;
}
if(!isset($context))
{
    $context = 'selectaddremove';
}
if(!isset($coltype))
{
    $coltype = 'col-xs-12';
}
if(!isset($name))
{
    echo("You must definte a name for the select element in a selectaddremove!");
}
if(!isset($options))
{
    $options = [];
}
if(!isset($selected_values))
{
    $selected_values = [];
}
if(!isset($addview))
{
    $addview = 'widgets_selectaddremove_addmodal';
}
if(!isset($change_action))
{
    $change_action = '';
}
else
{
    $change_action = ' data-change="' . $change_action . '"';
}
if(!isset($request_data))
{
    $request_data = '';
}
else
{
    $request_data = ' data-request_data="' . $request_data . '"';
}

?>

<div class="input-group <?php echo($coltype); ?>" data-widget="selectaddremove" data-context="<?php echo($context); ?>">
    <select data-context="select" class="form-control" name="<?php echo($name); ?>"<?php echo($change_action . $request_data); ?>>
        <?php
        foreach($options as $value=>$option) {
            $selected = in_array($value, $selected_values) ? ' selected' : '';
            echo("<option value=\"$value\"$selected>$option</option>");
        }
        ?>
    </select>

        <button data-context="addbutton" class="btn btn-success" type="button" data-link="view/<?php echo($addview); ?>" data-response_target="modal_area" data-request_data="modal,small"></button>
        <?php
        if($remove === true)
        {
            echo('<button class="btn btn-danger" data-toggle="modal"></button>');
        }
        ?>

    <?php if($remove === true) { ?>
    <div class="modal fade" id="selectaddremove-<?php echo($name); ?>" tabindex="-1" role="dialog" aria-labelledby="selectaddremove" aria-hidden="true">

Are you sure?

Are you sure you want to remove this option from the database?

<s>This cannot be undone!</s>

                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal" data-link="">Confirm</button>

    <?php } ?>


text:
package ice

import "testing"

func TestCandidatePriority(t *testing.T) {
	for _, test := range []struct {
		Candidate    *Candidate
		WantPriority uint32
	}{
		{
			Candidate: &Candidate{
				Type:            CandidateTypeHost,
				LocalPreference: defaultLocalPreference,
				Component:       ComponentRTP,
			},
			WantPriority: 2130706431,
		},
		{
			Candidate: &Candidate{
				Type:            CandidateTypePeerReflexive,
				LocalPreference: defaultLocalPreference,
				Component:       ComponentRTP,
			},
			WantPriority: 1862270975,
		},
		{
			Candidate: &Candidate{
				Type:            CandidateTypeServerReflexive,
				LocalPreference: defaultLocalPreference,
				Component:       ComponentRTP,
			},
			WantPriority: 1694498815,
		},
		{
			Candidate: &Candidate{
				Type:            CandidateTypeRelay,
				LocalPreference: defaultLocalPreference,
				Component:       ComponentRTP,
			},
			WantPriority: 16777215,
		},
	} {
		if got, want := test.Candidate.Priority(), test.WantPriority; got != want {
			t.Fatalf("Candidate(%v).Priority() = %d, want %d", test.Candidate, got, want)
		}
	}
}


text:
import BlueBirdPromise = require('bluebird');
import moment  = require('moment');
import {EnumSMSTemplateType, EnumVendorType} from "../../../models/EnumModel";
import {VendorInfo} from "../../../models/db/VendorInfo";
import {ConstVars} from "../../../global/ConstVars";
import {VendorTableService} from "../../dbservices/services/VendorTableService";

let log4js = require('log4js'),
    log = log4js.getLogger('SMSSender'),
    QcloudSms = require("qcloudsms_js");

/**
 *
 * 发送短信
 */
export class SMSSender {
    /**
     *
     * 发送  templateId 7839 对应的内容是"登录成功!账号ID: {1} 昵称:{2},登录服务器名称:{3}"
     * @param templateVar1 短信正文模板变量1
     * @param templateVar2 短信正文模板变量2
     * @param templateVar3 短信正文模板变量3
     * @param smsSign 签名 短信签名 NOTE: 这里的签名只是示例,请使用真实的已申请的签名, 签名参数使用的是`签名内容`,而不是`签名ID`
     * @param templateId 短信模板ID,需要在短信应用中申请  NOTE: 这里的模板ID`7839`只是一个示例,真实的模板ID需要在短信控制台中申请
     */
    static async send(templateVar1: string, templateVar2: string, templateVar3: string, smsSign: string, templateId: EnumSMSTemplateType): BlueBirdPromise<any> {
        //数组具体的元素个数和模板中变量个数必须一致,例如事例中templateId:5678对应一个变量,参数数组中元素个数也必须是一个
        let params = [templateVar1, templateVar2, templateVar3];

        let promiseArray: Array<BlueBirdPromise<VendorInfo>> = [];
        promiseArray.push(VendorTableService.getVendorInfo(EnumVendorType.TencentSMS));
        promiseArray.push(VendorTableService.getVendorInfo(EnumVendorType.UserPhone));
        return BlueBirdPromise.all(promiseArray)
            .then((vendorList: Array<VendorInfo>) => {
                let tencentSMSVendor: VendorInfo = vendorList[0];
                let userPhone: VendorInfo = vendorList[1];
                // 需要发送短信的手机号码
                let phoneNumbers = [userPhone.key];
                // 短信应用SDK AppID
                let appid = tencentSMSVendor.key;  // SDK AppID是1400开头
                // 短信应用SDK AppKey
                let appkey = tencentSMSVendor.value;
                // 实例化QcloudSms
                let qcloudsms = QcloudSms(appid, appkey);
                let ssender = qcloudsms.SmsSingleSender();
                return new BlueBirdPromise<any>((resolve, reject) => {
                    ssender.sendWithParam(86, phoneNumbers[0], templateId,
                        params, smsSign, "", "", (err, res, resData) => {
                            if (err) {
                                log.error(err);
                                reject(err);
                            } else {
                                resolve(resData);
                                log.info(resData);
                            }
                        });  // 签名参数未提供或者为空时,会使用默认签名发送短信
                })
            })
            .catch((e) => {
                if (e) {
                    log.error("发送短信失败,当前时间:%s", moment().format(ConstVars.momentDateTimeFormatter));
                    log.error(e);
                }
            });
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<features name="${project.artifactId}-${project.version}" xmlns="http://karaf.apache.org/xmlns/features/v1.0.0">

    <feature name='${project.artifactId}' description='${project.name}' version='${project.version}'>
        <details>${project.description}</details>
        <!-- <config>foo=bar</config> -->
        <!--<feature version="${cxf.version}">cxf</feature>-->
        <!--<feature>this-project-dependants</feature>-->

        <bundle dependency="true">mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.xalan/2.7.1_7</bundle>
        <bundle dependency="true">mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.bcel/5.2_4</bundle>
        <!--<bundle start="true">mvn:org.slf4j/slf4j-api/1.6.1</bundle>-->
        <bundle start="true">mvn:${project.groupId}/department-model/${project.version}</bundle>
        <bundle start="true">mvn:${project.groupId}/department-server/${project.version}</bundle>
    </feature>

    <!--<feature name="this-project-dependants">-->
        <!--<!– Dependent bundles –>-->
        <!--<bundle>mvn:org.slf4j/slf4j-api/1.6.1</bundle>-->
    <!--</feature>-->

</features>


text:
class CurrentBagelOwner
  def self.fetch
    latest_bagel = Bagel.includes(:owner).order("baked_on desc, created_at desc, id desc").first
    current_owner = latest_bagel.nil? ? nil : latest_bagel.owner
    current_owner
  end
end


text:
#include <gtest/gtest.h>
#include <arrayfire.h>
#include <af/dim4.hpp>
#include <af/traits.hpp>
#include <vector>
#include <iostream>
#include <string>
#include <testHelpers.hpp>

using std::vector;
using std::string;
using std::cout;
using std::endl;
using af::cfloat;
using af::cdouble;

template<typename T>
class Resize : public ::testing::Test
{
    public:
        virtual void SetUp() {
            subMat0.push_back({0, 4, 1});
            subMat0.push_back({2, 6, 1});
            subMat0.push_back({0, 2, 1});
        }
        vector<af_seq> subMat0;
};

template<typename T>
class ResizeI : public ::testing::Test
{
    public:
        virtual void SetUp() {
            subMat0.push_back({0, 4, 1});
            subMat0.push_back({2, 6, 1});
            subMat0.push_back({0, 2, 1});

            subMat1.push_back({0, 5, 1});
            subMat1.push_back({0, 5, 1});
            subMat1.push_back({0, 2, 1});
        }
        vector<af_seq> subMat0;
        vector<af_seq> subMat1;
};

// create a list of types to be tested
typedef ::testing::Types<float, double> TestTypesF;
typedef ::testing::Types<int, unsigned, unsigned char> TestTypesI;

// register the type list
TYPED_TEST_CASE(Resize, TestTypesF);
TYPED_TEST_CASE(ResizeI, TestTypesI);

template<typename T>
void resizeTest(string pTestFile, const unsigned resultIdx, const dim_type odim0, const dim_type odim1, const af_interp_type method, bool isSubRef = false, const vector<af_seq> * seqv = nullptr)
{
    if (noDoubleTests<T>()) return;

    vector<af::dim4> numDims;
    vector<vector<T>>   in;
    vector<vector<T>>   tests;
    readTests<T, T, float>(pTestFile,numDims,in,tests);

    af::dim4 dims = numDims[0];

    af_array inArray = 0;
    af_array outArray = 0;
    af_array tempArray = 0;
    if (isSubRef) {

        ASSERT_EQ(AF_SUCCESS, af_create_array(&tempArray, &(in[0].front()), dims.ndims(), dims.get(), (af_dtype) af::dtype_traits<T>::af_type));

        ASSERT_EQ(AF_SUCCESS, af_index(&inArray, tempArray, seqv->size(), &seqv->front()));
    } else {
        ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &(in[0].front()), dims.ndims(), dims.get(), (af_dtype) af::dtype_traits<T>::af_type));
    }

    ASSERT_EQ(AF_SUCCESS, af_resize(&outArray, inArray, odim0, odim1, method));

    // Get result
    af::dim4 odims(odim0, odim1, dims[2], dims[3]);
    T* outData = new T[odims.elements()];
    ASSERT_EQ(AF_SUCCESS, af_get_data_ptr((void*)outData, outArray));

    // Compare result
    size_t nElems = tests[resultIdx].size();
    for (size_t elIter = 0; elIter < nElems; ++elIter) {
        ASSERT_NEAR(tests[resultIdx][elIter], outData[elIter], 0.0001) << "at: " << elIter << std::endl;
    }

    // Delete
    delete[] outData;

    if(inArray   != 0) af_destroy_array(inArray);
    if(outArray  != 0) af_destroy_array(outArray);
    if(tempArray != 0) af_destroy_array(tempArray);
}

TYPED_TEST(Resize, Resize3CSquareUpNearest)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/square.test"), 0, 16, 16, AF_INTERP_NEAREST);
}

TYPED_TEST(Resize, Resize3CSquareUpLinear)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/square.test"), 1, 16, 16, AF_INTERP_BILINEAR);
}

TYPED_TEST(Resize, Resize3CSquareDownNearest)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/square.test"), 2, 4, 4, AF_INTERP_NEAREST);
}

TYPED_TEST(Resize, Resize3CSquareDownLinear)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/square.test"), 3, 4, 4, AF_INTERP_BILINEAR);
}

TYPED_TEST(Resize, Resize3CSquareUpNearestSubref)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/square.test"), 4, 10, 10, AF_INTERP_NEAREST,
                          true, &(this->subMat0));
}

TYPED_TEST(Resize, Resize3CSquareUpLinearSubref)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/square.test"), 5, 10, 10, AF_INTERP_BILINEAR,
                          true, &(this->subMat0));
}

TYPED_TEST(Resize, Resize3CSquareDownNearestSubref)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/square.test"), 6, 3, 3, AF_INTERP_NEAREST,
                          true, &(this->subMat0));
}

TYPED_TEST(Resize, Resize3CSquareDownLinearSubref)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/square.test"), 7, 3, 3, AF_INTERP_BILINEAR,
                          true, &(this->subMat0));
}

TYPED_TEST(Resize, Resize1CRectangleUpNearest)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/rectangle.test"), 0, 12, 16, AF_INTERP_NEAREST);
}

TYPED_TEST(Resize, Resize1CRectangleUpLinear)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/rectangle.test"), 1, 12, 16, AF_INTERP_BILINEAR);
}

TYPED_TEST(Resize, Resize1CRectangleDownNearest)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/rectangle.test"), 2, 6, 2, AF_INTERP_NEAREST);
}

TYPED_TEST(Resize, Resize1CRectangleDownLinear)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/rectangle.test"), 3, 6, 2, AF_INTERP_BILINEAR);
}

TYPED_TEST(ResizeI, Resize3CSquareUpNearest)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/square.test"), 0, 16, 16, AF_INTERP_NEAREST);
}

TYPED_TEST(ResizeI, Resize3CSquareUpLinear)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/square.test"), 1, 16, 16, AF_INTERP_BILINEAR);
}

TYPED_TEST(ResizeI, Resize3CSquareDownNearest)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/square.test"), 2, 4, 4, AF_INTERP_NEAREST);
}

TYPED_TEST(ResizeI, Resize3CSquareDownLinear)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/square.test"), 3, 4, 4, AF_INTERP_BILINEAR);
}

TYPED_TEST(ResizeI, Resize3CSquareUpNearestSubref)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/square.test"), 4, 10, 10, AF_INTERP_NEAREST,
                          true, &(this->subMat0));
}

TYPED_TEST(ResizeI, Resize3CSquareUpLinearSubref)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/square.test"), 5, 10, 10, AF_INTERP_BILINEAR,
                          true, &(this->subMat0));
}

TYPED_TEST(ResizeI, Resize3CSquareDownNearestSubref)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/square.test"), 6, 3, 3, AF_INTERP_NEAREST,
                          true, &(this->subMat0));
}

TYPED_TEST(ResizeI, Resize3CSquareDownLinearSubref)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/square.test"), 8, 3, 3, AF_INTERP_BILINEAR,
                          true, &(this->subMat1));
}

TYPED_TEST(Resize, Resize1CLargeUpNearest)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/large.test"), 0, 256, 256, AF_INTERP_NEAREST);
}

TYPED_TEST(Resize, Resize1CLargeUpLinear)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/large.test"), 1, 256, 256, AF_INTERP_BILINEAR);
}

TYPED_TEST(Resize, Resize1CLargeDownNearest)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/large.test"), 2, 32, 32, AF_INTERP_NEAREST);
}

TYPED_TEST(Resize, Resize1CLargeDownLinear)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/large.test"), 3, 32, 32, AF_INTERP_BILINEAR);
}

TYPED_TEST(ResizeI, Resize1CLargeUpNearest)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/large.test"), 0, 256, 256, AF_INTERP_NEAREST);
}

TYPED_TEST(ResizeI, Resize1CLargeUpLinear)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/large.test"), 1, 256, 256, AF_INTERP_BILINEAR);
}

TYPED_TEST(ResizeI, Resize1CLargeDownNearest)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/large.test"), 2, 32, 32, AF_INTERP_NEAREST);
}

TYPED_TEST(ResizeI, Resize1CLargeDownLinear)
{
    resizeTest<TypeParam>(string(TEST_DIR"/resize/large.test"), 3, 32, 32, AF_INTERP_BILINEAR);
}

template<typename T>
void resizeArgsTest(af_err err, string pTestFile, const af::dim4 odims, const af_interp_type method)
{
    if (noDoubleTests<T>()) return;

    vector<af::dim4> numDims;
    vector<vector<T>>   in;
    vector<vector<T>>   tests;
    readTests<T, T, float>(pTestFile,numDims,in,tests);

    af::dim4 dims = numDims[0];

    af_array inArray = 0;
    af_array outArray = 0;
    ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &(in[0].front()), dims.ndims(), dims.get(), (af_dtype) af::dtype_traits<T>::af_type));

    ASSERT_EQ(err, af_resize(&outArray, inArray, odims[0], odims[1], method));

    if(inArray != 0) af_destroy_array(inArray);
    if(outArray != 0) af_destroy_array(outArray);
}

TYPED_TEST(Resize,InvalidArgsDims0)
{
    af::dim4 dims(0, 5, 2, 1);
    resizeArgsTest<TypeParam>(AF_ERR_SIZE, string(TEST_DIR"/resize/square.test"), dims, AF_INTERP_BILINEAR);
}

TYPED_TEST(Resize,InvalidArgsMethod)
{
    af::dim4 dims(10, 10, 1, 1);
    resizeArgsTest<TypeParam>(AF_ERR_ARG, string(TEST_DIR"/resize/square.test"), dims, AF_INTERP_CUBIC);
}

///////////////////////////////// CPP ////////////////////////////////////
//
TEST(Resize, CPP)
{
    if (noDoubleTests<float>()) return;

    vector<af::dim4> numDims;
    vector<vector<float>>   in;
    vector<vector<float>>   tests;
    readTests<float, float, float>(string(TEST_DIR"/resize/square.test"),numDims,in,tests);

    af::dim4 dims = numDims[0];
    af::array input(dims, &(in[0].front()));
    af::array output = af::resize(input, 16, 16);

    // Get result
    af::dim4 odims(16, 16, dims[2], dims[3]);
    float* outData = new float[odims.elements()];
    output.host((void*)outData);

    // Compare result
    size_t nElems = tests[0].size();
    for (size_t elIter = 0; elIter < nElems; ++elIter) {
        ASSERT_NEAR(tests[0][elIter], outData[elIter], 0.0001) << "at: " << elIter << std::endl;
    }

    // Delete
    delete[] outData;
}


text:
<?php

namespace Framework\BindingModels\User;

class UserLoginBindingModel extends \Framework\Core\BindingModel
{
	/**
     * @Required true
     */
	public $username;

	/**
     * @Required true
     */
	public $password;
}


text:
namespace oless {
	namespace excel {
		namespace records {

			class DxGColRecord : public Record {
			public:
				DxGColRecord(unsigned short type, std::vector<uint8_t> data) : Record(type, data) {

				}
			};
		}
	}
}


text:
namespace perf_test_files {

const std::vector<const char*>& GetPerfDataFiles() {
  static const std::vector<const char*>* files = new std::vector<const char*> {
    // The following perf data contains the following event types, as passed to
    // perf record via the -e option:
    // - cycles
    // - instructions
    // - cache-references
    // - cache-misses
    // - branches
    // - branch-misses

    // Obtained with "perf record -- echo > /dev/null"
    "perf.data.singleprocess-3.4",

    // Obtained with "perf record -a -- sleep $N", for N in {0, 1, 5}.
    "perf.data.systemwide.0-3.4",
#ifdef TEST_LARGE_PERF_DATA
    "perf.data.systemwide.1-3.4",
    "perf.data.systemwide.5-3.4",

    // Obtained with "perf record -a -- sleep $N", for N in {0, 1, 5}.
    // While in the background, this loop is running:
    //   while true; do ls > /dev/null; done
    "perf.data.busy.0-3.4",
    "perf.data.busy.1-3.4",
    "perf.data.busy.5-3.4",
#endif  // defined(TEST_LARGE_PERF_DATA)

    // Obtained with "perf record -a -- sleep 2"
    // While in the background, this loop is running:
    //   while true; do restart powerd; sleep .2; done
    "perf.data.forkexit-3.4",

#ifdef TEST_CALLGRAPH
    // Obtained with "perf record -a -g -- sleep 2"
    "perf.data.callgraph-3.4",
#endif
    // Obtained with "perf record -a -b -- sleep 2"
    "perf.data.branch-3.4",
#ifdef TEST_CALLGRAPH
    // Obtained with "perf record -a -g -b -- sleep 2"
    "perf.data.callgraph_and_branch-3.4",
#endif

    // Obtained with "perf record -a -R -- sleep 2"
    "perf.data.raw-3.4",
#ifdef TEST_CALLGRAPH
    // Obtained with "perf record -a -R -g -b -- sleep 2"
    "perf.data.raw_callgraph_branch-3.4",
#endif

    // Data from other architectures.
    "perf.data.i686-3.4",     // 32-bit x86
    "perf.data.armv7-3.4",    // ARM v7

    // Same as above, obtained from a system running kernel v3.8.
    "perf.data.singleprocess-3.8",
    "perf.data.systemwide.0-3.8",
#ifdef TEST_LARGE_PERF_DATA
    "perf.data.systemwide.1-3.8",
    "perf.data.systemwide.5-3.8",
    "perf.data.busy.0-3.8",
    "perf.data.busy.1-3.8",
    "perf.data.busy.5-3.8",
#endif  // defined(TEST_LARGE_PERF_DATA)

    "perf.data.forkexit-3.8",
#ifdef TEST_CALLGRAPH
    "perf.data.callgraph-3.8",
#endif
    "perf.data.branch-3.8",
#ifdef TEST_CALLGRAPH
    "perf.data.callgraph_and_branch-3.8",
#endif
    "perf.data.armv7.perf_3.14-3.8",      // ARM v7 obtained using perf 3.14.

    // Obtained from a system that uses NUMA topology.
    "perf.data.numatopology-3.2",

    // Perf data that contains hardware and software events.
    // Command:
    //    perf record -a -c 1000000 -e cycles,branch-misses,cpu-clock -- sleep 2
    // HW events are cycles and branch-misses, SW event is cpu-clock.
    // This also tests non-consecutive event types.
    "perf.data.hw_and_sw-3.4",

    // This test first mmap()s a DSO, then fork()s to copy the mapping to the
    // child and then modifies the mapping by mmap()ing a DSO on top of the old
    // one. It then records SAMPLEs events in the child. It ensures the SAMPLEs
    // in the child are attributed to the first DSO that was mmap()ed, not the
    // second one.
    "perf.data.remmap-3.2",

    // This is sample with a frequency higher than the max frequency, so it has
    // throttle and unthrottle events.
    "perf.data.throttle-3.8",
  };
  return *files;
}

const std::vector<const char*>& GetPerfPipedDataFiles() {
  static const std::vector<const char*>* files = new std::vector<const char*> {
    "perf.data.piped.host-3.2",
    "perf.data.piped.target-3.4",
    "perf.data.piped.target.throttled-3.4",
    "perf.data.piped.target-3.8",

    // Piped data that contains hardware and software events.
    // Command:
    //    perf record -a -c 1000000 -e cycles,branch-misses,cpu-clock -o -
    //        -- sleep 2
    // HW events are cycles and branch-misses, SW event is cpu-clock.
    "perf.data.piped.hw_and_sw-3.4",

    // Piped data with extra data at end.
    "perf.data.piped.extrabyte-3.4",
    "perf.data.piped.extradata-3.4",
  };
  return *files;
}

const std::vector<const char*>& GetCorruptedPerfPipedDataFiles()  {
  static const std::vector<const char*>* files = new std::vector<const char*> {
    // Has a SAMPLE event with size set to zero. Don't go into an infinite loop!
    "perf.data.piped.corrupted.zero_size_sample-3.2",
  };
  return *files;
}

const std::vector<const char*>& GetPerfDataProtoFiles()  {
  static const std::vector<const char*>* files = new std::vector<const char*> {
    "perf.callgraph.pb_text",
  };
  return *files;
}

}  // namespace perf_test_files


text:
<!doctype html>

    <meta charset="utf-8">
    <title>zchq88_seed</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="renderer" content="webkit">

    <link href="//cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet">


text:
/*
 *  SlowBuffer is only available through a 'require' statement, not
 *  implemented for now.
 */

/*---
{
    "skip": true
}
---*/

/*@include util-buffer.js@*/

function testSlowBuffer() {
    var buffer = require('buffer');
    print(buffer.SlowBuffer);
}

try {
    testSlowBuffer();
} catch (e) {
    print(e.stack || e);
}


text:
title: Getting Started with Sass
localeTitle: Empezando con Sass
---
### Introducción

Sass significa "Syntactically Awesome Stylesheets" y es un Pre-procesador de CSS. Un preprocesador compila el código escrito en un lenguaje específico hasta el código de "producto" que es legible por máquina (legible por el navegador). Básicamente, Sass compila código a CSS normal que nuestros navegadores pueden interpretar. _¿Por qué escribir código en Sass cuando CSS ya existe?_ La respuesta corta es que Sass viene con características más potentes incorporadas en su sintaxis que permiten a los desarrolladores escribir código de front-end DRY, escalable y más mantenible.

Si estás familiarizado con CSS, aprender Sass te resultará un poco más fácil. De lo contrario, podría ser ideal comenzar a aprender algunos conceptos básicos de CSS en la sección de HTML5 y CSS de Free Code Camp en su curso de Certificación de Desarrollo de Front End, así como echar un vistazo al [Artículo de CSS de MDN](https://developer.mozilla.org/en-US/docs/Web/CSS) .

En la Parte 1 de este artículo, explicaré cómo instalar Sass en su computadora y cómo compilar su código escrito en Sass en CSS.

## Instalación

La forma más sencilla de instalar Sass en su máquina es a través de la línea de comandos. Sass es una gema de Ruby y requerirá el siguiente comando:

Para Mac y PC:

`sudo gem install sass`

Para Linux, primero deberá instalar el lenguaje Ruby, luego:

`sudo su -c "gem install sass"`

Ahora debería poder verificar la versión de Sass instalada:

`sass -v`

Y debería devolver algo similar a:

`Sass 3.4.21 (Selective Steve)`

Si es así, felicidades, acabas de instalar Sass! Ahora en el uso de Sass.

## Uso básico y sintaxis

Comencemos con un ejemplo muy simple para ilustrar cómo funciona realmente Sass. Puedes seguir los pasos o simplemente leerlos.

_Una nota al margen de importación: Sass se puede escribir en dos estilos ligeramente diferentes, cada uno de los cuales tiene sus propios beneficios. Un estilo usará la extensión de archivo_ `.sass` _y el otro usará_ `.scss` . _Se darán breves explicaciones sobre las diferencias de los dos estilos más adelante. Para obtener una explicación detallada, consulte el artículo de John W. Long_ [Sass vs. SCSS](http://thesassway.com/editorial/sass-vs-scss-which-syntax-is-better) .

_En aras de la coherencia, este artículo proporcionará ejemplos de código en formato `.scss` , sin embargo, ambos estilos son igualmente populares._

Bien, vamos a empezar. Crearemos una nueva carpeta para alojar nuestros archivos de ejemplo (puede hacer esto en cualquier parte de su computadora y puede usar la línea de comandos o hacerlo manualmente).

En la carpeta, crearemos un archivo llamado `style.scss` y un archivo HTML para estilo llamado `index.html` :

_El comando de `tree` en la imagen de arriba es de un paquete npm que puede instalar y no es nativo de la línea de comandos. El comando `ls` esencialmente hace lo mismo._

Ahora que tenemos la configuración de la carpeta del proyecto, podemos usar el comando Sass watch para "vigilar" nuestro archivo Sass y compilar nuestro código cuando detecta un cambio en el archivo. Escribimos el comando watch en el archivo que queremos ver:

`sass --watch style.scss`

El siguiente paso es abrir la carpeta del proyecto en el editor de texto que elija. Una vez que tengamos nuestros archivos abiertos y listos para su edición, podemos agregar una página HTML muy básica (para nuestro estilo) que se verá como la siguiente:
```
<!DOCTYPE html>
 <html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>Sass!</title>
  <link rel="stylesheet" href="style.css">
 </head>
 <body>
  <article>
    <h1>Hello World</h1>
    <p class="cat-paragraph-1">Cat ipsum dolor sit amet, stand in front of the computer screen, so chase imaginary bugs has closed eyes but still sees you caticus cuteicus.</p>
    <p class="cat-paragraph-2">Drink water out of the faucet chew on cable or if it fits, i sits roll on the floor purring your whiskers off.</p>
  </article>
 </body>
 </html>
```

Después de configurar el HTML, podemos abrir nuestro archivo `style.scss` y comenzar a diseñar en Sass. En el código de ejemplo siguiente, probablemente observará cómo algunos selectores de estilo están anidados dentro del selector de artículos; algo único para Sass. No se preocupe, la sintaxis se explicará en la Parte 2. Por ahora solo queremos comprender cómo funciona Sass en su forma más simple.
```
article {
  h2 {
    font-family: Arial;
    color: blue;
  }
  .cat-paragraph-1 {
    color: red;
  }
  .cat-paragraph-2 {
    color: green;
  }
 }
```

Una vez que el código se haya escrito y guardado en el archivo `style.scss` , la tarea de `style.scss` que `style.scss` en la línea de comandos habrá detectado un cambio en el archivo, compilado nuestro Sass a CSS y `style.css` un nuevo archivo llamado `style.css` . También puede ver un archivo llamado `style.css.map` en su carpeta de proyecto que también ha aparecido mágicamente. Este archivo se llama sourcemap y es de gran utilidad para la depuración de Sass, pero por ahora solo lo dejaremos.

A continuación podemos ver los archivos listados en la carpeta del proyecto.

Y ahora, si abrimos `index.html` en un navegador web, podemos ver nuestra página HTML con el estilo de CSS que se compiló a partir del código Sass de muestra. Del mismo modo, podemos abrir el archivo `style.css` para ver cómo Sass `style.css` el código Sass original. Compacto, ¿no es así?

## ¿A dónde ir desde aquí?

_¡Estupendo! Ahora sé cómo compilar Sass en mi computadora. ¿Es asi?_

Ni por asomo. Este fue un claro ejemplo de cómo funciona Sass, por lo tanto, los beneficios de escribir en Sass sobre vainilla CSS pueden no ser evidentes. Escribimos 12 líneas de "Sass" y obtuvimos 7 líneas de CSS como resultado. No es exactamente una gran diferencia por cualquier norma. En la Parte 2 explicaremos la **magia** detrás de la sintaxis de Sass, como las variables y los mixins, y cómo el uso de tales herramientas puede darnos superpoderes cuando estilemos.

Si aún estás atascado en cómo Sass se está compilando mágicamente en CSS o tal vez te gustaría [jugar](http://www.sassmeister.com/) con el código de ejemplo un poco más, [Sassmeister](http://www.sassmeister.com/) es una gran interfaz en línea que te permite escribir en la sintaxis de Sass y ver instantáneamente tu código compilado en CSS sin Tener que instalar algo o hacer cualquier configuración en su computadora. Es un recurso muy útil para el sandboxing y para probar su código Sass.


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

-->
<selector xmlns:android="http://schemas.android.com/apk/res/android" android:dither="true">

    <item android:state_pressed="true"><shape>
            <gradient android:angle="270" android:endColor="#e64522" android:startColor="#c33219" />

            <stroke android:width="1dp" android:color="#c33219" />

            <corners android:radius="4dp" />

            <padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp" />
        </shape></item>
    <item><shape>
            <gradient android:angle="270" android:endColor="#c33219" android:startColor="#e64522" />

            <stroke android:width="1dp" android:color="#c33219" />

            <corners android:radius="4dp" />

            <padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp" />
        </shape></item>

</selector>


text:
dasein-cloud-vcloud
===================

The Dasein Cloud vCloud submodule to the [Dasein Cloud](https://github.com/greese/dasein-cloud) project provides
an implementation of the Dasein Cloud API for VMware's vCloud cloud computing platform. This submodule supports
private clouds built on top of vCloud as well as public clouds like Bluelock that leverage the vCloud platform.

* [Get started with Dasein Cloud](https://github.com/dasein-cloud)
* [Get started with Dasein Cloud + vCloud](https://github.com/greese/dasein-cloud-vcloud/wiki)


text:
class Skill < ActiveRecord::Base
end

# == Schema Information
#
# Table name: skills
#
#  id         :integer          not null, primary key
#  name       :string
#  created_at :datetime         not null
#  updated_at :datetime         not null
#  value      :integer
#  start_date :date
#


text:
var oldlib = require('./libs/old')

run()

function run () {
  oldlib.oldfunction()
}


text:
namespace ArangoDB.Model
{
    /// <author>Mark - mark at arangodb.com</author>
    /// <seealso>API Documentation
    /// 	</seealso>
    public class VertexDeleteOptions
    {
        private bool waitForSync;

        private string ifMatch;

        public VertexDeleteOptions()
            : base()
        {
        }

        public virtual bool getWaitForSync()
        {
            return waitForSync;
        }

        /// <param name="waitForSync">Wait until deletion operation has been synced to disk.</param>
        /// <returns>options</returns>
        public virtual VertexDeleteOptions waitForSync(bool waitForSync
            )
        {
            this.waitForSync = waitForSync;
            return this;
        }

        public virtual string getIfMatch()
        {
            return ifMatch;
        }

        /// <param name="ifMatch">remove a document based on a target revision</param>
        /// <returns>options</returns>
        public virtual VertexDeleteOptions ifMatch(string ifMatch)
        {
            this.ifMatch = ifMatch;
            return this;
        }
    }
}


text:
PROJ = test_rats_app
ROOTDIR = ../../../..
SRCS += rats.c
SRCS += linear.c
SRCS += ../test_rats/test_rats.c
include $(ROOTDIR)/config/Makerules

LDFLAGS += -lm

vpath rats.c $(ROOTDIR)/extensions/rats/
vpath linear.c $(ROOTDIR)/extensions/rats
vpath test_rats.c ../test_rats


text:
"""
    test_sv.py -- Test cases for Simple VIVO
"""

__author__ = "Michael Conlon"
__copyright__ = "Copyright 2015 (c) Michael Conlon"
__license__ = "New BSD license"
__version__ = "1.00"

def run_tests(tests):
    """
    Run a series of tests.  Produce timing for each
    :return: dictionary of test timings keyed by test id.
    """
    from datetime import datetime
    from subprocess import call

    test_timings = {}
    for test_id in tests:
        start = datetime.now()
        try:
            rc = call(tests[test_id], shell=True)
        except OSError as error_thing:
            rc = str(error_thing)
        end = datetime.now()
        elapsed = (end - start).total_seconds()
        test_timings[test_id] = [rc, elapsed]
    return test_timings

def main():
    """
    Run tests, print results
    :return: None
    """
    tests = {
        # "summarize": "python ../sv.py -a summarize",
        # "serialize": "python ../sv.py -a serialize",
        # "update": "python ../sv.py -a update",
        # "get": "python ../sv.py -a get -s get.txt",
        # "help": "python ../sv.py -h",
        # "test": "python ../sv.py -a test",
        # "config not found": "python ../sv.py -a update -c data/cfg_not_found.cfg",
        # "file not found": "python ../sv.py -a update -c data/file_not_found.cfg",
        "invalid access": "python ../sv.py -a test -c data/invalid_access.cfg",
        # "invalid JSON": "python ../sv.py -a update -d data/grant_invalid_def.json",
        # "awards get": "cd ../examples/awards; python ../../sv.py -a get -s get.txt",
        # "awards update": "cd ../examples/awards; python ../../sv.py -a update",
        # "concepts get": "cd ../examples/concepts; python ../../sv.py -a get -s get.txt",
        # "concepts update": "cd ../examples/concepts; python ../../sv.py -a update",
        # "courses get": "cd ../examples/courses; python ../../sv.py -c sv_courses.cfg -a get -s get.txt",
        # "courses update": "cd ../examples/courses; python ../../sv.py -c sv_courses.cfg -a update",
        # "teaching get": "cd ../examples/courses; python ../../sv.py -a get -s get.txt",
        # "teaching update": "cd ../examples/courses; python ../../sv.py -a update",
        # "dates get": "cd ../examples/dates; python ../../sv.py -a get -s get.txt",
        # "dates update": "cd ../examples/dates; python ../../sv.py -a update",
        # "education get": "cd ../examples/education; python ../../sv.py -a get -s get.txt",
        # "education update": "cd ../examples/education; python ../../sv.py -a update",
        # "grants get": "cd ../examples/grants; python ../../sv.py -a get -s get.txt",
        # "grants update": "cd ../examples/grants; python ../../sv.py -a update",
        # "journals get": "cd ../examples/journals; python ../../sv.py -a get -s get.txt",
        # "journals update": "cd ../examples/journals; python ../../sv.py -a update",
        # "locations get": "cd ../examples/locations; python ../../sv.py -a get -s get.txt",
        # "locations update": "cd ../examples/locations; python ../../sv.py -a update",
        # "orgs get": "cd ../examples/orgs; python ../../sv.py -a get -s get.txt",
        # "orgs update": "cd ../examples/orgs; python ../../sv.py -a update",
        # "people get": "cd ../examples/people; python ../../sv.py -a get -s get.txt",
        # "people update": "cd ../examples/people; python ../../sv.py -a update",
        # "positions get": "cd ../examples/positions; python ../../sv.py -a get -s get.txt",
        # "positions update": "cd ../examples/positions; python ../../sv.py -a update"
    }
    test_results = run_tests(tests)
    for testid in sorted(test_results):
        print testid.rjust(20), test_results[testid][0], "\t", test_results[testid][1]

if __name__ == "__main__":
    main()


text:
from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

app.run(debug=True, host='0.0.0.0', port=8000)


text:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.sql.SQLException;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;

/**
   Executes all SQL statements from a file or the console.
*/
public class ExecSQL
{
   public static void main(String[] args)
         throws SQLException, IOException, ClassNotFoundException
   {
      if (args.length == 0)
      {
         System.out.println(
               "Usage: java -classpath driver_class_path"
               + File.pathSeparator
               + ". ExecSQL propertiesFile [SQLcommandFile]");
         return;
      }

      SimpleDataSource.init(args[0]);

      Scanner in;
      if (args.length > 1)
      {
         in = new Scanner(new File(args[1]));
      }
      else
      {
         in = new Scanner(System.in);
      }

      try (Connection conn = SimpleDataSource.getConnection();
            Statement stat = conn.createStatement())
      {
         while (in.hasNextLine())
         {
            String line = in.nextLine();
            try
            {
               boolean hasResultSet = stat.execute(line);
               if (hasResultSet)
               {
                  try (ResultSet result = stat.getResultSet())
                  {
	             showResultSet(result);
                  }
               }
            }
            catch (SQLException ex)
            {
               System.out.println(ex);
            }
         }
      }
   }

   /**
      Prints a result set.
      @param result the result set
   */
   public static void showResultSet(ResultSet result)
         throws SQLException
   {
      ResultSetMetaData metaData = result.getMetaData();
      int columnCount = metaData.getColumnCount();

      for (int i = 1; i <= columnCount; i++)
      {
         if (i > 1) { System.out.print(", "); }
         System.out.print(metaData.getColumnLabel(i));
      }
      System.out.println();

      while (result.next())
      {
         for (int i = 1; i <= columnCount; i++)
         {
            if (i > 1) { System.out.print(", "); }
            System.out.print(result.getString(i));
         }
         System.out.println();
      }
   }
}


text:
package hello;

public class Customer {

    private long id;
    private String firstName, lastName;

    public Customer(long id, String firstName, String lastName) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return String.format(
                "Customer[id=%d, firstName='%s', lastName='%s']",
                id, firstName, lastName);
    }
}


text:
#include "../mana_common.h"

//#include "../File/file.h"

#include "resource_file.h"

namespace mana{

resource_file::resource_file():bTextMode_(false),nState_(NONE)
{
	pFile_ = make_shared<file::file_access>();
}

void resource_file::operator()()
{
	if(!pFile_->open(bTextMode_ ? file::file_access::READ_ALL_TEXT : file::file_access::READ_ALL))
	{
		set_state(FAIL);
		return;
	}

	set_state(LOADING);

	uint32_t rsize;
	int32_t r = pFile_->read(rsize);
	pFile_->close();

	if(r==file::file_access::FAIL)
		set_state(FAIL);
	else
		set_state(SUCCESS);

	logger::debugln("[resource_file]ファイル読み込み終了 : " + pFile_->filepath().str() + " " + to_str(nState_));
}

void resource_file::set_filepath(const string& sFilepath, bool bTextMode)
{
	pFile_->set_filepath(file::path(sFilepath));
	bTextMode_	= bTextMode;
	set_state(NONE);
}

} // namespace mana end


text:
<html>
<body>
Reports annotation interfaces.
Such interfaces are not supported under Java 1.4 and earlier.
<!-- tooltip end -->
<p>

</body>
</html>


text:
require 'spec_helper'

describe Kul::Path do

  context 'root path' do
    subject(:request) { Kul::Path.new('') }

    it '#extension is html' do
      request.extension.should == 'html'
    end
    it '#controller_name is nil' do
      request.controller_name.should be_nil
    end
    it '#action_name is nil' do
      request.action_name.should be_nil
    end
  end

  context '#file_path' do
    it 'returns the file path' do
      Kul::Path.new('foo/test.html?bar=bat&foo=bar').file_path.should == 'foo/test.html'
    end
    it 'returns index.html for the root path' do
      Kul::Path.new('').file_path.should == 'index.html'
    end
    it 'returns foo/index.html for the foo path' do
      Kul::Path.new('foo').file_path.should == 'foo/index.html'
    end
    it 'returns foo/index.html for the foo/ path' do
      Kul::Path.new('foo/').file_path.should == 'foo/index.html'
    end
  end

  describe '#extension' do
    it 'returns the extension' do
      Kul::Path.new('foo/test.js').extension.should == 'js'
    end
    it 'returns the extension correctly when get params' do
      Kul::Path.new('foo/test.js?test=thing').extension.should == 'js'
    end
    it 'returns html for app paths' do
      Kul::Path.new('foo').extension.should == 'html'
    end
    it 'returns html for app paths with trailing slash' do
      Kul::Path.new('foo/').extension.should == 'html'
    end
    it 'returns only the last extension' do
      Kul::Path.new('foo/test-3.4.3.min.js').extension.should == 'js'
    end
  end

  describe '#controller_name' do
    it 'returns the name' do
      Kul::Path.new('bar/baz?test=thing').controller_name.should == 'bar'
    end
    it 'returns name when it ends path with params' do
      test = Kul::Path.new('bar?test=thing').controller_name
      test.should == 'bar'
    end
    it 'returns name when it ends path' do
      test = Kul::Path.new('bar').controller_name
      test.should == 'bar'
    end
    it 'returns name when it ends path with slash' do
      test = Kul::Path.new('bar/?test=thing').controller_name
      test.should == 'bar'
    end
    it 'should return the same string' do
      request = Kul::Path.new('bar/baz?test=thing')
      test = request.controller_name
      test.should be_equal request.controller_name
    end
  end

  describe '#action_name' do
    it 'returns the name' do
      test = Kul::Path.new('bar/baz?test=thing').action_name
      test.should == 'baz'
    end
    it 'returns index if no action' do
      test = Kul::Path.new('bar?test=thing').action_name
      test.should == 'index'
    end
    it 'returns index with controller with trailing slash' do
      test = Kul::Path.new('bar/?test=thing').action_name
      test.should == 'index'
    end
    it 'returns nil when the path is longer than an action' do
      test = Kul::Path.new('bar/baz/more.html?test=thing').action_name
      test.should be_nil
    end
    it 'returns the name when there are no params' do
      test = Kul::Path.new('bar/baz').action_name
      test.should == 'baz'
    end
    it 'should return the same string' do
      request = Kul::Path.new('bar/baz?test=thing')
      test = request.action_name
      test.should be_equal request.action_name
    end
  end

end


text:
All Contacts

Top Contacts

                    {{contact.name}}

            <button class="btn" ng-click="goToRandom()">Show random contact</button>