text:
using namespace llvm;

static cl::opt<bool> PNaClMemoryOrderSeqCstOnly(
    "pnacl-memory-order-seq-cst-only",
    cl::desc("PNaCl should upgrade all atomic memory orders to seq_cst"),
    cl::init(false));

namespace {

class RewriteAtomics : public ModulePass {
public:
  static char ID; // Pass identification, replacement for typeid
  RewriteAtomics() : ModulePass(ID) {
    // This is a module pass because it may have to introduce
    // intrinsic declarations into the module and modify a global function.
    initializeRewriteAtomicsPass(*PassRegistry::getPassRegistry());
  }

  virtual bool runOnModule(Module &M);
};

template <class T> std::string ToStr(const T &V) {
  std::string S;
  raw_string_ostream OS(S);
  OS << const_cast<T &>(V);
  return OS.str();
}

class AtomicVisitor : public InstVisitor<AtomicVisitor> {
public:
  AtomicVisitor(Module &M, Pass &P)
      : M(M), C(M.getContext()),
        TD(M.getDataLayout()), AI(C),
        ModifiedModule(false) {}
  ~AtomicVisitor() {}
  bool modifiedModule() const { return ModifiedModule; }

  void visitLoadInst(LoadInst &I);
  void visitStoreInst(StoreInst &I);
  void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I);
  void visitAtomicRMWInst(AtomicRMWInst &I);
  void visitFenceInst(FenceInst &I);

private:
  Module &M;
  LLVMContext &C;
  const DataLayout TD;
  NaCl::AtomicIntrinsics AI;
  bool ModifiedModule;

  AtomicVisitor() = delete;
  AtomicVisitor(const AtomicVisitor &) = delete;
  AtomicVisitor &operator=(const AtomicVisitor &) = delete;

  /// Create an integer constant holding a NaCl::MemoryOrder that can be
  /// passed as an argument to one of the @llvm.nacl.atomic.*
  /// intrinsics. This function may strengthen the ordering initially
  /// specified by the instruction \p I for stability purpose.
  template <class Instruction>
  ConstantInt *freezeMemoryOrder(const Instruction &I, AtomicOrdering O) const;
  std::pair<ConstantInt *, ConstantInt *>
  freezeMemoryOrder(const AtomicCmpXchgInst &I, AtomicOrdering S,
                    AtomicOrdering F) const;

  /// Sanity-check that instruction \p I which has pointer and value
  /// parameters have matching sizes \p BitSize for the type-pointed-to
  /// and the value's type \p T.
  void checkSizeMatchesType(const Instruction &I, unsigned BitSize,
                            const Type *T) const;

  /// Verify that loads and stores are at least naturally aligned. Use
  /// byte alignment because converting to bits could truncate the
  /// value.
  void checkAlignment(const Instruction &I, unsigned ByteAlignment,
                      unsigned ByteSize) const;

  /// Create a cast before Instruction \p I from \p Src to \p Dst with \p Name.
  CastInst *createCast(Instruction &I, Value *Src, Type *Dst, Twine Name) const;

  /// Try to find the atomic intrinsic of with its \p ID and \OverloadedType.
  /// Report fatal error on failure.
  const NaCl::AtomicIntrinsics::AtomicIntrinsic *
  findAtomicIntrinsic(const Instruction &I, Intrinsic::ID ID,
                      Type *OverloadedType) const;

  /// Helper function which rewrites a single instruction \p I to a
  /// particular \p intrinsic with overloaded type \p OverloadedType,
  /// and argument list \p Args. Will perform a bitcast to the proper \p
  /// DstType, if different from \p OverloadedType.
  void replaceInstructionWithIntrinsicCall(
      Instruction &I, const NaCl::AtomicIntrinsics::AtomicIntrinsic *Intrinsic,
      Type *DstType, Type *OverloadedType, ArrayRef<Value *> Args);

  /// Most atomics instructions deal with at least one pointer, this
  /// struct automates some of this and has generic sanity checks.
  template <class Instruction> struct PointerHelper {
    Value *P;
    Type *OriginalPET;
    Type *PET;
    unsigned BitSize;
    PointerHelper(const AtomicVisitor &AV, Instruction &I)
        : P(I.getPointerOperand()) {
      if (I.getPointerAddressSpace() != 0)
        report_fatal_error("unhandled pointer address space " +
                           Twine(I.getPointerAddressSpace()) + " for atomic: " +
                           ToStr(I));
      assert(P->getType()->isPointerTy() && "expected a pointer");
      PET = OriginalPET = P->getType()->getPointerElementType();
      BitSize = AV.TD.getTypeSizeInBits(OriginalPET);
      if (!OriginalPET->isIntegerTy()) {
        // The pointer wasn't to an integer type. We define atomics in
        // terms of integers, so bitcast the pointer to an integer of
        // the proper width.
        Type *IntNPtr = Type::getIntNPtrTy(AV.C, BitSize);
        P = AV.createCast(I, P, IntNPtr, P->getName() + ".cast");
        PET = P->getType()->getPointerElementType();
      }
      AV.checkSizeMatchesType(I, BitSize, PET);
    }
  };
};
}

char RewriteAtomics::ID = 0;
INITIALIZE_PASS(RewriteAtomics, "nacl-rewrite-atomics",
                "rewrite atomics, volatiles and fences into stable "
                "@llvm.nacl.atomics.* intrinsics",
                false, false)

bool RewriteAtomics::runOnModule(Module &M) {
  AtomicVisitor AV(M, *this);
  AV.visit(M);
  return AV.modifiedModule();
}

template <class Instruction>
ConstantInt *AtomicVisitor::freezeMemoryOrder(const Instruction &I,
                                              AtomicOrdering O) const {
  NaCl::MemoryOrder AO = NaCl::MemoryOrderInvalid;

  // TODO Volatile load/store are promoted to sequentially consistent
  //      for now. We could do something weaker.
  if (const LoadInst *L = dyn_cast<LoadInst>(&I)) {
    if (L->isVolatile())
      AO = NaCl::MemoryOrderSequentiallyConsistent;
  } else if (const StoreInst *S = dyn_cast<StoreInst>(&I)) {
    if (S->isVolatile())
      AO = NaCl::MemoryOrderSequentiallyConsistent;
  }

  if (AO == NaCl::MemoryOrderInvalid) {
    switch (O) {
    case NotAtomic: llvm_unreachable("unexpected memory order");
    // Monotonic is a strict superset of Unordered. Both can therefore
    // map to Relaxed ordering, which is in the C11/C++11 standard.
    case Unordered: AO = NaCl::MemoryOrderRelaxed; break;
    case Monotonic: AO = NaCl::MemoryOrderRelaxed; break;
    // TODO Consume is currently unspecified by LLVM's internal IR.
    case Acquire: AO = NaCl::MemoryOrderAcquire; break;
    case Release: AO = NaCl::MemoryOrderRelease; break;
    case AcquireRelease: AO = NaCl::MemoryOrderAcquireRelease; break;
    case SequentiallyConsistent:
      AO = NaCl::MemoryOrderSequentiallyConsistent; break;
    }
  }

  // TODO For now only acquire/release/acq_rel/seq_cst are allowed.
  if (PNaClMemoryOrderSeqCstOnly || AO == NaCl::MemoryOrderRelaxed)
    AO = NaCl::MemoryOrderSequentiallyConsistent;

  return ConstantInt::get(Type::getInt32Ty(C), AO);
}

std::pair<ConstantInt *, ConstantInt *>
AtomicVisitor::freezeMemoryOrder(const AtomicCmpXchgInst &I, AtomicOrdering S,
                                 AtomicOrdering F) const {
  if (S == Release || (S == AcquireRelease && F != Acquire))
    // According to C++11's [atomics.types.operations.req], cmpxchg with release
    // success memory ordering must have relaxed failure memory ordering, which
    // PNaCl currently disallows. The next-strongest ordering is acq_rel which
    // is also an invalid failure ordering, we therefore have to change the
    // success ordering to seq_cst, which can then fail as seq_cst.
    S = F = SequentiallyConsistent;
  if (F == Unordered || F == Monotonic) // Both are treated as relaxed.
    F = AtomicCmpXchgInst::getStrongestFailureOrdering(S);
  return std::make_pair(freezeMemoryOrder(I, S), freezeMemoryOrder(I, F));
}

void AtomicVisitor::checkSizeMatchesType(const Instruction &I, unsigned BitSize,
                                         const Type *T) const {
  Type *IntType = Type::getIntNTy(C, BitSize);
  if (IntType && T == IntType)
    return;
  report_fatal_error("unsupported atomic type " + ToStr(*T) + " of size " +
                     Twine(BitSize) + " bits in: " + ToStr(I));
}

void AtomicVisitor::checkAlignment(const Instruction &I, unsigned ByteAlignment,
                                   unsigned ByteSize) const {
  if (ByteAlignment < ByteSize)
    report_fatal_error("atomic load/store must be at least naturally aligned, "
                       "got " +
                       Twine(ByteAlignment) + ", bytes expected at least " +
                       Twine(ByteSize) + " bytes, in: " + ToStr(I));
}

CastInst *AtomicVisitor::createCast(Instruction &I, Value *Src, Type *Dst,
                                    Twine Name) const {
  Type *SrcT = Src->getType();
  Instruction::CastOps Op = SrcT->isIntegerTy() && Dst->isPointerTy()
                                ? Instruction::IntToPtr
                                : SrcT->isPointerTy() && Dst->isIntegerTy()
                                      ? Instruction::PtrToInt
                                      : Instruction::BitCast;
  if (!CastInst::castIsValid(Op, Src, Dst))
    report_fatal_error("cannot emit atomic instruction while converting type " +
                       ToStr(*SrcT) + " to " + ToStr(*Dst) + " for " + Name +
                       " in " + ToStr(I));
  return CastInst::Create(Op, Src, Dst, Name, &I);
}

const NaCl::AtomicIntrinsics::AtomicIntrinsic *
AtomicVisitor::findAtomicIntrinsic(const Instruction &I, Intrinsic::ID ID,
                                   Type *OverloadedType) const {
  if (const NaCl::AtomicIntrinsics::AtomicIntrinsic *Intrinsic =
          AI.find(ID, OverloadedType))
    return Intrinsic;
  report_fatal_error("unsupported atomic instruction: " + ToStr(I));
}

void AtomicVisitor::replaceInstructionWithIntrinsicCall(
    Instruction &I, const NaCl::AtomicIntrinsics::AtomicIntrinsic *Intrinsic,
    Type *DstType, Type *OverloadedType, ArrayRef<Value *> Args) {
  std::string Name(I.getName());
  Function *F = Intrinsic->getDeclaration(&M);
  CallInst *Call = CallInst::Create(F, Args, "", &I);
  Call->setDebugLoc(I.getDebugLoc());
  Instruction *Res = Call;

  assert((I.getType()->isStructTy() == isa<AtomicCmpXchgInst>(&I)) &&
         "cmpxchg returns a struct, and other instructions don't");
  if (auto S = dyn_cast<StructType>(I.getType())) {
    assert(S->getNumElements() == 2 &&
           "cmpxchg returns a struct with two elements");
    assert(S->getElementType(0) == DstType &&
           "cmpxchg struct's first member should be the value type");
    assert(S->getElementType(1) == Type::getInt1Ty(C) &&
           "cmpxchg struct's second member should be the success flag");
    // Recreate struct { T value, i1 success } after the call.
    auto Success = CmpInst::Create(
        Instruction::ICmp, CmpInst::ICMP_EQ, Res,
        cast<AtomicCmpXchgInst>(&I)->getCompareOperand(), "success", &I);
    Res = InsertValueInst::Create(
        InsertValueInst::Create(UndefValue::get(S), Res, 0,
                                Name + ".insert.value", &I),
        Success, 1, Name + ".insert.success", &I);
  } else if (!Call->getType()->isVoidTy() && DstType != OverloadedType) {
    // The call returns a value which needs to be cast to a non-integer.
    Res = createCast(I, Call, DstType, Name + ".cast");
    Res->setDebugLoc(I.getDebugLoc());
  }

  I.replaceAllUsesWith(Res);
  I.eraseFromParent();
  Call->setName(Name);
  ModifiedModule = true;
}

///   %res = load {atomic|volatile} T* %ptr memory_order, align sizeof(T)
/// becomes:
///   %res = call T @llvm.nacl.atomic.load.i<size>(%ptr, memory_order)
void AtomicVisitor::visitLoadInst(LoadInst &I) {
  return; // XXX EMSCRIPTEN
  if (I.isSimple())
    return;
  PointerHelper<LoadInst> PH(*this, I);
  const NaCl::AtomicIntrinsics::AtomicIntrinsic *Intrinsic =
      findAtomicIntrinsic(I, Intrinsic::nacl_atomic_load, PH.PET);
  checkAlignment(I, I.getAlignment(), PH.BitSize / CHAR_BIT);
  Value *Args[] = {PH.P, freezeMemoryOrder(I, I.getOrdering())};
  replaceInstructionWithIntrinsicCall(I, Intrinsic, PH.OriginalPET, PH.PET,
                                      Args);
}

///   store {atomic|volatile} T %val, T* %ptr memory_order, align sizeof(T)
/// becomes:
///   call void @llvm.nacl.atomic.store.i<size>(%val, %ptr, memory_order)
void AtomicVisitor::visitStoreInst(StoreInst &I) {
  return; // XXX EMSCRIPTEN
  if (I.isSimple())
    return;
  PointerHelper<StoreInst> PH(*this, I);
  const NaCl::AtomicIntrinsics::AtomicIntrinsic *Intrinsic =
      findAtomicIntrinsic(I, Intrinsic::nacl_atomic_store, PH.PET);
  checkAlignment(I, I.getAlignment(), PH.BitSize / CHAR_BIT);
  Value *V = I.getValueOperand();
  if (!V->getType()->isIntegerTy()) {
    // The store isn't of an integer type. We define atomics in terms of
    // integers, so bitcast the value to store to an integer of the
    // proper width.
    CastInst *Cast = createCast(I, V, Type::getIntNTy(C, PH.BitSize),
                                V->getName() + ".cast");
    Cast->setDebugLoc(I.getDebugLoc());
    V = Cast;
  }
  checkSizeMatchesType(I, PH.BitSize, V->getType());
  Value *Args[] = {V, PH.P, freezeMemoryOrder(I, I.getOrdering())};
  replaceInstructionWithIntrinsicCall(I, Intrinsic, PH.OriginalPET, PH.PET,
                                      Args);
}

///   %res = atomicrmw OP T* %ptr, T %val memory_order
/// becomes:
///   %res = call T @llvm.nacl.atomic.rmw.i<size>(OP, %ptr, %val, memory_order)
void AtomicVisitor::visitAtomicRMWInst(AtomicRMWInst &I) {
  return; // XXX EMSCRIPTEN
  NaCl::AtomicRMWOperation Op;
  switch (I.getOperation()) {
  default: report_fatal_error("unsupported atomicrmw operation: " + ToStr(I));
  case AtomicRMWInst::Add: Op = NaCl::AtomicAdd; break;
  case AtomicRMWInst::Sub: Op = NaCl::AtomicSub; break;
  case AtomicRMWInst::And: Op = NaCl::AtomicAnd; break;
  case AtomicRMWInst::Or:  Op = NaCl::AtomicOr;  break;
  case AtomicRMWInst::Xor: Op = NaCl::AtomicXor; break;
  case AtomicRMWInst::Xchg: Op = NaCl::AtomicExchange; break;
  }
  PointerHelper<AtomicRMWInst> PH(*this, I);
  const NaCl::AtomicIntrinsics::AtomicIntrinsic *Intrinsic =
      findAtomicIntrinsic(I, Intrinsic::nacl_atomic_rmw, PH.PET);
  checkSizeMatchesType(I, PH.BitSize, I.getValOperand()->getType());
  Value *Args[] = {ConstantInt::get(Type::getInt32Ty(C), Op), PH.P,
                   I.getValOperand(), freezeMemoryOrder(I, I.getOrdering())};
  replaceInstructionWithIntrinsicCall(I, Intrinsic, PH.OriginalPET, PH.PET,
                                      Args);
}

///   %res = cmpxchg [weak] T* %ptr, T %old, T %new, memory_order_success
///       memory_order_failure
///   %val = extractvalue { T, i1 } %res, 0
///   %success = extractvalue { T, i1 } %res, 1
/// becomes:
///   %val = call T @llvm.nacl.atomic.cmpxchg.i<size>(
///       %object, %expected, %desired, memory_order_success,
///       memory_order_failure)
///   %success = icmp eq %old, %val
/// Note: weak is currently dropped if present, the cmpxchg is always strong.
void AtomicVisitor::visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
  PointerHelper<AtomicCmpXchgInst> PH(*this, I);
  const NaCl::AtomicIntrinsics::AtomicIntrinsic *Intrinsic =
      findAtomicIntrinsic(I, Intrinsic::nacl_atomic_cmpxchg, PH.PET);
  checkSizeMatchesType(I, PH.BitSize, I.getCompareOperand()->getType());
  checkSizeMatchesType(I, PH.BitSize, I.getNewValOperand()->getType());
  auto Order =
      freezeMemoryOrder(I, I.getSuccessOrdering(), I.getFailureOrdering());
  Value *Args[] = {PH.P, I.getCompareOperand(), I.getNewValOperand(),
                   Order.first, Order.second};
  replaceInstructionWithIntrinsicCall(I, Intrinsic, PH.OriginalPET, PH.PET,
                                      Args);
}

///   fence memory_order
/// becomes:
///   call void @llvm.nacl.atomic.fence(memory_order)
/// and
///   call void asm sideeffect "", "~{memory}"()
///   fence seq_cst
///   call void asm sideeffect "", "~{memory}"()
/// becomes:
///   call void asm sideeffect "", "~{memory}"()
///   call void @llvm.nacl.atomic.fence.all()
///   call void asm sideeffect "", "~{memory}"()
/// Note that the assembly gets eliminated by the -remove-asm-memory pass.
void AtomicVisitor::visitFenceInst(FenceInst &I) {
  return; // XXX EMSCRIPTEN
  Type *T = Type::getInt32Ty(C); // Fences aren't overloaded on type.
  BasicBlock::InstListType &IL(I.getParent()->getInstList());
  bool isFirst = IL.empty() || &*I.getParent()->getInstList().begin() == &I;
  bool isLast = IL.empty() || &*I.getParent()->getInstList().rbegin() == &I;
  CallInst *PrevC = isFirst ? 0 : dyn_cast<CallInst>(I.getPrevNode());
  CallInst *NextC = isLast ? 0 : dyn_cast<CallInst>(I.getNextNode());

  if ((PrevC && PrevC->isInlineAsm() &&
       cast<InlineAsm>(PrevC->getCalledValue())->isAsmMemory()) &&
      (NextC && NextC->isInlineAsm() &&
       cast<InlineAsm>(NextC->getCalledValue())->isAsmMemory()) &&
      I.getOrdering() == SequentiallyConsistent) {
    const NaCl::AtomicIntrinsics::AtomicIntrinsic *Intrinsic =
        findAtomicIntrinsic(I, Intrinsic::nacl_atomic_fence_all, T);
    replaceInstructionWithIntrinsicCall(I, Intrinsic, T, T,
                                        ArrayRef<Value *>());
  } else {
    const NaCl::AtomicIntrinsics::AtomicIntrinsic *Intrinsic =
        findAtomicIntrinsic(I, Intrinsic::nacl_atomic_fence, T);
    Value *Args[] = {freezeMemoryOrder(I, I.getOrdering())};
    replaceInstructionWithIntrinsicCall(I, Intrinsic, T, T, Args);
  }
}

ModulePass *llvm::createRewriteAtomicsPass() { return new RewriteAtomics(); }


text:
export NotificationList from './NotificationList';
export NotificationEntry from './NotificationEntry';

redpajama_set_name: RedPajamaGithub


text:
SEQAN_BEGIN_TESTSUITE(test_clusterSearch)
{
	SEQAN_CALL_TEST(test_clusterSearch_emptyFiles);
	SEQAN_CALL_TEST(test_clusterSearch_benchmarking_emptyFiles);
}
SEQAN_END_TESTSUITE


text:
class BansheePackage (Package):
	def __init__ (self):
		Package.__init__ (self, 'banshee', 'stable-2.4')

		self.sources = [
			'git://git.gnome.org/banshee'
		]
		self.git_branch = 'stable-2.4'

		self.configure = [ 'NOCONFIGURE=1 ./autogen.sh && ./profile-configure %{profile.name} --prefix=%{prefix}' ]
		self.sources.extend([

			# switch over from ige_* to gtk_* binding
			'patches/banshee-gtk-mac-integration.patch'
		])

	def prep (self):
		Package.prep (self)
		self.sh ('patch -p1 < %{sources[1]}')

BansheePackage ()


text:
package co.mewf.minirs.rs.core;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.net.URI;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import co.mewf.minirs.internal.javax.ws.rs.core.EntityTag;
import co.mewf.minirs.internal.javax.ws.rs.core.GenericType;
import co.mewf.minirs.internal.javax.ws.rs.core.HttpHeaders;
import co.mewf.minirs.internal.javax.ws.rs.core.Link;
import co.mewf.minirs.internal.javax.ws.rs.core.MediaType;
import co.mewf.minirs.internal.javax.ws.rs.core.MultivaluedHashMap;
import co.mewf.minirs.internal.javax.ws.rs.core.MultivaluedMap;
import co.mewf.minirs.internal.javax.ws.rs.core.NewCookie;
import co.mewf.minirs.internal.javax.ws.rs.ext.MessageBodyWriter;
import co.mewf.minirs.internal.javax.ws.rs.ext.ParamConverter;
import co.mewf.minirs.util.Dates;
import co.mewf.minirs.util.Locales;

import com.google.common.base.Function;
import com.google.common.collect.Lists;

public class MiniRsResponse extends Response {
  private Object entity;
  private int status;
  private MultivaluedMap<String, Object> metadata;
  private Type genericType;
  private boolean closed;
  private HttpServletResponse httpResponse;
  private MessageBodyWriter writer;

  public MiniRsResponse(int status, MultivaluedMap<String, Object> metadata) {
    this.status = status;
    this.metadata = metadata;
  }

  @Override
  public Object getEntity() {
    abortIfClosed();
    return entity;
  }

  @Override
  public int getStatus() {
    return status;
  }

  @Override
  public StatusType getStatusInfo() {
    StatusType statusType = Status.fromStatusCode(status);
    if (statusType == null) {
      statusType = new StatusType() {
        @Override
        public int getStatusCode() {
          return status;
        }

        @Override
        public Status.Family getFamily() {
          return Status.Family.familyOf(status);
        }

        @Override
        public String getReasonPhrase() {
          return "Unknown Code";
        }
      };
    }

    return statusType;
  }

  @Override
  public MultivaluedMap<String, Object> getMetadata() {
    return metadata;
  }

  public void setStatus(int status) {
    this.status = status;
  }

  @Override
  public <T> T readEntity(Class<T> type, Annotation[] annotations) {
    return readEntity(type, null, annotations);
  }

  @Override
  public <T> T readEntity(GenericType<T> entityType, Annotation[] annotations) {
    return readEntity((Class<T>) entityType.getRawType(), entityType.getType(), annotations);
  }

  @Override
  public <T> T readEntity(Class<T> type) {
    return readEntity(type, null, null);
  }

  @Override
  public <T> T readEntity(GenericType<T> entityType) {
    return readEntity((Class<T>) entityType.getRawType(), entityType.getType(), null);
  }

  public <T> T readEntity(Class<T> type, Type genericType, Annotation[] anns) {
    throw new IllegalStateException("Entity is not backed by an input stream");
  }

  @Override
  public boolean hasEntity() {
    abortIfClosed();
    return entity != null;
  }

  @Override
  public boolean bufferEntity() {
    abortIfClosed();
    // no-op
    return false;
  }

  private boolean isClosed() {
    return closed;
  }

  private void abortIfClosed() {
    if (isClosed()) throw new IllegalStateException("Response is closed.");
  }

  @Override
  public void close() {
    closed = true;
  }

  @Override
  public Locale getLanguage() {
    Object obj = metadata.getFirst(HttpHeaders.CONTENT_LANGUAGE);
    if (obj == null) return null;
    if (obj instanceof Locale) return (Locale) obj;

    return Locales.valueOf(toHeaderString(obj));
  }

  @Override
  public int getLength() {
    Object obj = metadata.getFirst(HttpHeaders.CONTENT_LENGTH);
    if (obj == null) return -1;
    if (obj instanceof Integer) return (Integer) obj;
    return Integer.valueOf(toHeaderString(obj));
  }

  @Override
  public MediaType getMediaType() {
    Object obj = metadata.getFirst(HttpHeaders.CONTENT_TYPE);
    if (obj instanceof MediaType) return (MediaType) obj;
    if (obj == null) return null;
    return MediaType.valueOf(toHeaderString(obj));
  }

  @Override
  public Map<String, NewCookie> getCookies() {
    Map<String, NewCookie> cookies = new HashMap<String, NewCookie>();
    List list = metadata.get(HttpHeaders.SET_COOKIE);
    if (list == null) return cookies;
    for (Object obj : list) {
      if (obj instanceof NewCookie) {
        NewCookie cookie = (NewCookie) obj;
        cookies.put(cookie.getName(), cookie);
      } else {
        String str = toHeaderString(obj);
        NewCookie cookie = NewCookie.valueOf(str);
        cookies.put(cookie.getName(), cookie);
      }
    }
    return cookies;
  }

  @Override
  public EntityTag getEntityTag() {
    Object d = metadata.getFirst(HttpHeaders.ETAG);
    if (d == null) return null;
    if (d instanceof EntityTag) return (EntityTag) d;
    return EntityTag.valueOf(toHeaderString(d));
  }

  @Override
  public Date getDate() {
    Object d = metadata.getFirst(HttpHeaders.DATE);
    if (d == null) return null;
    if (d instanceof Date) return (Date) d;
    return Dates.parse(d.toString());
  }

  @Override
  public Date getLastModified() {
    Object d = metadata.getFirst(HttpHeaders.LAST_MODIFIED);
    if (d == null) return null;
    if (d instanceof Date) return (Date) d;
    return Dates.parse(d.toString());
  }

  @Override
  public Set<String> getAllowedMethods() {
    Set<String> allowedMethods = new HashSet<String>();
    List<Object> allowed = metadata.get("Allow");
    if (allowed == null) return allowedMethods;
    for (Object header : allowed) {
      if (header != null && header instanceof String) {
        String[] list = ((String) header).split(",");
        for (String str : list) {
          if (!"".equals(str.trim())) {
            allowedMethods.add(str.trim().toUpperCase());
          }
        }
      } else {
        allowedMethods.add(toHeaderString(header).toUpperCase());
      }
    }

    return allowedMethods;
  }

  private String toHeaderString(Object object) {
    if (object instanceof String) return (String) object;
//    Class<?> aClass = object.getClass();
    ParamConverter paramConverter = null;
    if (paramConverter != null) {
      return paramConverter.toString(object);
    } else {
      return object.toString();
    }
  }

  @Override
  public MultivaluedMap<String, String> getStringHeaders() {
    MultivaluedMap<String, String> map = new MultivaluedHashMap<String, String>() {
      @Override
      public List<String> get(Object key) {
        return Lists.transform(metadata.get(key), new Function<Object, String>() {
          @Override
          public String apply(Object input) {
            return toHeaderString(input);
          }
        });
      }
    };

    return map;
  }

  @Override
  public String getHeaderString(String name) {
    List vals = metadata.get(name);
    if (vals == null) return null;
    StringBuilder builder = new StringBuilder();
    boolean first = true;
    for (Object val : vals) {
      if (first) first = false;
      else builder.append(",");
      val = toHeaderString(val);
      if (val == null) val = "";
      builder.append(val);
    }
    return builder.toString();
  }

  @Override
  public URI getLocation() {
    Object uri = metadata.getFirst(HttpHeaders.LOCATION);
    if (uri == null) return null;
    if (uri instanceof URI) return (URI) uri;
    String str = null;
    if (uri instanceof String) str = (String) uri;
    else str = toHeaderString(uri);
    return URI.create(str);
  }

  @Override
  public Set<Link> getLinks() {
    Set<Link> links = new HashSet<>();
    for (Map.Entry<String, List<Object>> entry : metadata.entrySet()) {
      if (entry.getKey().startsWith(HttpHeaders.LINK)) {
        for (Object o : entry.getValue()) {
          links.add(new MiniRsLink());
        }
      }
    }

    return links;
  }

  @Override
  public boolean hasLink(String relation) {
    return false;
  }

  @Override
  public Link getLink(String relation) {
    return null;
  }

  @Override
  public Link.Builder getLinkBuilder(String relation) {
    return null;
  }

  public HttpServletResponse getHttpResponse() {
    return httpResponse;
  }

  public void setHttpResponse(HttpServletResponse httpResponse) {
    this.httpResponse = httpResponse;
  }

  public MessageBodyWriter getWriter() {
    return writer;
  }

  public void setWriter(MessageBodyWriter<?> writer) {
    this.writer = writer;
  }

}


text:
package com.jsh.erp.datasource.mappers;

import com.jsh.erp.datasource.entities.Role;
import com.jsh.erp.datasource.entities.RoleExample;
import org.apache.ibatis.annotations.Param;

import java.util.Date;
import java.util.List;

public interface RoleMapperEx {

    List<Role> selectByConditionRole(
            @Param("name") String name,
            @Param("offset") Integer offset,
            @Param("rows") Integer rows);

    Long countsByRole(
            @Param("name") String name);

    int batchDeleteRoleByIds(@Param("updateTime") Date updateTime, @Param("updater") Long updater, @Param("ids") String ids[]);

    Role getRoleWithoutTenant(
            @Param("roleId") Long roleId);
}


text:
title:  Missionsnytt
date:  19/08/2022
---

#### Kyrkan under mangoträdet

Kyrkan under mangoträdet

Pastorn riktade en vädjan i sin predikan som Karla inte kunde motstå.

"Vänner, i två år har jag letat efter någon som kan hjälpa till att bygga en kyrka på landsbygden utanför vår stad", sa han. "Jag vet att platsen ligger långt från staden. Jag vet att det är svårt att resa dit. Jag vet att området saknar stadens bekvämligheter. Men om vi inte hjälper våra trossyskon där, vem gör det istället?"

Karla var tandläkare. Hon och hennes man hade nyligen flyttat till nordvästra Brasilien. Pastorns ord talade till henne. Hon ville hjälpa till att bygga en kyrka åt den lilla adventistförsamlingen. Hon bestämde sig för att i sin egen kyrka ställa en sparbössa där hon och de andra medlemmarna kunde lägga pengar till projektet.

Ett år senare tyckte Karla att det var dags att leta efter en tomt för den nya kyrkan. Men tomter på landet var mycket dyra. Till sist hittade hon en attraktiv tomt på en huvudgata, och hon hörde att den erbjöds till ett lågt pris. Hon sökte upp markägaren. Han begärde ٣٥ ٠٠٠ brasilianska real (٥٧ ٠٠٠ kronor) för sin mark. Karla hade inte pengarna, men hon vågade ändå göra ett motbud.

"Om vi ger dig en handpenning på ٥ ٠٠٠ real [٨ ٠٠٠ kronor], skulle du tillåta oss att betala resten i månatliga avbetalningar?" frågade hon.

"Hur många månatliga avbetalningar skulle ni göra?" frågade han.

"Vi kan bara betala dig ٥٠٠ real [٨٠٠ kronor] i månaden", sa hon.

"Sextio avbetalningar?" utbrast han. "Vill du betala av marken över fem år? Jag kommer att gå i konkurs under den tiden!"

"Men tomten kommer att användas till en god sak", framhärdade hon. "Det är till att bygga en kyrka."

Han gick med på att sälja marken. Men Karla behövde först hitta ٥ ٠٠٠ real för att lämna i handpenning. Hon bad församlingsmedlemmarna om hjälp och lyckades samla in ٢ ٧٠٠ real. Men hon behövde fortfarande ٢ ٣٠٠ real. Sedan kom hon ihåg sparbössan som hon hade placerat i kyrkan. Hon öppnade den och hittade exakt ٢ ٣٠٠ real inuti. Hon gjorde den första betalningen.

Efter det gjorde Karla en avbetalning varje månad tills hon nästan tappade räkningen på hur många avbetalningar hon hade gjort. Ett år gick. Två år. Under det tredje året bestämde hon sig för att be en djärv bön till Gud.

"Käre Gud, kan du hjälpa oss att betala av skulden i år så att vi kan börja bygga två år tidigare?" bad hon.

Målet verkade omöjligt. Men i oktober lyckades hon göra fem avbetalningar. I november gjorde hon fyra, och i december gjorde hon de tre sista. Församlingsmedlemmarna firade slutförandet av markköpet den 19 december.

Idag firar 20 församlingsmedlemmar gudstjänst varje sabbat i det de kallar sin "kyrka under mangoträdet". De samlas i skuggan av ett mangoträd medan deras nya kyrka är under uppbyggnad i närheten.

Karla säger: "Av hela våra hjärtan älskar vi vår Gud som kan förvandla det omöjliga till verklighet."


text:
package org.apache.pig.newplan;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.pig.Expression;
import org.apache.pig.PigException;
import org.apache.pig.impl.logicalLayer.FrontendException;
import org.apache.pig.impl.util.Pair;

import org.apache.pig.Expression.OpType;
import org.apache.pig.newplan.logical.expression.AddExpression;
import org.apache.pig.newplan.logical.expression.AndExpression;
import org.apache.pig.newplan.logical.expression.BinCondExpression;
import org.apache.pig.newplan.logical.expression.BinaryExpression;
import org.apache.pig.newplan.logical.expression.CastExpression;
import org.apache.pig.newplan.logical.expression.ConstantExpression;
import org.apache.pig.newplan.logical.expression.DivideExpression;
import org.apache.pig.newplan.logical.expression.EqualExpression;
import org.apache.pig.newplan.logical.expression.GreaterThanEqualExpression;
import org.apache.pig.newplan.logical.expression.GreaterThanExpression;
import org.apache.pig.newplan.logical.expression.IsNullExpression;
import org.apache.pig.newplan.logical.expression.LessThanEqualExpression;
import org.apache.pig.newplan.logical.expression.LessThanExpression;
import org.apache.pig.newplan.logical.expression.LogicalExpression;
import org.apache.pig.newplan.logical.expression.ModExpression;
import org.apache.pig.newplan.logical.expression.MultiplyExpression;
import org.apache.pig.newplan.logical.expression.NotEqualExpression;
import org.apache.pig.newplan.logical.expression.NotExpression;
import org.apache.pig.newplan.logical.expression.OrExpression;
import org.apache.pig.newplan.logical.expression.ProjectExpression;
import org.apache.pig.newplan.logical.expression.RegexExpression;
import org.apache.pig.newplan.logical.expression.SubtractExpression;
import org.apache.pig.newplan.logical.expression.UserFuncExpression;
import org.apache.pig.newplan.DepthFirstWalker;

/**
 * This Visitor works on the filter condition of a LOFilter which immediately
 * follows a LOLoad that interacts with a metadata system (currently OWL) to
 * read table data. The visitor looks for conditions on partition columns in the
 * filter condition and extracts those conditions out of the filter condition.
 * The condition on partition cols will be used to prune partitions of the table.
 *
 */
public class PColFilterExtractor extends PlanVisitor {
	/**
	 * partition columns associated with the table
	 * present in the load on which the filter whose
	 * inner plan is being visited is applied
	 */
	private List<String> partitionCols;

	/**
	 * will contain the partition column filter conditions
	 * accumulated during the visit - the final condition will an expression
	 * built from these sub expressions connected with AND
	 */
	private ArrayList<Expression> pColConditions = new ArrayList<Expression>();

	/**
	 * flag used during visit to indicate if a partition key
	 * was seen
	 */
	private boolean sawKey;

	private boolean sawNonKeyCol;

	private enum Side { LEFT, RIGHT, NONE };
	private Side replaceSide = Side.NONE;

	private boolean filterRemovable = false;

	@Override
	public void visit() throws FrontendException {
		// we will visit the leaf and it will recursively walk the plan
		LogicalExpression leaf = (LogicalExpression)plan.getSources().get( 0 );
		// if the leaf is a unary operator it should be a FilterFunc in
		// which case we don't try to extract partition filter conditions
		if(leaf instanceof BinaryExpression) {
			BinaryExpression binExpr = (BinaryExpression)leaf;
			visit( binExpr );
			replaceChild( binExpr );
			// if the entire expression is to be removed, then the above
			// replaceChild will not set sawKey to false (sawKey is set to
			// false only in replaceChild()
			if(sawKey == true) {
				//there are only conditions on partition columns in the filter
				//extract it
				pColConditions.add( getExpression( leaf ) );
				filterRemovable = true;
			}
		}
	}

	/**
	 *
	 * @param plan logical plan corresponding the filter's comparison condition
	 * @param partitionCols list of partition columns of the table which is
	 * being loaded in the LOAD statement which is input to the filter
	 */
	public PColFilterExtractor(OperatorPlan plan,
			List<String> partitionCols) {
		// though we configure a DepthFirstWalker to be the walker, we will not
		// use it - we will visit the leaf and it will recursively walk the
		// plan
		super( plan, new DepthFirstWalker( plan ) );
		this.partitionCols = new ArrayList<String>(partitionCols);
	}

	protected void visit(ProjectExpression project) throws FrontendException {
		String fieldName = project.getFieldSchema().alias;
		if(partitionCols.contains(fieldName)) {
			sawKey = true;
			// The condition on partition column will be used to prune the
			// scan and removed from the filter condition. Hence the condition
			// on the partition column will not be re applied when data is read,
			// so the following cases should throw error until that changes.
			List<Class<?>> opsToCheckFor = new ArrayList<Class<?>>();
			opsToCheckFor.add(RegexExpression.class);
			int errCode = 1110;
			if(checkSuccessors(project, opsToCheckFor)) {
				throw new FrontendException("Unsupported query: " +
						"You have an partition column ("
						+ fieldName + ") inside a regexp operator in the " +
						"filter condition.", errCode, PigException.INPUT);
			}
			opsToCheckFor.set(0, UserFuncExpression.class);
			if(checkSuccessors(project, opsToCheckFor)) {
				throw new FrontendException("Unsupported query: " +
						"You have an partition column ("
						+ fieldName + ") inside a function in the " +
						"filter condition.", errCode, PigException.INPUT);
			}
			opsToCheckFor.set(0, CastExpression.class);
			if(checkSuccessors(project, opsToCheckFor)) {
				throw new FrontendException("Unsupported query: " +
						"You have an partition column ("
						+ fieldName + ") inside a cast in the " +
						"filter condition.", errCode, PigException.INPUT);
			}

			opsToCheckFor.set(0, IsNullExpression.class);
			if(checkSuccessors(project, opsToCheckFor)) {
				throw new FrontendException("Unsupported query: " +
						"You have an partition column ("
						+ fieldName + ") inside a null check operator in the " +
						"filter condition.", errCode, PigException.INPUT);
			}
			opsToCheckFor.set(0, BinCondExpression.class);
			if(checkSuccessors(project, opsToCheckFor)) {
				throw new FrontendException("Unsupported query: " +
						"You have an partition column ("
						+ fieldName + ") inside a bincond operator in the " +
						"filter condition.", errCode, PigException.INPUT);
			}
			opsToCheckFor.set(0, AndExpression.class);
			opsToCheckFor.add(OrExpression.class);
			if(checkSuccessors(project, opsToCheckFor)) {
				errCode = 1112;
				throw new FrontendException("Unsupported query: " +
						"You have an partition column (" + fieldName +
						" ) in a construction like: " +
						"(pcond  and ...) or (pcond and ...) " +
						"where pcond is a condition on a partition column.",
						errCode, PigException.INPUT);
			}
		} else {
			sawNonKeyCol = true;
		}
	}

	private void visit(BinaryExpression binOp) throws FrontendException {
		boolean lhsSawKey = false;
		boolean rhsSawKey = false;
		boolean lhsSawNonKeyCol = false;
		boolean rhsSawNonKeyCol = false;

		sawKey = false;
		sawNonKeyCol = false;
		visit( binOp.getLhs() );
		replaceChild(binOp.getLhs());
		lhsSawKey = sawKey;
		lhsSawNonKeyCol = sawNonKeyCol;

		sawKey = false;
		sawNonKeyCol = false;
		visit( binOp.getRhs() );
		replaceChild(binOp.getRhs());
		rhsSawKey = sawKey;
		rhsSawNonKeyCol = sawNonKeyCol;

		// only in the case of an AND, we potentially split the AND to
		// remove conditions on partition columns out of the AND. For this
		// we set replaceSide accordingly so that when we reach a predecessor
		// we can trim the appropriate side. If both sides of the AND have
		// conditions on partition columns, we will remove the AND completely -
		// in this case, we will not set replaceSide, but sawKey will be
		// true so that as we go to higher predecessor ANDs we can trim later.
		if(binOp instanceof AndExpression) {
			if(lhsSawKey && rhsSawNonKeyCol){
				replaceSide = Side.LEFT;
			}else if(rhsSawKey && lhsSawNonKeyCol){
				replaceSide = Side.RIGHT;
			}
		} else if(lhsSawKey && rhsSawNonKeyCol || rhsSawKey && lhsSawNonKeyCol){
			int errCode = 1111;
			String errMsg = "Use of partition column/condition with" +
			" non partition column/condition in filter expression is not " +
			"supported." ;
			throw new FrontendException(errMsg, errCode, PigException.INPUT);
		}

		sawKey = lhsSawKey || rhsSawKey;
		sawNonKeyCol = lhsSawNonKeyCol || rhsSawNonKeyCol;
	}

	/**
	 * @return the condition on partition columns extracted from filter
	 */
	public  Expression getPColCondition(){
		if(pColConditions.size() == 0)
			return null;
		Expression cond =  pColConditions.get(0);
		for(int i=1; i<pColConditions.size(); i++){
			//if there is more than one condition expression
			// connect them using "AND"s
			cond = new Expression.BinaryExpression(cond, pColConditions.get(i),
                    OpType.OP_AND);
		}
		return cond;
	}

	/**
	 * @return the filterRemovable
	 */
	public boolean isFilterRemovable() {
		return filterRemovable;
	}

	//////// helper methods /////////////////////////
	/**
	 * check for the presence of a certain operator type in the Successors
	 * @param opToStartFrom
	 * @param opsToCheckFor operators to be checked for at each level of
	 * Successors - the ordering in the list is the order in which the ops
	 * will be checked.
	 * @return true if opsToCheckFor are found
	 * @throws IOException
	 */
	private boolean checkSuccessors(Operator opToStartFrom,
			List<Class<?>> opsToCheckFor) throws FrontendException {
		boolean done = checkSuccessorsHelper(opToStartFrom, opsToCheckFor);
		if(!done && !opsToCheckFor.isEmpty()) {
			// continue checking if there is more to check
			while(!done) {
				opToStartFrom = plan.getPredecessors(opToStartFrom).get(0);
				done = checkSuccessorsHelper(opToStartFrom, opsToCheckFor);
			}
		}
		return opsToCheckFor.isEmpty();
	}

	private boolean checkSuccessorsHelper(Operator opToStartFrom,
			List<Class<?>> opsToCheckFor) throws FrontendException {
		List<Operator> successors = plan.getPredecessors(
				opToStartFrom);
		if(successors == null || successors.size() == 0) {
			return true; // further checking cannot be done
		}
		if(successors.size() == 1) {
			Operator suc  = successors.get(0);
			if(suc.getClass().getCanonicalName().equals(
					opsToCheckFor.get(0).getCanonicalName())) {
				// trim the list of operators to check
				opsToCheckFor.remove(0);
				if(opsToCheckFor.isEmpty()) {
					return true; //no further checks required
				}
			}
		} else {
			throwException();
		}
		return false; // more checking can be done
	}

	private void replaceChild(LogicalExpression childExpr) throws FrontendException {

		if(replaceSide == Side.NONE) {
			// the child is trimmed when the appropriate
			// flag is set to indicate that it needs to be trimmed.
			return;
		}

		// eg if replaceSide == Side.LEFT
		//    binexpop
		//   /   \ \
		// child (this is the childExpr argument send in)
		//  /  \
		// Lt   Rt
		//
		// gets converted to
		//  binexpop
		//  /
		// Rt

		if( !( childExpr instanceof BinaryExpression ) ) {
			throwException();
		}
		// child's lhs operand
		LogicalExpression leftChild =
			((BinaryExpression)childExpr).getLhs();
		// child's rhs operand
		LogicalExpression rightChild =
			((BinaryExpression)childExpr).getRhs();

		plan.disconnect( childExpr, leftChild );
		plan.disconnect( childExpr, rightChild );

		if(replaceSide == Side.LEFT) {
			// remove left child and replace childExpr with its right child
			remove( leftChild );
			replace(childExpr, rightChild);
		} else if(replaceSide == Side.RIGHT){
			// remove right child and replace childExpr with its left child
			remove(rightChild);
			replace(childExpr, leftChild);
		}else {
			throwException();
		}
		//reset
		replaceSide = Side.NONE;
		sawKey = false;

	}

	private void replace(Operator oldOp, Operator newOp) throws FrontendException {
		List<Operator> grandParents = plan.getPredecessors( oldOp );
		if( grandParents == null || grandParents.size() == 0 ) {
			plan.remove( oldOp );
			return;
		}
		Operator grandParent = plan.getPredecessors( oldOp ).get( 0 );
		Pair<Integer, Integer> pair = plan.disconnect( grandParent, oldOp );
		plan.add( newOp );
		plan.connect( grandParent, pair.first, newOp, pair.second );
		plan.remove( oldOp );
	}

	/**
	 * @param op
	 * @throws IOException
	 * @throws IOException
	 * @throws IOException
	 */
	private void remove(LogicalExpression op) throws FrontendException {
		pColConditions.add( getExpression( op ) );
		removeTree( op );
	}

	/**
	 * Assume that the given operator is already disconnected from its predecessors.
	 * @param op
	 * @throws FrontendException
	 */
	private void removeTree(Operator op) throws FrontendException {
		List<Operator> succs = plan.getSuccessors( op );
		if( succs == null ) {
			plan.remove( op );
			return;
		}

		Operator[] children = new Operator[succs.size()];
		for( int i = 0; i < succs.size(); i++ ) {
			children[i] = succs.get(i);
		}

		for( Operator succ : children ) {
			plan.disconnect( op, succ );
			removeTree( succ );
		}

		plan.remove( op );
	}

	public static Expression getExpression(LogicalExpression op) throws FrontendException
	 {
		if(op instanceof ConstantExpression) {
			ConstantExpression constExpr =(ConstantExpression)op ;
			return new Expression.Const( constExpr.getValue() );
		} else if (op instanceof ProjectExpression) {
			ProjectExpression projExpr = (ProjectExpression)op;
			String fieldName = projExpr.getFieldSchema().alias;
            return new Expression.Column(fieldName);
        } else {
			if( !( op instanceof BinaryExpression ) ) {
				throwException();
			}
			BinaryExpression binOp = (BinaryExpression)op;
			if(binOp instanceof AddExpression) {
				return getExpression( binOp, OpType.OP_PLUS );
			} else if(binOp instanceof SubtractExpression) {
				return getExpression(binOp, OpType.OP_MINUS);
			} else if(binOp instanceof MultiplyExpression) {
				return getExpression(binOp, OpType.OP_TIMES);
			} else if(binOp instanceof DivideExpression) {
				return getExpression(binOp, OpType.OP_DIV);
			} else if(binOp instanceof ModExpression) {
				return getExpression(binOp, OpType.OP_MOD);
			} else if(binOp instanceof AndExpression) {
				return getExpression(binOp, OpType.OP_AND);
			} else if(binOp instanceof OrExpression) {
				return getExpression(binOp, OpType.OP_OR);
			} else if(binOp instanceof EqualExpression) {
				return getExpression(binOp, OpType.OP_EQ);
			} else if(binOp instanceof NotEqualExpression) {
				return getExpression(binOp, OpType.OP_NE);
			} else if(binOp instanceof GreaterThanExpression) {
				return getExpression(binOp, OpType.OP_GT);
			} else if(binOp instanceof GreaterThanEqualExpression) {
				return getExpression(binOp, OpType.OP_GE);
			} else if(binOp instanceof LessThanExpression) {
				return getExpression(binOp, OpType.OP_LT);
			} else if(binOp instanceof LessThanEqualExpression) {
				return getExpression(binOp, OpType.OP_LE);
			} else {
				throwException();
			}
		}
		return null;
	}

    private static Expression getExpression(BinaryExpression binOp, OpType
            opType) throws FrontendException {
        return new Expression.BinaryExpression(getExpression(binOp.getLhs())
                ,getExpression(binOp.getRhs()), opType);
    }
	private static void throwException() throws FrontendException {
		int errCode = 2209;
		throw new FrontendException(
				"Internal error while processing any partition filter " +
				"conditions in the filter after the load" ,
				errCode,
				PigException.BUG
		);
	}

	// this might get called from some visit() - in that case, delegate to
	// the other visit()s which we have defined here
	private void visit(LogicalExpression op) throws FrontendException {
		if(op instanceof ProjectExpression) {
			visit((ProjectExpression)op);
		} else if (op instanceof BinaryExpression) {
			visit((BinaryExpression)op);
		} else if (op instanceof CastExpression) {
			visit((CastExpression)op);
		} else if (op instanceof BinCondExpression) {
			visit((BinCondExpression)op);
		} else if (op instanceof UserFuncExpression) {
			visit((UserFuncExpression)op);
		} else if (op instanceof IsNullExpression) {
			visit((IsNullExpression)op);
		} else if( op instanceof NotExpression ) {
			visit( (NotExpression)op );
		} else if( op instanceof RegexExpression ) {
			visit( (RegexExpression)op );
		}
	}

	// some specific operators which are of interest to catch some
	// unsupported scenarios
	private void visit(CastExpression cast) throws FrontendException {
		visit(cast.getExpression());
	}

	private void visit(NotExpression not) throws FrontendException {
		visit(not.getExpression());
	}

	private void visit(RegexExpression regexp) throws FrontendException {
		visit((BinaryExpression)regexp);
	}

	private void visit(BinCondExpression binCond) throws FrontendException {
		visit(binCond.getCondition());
		visit(binCond.getLhs());
		visit(binCond.getRhs());
	}

	private void visit(UserFuncExpression udf) throws FrontendException {
		for (LogicalExpression op : udf.getArguments()) {
			visit(op);
		}
	}

	private void visit(IsNullExpression isNull) throws FrontendException {
		visit(isNull.getExpression());
	}

}


text:
package com.ycombinator.news.dto;

import android.support.annotation.NonNull;
import java.util.ArrayList;
import java.util.Collection;

/**
* Necessary to properly serialise lists of ItemDTOs with the proper type.
*/
public class ItemDTOList extends ArrayList<ItemDTO>
{
    @SuppressWarnings("UnusedDeclaration") // Necessary for deserialisation
    public ItemDTOList()
    {
    }

    @SuppressWarnings("UnusedDeclaration")
    public ItemDTOList(@NonNull Collection<? extends ItemDTO> collection)
    {
        super(collection);
    }
}


text:
package com.alibaba.csp.sentinel.dashboard.util;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Eric Zhao
 * @since 1.4.1
 */
public final class AsyncUtils {

    private static final Logger LOG = LoggerFactory.getLogger(AsyncUtils.class);

    public static <R> CompletableFuture<R> newFailedFuture(Throwable ex) {
        CompletableFuture<R> future = new CompletableFuture<>();
        future.completeExceptionally(ex);
        return future;
    }

    public static <R> CompletableFuture<List<R>> sequenceFuture(List<CompletableFuture<R>> futures) {
        return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
            .thenApply(v -> futures.stream()
                .map(AsyncUtils::getValue)
                .filter(Objects::nonNull)
                .collect(Collectors.toList())
            );
    }

    public static <R> CompletableFuture<List<R>> sequenceSuccessFuture(List<CompletableFuture<R>> futures) {
        return CompletableFuture.supplyAsync(() -> futures.parallelStream()
            .map(AsyncUtils::getValue)
            .filter(Objects::nonNull)
            .collect(Collectors.toList())
        );
    }

    public static <T> T getValue(CompletableFuture<T> future) {
        try {
            return future.get(10, TimeUnit.SECONDS);
        } catch (Exception ex) {
            LOG.error("getValue for async result failed", ex);
        }
        return null;
    }

    public static boolean isSuccessFuture(CompletableFuture future) {
        return future.isDone() && !future.isCompletedExceptionally() && !future.isCancelled();
    }

    private AsyncUtils() {}
}


text:
/*!
 * \file
 * \brief dEQP platform capability query instrumentation
 *//*--------------------------------------------------------------------*/

package com.drawelements.deqp.platformutil;

import android.app.Instrumentation;
import android.os.Bundle;

public class DeqpPlatformCapabilityQueryInstrumentation extends Instrumentation
{
	static
	{
		System.loadLibrary("deqp");
	}

	private static final String	LOG_TAG							= "dEQP/PlatformCapabilityQueryInstrumentation";
	private static final int	CONFIGQUERYRESULT_SUPPORTED		= 0;
	private static final int	CONFIGQUERYRESULT_NOT_SUPPORTED	= 1;
	private static final int	CONFIGQUERYRESULT_GENERIC_ERROR	= -1;

	private String				m_cmdLine;
	private String				m_queryType;

	@Override
	public void onCreate (Bundle arguments) {
		super.onCreate(arguments);

		m_queryType = arguments.getString("deqpQueryType");
		m_cmdLine = arguments.getString("deqpCmdLine");

		start();
	}

	@Override
	public void onStart () {
		super.onStart();

		Bundle resultInfo;
		int resultCode = 0;

		try
		{
			if ("renderConfigSupported".equals(m_queryType))
				resultInfo = doRenderConfigSupportedQuery();
			else
			{
				resultInfo = new Bundle();
				resultInfo.putString("Error", "unknown query");
				resultInfo.putString("QueryType", m_queryType);
				resultInfo.putString("CmdLine", m_cmdLine);
				resultCode = 2;
			}
		}
		catch (Exception e)
		{
			resultInfo = new Bundle();
			resultInfo.putString("Error", e.getMessage());
			resultCode = 1;
		}

		finish(resultCode, resultInfo);
	}

	private Bundle doRenderConfigSupportedQuery ()
	{
		if (m_cmdLine == null)
			throw new RuntimeException("missing command line");

		final int result = nativeRenderConfigSupportedQuery(m_cmdLine);

		if (result == CONFIGQUERYRESULT_SUPPORTED)
		{
			final Bundle resultInfo = new Bundle();
			resultInfo.putString("Supported", "Yes");
			return resultInfo;
		}
		else if (result == CONFIGQUERYRESULT_NOT_SUPPORTED)
		{
			final Bundle resultInfo = new Bundle();
			resultInfo.putString("Supported", "No");
			return resultInfo;
		}
		else if (result == CONFIGQUERYRESULT_GENERIC_ERROR)
			throw new RuntimeException("platform query reported failure");
		else
			throw new RuntimeException("platform query returned out-of-range result");
	}

	private static native int nativeRenderConfigSupportedQuery (String cmdLine);
}


text:
cppcheckBuild
=============
A :code:`cppcheckBuild` analyzes a project using :code:`cppcheck`.  It does
*not* compile the project.

Steps
-----
In addition to the `common steps`_, a cppcheckBuild performs:

1. configure_
2. cppcheck_

Notes
-----
  - :code:`cppcheck` is run using the :code:`--project` argument.  This is a
    moderately recent addtion, so you may need to update the version of
    cppcheck on your build slaves.

Example
-------
::

    cppcheckBuild {
        git = 'https://github.com/snewell/bureaucracy'
    }

.. _common steps: ../step/common-steps.rst
.. _configure: ../step/configure.rst
.. _cppcheck: ../step/cppcheck.rst


text:
define([
    "hr/utils",
    "hr/dom",
    "hr/hr",
    "models/command",
    "utils/dragdrop",
    "utils/keyboard",
    "utils/contextmenu"
], function(_, $, hr, Command, dnd, Keyboard, ContextMenu) {

    // Tab header
    var TabView = hr.List.Item.extend({
        className: "component-tab",
        defaults: {
            title: "",
            tabid: "",
            close: true
        },
        events: {
            "mousedown .close": "close",
            "dblclick": "open",
            "click .close": "close",
            "click": "open",
        },
        states: {
            'modified': "fa-asterisk",
            'warning': "fa-exclamation",
            'offline': "fa-flash",
            'sync': "fa-exchange",
            'loading': "fa fa-refresh fa-spin"
        },

        // Constructor
        initialize: function() {
            TabView.__super__.initialize.apply(this, arguments);

            var that = this;
            var $document = $(document);

            // Drop tabs to order
            this.dropArea = new dnd.DropArea({
                view: this,
                dragType: this.model.manager.drag,
                handler: function(tab) {
                    var i = that.list.collection.indexOf(that.model);
                    var ib = that.list.collection.indexOf(tab);

                    if (ib >= 0 && ib < i) {
                        i = i - 1;
                    }
                    console.log("drop tab at position", i);
                    that.model.manager.changeTabSection(tab, that.list.collection.sectionId, {
                        at: i
                    });
                }
            });

            this.model.manager.drag.enableDrag({
                view: this,
                data: this.model,
                baseDropArea: this.list.dropArea,
                start: function() {
                    that.open();
                }
            });

            // Context menu
            ContextMenu.add(this.$el, _.compact([
                (this.model.manager.options.newTab ? {
                    'id': "tab.new",
                    'type': "action",
                    'title': "New Tab",
                    'action': function() {
                        that.model.manager.openDefault();
                    }
                } : null),
                (this.model.manager.options.newTab ? { 'type': "divider" } : null),
                {
                    'id': "tab.close",
                    'type': "action",
                    'title': "Close",
                    'action': function() {
                        that.close();
                    }
                },
                {
                    'id': "tab.close.others",
                    'type': "action",
                    'title': "Close Other Tabs",
                    'action': function() {
                        that.closeOthers();
                    }
                },
                { 'type': "divider" },
                {
                    'id': "tab.group.new",
                    'type': "action",
                    'title': "New Group",
                    'action': function() {
                        that.model.splitSection();
                    }
                },
                { 'type': "divider" },
                that.model.manager.layoutCommand
            ]));

            return this;
        },

        // Render the tab
        render: function() {
            this.$el.empty();

            var inner = $("<div>", {
                "class": "inner",
                "html": this.model.get("title")
            }).appendTo(this.$el);

            var states = this.model.get("state", "").split(" ");
            _.each(states, function(state) {
                if (state && this.states[state]) {
                    $("<i>", {
                        "class": "state fa "+this.states[state]+" state-"+state
                    }).prependTo(inner);
                }
            }, this);

            $("<a>", {
                "class": "close",
                "href": "#",
                "html": "×"
            }).prependTo(inner);

            this.$el.toggleClass("active", this.model.isActive());

            return this.ready();
        },

        // Return true if is active
        isActive: function() {
            return this.$el.hasClass("active");
        },

        // (event) open
        open: function(e) {
            if (e != null) {
                e.preventDefault();
                e.stopPropagation();
            }
            this.model.active();
        },

        // (event) close
        close: function(e) {
            if (e != null) {
                e.preventDefault();
                e.stopPropagation();
            }
            this.model.close();
        },

        // (event) close others tabs
        closeOthers: function(e) {
            this.model.closeOthers();
        }
    });

    return TabView;
});


text:
<?php

namespace GoalioForgotPassword\Form;

use ZfcBase\InputFilter\ProvidesEventsInputFilter as InputFilter;
use GoalioForgotPassword\Options\ForgotOptionsInterface;

class ResetFilter extends InputFilter
{
    public function __construct(ForgotOptionsInterface $options)
    {
        $this->add(array(
            'name'       => 'newCredential',
            'required'   => true,
            'validators' => array(
                array(
                    'name'    => 'StringLength',
                    'options' => array(
                        'min' => 6,
                    ),
                ),
            ),
            'filters'   => array(
                array('name' => 'StringTrim'),
            ),
        ));

        $this->add(array(
            'name'       => 'newCredentialVerify',
            'required'   => true,
            'validators' => array(
                array(
                    'name'    => 'StringLength',
                    'options' => array(
                        'min' => 6,
                    ),
                ),
                array(
                    'name' => 'identical',
                    'options' => array(
                        'token' => 'newCredential'
                    )
                ),
            ),
            'filters'   => array(
                array('name' => 'StringTrim'),
            ),
        ));

		$this->getEventManager()->trigger('init', $this);
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using LibGit2Sharp.Tests.TestHelpers;
using Xunit;
using Xunit.Extensions;

namespace LibGit2Sharp.Tests
{
    public class IndexFixture : BaseFixture
    {
        private static readonly string subBranchFile = Path.Combine("1", "branch_file.txt");
        private readonly string[] expectedEntries = new[]
                                                        {
                                                            "1.txt",
                                                            subBranchFile,
                                                            "README",
                                                            "branch_file.txt",
                                                            //"deleted_staged_file.txt",
                                                            "deleted_unstaged_file.txt",
                                                            "modified_staged_file.txt",
                                                            "modified_unstaged_file.txt",
                                                            "new.txt",
                                                            "new_tracked_file.txt"
                                                        };

        [Fact]
        public void CanCountEntriesInIndex()
        {
            var path = SandboxStandardTestRepoGitDir();
            using (var repo = new Repository(path))
            {
                Assert.Equal(expectedEntries.Count(), repo.Index.Count);
            }
        }

        [Fact]
        public void CanEnumerateIndex()
        {
            var path = SandboxStandardTestRepoGitDir();
            using (var repo = new Repository(path))
            {
                Assert.Equal(expectedEntries,
                    repo.Index.Select(e => e.Path).OrderBy(p => p, StringComparer.Ordinal).ToArray());
            }
        }

        [Fact]
        public void CanFetchAnIndexEntryByItsName()
        {
            var path = SandboxStandardTestRepoGitDir();
            using (var repo = new Repository(path))
            {
                IndexEntry entry = repo.Index["README"];
                Assert.Equal("README", entry.Path);

                // Expressed in Posix format...
                IndexEntry entryWithPath = repo.Index["1/branch_file.txt"];
                Assert.Equal(subBranchFile, entryWithPath.Path);

                //...or in native format
                IndexEntry entryWithPath2 = repo.Index[subBranchFile];
                Assert.Equal(entryWithPath, entryWithPath2);
            }
        }

        [Fact]
        public void FetchingAnUnknownIndexEntryReturnsNull()
        {
            var path = SandboxStandardTestRepoGitDir();
            using (var repo = new Repository(path))
            {
                IndexEntry entry = repo.Index["I-do-not-exist.txt"];
                Assert.Null(entry);
            }
        }

        [Fact]
        public void ReadIndexWithBadParamsFails()
        {
            var path = SandboxStandardTestRepoGitDir();
            using (var repo = new Repository(path))
            {
                Assert.Throws<ArgumentNullException>(() => { IndexEntry entry = repo.Index[null]; });
                Assert.Throws<ArgumentException>(() => { IndexEntry entry = repo.Index[string.Empty]; });
            }
        }

        [Fact]
        public void CanRenameAFile()
        {
            string repoPath = InitNewRepository();

            using (var repo = new Repository(repoPath))
            {
                Assert.Equal(0, repo.Index.Count);

                const string oldName = "polite.txt";

                Assert.Equal(FileStatus.Nonexistent, repo.RetrieveStatus(oldName));

                Touch(repo.Info.WorkingDirectory, oldName, "hello test file\n");
                Assert.Equal(FileStatus.Untracked, repo.RetrieveStatus(oldName));

                repo.Stage(oldName);
                Assert.Equal(FileStatus.Added, repo.RetrieveStatus(oldName));

                // Generated through
                // $ echo "hello test file" | git hash-object --stdin
                const string expectedHash = "88df547706c30fa19f02f43cb2396e8129acfd9b";
                Assert.Equal(expectedHash, repo.Index[oldName].Id.Sha);

                Assert.Equal(1, repo.Index.Count);

                Signature who = Constants.Signature;
                repo.Commit("Initial commit", who, who);

                Assert.Equal(FileStatus.Unaltered, repo.RetrieveStatus(oldName));

                const string newName = "being.frakking.polite.txt";

                repo.Move(oldName, newName);
                Assert.Equal(FileStatus.Removed, repo.RetrieveStatus(oldName));
                Assert.Equal(FileStatus.Added, repo.RetrieveStatus(newName));

                Assert.Equal(1, repo.Index.Count);
                Assert.Equal(expectedHash, repo.Index[newName].Id.Sha);

                who = who.TimeShift(TimeSpan.FromMinutes(5));
                Commit commit = repo.Commit("Fix file name", who, who);

                Assert.Equal(FileStatus.Nonexistent, repo.RetrieveStatus(oldName));
                Assert.Equal(FileStatus.Unaltered, repo.RetrieveStatus(newName));

                Assert.Equal(expectedHash, commit.Tree[newName].Target.Id.Sha);
            }
        }

        [Theory]
        [InlineData("README", FileStatus.Unaltered, "deleted_unstaged_file.txt", FileStatus.Missing, FileStatus.Removed, FileStatus.Staged)]
        [InlineData("new_tracked_file.txt", FileStatus.Added, "deleted_unstaged_file.txt", FileStatus.Missing, FileStatus.Nonexistent, FileStatus.Staged)]
        [InlineData("modified_staged_file.txt", FileStatus.Staged, "deleted_unstaged_file.txt", FileStatus.Missing, FileStatus.Removed, FileStatus.Staged)]
        [InlineData("modified_unstaged_file.txt", FileStatus.Modified, "deleted_unstaged_file.txt", FileStatus.Missing, FileStatus.Removed, FileStatus.Staged)]
        public void CanMoveAnExistingFileOverANonExistingFile(string sourcePath, FileStatus sourceStatus, string destPath, FileStatus destStatus, FileStatus sourcePostStatus, FileStatus destPostStatus)
        {
            string path = SandboxStandardTestRepo();
            using (var repo = new Repository(path))
            {
                Assert.Equal(sourceStatus, repo.RetrieveStatus(sourcePath));
                Assert.Equal(destStatus, repo.RetrieveStatus(destPath));

                repo.Move(sourcePath, destPath);

                Assert.Equal(sourcePostStatus, repo.RetrieveStatus(sourcePath));
                Assert.Equal(destPostStatus, repo.RetrieveStatus(destPath));
            }
        }

        [Theory]
        [InlineData("README", FileStatus.Unaltered, new[] { "README", "new_tracked_file.txt", "modified_staged_file.txt", "modified_unstaged_file.txt", "new_untracked_file.txt" })]
        [InlineData("new_tracked_file.txt", FileStatus.Added, new[] { "README", "new_tracked_file.txt", "modified_staged_file.txt", "modified_unstaged_file.txt", "new_untracked_file.txt" })]
        [InlineData("modified_staged_file.txt", FileStatus.Staged, new[] { "README", "new_tracked_file.txt", "modified_staged_file.txt", "modified_unstaged_file.txt", "new_untracked_file.txt" })]
        [InlineData("modified_unstaged_file.txt", FileStatus.Modified, new[] { "README", "new_tracked_file.txt", "modified_staged_file.txt", "modified_unstaged_file.txt", "new_untracked_file.txt" })]
        public void MovingOverAnExistingFileThrows(string sourcePath, FileStatus sourceStatus, IEnumerable<string> destPaths)
        {
            InvalidMoveUseCases(sourcePath, sourceStatus, destPaths);
        }

        [Theory]
        [InlineData("new_untracked_file.txt", FileStatus.Untracked, new[] { "README", "new_tracked_file.txt", "modified_staged_file.txt", "modified_unstaged_file.txt", "new_untracked_file.txt", "deleted_unstaged_file.txt", "deleted_staged_file.txt", "i_dont_exist.txt" })]
        public void MovingAFileWichIsNotUnderSourceControlThrows(string sourcePath, FileStatus sourceStatus, IEnumerable<string> destPaths)
        {
            InvalidMoveUseCases(sourcePath, sourceStatus, destPaths);
        }

        [Theory]
        [InlineData("deleted_unstaged_file.txt", FileStatus.Missing, new[] { "README", "new_tracked_file.txt", "modified_staged_file.txt", "modified_unstaged_file.txt", "new_untracked_file.txt", "deleted_unstaged_file.txt", "deleted_staged_file.txt", "i_dont_exist.txt" })]
        [InlineData("deleted_staged_file.txt", FileStatus.Removed, new[] { "README", "new_tracked_file.txt", "modified_staged_file.txt", "modified_unstaged_file.txt", "new_untracked_file.txt", "deleted_unstaged_file.txt", "deleted_staged_file.txt", "i_dont_exist.txt" })]
        [InlineData("i_dont_exist.txt", FileStatus.Nonexistent, new[] { "README", "new_tracked_file.txt", "modified_staged_file.txt", "modified_unstaged_file.txt", "new_untracked_file.txt", "deleted_unstaged_file.txt", "deleted_staged_file.txt", "i_dont_exist.txt" })]
        public void MovingAFileNotInTheWorkingDirectoryThrows(string sourcePath, FileStatus sourceStatus, IEnumerable<string> destPaths)
        {
            InvalidMoveUseCases(sourcePath, sourceStatus, destPaths);
        }

        private void InvalidMoveUseCases(string sourcePath, FileStatus sourceStatus, IEnumerable<string> destPaths)
        {
            var repoPath = SandboxStandardTestRepoGitDir();
            using (var repo = new Repository(repoPath))
            {
                Assert.Equal(sourceStatus, repo.RetrieveStatus(sourcePath));

                foreach (var destPath in destPaths)
                {
                    string path = destPath;
                    Assert.Throws<LibGit2SharpException>(() => repo.Move(sourcePath, path));
                }
            }
        }

        [Fact]
        public void PathsOfIndexEntriesAreExpressedInNativeFormat()
        {
            // Build relative path
            string relFilePath = Path.Combine("directory", "Testfile.txt");

            string repoPath = InitNewRepository();

            using (var repo = new Repository(repoPath))
            {
                Touch(repo.Info.WorkingDirectory, relFilePath, "Anybody out there?");

                // Stage the file
                repo.Stage(relFilePath);

                // Get the index
                Index index = repo.Index;

                // Get the index entry
                IndexEntry ie = index[relFilePath];

                // Make sure the IndexEntry has been found
                Assert.NotNull(ie);

                // Make sure that the (native) relFilePath and ie.Path are equal
                Assert.Equal(relFilePath, ie.Path);
            }
        }

        [Fact]
        public void CanReadIndexEntryAttributes()
        {
            var path = SandboxStandardTestRepoGitDir();
            using (var repo = new Repository(path))
            {
                Assert.Equal(Mode.NonExecutableFile, repo.Index["README"].Mode);
                Assert.Equal(Mode.ExecutableFile, repo.Index["1/branch_file.txt"].Mode);
            }
        }

        [Fact]
        public void StagingAFileWhenTheIndexIsLockedThrowsALockedFileException()
        {
            string repoPath = InitNewRepository();

            using (var repo = new Repository(repoPath))
            {
                Touch(repo.Info.Path, "index.lock");

                Touch(repo.Info.WorkingDirectory, "newfile", "my my, this is gonna crash\n");
                Assert.Throws<LockedFileException>(() => repo.Stage("newfile"));
            }
        }

        [Fact]
        public void CanCopeWithExternalChangesToTheIndex()
        {
            SelfCleaningDirectory scd = BuildSelfCleaningDirectory();

            Touch(scd.DirectoryPath, "a.txt", "a\n");
            Touch(scd.DirectoryPath, "b.txt", "b\n");

            string path = Repository.Init(scd.DirectoryPath);

            using (var repoWrite = new Repository(path))
            using (var repoRead = new Repository(path))
            {
                var writeStatus = repoWrite.RetrieveStatus();
                Assert.True(writeStatus.IsDirty);
                Assert.Equal(0, repoWrite.Index.Count);

                var readStatus = repoRead.RetrieveStatus();
                Assert.True(readStatus.IsDirty);
                Assert.Equal(0, repoRead.Index.Count);

                repoWrite.Stage("*");
                repoWrite.Commit("message", Constants.Signature, Constants.Signature);

                writeStatus = repoWrite.RetrieveStatus();
                Assert.False(writeStatus.IsDirty);
                Assert.Equal(2, repoWrite.Index.Count);

                readStatus = repoRead.RetrieveStatus();
                Assert.False(readStatus.IsDirty);
                Assert.Equal(2, repoRead.Index.Count);
            }
        }

        [Fact]
        public void CanResetFullyMergedIndexFromTree()
        {
            string path = SandboxStandardTestRepo();

            const string testFile = "new_tracked_file.txt";

            // It is sufficient to check just one of the stage area changes, such as the added file,
            // to verify that the index has indeed been read from the tree.
            using (var repo = new Repository(path))
            {
                const string headIndexTreeSha = "e5d221fc5da11a3169bf503d76497c81be3207b6";

                Assert.True(repo.Index.IsFullyMerged);
                Assert.Equal(FileStatus.Added, repo.RetrieveStatus(testFile));

                var headIndexTree = repo.Lookup<Tree>(headIndexTreeSha);
                Assert.NotNull(headIndexTree);
                repo.Index.Replace(headIndexTree);

                Assert.True(repo.Index.IsFullyMerged);
                Assert.Equal(FileStatus.Untracked, repo.RetrieveStatus(testFile));
            }

            // Check that the index was persisted to disk.
            using (var repo = new Repository(path))
            {
                Assert.Equal(FileStatus.Untracked, repo.RetrieveStatus(testFile));
            }
        }

        [Fact]
        public void CanResetIndexWithUnmergedEntriesFromTree()
        {
            string path = SandboxMergedTestRepo();

            const string testFile = "one.txt";

            // It is sufficient to check just one of the stage area changes, such as the modified file,
            // to verify that the index has indeed been read from the tree.
            using (var repo = new Repository(path))
            {
                const string headIndexTreeSha = "1cb365141a52dfbb24933515820eb3045fbca12b";

                Assert.False(repo.Index.IsFullyMerged);
                Assert.Equal(FileStatus.Staged, repo.RetrieveStatus(testFile));

                var headIndexTree = repo.Lookup<Tree>(headIndexTreeSha);
                Assert.NotNull(headIndexTree);
                repo.Index.Replace(headIndexTree);

                Assert.True(repo.Index.IsFullyMerged);
                Assert.Equal(FileStatus.Modified, repo.RetrieveStatus(testFile));
            }

            // Check that the index was persisted to disk.
            using (var repo = new Repository(path))
            {
                Assert.Equal(FileStatus.Modified, repo.RetrieveStatus(testFile));
            }
        }

        [Fact]
        public void CanClearTheIndex()
        {
            string path = SandboxStandardTestRepo();
            const string testFile = "1.txt";

            // It is sufficient to check just one of the stage area changes, such as the modified file,
            // to verify that the index has indeed been read from the tree.
            using (var repo = new Repository(path))
            {
                Assert.Equal(FileStatus.Unaltered, repo.RetrieveStatus(testFile));
                Assert.NotEqual(0, repo.Index.Count);

                repo.Index.Clear();
                Assert.Equal(0, repo.Index.Count);

                Assert.Equal(FileStatus.Removed | FileStatus.Untracked, repo.RetrieveStatus(testFile));
            }

            // Check that the index was persisted to disk.
            using (var repo = new Repository(path))
            {
                Assert.Equal(FileStatus.Removed | FileStatus.Untracked, repo.RetrieveStatus(testFile));
            }
        }
    }
}


text:
Grammer_Node* Grammer_Node::AddBortherNode(Grammer_Node* _brother){
    Grammer_Node* p = this;
    Grammer_Node* q = p->brother;
    while (q != NULL) { p = q; q = p->brother; }
    	p->brother = _brother;
}

Grammer_Node* Grammer_Node::AddChildrenNode(Grammer_Node* _children){
    if (children == NULL)
	children = _children;
    else
	children->AddBortherNode(_children);
}

Grammer_Node* Grammer_Node::NewNode()
{
	return new Grammer_Node();
}


text:
import React from "react"
import { useSelector, useDispatch } from "react-redux"
import orderBy from "lodash/orderBy"

import Form from "./form"
import Manage from "../index"

import {
  deleteWrestler as deleteById,
  updateWrestler as update,
  createWrestler as create,
  resetRoster as reset
} from "actions/wrestlers"

const arrayToObject = (array, keyField) =>
  array.reduce((obj, item) => {
    obj[item[keyField]] = item
    return obj
  }, {})

export default function() {
  const dispatch = useDispatch()
  const { wrestlers, brands, } = useSelector(state => state)
  const brandsById = arrayToObject(brands, "id")

  const collection = orderBy(wrestlers, "points", "desc").map(item => {
    let backgroundColor = "black",
      color = "white"
    if (brandsById[item.brandId]) {
      backgroundColor = brandsById[item.brandId].backgroundColor
      color = brandsById[item.brandId].color
    }
    return { ...item, backgroundColor, color, }
  })
  const clickActions = {
    onUpdate: item => dispatch(update(item)),
    onCreate: item => dispatch(create(item)),
    onDelete: id => dispatch(deleteById(id)),
    onClear: () => dispatch(reset()),
  }

  const props = {
    Form,
    collection,
    title: "Wrestlers",
  }

  return <Manage title="Manage Roster" {...props} {...clickActions} />
}


text:
[![GitHub Link](https://img.shields.io/github/stars/inadarei/nodebootstrap.svg?style=flat)](https://github.com/inadarei/nodebootstrap)
![npm version](https://img.shields.io/npm/v/nodebootstrap.svg?style=flat)
![build status](https://travis-ci.org/inadarei/nodebootstrap.svg?branch=master)
[![Codacy Badge](https://www.codacy.com/project/badge/41c49bb9c9384b7e8042f1e6c9645431)](https://www.codacy.com/public/irakli/nodebootstrap_2)
[![Code Climate](https://codeclimate.com/github/inadarei/nodebootstrap/badges/gpa.svg)](https://codeclimate.com/github/inadarei/nodebootstrap)

Organize your Node project like a pro. Right out of the gate N.B. gets a [metric] ton of boilerplate taken care of: clustering, Docker-support, error-handling, code modularity, logging, views, environments – you name it. And all of that without having to deal with a heavy or an opinionated framework!

NodeBootstrap is a project skeleton for [Node.js](http://nodejs.org/)/[Express.js](http://expressjs.com)
development. It captures common best-practices, used by Node community, for project layout and setup configuration.

For demonstration purposes NodeBootstrap also packs Twitter's [Bootstrap](http://twitter.github.com/bootstrap/)
framework and shows how to manage Mustache/Handlebars-based view. It's not a mandatory part of the project.
NodeBootstrap is often used for web API projects, where there is no human-centric UI.

To learn more: [http://nodebootstrap.io](http://nodebootstrap.io)

[![Join the chat at https://gitter.im/inadarei/nodebootstrap](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/inadarei/nodebootstrap?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

## License

(The MIT License)

Copyright (c) 2012-2015 Irakli Nadareishvili [@inadarei](http://twitter.com/inadarei)

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
package com.commonsware.android.tabfrag;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

public class EditorFragment extends Fragment {
  private static final String KEY_POSITION="position";
  private static final String KEY_TEXT="text";
  private EditText editor=null;

  static EditorFragment newInstance(int position,
                                    CharSequence text) {
    EditorFragment frag=new EditorFragment();
    Bundle args=new Bundle();

    args.putInt(KEY_POSITION, position);
    args.putCharSequence(KEY_TEXT, text);
    frag.setArguments(args);

    return(frag);
  }

  @Override
  public View onCreateView(LayoutInflater inflater,
                           ViewGroup container,
                           Bundle savedInstanceState) {
    View result=inflater.inflate(R.layout.editor, container, false);

    editor=(EditText)result.findViewById(R.id.editor);

    int position=getArguments().getInt(KEY_POSITION, -1);

    editor.setHint(String.format(getString(R.string.hint), position + 1));
    editor.setText(getArguments().getCharSequence(KEY_TEXT));

    return(result);
  }

  CharSequence getText() {
    return(editor.getText());
  }
}