text:
//===------ RegAllocPBQP.cpp ---- PBQP Register Allocator -------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains a Partitioned Boolean Quadratic Programming (PBQP) based
// register allocator for LLVM. This allocator works by constructing a PBQP
// problem representing the register allocation problem under consideration,
// solving this using a PBQP solver, and mapping the solution back to a
// register assignment. If any variables are selected for spilling then spill
// code is inserted and the process repeated.
//
// The PBQP solver (pbqp.c) provided for this allocator uses a heuristic tuned
// for register allocation. For more information on PBQP for register
// allocation, see the following papers:
//
//   (1) Hames, L. and Scholz, B. 2006. Nearly optimal register allocation with
//   PBQP. In Proceedings of the 7th Joint Modular Languages Conference
//   (JMLC'06). LNCS, vol. 4228. Springer, New York, NY, USA. 346-361.
//
//   (2) Scholz, B., Eckstein, E. 2002. Register allocation for irregular
//   architectures. In Proceedings of the Joint Conference on Languages,
//   Compilers and Tools for Embedded Systems (LCTES'02), ACM Press, New York,
//   NY, USA, 139-148.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "regalloc"

#include "PBQP/HeuristicSolver.h"
#include "PBQP/Graph.h"
#include "PBQP/Heuristics/Briggs.h"
#include "VirtRegMap.h"
#include "VirtRegRewriter.h"
#include "llvm/CodeGen/CalcSpillWeights.h"
#include "llvm/CodeGen/LiveIntervalAnalysis.h"
#include "llvm/CodeGen/LiveStackAnalysis.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/RegAllocRegistry.h"
#include "llvm/CodeGen/RegisterCoalescer.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include <limits>
#include <map>
#include <memory>
#include <set>
#include <vector>

using namespace llvm;

static RegisterRegAlloc
registerPBQPRepAlloc("pbqp", "PBQP register allocator",
                       llvm::createPBQPRegisterAllocator);

static cl::opt<bool>
pbqpCoalescing("pbqp-coalescing",
                cl::desc("Attempt coalescing during PBQP register allocation."),
                cl::init(false), cl::Hidden);

namespace {

  ///
  /// PBQP based allocators solve the register allocation problem by mapping
  /// register allocation problems to Partitioned Boolean Quadratic
  /// Programming problems.
  class PBQPRegAlloc : public MachineFunctionPass {
  public:

    static char ID;

    /// Construct a PBQP register allocator.
    PBQPRegAlloc() : MachineFunctionPass(&ID) {}

    /// Return the pass name.
    virtual const char* getPassName() const {
      return "PBQP Register Allocator";
    }

    /// PBQP analysis usage.
    virtual void getAnalysisUsage(AnalysisUsage &au) const {
      au.addRequired<SlotIndexes>();
      au.addPreserved<SlotIndexes>();
      au.addRequired<LiveIntervals>();
      //au.addRequiredID(SplitCriticalEdgesID);
      au.addRequired<RegisterCoalescer>();
      au.addRequired<CalculateSpillWeights>();
      au.addRequired<LiveStacks>();
      au.addPreserved<LiveStacks>();
      au.addRequired<MachineLoopInfo>();
      au.addPreserved<MachineLoopInfo>();
      au.addRequired<VirtRegMap>();
      MachineFunctionPass::getAnalysisUsage(au);
    }

    /// Perform register allocation
    virtual bool runOnMachineFunction(MachineFunction &MF);

  private:
    typedef std::map<const LiveInterval*, unsigned> LI2NodeMap;
    typedef std::vector<const LiveInterval*> Node2LIMap;
    typedef std::vector<unsigned> AllowedSet;
    typedef std::vector<AllowedSet> AllowedSetMap;
    typedef std::set<unsigned> RegSet;
    typedef std::pair<unsigned, unsigned> RegPair;
    typedef std::map<RegPair, PBQP::PBQPNum> CoalesceMap;

    typedef std::set<LiveInterval*> LiveIntervalSet;

    typedef std::vector<PBQP::Graph::NodeItr> NodeVector;

    MachineFunction *mf;
    const TargetMachine *tm;
    const TargetRegisterInfo *tri;
    const TargetInstrInfo *tii;
    const MachineLoopInfo *loopInfo;
    MachineRegisterInfo *mri;

    LiveIntervals *lis;
    LiveStacks *lss;
    VirtRegMap *vrm;

    LI2NodeMap li2Node;
    Node2LIMap node2LI;
    AllowedSetMap allowedSets;
    LiveIntervalSet vregIntervalsToAlloc,
                    emptyVRegIntervals;
    NodeVector problemNodes;

    /// Builds a PBQP cost vector.
    template <typename RegContainer>
    PBQP::Vector buildCostVector(unsigned vReg,
                                 const RegContainer &allowed,
                                 const CoalesceMap &cealesces,
                                 PBQP::PBQPNum spillCost) const;

    /// \brief Builds a PBQP interference matrix.
    ///
    /// @return Either a pointer to a non-zero PBQP matrix representing the
    ///         allocation option costs, or a null pointer for a zero matrix.
    ///
    /// Expects allowed sets for two interfering LiveIntervals. These allowed
    /// sets should contain only allocable registers from the LiveInterval's
    /// register class, with any interfering pre-colored registers removed.
    template <typename RegContainer>
    PBQP::Matrix* buildInterferenceMatrix(const RegContainer &allowed1,
                                          const RegContainer &allowed2) const;

    ///
    /// Expects allowed sets for two potentially coalescable LiveIntervals,
    /// and an estimated benefit due to coalescing. The allowed sets should
    /// contain only allocable registers from the LiveInterval's register
    /// classes, with any interfering pre-colored registers removed.
    template <typename RegContainer>
    PBQP::Matrix* buildCoalescingMatrix(const RegContainer &allowed1,
                                        const RegContainer &allowed2,
                                        PBQP::PBQPNum cBenefit) const;

    /// \brief Finds coalescing opportunities and returns them as a map.
    ///
    /// Any entries in the map are guaranteed coalescable, even if their
    /// corresponding live intervals overlap.
    CoalesceMap findCoalesces();

    /// \brief Finds the initial set of vreg intervals to allocate.
    void findVRegIntervalsToAlloc();

    /// \brief Constructs a PBQP problem representation of the register
    /// allocation problem for this function.
    ///
    /// @return a PBQP solver object for the register allocation problem.
    PBQP::Graph constructPBQPProblem();

    /// \brief Adds a stack interval if the given live interval has been
    /// spilled. Used to support stack slot coloring.
    void addStackInterval(const LiveInterval *spilled,MachineRegisterInfo* mri);

    /// \brief Given a solved PBQP problem maps this solution back to a register
    /// assignment.
    bool mapPBQPToRegAlloc(const PBQP::Solution &solution);

    /// \brief Postprocessing before final spilling. Sets basic block "live in"
    /// variables.
    void finalizeAlloc() const;

  };

  char PBQPRegAlloc::ID = 0;
}

template <typename RegContainer>
PBQP::Vector PBQPRegAlloc::buildCostVector(unsigned vReg,
                                           const RegContainer &allowed,
                                           const CoalesceMap &coalesces,
                                           PBQP::PBQPNum spillCost) const {

  typedef typename RegContainer::const_iterator AllowedItr;

  // Allocate vector. Additional element (0th) used for spill option
  PBQP::Vector v(allowed.size() + 1, 0);

  v[0] = spillCost;

  // Iterate over the allowed registers inserting coalesce benefits if there
  // are any.
  unsigned ai = 0;
  for (AllowedItr itr = allowed.begin(), end = allowed.end();
       itr != end; ++itr, ++ai) {

    unsigned pReg = *itr;

    CoalesceMap::const_iterator cmItr =
      coalesces.find(RegPair(vReg, pReg));

    // No coalesce - on to the next preg.
    if (cmItr == coalesces.end())
      continue;

    // We have a coalesce - insert the benefit.
    v[ai + 1] = -cmItr->second;
  }

  return v;
}

template <typename RegContainer>
PBQP::Matrix* PBQPRegAlloc::buildInterferenceMatrix(
      const RegContainer &allowed1, const RegContainer &allowed2) const {

  typedef typename RegContainer::const_iterator RegContainerIterator;

  // Construct a PBQP matrix representing the cost of allocation options. The
  // rows and columns correspond to the allocation options for the two live
  // intervals.  Elements will be infinite where corresponding registers alias,
  // since we cannot allocate aliasing registers to interfering live intervals.
  // All other elements (non-aliasing combinations) will have zero cost. Note
  // that the spill option (element 0,0) has zero cost, since we can allocate
  // both intervals to memory safely (the cost for each individual allocation
  // to memory is accounted for by the cost vectors for each live interval).
  PBQP::Matrix *m =
    new PBQP::Matrix(allowed1.size() + 1, allowed2.size() + 1, 0);

  // Assume this is a zero matrix until proven otherwise.  Zero matrices occur
  // between interfering live ranges with non-overlapping register sets (e.g.
  // non-overlapping reg classes, or disjoint sets of allowed regs within the
  // same class). The term "overlapping" is used advisedly: sets which do not
  // intersect, but contain registers which alias, will have non-zero matrices.
  // We optimize zero matrices away to improve solver speed.
  bool isZeroMatrix = true;

  // Row index. Starts at 1, since the 0th row is for the spill option, which
  // is always zero.
  unsigned ri = 1;

  // Iterate over allowed sets, insert infinities where required.
  for (RegContainerIterator a1Itr = allowed1.begin(), a1End = allowed1.end();
       a1Itr != a1End; ++a1Itr) {

    // Column index, starts at 1 as for row index.
    unsigned ci = 1;
    unsigned reg1 = *a1Itr;

    for (RegContainerIterator a2Itr = allowed2.begin(), a2End = allowed2.end();
         a2Itr != a2End; ++a2Itr) {

      unsigned reg2 = *a2Itr;

      // If the row/column regs are identical or alias insert an infinity.
      if (tri->regsOverlap(reg1, reg2)) {
        (*m)[ri][ci] = std::numeric_limits<PBQP::PBQPNum>::infinity();
        isZeroMatrix = false;
      }

      ++ci;
    }

    ++ri;
  }

  // If this turns out to be a zero matrix...
  if (isZeroMatrix) {
    // free it and return null.
    delete m;
    return 0;
  }

  // ...otherwise return the cost matrix.
  return m;
}

template <typename RegContainer>
PBQP::Matrix* PBQPRegAlloc::buildCoalescingMatrix(
      const RegContainer &allowed1, const RegContainer &allowed2,
      PBQP::PBQPNum cBenefit) const {

  typedef typename RegContainer::const_iterator RegContainerIterator;

  // Construct a PBQP Matrix representing the benefits of coalescing. As with
  // interference matrices the rows and columns represent allowed registers
  // for the LiveIntervals which are (potentially) to be coalesced. The amount
  // -cBenefit will be placed in any element representing the same register
  // for both intervals.
  PBQP::Matrix *m =
    new PBQP::Matrix(allowed1.size() + 1, allowed2.size() + 1, 0);

  // Reset costs to zero.
  m->reset(0);

  // Assume the matrix is zero till proven otherwise. Zero matrices will be
  // optimized away as in the interference case.
  bool isZeroMatrix = true;

  // Row index. Starts at 1, since the 0th row is for the spill option, which
  // is always zero.
  unsigned ri = 1;

  // Iterate over the allowed sets, insert coalescing benefits where
  // appropriate.
  for (RegContainerIterator a1Itr = allowed1.begin(), a1End = allowed1.end();
       a1Itr != a1End; ++a1Itr) {

    // Column index, starts at 1 as for row index.
    unsigned ci = 1;
    unsigned reg1 = *a1Itr;

    for (RegContainerIterator a2Itr = allowed2.begin(), a2End = allowed2.end();
         a2Itr != a2End; ++a2Itr) {

      // If the row and column represent the same register insert a beneficial
      // cost to preference this allocation - it would allow us to eliminate a
      // move instruction.
      if (reg1 == *a2Itr) {
        (*m)[ri][ci] = -cBenefit;
        isZeroMatrix = false;
      }

      ++ci;
    }

    ++ri;
  }

  // If this turns out to be a zero matrix...
  if (isZeroMatrix) {
    // ...free it and return null.
    delete m;
    return 0;
  }

  return m;
}

PBQPRegAlloc::CoalesceMap PBQPRegAlloc::findCoalesces() {

  typedef MachineFunction::const_iterator MFIterator;
  typedef MachineBasicBlock::const_iterator MBBIterator;
  typedef LiveInterval::const_vni_iterator VNIIterator;

  CoalesceMap coalescesFound;

  // To find coalesces we need to iterate over the function looking for
  // copy instructions.
  for (MFIterator bbItr = mf->begin(), bbEnd = mf->end();
       bbItr != bbEnd; ++bbItr) {

    const MachineBasicBlock *mbb = &*bbItr;

    for (MBBIterator iItr = mbb->begin(), iEnd = mbb->end();
         iItr != iEnd; ++iItr) {

      const MachineInstr *instr = &*iItr;
      unsigned srcReg, dstReg, srcSubReg, dstSubReg;

      // If this isn't a copy then continue to the next instruction.
      if (!tii->isMoveInstr(*instr, srcReg, dstReg, srcSubReg, dstSubReg))
        continue;

      // If the registers are already the same our job is nice and easy.
      if (dstReg == srcReg)
        continue;

      bool srcRegIsPhysical = TargetRegisterInfo::isPhysicalRegister(srcReg),
           dstRegIsPhysical = TargetRegisterInfo::isPhysicalRegister(dstReg);

      // If both registers are physical then we can't coalesce.
      if (srcRegIsPhysical && dstRegIsPhysical)
        continue;

      // If it's a copy that includes a virtual register but the source and
      // destination classes differ then we can't coalesce, so continue with
      // the next instruction.
      const TargetRegisterClass *srcRegClass = srcRegIsPhysical ?
          tri->getPhysicalRegisterRegClass(srcReg) : mri->getRegClass(srcReg);

      const TargetRegisterClass *dstRegClass = dstRegIsPhysical ?
          tri->getPhysicalRegisterRegClass(dstReg) : mri->getRegClass(dstReg);

      if (srcRegClass != dstRegClass)
        continue;

      // We also need any physical regs to be allocable, coalescing with
      // a non-allocable register is invalid.
      if (srcRegIsPhysical) {
        if (std::find(dstRegClass->allocation_order_begin(*mf),
                      dstRegClass->allocation_order_end(*mf), srcReg) ==
            dstRegClass->allocation_order_end(*mf))
          continue;
      }

      if (dstRegIsPhysical) {
        if (std::find(srcRegClass->allocation_order_begin(*mf),
                      srcRegClass->allocation_order_end(*mf), dstReg) ==
            srcRegClass->allocation_order_end(*mf))
          continue;
      }

      // If we've made it here we have a copy with compatible register classes.
      // We can probably coalesce, but we need to consider overlap.
      const LiveInterval *srcLI = &lis->getInterval(srcReg),
                         *dstLI = &lis->getInterval(dstReg);

      if (srcLI->overlaps(*dstLI)) {
        // Even in the case of an overlap we might still be able to coalesce,
        // but we need to make sure that no definition of either range occurs
        // while the other range is live.

        // Otherwise start by assuming we're ok.
        bool badDef = false;

        // Test all defs of the source range.
        for (VNIIterator
               vniItr = srcLI->vni_begin(), vniEnd = srcLI->vni_end();
               vniItr != vniEnd; ++vniItr) {

          // If we find a poorly defined def we err on the side of caution.
          if (!(*vniItr)->def.isValid()) {
            badDef = true;
            break;
          }

          // If we find a def that kills the coalescing opportunity then
          // record it and break from the loop.
          if (dstLI->liveAt((*vniItr)->def)) {
            badDef = true;
            break;
          }
        }

        // If we have a bad def give up, continue to the next instruction.
        if (badDef)
          continue;

        // Otherwise test definitions of the destination range.
        for (VNIIterator
               vniItr = dstLI->vni_begin(), vniEnd = dstLI->vni_end();
               vniItr != vniEnd; ++vniItr) {

          // We want to make sure we skip the copy instruction itself.
          if ((*vniItr)->getCopy() == instr)
            continue;

          if (!(*vniItr)->def.isValid()) {
            badDef = true;
            break;
          }

          if (srcLI->liveAt((*vniItr)->def)) {
            badDef = true;
            break;
          }
        }

        // As before a bad def we give up and continue to the next instr.
        if (badDef)
          continue;
      }

      // If we make it to here then either the ranges didn't overlap, or they
      // did, but none of their definitions would prevent us from coalescing.
      // We're good to go with the coalesce.

      float cBenefit = powf(10.0f, loopInfo->getLoopDepth(mbb)) / 5.0;

      coalescesFound[RegPair(srcReg, dstReg)] = cBenefit;
      coalescesFound[RegPair(dstReg, srcReg)] = cBenefit;
    }

  }

  return coalescesFound;
}

void PBQPRegAlloc::findVRegIntervalsToAlloc() {

  // Iterate over all live ranges.
  for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
       itr != end; ++itr) {

    // Ignore physical ones.
    if (TargetRegisterInfo::isPhysicalRegister(itr->first))
      continue;

    LiveInterval *li = itr->second;

    // If this live interval is non-empty we will use pbqp to allocate it.
    // Empty intervals we allocate in a simple post-processing stage in
    // finalizeAlloc.
    if (!li->empty()) {
      vregIntervalsToAlloc.insert(li);
    }
    else {
      emptyVRegIntervals.insert(li);
    }
  }
}

PBQP::Graph PBQPRegAlloc::constructPBQPProblem() {

  typedef std::vector<const LiveInterval*> LIVector;
  typedef std::vector<unsigned> RegVector;

  // This will store the physical intervals for easy reference.
  LIVector physIntervals;

  // Start by clearing the old node <-> live interval mappings & allowed sets
  li2Node.clear();
  node2LI.clear();
  allowedSets.clear();

  // Populate physIntervals, update preg use:
  for (LiveIntervals::iterator itr = lis->begin(), end = lis->end();
       itr != end; ++itr) {

    if (TargetRegisterInfo::isPhysicalRegister(itr->first)) {
      physIntervals.push_back(itr->second);
      mri->setPhysRegUsed(itr->second->reg);
    }
  }

  // Iterate over vreg intervals, construct live interval <-> node number
  //  mappings.
  for (LiveIntervalSet::const_iterator
       itr = vregIntervalsToAlloc.begin(), end = vregIntervalsToAlloc.end();
       itr != end; ++itr) {
    const LiveInterval *li = *itr;

    li2Node[li] = node2LI.size();
    node2LI.push_back(li);
  }

  // Get the set of potential coalesces.
  CoalesceMap coalesces;

  if (pbqpCoalescing) {
    coalesces = findCoalesces();
  }

  // Construct a PBQP solver for this problem
  PBQP::Graph problem;
  problemNodes.resize(vregIntervalsToAlloc.size());

  // Resize allowedSets container appropriately.
  allowedSets.resize(vregIntervalsToAlloc.size());

  // Iterate over virtual register intervals to compute allowed sets...
  for (unsigned node = 0; node < node2LI.size(); ++node) {

    // Grab pointers to the interval and its register class.
    const LiveInterval *li = node2LI[node];
    const TargetRegisterClass *liRC = mri->getRegClass(li->reg);

    // Start by assuming all allocable registers in the class are allowed...
    RegVector liAllowed(liRC->allocation_order_begin(*mf),
                        liRC->allocation_order_end(*mf));

    // Eliminate the physical registers which overlap with this range, along
    // with all their aliases.
    for (LIVector::iterator pItr = physIntervals.begin(),
       pEnd = physIntervals.end(); pItr != pEnd; ++pItr) {

      if (!li->overlaps(**pItr))
        continue;

      unsigned pReg = (*pItr)->reg;

      // If we get here then the live intervals overlap, but we're still ok
      // if they're coalescable.
      if (coalesces.find(RegPair(li->reg, pReg)) != coalesces.end())
        continue;

      // If we get here then we have a genuine exclusion.

      // Remove the overlapping reg...
      RegVector::iterator eraseItr =
        std::find(liAllowed.begin(), liAllowed.end(), pReg);

      if (eraseItr != liAllowed.end())
        liAllowed.erase(eraseItr);

      const unsigned *aliasItr = tri->getAliasSet(pReg);

      if (aliasItr != 0) {
        // ...and its aliases.
        for (; *aliasItr != 0; ++aliasItr) {
          RegVector::iterator eraseItr =
            std::find(liAllowed.begin(), liAllowed.end(), *aliasItr);

          if (eraseItr != liAllowed.end()) {
            liAllowed.erase(eraseItr);
          }
        }
      }
    }

    // Copy the allowed set into a member vector for use when constructing cost
    // vectors & matrices, and mapping PBQP solutions back to assignments.
    allowedSets[node] = AllowedSet(liAllowed.begin(), liAllowed.end());

    // Set the spill cost to the interval weight, or epsilon if the
    // interval weight is zero
    PBQP::PBQPNum spillCost = (li->weight != 0.0) ?
        li->weight : std::numeric_limits<PBQP::PBQPNum>::min();

    // Build a cost vector for this interval.
    problemNodes[node] =
      problem.addNode(
        buildCostVector(li->reg, allowedSets[node], coalesces, spillCost));

  }

  // Now add the cost matrices...
  for (unsigned node1 = 0; node1 < node2LI.size(); ++node1) {
    const LiveInterval *li = node2LI[node1];

    // Test for live range overlaps and insert interference matrices.
    for (unsigned node2 = node1 + 1; node2 < node2LI.size(); ++node2) {
      const LiveInterval *li2 = node2LI[node2];

      CoalesceMap::const_iterator cmItr =
        coalesces.find(RegPair(li->reg, li2->reg));

      PBQP::Matrix *m = 0;

      if (cmItr != coalesces.end()) {
        m = buildCoalescingMatrix(allowedSets[node1], allowedSets[node2],
                                  cmItr->second);
      }
      else if (li->overlaps(*li2)) {
        m = buildInterferenceMatrix(allowedSets[node1], allowedSets[node2]);
      }

      if (m != 0) {
        problem.addEdge(problemNodes[node1],
                        problemNodes[node2],
                        *m);

        delete m;
      }
    }
  }

  assert(problem.getNumNodes() == allowedSets.size());
/*
  std::cerr << "Allocating for " << problem.getNumNodes() << " nodes, "
            << problem.getNumEdges() << " edges.\n";

  problem.printDot(std::cerr);
*/
  // We're done, PBQP problem constructed - return it.
  return problem;
}

void PBQPRegAlloc::addStackInterval(const LiveInterval *spilled,
                                    MachineRegisterInfo* mri) {
  int stackSlot = vrm->getStackSlot(spilled->reg);

  if (stackSlot == VirtRegMap::NO_STACK_SLOT)
    return;

  const TargetRegisterClass *RC = mri->getRegClass(spilled->reg);
  LiveInterval &stackInterval = lss->getOrCreateInterval(stackSlot, RC);

  VNInfo *vni;
  if (stackInterval.getNumValNums() != 0)
    vni = stackInterval.getValNumInfo(0);
  else
    vni = stackInterval.getNextValue(
      SlotIndex(), 0, false, lss->getVNInfoAllocator());

  LiveInterval &rhsInterval = lis->getInterval(spilled->reg);
  stackInterval.MergeRangesInAsValue(rhsInterval, vni);
}

bool PBQPRegAlloc::mapPBQPToRegAlloc(const PBQP::Solution &solution) {

  // Set to true if we have any spills
  bool anotherRoundNeeded = false;

  // Clear the existing allocation.
  vrm->clearAllVirt();

  // Iterate over the nodes mapping the PBQP solution to a register assignment.
  for (unsigned node = 0; node < node2LI.size(); ++node) {
    unsigned virtReg = node2LI[node]->reg,
             allocSelection = solution.getSelection(problemNodes[node]);

    // If the PBQP solution is non-zero it's a physical register...
    if (allocSelection != 0) {
      // Get the physical reg, subtracting 1 to account for the spill option.
      unsigned physReg = allowedSets[node][allocSelection - 1];

      DEBUG(dbgs() << "VREG " << virtReg << " -> "
                   << tri->getName(physReg) << "\n");

      assert(physReg != 0);

      // Add to the virt reg map and update the used phys regs.
      vrm->assignVirt2Phys(virtReg, physReg);
    }
    // ...Otherwise it's a spill.
    else {

      // Make sure we ignore this virtual reg on the next round
      // of allocation
      vregIntervalsToAlloc.erase(&lis->getInterval(virtReg));

      // Insert spill ranges for this live range
      const LiveInterval *spillInterval = node2LI[node];
      double oldSpillWeight = spillInterval->weight;
      SmallVector<LiveInterval*, 8> spillIs;
      std::vector<LiveInterval*> newSpills =
        lis->addIntervalsForSpills(*spillInterval, spillIs, loopInfo, *vrm);
      addStackInterval(spillInterval, mri);

      (void) oldSpillWeight;
      DEBUG(dbgs() << "VREG " << virtReg << " -> SPILLED (Cost: "
                   << oldSpillWeight << ", New vregs: ");

      // Copy any newly inserted live intervals into the list of regs to
      // allocate.
      for (std::vector<LiveInterval*>::const_iterator
           itr = newSpills.begin(), end = newSpills.end();
           itr != end; ++itr) {

        assert(!(*itr)->empty() && "Empty spill range.");

        DEBUG(dbgs() << (*itr)->reg << " ");

        vregIntervalsToAlloc.insert(*itr);
      }

      DEBUG(dbgs() << ")\n");

      // We need another round if spill intervals were added.
      anotherRoundNeeded |= !newSpills.empty();
    }
  }

  return !anotherRoundNeeded;
}

void PBQPRegAlloc::finalizeAlloc() const {
  typedef LiveIntervals::iterator LIIterator;
  typedef LiveInterval::Ranges::const_iterator LRIterator;

  // First allocate registers for the empty intervals.
  for (LiveIntervalSet::const_iterator
         itr = emptyVRegIntervals.begin(), end = emptyVRegIntervals.end();
         itr != end; ++itr) {
    LiveInterval *li = *itr;

    unsigned physReg = vrm->getRegAllocPref(li->reg);

    if (physReg == 0) {
      const TargetRegisterClass *liRC = mri->getRegClass(li->reg);
      physReg = *liRC->allocation_order_begin(*mf);
    }

    vrm->assignVirt2Phys(li->reg, physReg);
  }

  // Finally iterate over the basic blocks to compute and set the live-in sets.
  SmallVector<MachineBasicBlock*, 8> liveInMBBs;
  MachineBasicBlock *entryMBB = &*mf->begin();

  for (LIIterator liItr = lis->begin(), liEnd = lis->end();
       liItr != liEnd; ++liItr) {

    const LiveInterval *li = liItr->second;
    unsigned reg = 0;

    // Get the physical register for this interval
    if (TargetRegisterInfo::isPhysicalRegister(li->reg)) {
      reg = li->reg;
    }
    else if (vrm->isAssignedReg(li->reg)) {
      reg = vrm->getPhys(li->reg);
    }
    else {
      // Ranges which are assigned a stack slot only are ignored.
      continue;
    }

    if (reg == 0) {
      // Filter out zero regs - they're for intervals that were spilled.
      continue;
    }

    // Iterate over the ranges of the current interval...
    for (LRIterator lrItr = li->begin(), lrEnd = li->end();
         lrItr != lrEnd; ++lrItr) {

      // Find the set of basic blocks which this range is live into...
      if (lis->findLiveInMBBs(lrItr->start, lrItr->end,  liveInMBBs)) {
        // And add the physreg for this interval to their live-in sets.
        for (unsigned i = 0; i < liveInMBBs.size(); ++i) {
          if (liveInMBBs[i] != entryMBB) {
            if (!liveInMBBs[i]->isLiveIn(reg)) {
              liveInMBBs[i]->addLiveIn(reg);
            }
          }
        }
        liveInMBBs.clear();
      }
    }
  }

}

bool PBQPRegAlloc::runOnMachineFunction(MachineFunction &MF) {

  mf = &MF;
  tm = &mf->getTarget();
  tri = tm->getRegisterInfo();
  tii = tm->getInstrInfo();
  mri = &mf->getRegInfo();

  lis = &getAnalysis<LiveIntervals>();
  lss = &getAnalysis<LiveStacks>();
  loopInfo = &getAnalysis<MachineLoopInfo>();

  vrm = &getAnalysis<VirtRegMap>();

  DEBUG(dbgs() << "PBQP Register Allocating for " << mf->getFunction()->getName() << "\n");

  // Allocator main loop:
  //
  // * Map current regalloc problem to a PBQP problem
  // * Solve the PBQP problem
  // * Map the solution back to a register allocation
  // * Spill if necessary
  //
  // This process is continued till no more spills are generated.

  // Find the vreg intervals in need of allocation.
  findVRegIntervalsToAlloc();

  // If there are non-empty intervals allocate them using pbqp.
  if (!vregIntervalsToAlloc.empty()) {

    bool pbqpAllocComplete = false;
    unsigned round = 0;

    while (!pbqpAllocComplete) {
      DEBUG(dbgs() << "  PBQP Regalloc round " << round << ":\n");

      PBQP::Graph problem = constructPBQPProblem();
      PBQP::Solution solution =
        PBQP::HeuristicSolver<PBQP::Heuristics::Briggs>::solve(problem);

      pbqpAllocComplete = mapPBQPToRegAlloc(solution);

      ++round;
    }
  }

  // Finalise allocation, allocate empty ranges.
  finalizeAlloc();

  vregIntervalsToAlloc.clear();
  emptyVRegIntervals.clear();
  li2Node.clear();
  node2LI.clear();
  allowedSets.clear();
  problemNodes.clear();

  DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");

  // Run rewriter
  std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());

  rewriter->runOnMachineFunction(*mf, *vrm, lis);

  return true;
}

FunctionPass* llvm::createPBQPRegisterAllocator() {
  return new PBQPRegAlloc();
}

#undef DEBUG_TYPE


text:
module.exports = function processId (record) {
  const rid = record['@rid'];

  record.id = [rid.cluster, rid.position].join(':');
  delete record['@rid'];

  return record;
};

redpajama_set_name: RedPajamaGithub


text:
/**
 * httpRoutes.js
 *
 * Description:
 *  routing file for http requests
 *
 * Author:
 *  sota1235
 */

var path   = require('path');
var multer = require('multer');

var upload = multer({ dest: path.join(__dirname, '..', 'public', 'uploads') });

module.exports = function(app) {
  var QuestionService = app.get('services').QuestionService(app);
  var ImageService    = app.get('services').ImageService(app);

  app.get('/', function(req, res, next) {
    res.render('index');
  });

  app.get('/quiz', function(req, res, next) {
    res.render('quiz');
  });

  app.get('/admin', function(req, res, next) {
    res.render('admin');
  });

  /* access to models */
  // Questions
  app.post('/upload', upload.single('questionImg'), function(req, res, next) {
    QuestionService.updateImage(req, res);
  });

  app.get('/get/questions', function(req, res, next) {
    QuestionService.readAll(res);
  });

  app.get('/get/question/:id', function(req, res, next) {
    QuestionService.read(req, res);
  });

  app.post('/add/question', function(req, res, next) {
    QuestionService.create(req, res)
      .then(function(result) {
        QuestionService.readAll(res);
      });
  });

  app.post('/delete/question', function(req, res, next) {
    QuestionService.delete(req, res);
  });

  // Images
  app.post('/upload/img', upload.single('normalImg'), function(req, res, next) {
    ImageService.create(req, res);
  });

  app.get('/get/images', function(req, res, next) {
    ImageService.readAll(res);
  });

  app.get('/get/image/:id', function(req, res, next) {
    ImageService.read(req, res);
  });

  app.post('/delete/image', function(req, res, next) {
    ImageService.delete(req, res);
  });
};


text:
var fs     = require('fs');
var spawn  = require('child_process').spawn;
var spawnSync = require('child_process').spawnSync;
var join   = require('path').join;
var http   = require('http');
var shell  = require('shelljs');
var _      = require('lodash');

module.exports = function($, logger) {
  return new NodeJS($, logger);
};

function NodeJS($, logger){
  this.$ = $;
  this.log = require('../log')($, 'electrify:plugins:nodejs');
  this.name = 'nodejs';
  this.app_node_path = join(this.$.env.app.bin, 'node');
  this.killed = false;

  if(this.$.env.os.is_windows)
    this.app_node_path += '.exe';

  this.config = {
    ROOT_URL: 'http://' + this.$.env.app.hostname + ':' + this.$.env.app.devPort // find meteor's port in run time?
  };

  this.log = logger(this.$, 'electrify:plugins:' + this.name);
}

NodeJS.prototype.acquire = function(done){

  if(!fs.existsSync(this.app_node_path) || this.$.env.plugins.aquiringVersionMissmatch){
    this.log.info('acquiring nodejs');
    shell.cp(this.$.env.meteor.node, this.$.env.app.bin);
    var versionResult = spawnSync(this.app_node_path, ['--version']);
    var regexResult = /^v(\d+\.\d+\.\d+)$/gm.exec(versionResult.stdout.toString());
    if (regexResult && regexResult[1]) {
      this.$.env.plugins.binVersions.node = regexResult[1];
    }
  } else
    this.log.info('nodejs already acquired, moving on');

  done();
};

NodeJS.prototype.start = function(done) {
  this.env = {
    ELECTRIFY_VERSION     : this.$.env.version,
    ELECTRIFY_API_VERSION : this.$.env.apiVersion,
    ELECTRON_VERSION      : process.versions.electron,
    CHROME_VERSION        : process.versions.chrome
  };

  // in development mode, when app is not inside elctron, mongodb is just not
  // needed, since meteor itself is already running its own mongodb
  if(!this.$.env.app.is_packaged) {
    this.log.info('app not packaged, skipping start');
    return setTimeout(done, 1);
  }

  this.log.info('starting meteor...');

  this.meteor_main = join(this.$.env.app.root, 'app', 'main.js');

  var self = this;

  this.$.freeport(null, function(meteor_port){
    self.meteor_port = meteor_port;

    // mimics the process' env data and sets meteor vars on it
    self.config = _.extend({
      PORT               : self.meteor_port,
      ROOT_URL           : 'http://' + self.$.env.app.hostname + ':' + self.meteor_port,
      METEOR_SETTINGS    : JSON.stringify(self.$.env.app.settings)
    }, process.env);

    _.extend(self.config, self.$.plugins.env());
    self.process = spawn(self.app_node_path, [self.meteor_main], {
      env: self.config
      // , stdio: 'inherit'
      // when setting stdio to 'inherit', the node/meteor process CANNOT be
      // spawned and also, no error is shown. it was discovered with try'n'error
      // so now we just listen for stdout and stderr instead, and things appear
      // to be working again
    });

    // mimics inherit without prefixing
    self.process.stdout.pipe(process.stdout);
    self.process.stderr.pipe(process.stderr);

    self.log.debug('waiting for meteor ready');

    self.meteor_ready(self.config.ROOT_URL, done);
  });
};

NodeJS.prototype.meteor_ready = function(url, done) {
  var self = this;
  var fired = false;

  http.get(url, function(/* res */) {
    if(!fired) {
      fired = true;
      self.log.debug('meteor ready');
      done();
    }
  }).on('error', function(/* err */) {
    if(fired || this.killed) return;
    setTimeout(function(){
      self.meteor_ready(url, done);
    }, 30);
  });
};

NodeJS.prototype.stop = function() {
  this.log.debug('Stop node process');
  this.killed = true;
  if(this.process) {
    this.$._kill(this.process);
  }
};


text:
layout: post
date: 2016-11-06
title: "Alessandro Angelozzi 54 Sleeveless"
category: Alessandro Angelozzi
tags: [Alessandro Angelozzi,Alessandro Angelozzi ,Strapless,Sleeveless]
---
### Alessandro Angelozzi 54
Just **$299.99**
###   Sleeveless

BRANDS	Alessandro Angelozzi

Neckline	Strapless

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/alessandro-angelozzi/14025-alessandro-angelozzi-54.html](https://www.readybrides.com/en/alessandro-angelozzi/14025-alessandro-angelozzi-54.html)


text:
namespace FrameTrapped.ComboTrainer.Messages
{
    using System;

    public class FocusStreetFighterMessage
    {
    }
}


text:
#![deny(warnings)]

extern crate coreutils;
extern crate extra;

use std::env;
use std::fs;
use std::io::{stderr, stdout, Write};
use std::process::exit;
use coreutils::ArgParser;
use extra::option::OptionalExt;

const MAN_PAGE: &'static str = /* @MANSTART{shutdown} */ r#"
NAME
    shutdown - stop the system

SYNOPSIS
    shutdown [ -h | -help ]

DESCRIPTION
    Attempt to shutdown the system using ACPI. Failure will be logged to the terminal

OPTIONS
    -h
    --help
        display this help and exit
"#; /* @MANEND */

fn main() {
    let stdout = stdout();
    let mut stdout = stdout.lock();
    let mut stderr = stderr();
    let mut parser = ArgParser::new(1)
        .add_flag(&["h", "help"]);
    parser.parse(env::args());

    if parser.found("help") {
        stdout.write(MAN_PAGE.as_bytes()).try(&mut stderr);
        stdout.flush().try(&mut stderr);
        exit(0);
    }

    fs::File::create("acpi:off").try(&mut stderr);
}


text:
/**
 * @fileoverview Statusbar control.
 *
 * @author benvanik@google.com (Ben Vanik)
 */

goog.provide('wtf.app.Statusbar');

goog.require('goog.events.EventType');
goog.require('goog.soy');
goog.require('goog.style');
goog.require('wtf.app.statusbar');
goog.require('wtf.db.Unit');
goog.require('wtf.events');
goog.require('wtf.events.EventType');
goog.require('wtf.events.Keyboard');
goog.require('wtf.ui.Control');
goog.require('wtf.util');

/**
 * Statusbar control.
 *
 * @param {!wtf.app.DocumentView} documentView Parent document view.
 * @param {!Element} parentElement Element to display in.
 * @constructor
 * @extends {wtf.ui.Control}
 */
wtf.app.Statusbar = function(documentView, parentElement) {
  goog.base(this, parentElement, documentView.getDom());

  /**
   * Parent document view.
   * @type {!wtf.app.DocumentView}
   * @private
   */
  this.documentView_ = documentView;

  /**
   * Content DIVs.
   * @type {!Object.<!HTMLDivElement>}
   * @private
   */
  this.divs_ = {
    selectionCounts: this.getChildElement(
        goog.getCssName('selectionCounts')),
    selectionTimes: this.getChildElement(
        goog.getCssName('selectionTimes')),
    timeTotals: this.getChildElement(
        goog.getCssName('timeTotals')),
    timeRange: this.getChildElement(
        goog.getCssName('timeRange'))
  };

  var commandManager = wtf.events.getCommandManager();
  var eh = this.getHandler();
  eh.listen(this.getChildElement('selectAll'),
      goog.events.EventType.CLICK, function(e) {
        e.preventDefault();
        commandManager.execute('select_all', this, null);
      });
  eh.listen(this.getChildElement('selectVisible'),
      goog.events.EventType.CLICK, function(e) {
        e.preventDefault();
        commandManager.execute('select_visible', this, null);
      });
  eh.listen(this.getChildElement('viewHealthLink'),
      goog.events.EventType.CLICK, function(e) {
        e.preventDefault();
        commandManager.execute('view_trace_health', this, null);
      });

  var db = this.documentView_.getDatabase();
  db.addListener(wtf.events.EventType.INVALIDATED, this.update_, this);
  var selection = this.documentView_.getSelection();
  selection.addListener(wtf.events.EventType.INVALIDATED, this.update_, this);

  this.update_();
};
goog.inherits(wtf.app.Statusbar, wtf.ui.Control);

/**
 * @override
 */
wtf.app.Statusbar.prototype.createDom = function(dom) {
  return /** @type {!Element} */ (goog.soy.renderAsFragment(
      wtf.app.statusbar.control, {
        system_key: wtf.events.Keyboard.SYSTEM_KEY
      }, undefined, dom));
};

/**
 * Updates the statusbar when the database/selection/etc change.
 * @private
 */
wtf.app.Statusbar.prototype.update_ = function() {
  var dom = this.getDom();
  var db = this.documentView_.getDatabase();
  var selection = this.documentView_.getSelection();
  var units = db.getUnits();

  if (!db.getLastEventTime()) {
    goog.style.setElementShown(this.getRootElement(), false);
    return;
  }
  goog.style.setElementShown(this.getRootElement(), true);

  var timebase = db.getTimebase();
  var firstEventTime = db.getFirstEventTime();
  var lastEventTime = db.getLastEventTime();
  var totalEventCount = 0;
  var zones = db.getZones();
  for (var n = 0; n < zones.length; n++) {
    var eventList = zones[n].getEventList();
    totalEventCount += eventList.getTotalEventCount();
  }

  var table = selection.getSelectionStatistics();
  var filteredEventCount = table.getEventCount();

  var selectionCounts = [
    filteredEventCount,
    totalEventCount
  ].join('/');
  dom.setTextContent(this.divs_.selectionCounts, selectionCounts);

  var totalDuration = wtf.db.Unit.format(lastEventTime - firstEventTime, units);
  if (selection.hasTimeRangeSpecified()) {
    var selectionTimeStart = selection.getTimeStart();
    var selectionTimeEnd = selection.getTimeEnd();
    dom.setTextContent(this.divs_.selectionTimes, [
      wtf.db.Unit.format(selectionTimeEnd - selectionTimeStart, units),
      totalDuration
    ].join('/'));
  } else {
    dom.setTextContent(this.divs_.selectionTimes, [
      totalDuration,
      totalDuration
    ].join('/'));
  }

  if (units == wtf.db.Unit.TIME_MILLISECONDS) {
    dom.setTextContent(this.divs_.timeRange, [
      wtf.util.formatWallTime(timebase + firstEventTime),
      wtf.util.formatWallTime(timebase + lastEventTime)
    ].join('-'));
  } else {
    dom.setTextContent(this.divs_.timeRange, '');
  }
};


text:
package laika.parse.rst

import org.scalatest.FlatSpec
import org.scalatest.Matchers

import laika.api._
import laika.tree.Elements._
import laika.parse.rst.Elements._
import laika.parse.rst.Directives._
import laika.parse.rst.TextRoles._
import laika.parse.rst.Directives.Parts._
import laika.directive.Directives.Blocks
import laika.directive.Directives.Spans
import laika.tree.helper.ModelBuilder

class APISpec extends FlatSpec
                 with Matchers
                 with ModelBuilder {

  "The API" should "support registration of block directives" in {
    val directives = List(
      BlockDirective("oneArg")(argument() map p),
      BlockDirective("twoArgs")((argument() ~ argument()) { (arg1,arg2) => p(arg1+arg2) })
    )
    val input = """.. oneArg:: arg
      |
      |.. twoArgs:: arg arg""".stripMargin
    (Parse as (ReStructuredText withBlockDirectives (directives:_*)) fromString input).content should be (root (p("arg"),p("argarg")))
  }

  it should "support registration of span directives" in {
    val directives = List(
      SpanDirective("oneArg")(argument() map (Text(_))),
      SpanDirective("twoArgs")((argument() ~ argument()) { (arg1,arg2) => Text(arg1+arg2) })
    )
    val input = """foo |one| foo |two|
      |
      |.. |one| oneArg:: arg
      |
      |.. |two| twoArgs:: arg arg""".stripMargin
    (Parse as (ReStructuredText withSpanDirectives (directives:_*)) fromString input).content should be (root
        (p(txt("foo "), txt("arg"), txt(" foo "), txt("argarg"))))
  }

  it should "support registration of text roles" in {
    import laika.parse.rst.TextRoles.{Parts=>P}
    val roles = List(
      TextRole("oneArg", "foo1")(P.field("name")) { (res,text) =>
       txt(res+text)
      },
      TextRole("twoArgs", "foo2")
        ((P.field("name1") ~ P.field("name2")) { (arg1,arg2) => arg1+arg2 })
        { (res,text) => txt(res+text) }
    )
    val input = """foo `one`:one: foo :two:`two`
      |
      |.. role::one(oneArg)
      | :name: val
      |
      |.. role::two(twoArgs)
      | :name1: val1
      | :name2: val2""".stripMargin
    (Parse as (ReStructuredText withTextRoles (roles:_*)) fromString input).content should be (root
        (p(txt("foo "), txt("valone"), txt(" foo "), txt("val1val2two"))))
  }

  trait BlockDirectives {
    import Blocks.Combinators._
    import Blocks.Converters._
    import laika.util.Builders._
    import laika.directive.Directives.Default

    val directives: List[Blocks.Directive] = List(
      Blocks.create("oneArg")(attribute(Default) map p),
      Blocks.create("twoArgs")((attribute(Default) ~ attribute("name")) { (arg1,arg2) => p(arg1+arg2) })
    )
  }

  trait SpanDirectives {
    import Spans.Combinators._
    import Spans.Converters._
    import laika.util.Builders._
    import laika.directive.Directives.Default

    val directives: List[Spans.Directive] = List(
      Spans.create("oneArg")(attribute(Default) map txt),
      Spans.create("twoArgs")((attribute(Default) ~ attribute("name")) { (arg1,arg2) => txt(arg1+arg2) })
    )
  }

  it should "support the registration of Laika block directives" in {
    new BlockDirectives {
      val input = """@:oneArg arg.
        |
        |@:twoArgs arg1 name=arg2.""".stripMargin
      (Parse as (ReStructuredText withLaikaBlockDirectives (directives:_*)) fromString input).content should be (root (p("arg"),p("arg1arg2")))
    }
  }

  it should "ignore the registration of Laika block directives when run in strict mode" in {
    new BlockDirectives {
      val input = """@:oneArg arg.
        |
        |@:twoArgs arg1 name=arg2.""".stripMargin
      (Parse as (ReStructuredText withLaikaBlockDirectives (directives:_*) strict) fromString input).content should be (root (p("@:oneArg arg."),p("@:twoArgs arg1 name=arg2.")))
    }
  }

  it should "support the registration of Laika span directives" in {
    new SpanDirectives {
      val input = """one @:oneArg arg. two @:twoArgs arg1 name=arg2. three"""
      (Parse as (ReStructuredText withLaikaSpanDirectives (directives:_*)) fromString input).content should be (root (p("one arg two arg1arg2 three")))
    }
  }

  it should "ignore the registration of Laika span directives when run in strict mode" in {
    new SpanDirectives {
      val input = """one @:oneArg arg. two @:twoArgs arg1 name=arg2. three"""
      (Parse as (ReStructuredText withLaikaSpanDirectives (directives:_*) strict) fromString input).content should be (root (p("one @:oneArg arg. two @:twoArgs arg1 name=arg2. three")))
    }
  }

  it should "preprocess tabs" in {
    val input = " Line1\n\tLine2\n\tLine3"
    (Parse as ReStructuredText fromString input).content should be (root( quote(defList + ("Line1", p("Line2\nLine3")))))
  }

}


text:
"""Utilities related to MAL."""

import re
from datetime import datetime, timedelta

last_online_minutes = re.compile(r'(?P<minutes>\d+) minutes? ago')
last_online_hours = re.compile(r'(?P<hours>\d+) hours? ago')

def get_datetime(text, relative_to=None):  # noqa: C901 (code complexity)
    """Convert a datetime like "Oct 1, 4:29 AM"

    Timestamps that are relative "3 hours ago" can be given a base time
    in case the timestamp was generated at a different time.

    Args:
        text (str): The following examples are supported (with varying accuracy)
            Oct 1, 2013 11:04 PM
            Oct 1, 4:29 AM
            Today, 1:22 AM
            Yesterday, 9:58 AM
            4 hours ago
            1 hour ago
            12 minutes ago
            1 minute ago
            Now

    Returns:
        datetime.datetime

    Raises:
        ValueError if the conversion fails

    Issues:
        - Potentially locale-dependent.
    """
    relative_to = relative_to or datetime.utcnow()
    text = text.strip().lower()

    # Now
    if text == 'now':
        return relative_to

    # x minute(s) ago
    minutes_match = last_online_minutes.match(text)
    if minutes_match is not None:
        return relative_to - timedelta(minutes=int(minutes_match.group('minutes')))

    # x hour(s) ago
    hours_match = last_online_hours.match(text)
    if hours_match is not None:
        return relative_to - timedelta(hours=int(hours_match.group('hours')))

    if text.startswith(('today,', 'yesterday,')):
        if text.startswith('today'):
            # Today, 1:22 AM
            base = relative_to
        elif text.startswith('yesterday'):
            # Yesterday, 9:58 AM
            base = relative_to - timedelta(days=1)
        else:
            raise RuntimeError('Invalid Branch')

        time_text = text.split(',')[1].lstrip()
        try:
            time = datetime.strptime(time_text, '%I:%M %p')
        except ValueError:
            pass
        else:
            return datetime.replace(time, year=base.year, month=base.month, day=base.day)

    # Oct 1, 4:29 AM
    try:
        time = datetime.strptime(text, '%b %d, %I:%M %p')
    except ValueError:
        pass
    else:
        return datetime.replace(time, year=relative_to.year)

    # Oct 1, 2013 11:04 PM
    return datetime.strptime(text, '%b %d, %Y %I:%M %p')

def get_date(text):
    """Return a datetime from a date like "Apr 3, 1998", or None.

    Args:
        text (str): The following examples are supported
            Apr 3, 1998
            Apr, 1994   (This will convert to 1st Apr 1994 as a best guess;
                         https://myanimelist.net/anime/730)
            2003        (This will convert to 1st Jan 2003 as a best guess;
                         https://myanimelist.net/anime/1190)

    Returns:
        datetime.date

    Raises:
        ValueError if the conversion fails

    Issues:
        This may be locale dependent
    """
    try:
        return datetime.strptime(text, '%b %d, %Y').date()
    except ValueError:
        pass

    try:
        return datetime.strptime(text, '%b, %Y').date()
    except ValueError:
        pass

    try:
        return datetime.strptime(text, '%Y').date()
    except ValueError:
        pass


text:
@implementation Model

-(instancetype)initWithDictionary:(NSMutableDictionary *)dic{
    self = [super init];
    if (self) {
        self.title = dic[@"title"];
        self.Titleimage = dic[@"imag"];
        self.subTitle = dic[@"subTitle"];
    }
    return self;
}

@end


text:
package com.wildducktheories.raft.encoding;

public interface Decoder<T, E> {
	/**
	 * Decode an instance of type E into an instance of type T.
	 * @param The encoded instance.
	 * @return The the decoded instance.
	 */
	T decode(E e);
}


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.model;

import com.yahoo.config.application.api.ApplicationPackage;
import com.yahoo.config.application.api.DeployLogger;
import com.yahoo.config.model.api.ModelContext;
import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.producer.AbstractConfigProducer;
import com.yahoo.vespa.model.VespaModel;

import java.util.stream.Stream;

/**
 * This class contains a context that is passed to a model builder, and can be used to retrieve the application package,
 * logger etc.
 *
 * @author Ulf Lilleengen
 */
public final class ConfigModelContext {

    private final AbstractConfigProducer<?> parent;
    private final String producerId;
    private final DeployState deployState;
    private final VespaModel vespaModel;
    private final ConfigModelRepoAdder configModelRepoAdder;
    private final ApplicationType applicationType;

    private ConfigModelContext(ApplicationType applicationType,
                               DeployState deployState,
                               VespaModel vespaModel,
                               ConfigModelRepoAdder configModelRepoAdder,
                               AbstractConfigProducer<?> parent,
                               String producerId) {
        this.applicationType = applicationType;
        this.deployState = deployState;
        this.vespaModel = vespaModel;
        this.configModelRepoAdder = configModelRepoAdder;
        this.parent = parent;
        this.producerId = producerId;
    }

    public ApplicationPackage getApplicationPackage() { return deployState.getApplicationPackage(); }
    public String getProducerId() { return producerId; }
    public AbstractConfigProducer<?> getParentProducer() { return parent; }
    public DeployLogger getDeployLogger() { return deployState.getDeployLogger(); }
    public DeployState getDeployState() { return deployState; }
    public ApplicationType getApplicationType() { return applicationType; }
    public VespaModel vespaModel() { return vespaModel; }
    public ModelContext.Properties properties() { return deployState.getProperties(); }
    public ModelContext.FeatureFlags featureFlags() { return deployState.featureFlags(); }

    /** Returns write access to the config model repo, or null (only) if this is improperly initialized during testing */
    public ConfigModelRepoAdder getConfigModelRepoAdder() { return configModelRepoAdder; }

    /** Create a new context with a different parent */
    public ConfigModelContext withParent(AbstractConfigProducer<?> newParent) {
        return ConfigModelContext.create(deployState, vespaModel, configModelRepoAdder, newParent, producerId);
    }

    /** Create a new context with a different config model producer id */
    public ConfigModelContext withId(String producerId) {
        return ConfigModelContext.create(deployState, vespaModel, configModelRepoAdder, parent, producerId);
    }

    public ConfigModelContext with(VespaModel vespaModel) {
        return ConfigModelContext.create(deployState, vespaModel, configModelRepoAdder, parent, producerId);
    }

    /**
     * Create an application context from a parent producer and an id.
     *
     * @param deployState the global deploy state for this model
     * @param parent the parent to be used for the config model
     * @param producerId the id to be used for the config model
     * @return a model context that can be passed to a model
     */
    public static ConfigModelContext create(DeployState deployState,
                                            VespaModel vespaModel,
                                            ConfigModelRepoAdder configModelRepoAdder,
                                            AbstractConfigProducer<?> parent,
                                            String producerId) {
        return new ConfigModelContext(ApplicationType.DEFAULT, deployState, vespaModel, configModelRepoAdder, parent, producerId);
    }

    /**
     * Create an application context from an application type, a parent producer and an id.
     *
     * @param applicationType the application type
     * @param deployState the global deploy state for this model
     * @param parent the parent to be used for the config model
     * @param producerId the id to be used for the config model
     * @return a model context that can be passed to a model
     */
    public static ConfigModelContext create(ApplicationType applicationType,
                                            DeployState deployState,
                                            VespaModel vespaModel,
                                            ConfigModelRepoAdder configModelRepoAdder,
                                            AbstractConfigProducer<?> parent,
                                            String producerId) {
        return new ConfigModelContext(applicationType, deployState, vespaModel, configModelRepoAdder, parent, producerId);
    }

    public enum ApplicationType {
        DEFAULT("default"),
        HOSTED_INFRASTRUCTURE("hosted-infrastructure");

        private final String type;

        ApplicationType(String type) {
            this.type = type;
        }

        public static ApplicationType fromString(String value) {
            return Stream.of(ApplicationType.values())
                    .filter(applicationType -> applicationType.type.equals(value))
                    .findFirst()
                    .orElse(DEFAULT);

        }

    }
}


text:
import edu.uta.diql._
import org.apache.spark._
import org.apache.spark.rdd._
import org.apache.log4j._

object Test {

  case class Customer ( name: String, cid: Int, account: Float )

  case class Order ( oid: Int, cid: Int, price: Float )

  def main ( args: Array[String] ) {
    val CF = args(0)
    val OF = args(1)
    val output_file = args(2)
    val conf = new SparkConf().setAppName("Nested")
    val sc = new SparkContext(conf)

    conf.set("spark.logConf","false")
    conf.set("spark.eventLog.enabled","false")
    LogManager.getRootLogger().setLevel(Level.WARN)

    //explain(true)
    val t: Long = System.currentTimeMillis()

    val customers = sc.textFile(CF).map{ line => line.split(",")
                          match { case Array(a,b,c) => Customer(a,b.toInt,c.toFloat) } }
    val orders = sc.textFile(OF).map{ line => line.split(",")
                          match { case Array(a,b,c) => Order(a.toInt,b.toInt,c.toFloat) } }

    q("""
     select c.name
     from c <- customers
     where c.account < +/(select o.price from o <- orders where o.cid == c.cid)
     """).saveAsTextFile(output_file)

    sc.stop()

    println("**** DIQL Spark run time: "+(System.currentTimeMillis()-t)/1000.0+" secs")
  }
}


text:
/**
 * Marhsalling for the various types represented by AWSLogs.
 */
 package com.amazonaws.services.logs.model.transform;


text:
<?php

namespace Admin\Model\Catalog;
use Oculus\Engine\Model;

class Download extends Model {
    public function addDownload($data) {
        $this->db->query("
			INSERT INTO {$this->db->prefix}download
			SET
				filename = '" . $this->db->escape($data['filename']) . "',
				mask = '" . $this->db->escape($data['mask']) . "',
				remaining = '" . (int)$data['remaining'] . "',
				date_added = NOW()");

        $download_id = $this->db->getLastId();

        foreach ($data['download_description'] as $language_id => $value) {
            $this->db->query("
				INSERT INTO {$this->db->prefix}download_description
				SET
					download_id = '" . (int)$download_id . "',
					language_id = '" . (int)$language_id . "',
					name = '" . $this->db->escape($value['name']) . "'");
        }

        $this->theme->trigger('admin_add_download', array('download_id' => $download_id));
    }

    public function editDownload($download_id, $data) {
        if (!empty($data['update'])) {
            $download_info = $this->getDownload($download_id);

            if ($download_info) {

                // delete the old file
                if ($download_info['filename'] != $data['filename']):
                    unlink($this->app['path.download'] . $download_info['filename']);
                endif;

                $this->db->query("
					UPDATE {$this->db->prefix}order_download
					SET
						`filename` = '" . $this->db->escape($data['filename']) . "',
						mask = '" . $this->db->escape($data['mask']) . "',
						remaining = '" . (int)$data['remaining'] . "'
					WHERE `filename` = '" . $this->db->escape($download_info['filename']) . "'");
            }
        }

        $this->db->query("
			UPDATE {$this->db->prefix}download
			SET
				filename = '" . $this->db->escape($data['filename']) . "',
				mask = '" . $this->db->escape($data['mask']) . "',
				remaining = '" . (int)$data['remaining'] . "'
			WHERE download_id = '" . (int)$download_id . "'");

        $this->db->query("
			DELETE
			FROM {$this->db->prefix}download_description
			WHERE download_id = '" . (int)$download_id . "'");

        foreach ($data['download_description'] as $language_id => $value) {
            $this->db->query("
				INSERT INTO {$this->db->prefix}download_description
				SET
					download_id = '" . (int)$download_id . "',
					language_id = '" . (int)$language_id . "',
					name = '" . $this->db->escape($value['name']) . "'");
        }

        $this->theme->trigger('admin_edit_download', array('download_id' => $download_id));
    }

    public function deleteDownload($download_id) {

        // delete the download file
        $download = $this->getDownload($download_id);

        unlink($this->app['path.download'] . $download['filename']);

        $this->db->query("
			DELETE FROM {$this->db->prefix}download
			WHERE download_id = '" . (int)$download_id . "'");

        $this->db->query("
			DELETE FROM {$this->db->prefix}download_description
			WHERE download_id = '" . (int)$download_id . "'");

        $this->theme->trigger('admin_delete_download', array('download_id' => $download_id));
    }

    public function getDownload($download_id) {
        $query = $this->db->query("
			SELECT DISTINCT *
			FROM {$this->db->prefix}download d
			LEFT JOIN {$this->db->prefix}download_description dd
				ON (d.download_id = dd.download_id)
			WHERE d.download_id = '" . (int)$download_id . "'
			AND dd.language_id = '" . (int)$this->config->get('config_language_id') . "'");

        return $query->row;
    }

    public function getDownloads($data = array()) {
        $sql = "
			SELECT *
			FROM {$this->db->prefix}download d
			LEFT JOIN {$this->db->prefix}download_description dd
				ON (d.download_id = dd.download_id)
			WHERE dd.language_id = '" . (int)$this->config->get('config_language_id') . "'";

        if (!empty($data['filter_name'])) {
            $sql.= " AND dd.name LIKE '" . $this->db->escape($data['filter_name']) . "%'";
        }

        $sort_data = array('dd.name', 'd.remaining');

        if (!empty($data['sort']) && in_array($data['sort'], $sort_data)) {
            $sql.= " ORDER BY {$data['sort']}";
        } else {
            $sql.= " ORDER BY dd.name";
        }

        if (isset($data['order']) && ($data['order'] == 'DESC')) {
            $sql.= " DESC";
        } else {
            $sql.= " ASC";
        }

        if (isset($data['start']) || isset($data['limit'])) {
            if ($data['start'] < 0) {
                $data['start'] = 0;
            }

            if ($data['limit'] < 1) {
                $data['limit'] = 20;
            }

            $sql.= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
        }

        $query = $this->db->query($sql);

        return $query->rows;
    }

    public function getDownloadDescriptions($download_id) {
        $download_description_data = array();

        $query = $this->db->query("
			SELECT *
			FROM {$this->db->prefix}download_description
			WHERE download_id = '" . (int)$download_id . "'");

        foreach ($query->rows as $result) {
            $download_description_data[$result['language_id']] = array('name' => $result['name']);
        }

        return $download_description_data;
    }

    public function getTotalDownloads() {
        $query = $this->db->query("
			SELECT COUNT(*) AS total
			FROM {$this->db->prefix}download");

        return $query->row['total'];
    }
}


text:
package docker // import "docker.io/go-docker"

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"testing"

	"golang.org/x/net/context"
)

func TestContainerExportError(t *testing.T) {
	client := &Client{
		client: newMockClient(errorMock(http.StatusInternalServerError, "Server error")),
	}
	_, err := client.ContainerExport(context.Background(), "nothing")
	if err == nil || err.Error() != "Error response from daemon: Server error" {
		t.Fatalf("expected a Server Error, got %v", err)
	}
}

func TestContainerExport(t *testing.T) {
	expectedURL := "/containers/container_id/export"
	client := &Client{
		client: newMockClient(func(r *http.Request) (*http.Response, error) {
			if !strings.HasPrefix(r.URL.Path, expectedURL) {
				return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, r.URL)
			}

			return &http.Response{
				StatusCode: http.StatusOK,
				Body:       ioutil.NopCloser(bytes.NewReader([]byte("response"))),
			}, nil
		}),
	}
	body, err := client.ContainerExport(context.Background(), "container_id")
	if err != nil {
		t.Fatal(err)
	}
	defer body.Close()
	content, err := ioutil.ReadAll(body)
	if err != nil {
		t.Fatal(err)
	}
	if string(content) != "response" {
		t.Fatalf("expected response to contain 'response', got %s", string(content))
	}
}


text:
require 'spec_helper'

describe "gws_staff_record_public_groups", type: :feature, dbscope: :example do
  let(:site) { gws_site }
  let(:year) { create :gws_staff_record_year }
  let!(:item) { create :gws_staff_record_group, year_id: year.id }
  let(:index_path) { gws_staff_record_groups_path(site, year) }

  context "with auth", js: true do
    before { login_gws_user }

    it_behaves_like 'crud flow'

    it "#download" do
      visit index_path
      click_link I18n.t('ss.links.download')
      #expect(page.response_headers['Content-Type']).to eq 'text/csv'

      visit index_path
      click_link I18n.t('ss.links.import')
      click_button I18n.t('ss.import')
    end
  end
end


text:
<!DOCTYPE html>

  <title>BaseResource.php</title>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <link rel="stylesheet" media="all" href="public/stylesheets/normalize.css" />
  <link rel="stylesheet" media="all" href="docco.css" />

BaseResource.php

Table of Contents

                    server.php

                    Constants.php

                    Core.php

                    HttpBasicAuthentification.php

                    Permission.php

                    BaseResource.php

                    ExceptionMiddleware.php

                    IdeaMiddleware.php

                    ProjectMiddleware.php

                    Routing.php

                    UserMiddleware.php

<?php

namespace Personal\Server\Routing;

class BaseResource
{
  private $url;

  function __construct($url)
  {
    $this->url = $url;
  }

  public static function newResource($url)
  {
    return new BaseResource($url);
  }

  public function getURL(){ return $this->url; }
  public function setURL($url){ $this->url = $url; }

  public function url_isValid()
  {
    $parts = explode('/', $this->getURL());
    $resource_name = $parts[count($parts) - 1];
    $pattern = "#[^,|\\^~\[\]`\#;/\?:@=&]#";
    return preg_match($pattern, $resource_name);
  }

  public function initializes_server()
  {
    global $app;
    $files = array_diff(scandir($app->config["base_dir"]), array('.','..'));
    foreach ($files as $file)
    {
      (is_dir($app->config["base_dir"]."/$file")) ? $this->rrmdir($app->config["base_dir"]."/$file") : unlink($app->config["base_dir"]."/$file");
    }
    $info = array('name' => 'Root base');
    $auth = array('login' => $app->config["user_root"],
                  'password' => password_hash($app->config["user_root"].'toto', PASSWORD_DEFAULT));
    file_put_contents($app->config["base_dir"]."/info.json", json_encode($info));
    mkdir($app->config["base_dir"]."/users");
    $info['name'] = "User list";
    file_put_contents($app->config["base_dir"]."/users/info.json", json_encode($info));
    mkdir($app->config["base_dir"]."/projects");
    $info['name'] = "Project list";
    file_put_contents($app->config["base_dir"]."/projects/info.json", json_encode($info));
    mkdir($app->config["base_dir"]."/users/".$app->config["user_root"]);
    $info['name'] = "Root base";
    file_put_contents($app->config["base_dir"]."/users/".$app->config["user_root"]."/info.json", json_encode($info));
    file_put_contents($app->config["base_dir"]."/users/".$app->config["user_root"]."/auth.json", json_encode($auth));
  }

  public function readList()
  {
    global $app;
    $data = json_decode(file_get_contents($app->config["base_dir"].$this->getURL()."/info.json"), TRUE);
    $resourceList = array();
    foreach (glob($app->config["base_dir"].$this->getURL().'/*', GLOB_NOESCAPE) as $file)
    {
      if (!is_dir($file))
        continue;
      try
      {
        $tmp = json_decode(file_get_contents($file."/info.json"), TRUE);
        $resourceList[] = array('href' => $this->getURL()."/".basename($file), 'name' => $tmp["name"]);
      }
      catch (\Exception $e){ continue; }
    }
    $data["resource_list"] = $resourceList;
    $app->response->headers->set('Content-Type','application/json');
    $app->response->setStatus(STATUS_OK);
    return $data;
  }

  public function delete_dir()
  {
    global $app;
    $this->rrmdir($app->config["base_dir"].$this->url);
    $app->response->setStatus(STATUS_NO_CONTENT);
  }

  public function delete_file()
  {
    global $app;
    unlink($app->config["base_dir"].$this->url);
    $app->response->setStatus(STATUS_NO_CONTENT);
  }

  public function canCreate($user)
  {
    global $app;
    if ($this->isRootURL())
    {
      return false;
    }
    else if (is_null($user))
    {
      return false;
    }
    else if ($this->getURLBase() == "users")
    {
      $parts = explode('/', $this->url);
      if (count($parts) == 3)
      {
        return ($this->isOwner($user) || $user["login"] == $app->config["user_root"] || $this->canAdmin($user));
      }
      else
        return ($this->isOwner($user));
    }
    else if ($this->getURLBase() == "projects")
    {
      $parts = explode('/', $this->url);
      if (count($parts) == 3)
      {
        return ($this->canAdmin($user));
      }
      else if (count($parts) == 5 && ($parts[3] == "users" || $parts[3] == "invitations"))
      {
        return ($this->canAdmin($user));
      }
      else
      {
        if (!$this->canParticipate($user)){ return false; }
        $auth = json_decode(file_get_contents($app->config["base_dir"]."/projects/".$parts[2]."/auth.json"), TRUE);
        $users = $auth["users"];
        $permissions = $users[$user["login"]];
        return ($permissions["edit_project"]);
      }
    }
    else
      return false;
  }

  public function canWrite($user)
  {
    global $app;
    return $this->canCreate($user);
  }

  public function canDelete($user)
  {
    global $app;
    if ($this->isRootURL())
    {
      return false;
    }
    else if (is_null($user))
    {
      return false;
    }
    else if ($this->getURLBase() == "users")
    {
      $parts = explode('/', $this->url);
      if (count($parts) == 3)
      {
        return ($this->isOwner($user) || $user["login"] == $app->config["user_root"] || $this->canAdmin($user));
      }
      else
        return ($this->isOwner($user));
    }
    else if ($this->getURLBase() == "projects")
    {
      $parts = explode('/', $this->url);
      if (count($parts) == 3)
      {
        return ($this->canAdmin($user));
      }
      else if (count($parts) == 5 && $parts[3] == "users")
      {
        return ($this->canAdmin($user) || $parts[4] == $user["login"]);
      }
      else if (count($parts) == 5 && $parts[3] == "invitations")
      {
        return ($this->canAdmin($user));
      }
      else
      {
        if (!$this->canParticipate($user)){ return false; }
        $auth = json_decode(file_get_contents($app->config["base_dir"]."/projects/".$parts[2]."/auth.json"), TRUE);
        $users = $auth["users"];
        $permissions = $users[$user["login"]];
        return ($permissions["edit_project"]);
      }
    }
    else
      return false;
  }

  public function canRead($user)
  {
    global $app;
    if ($this->isRootURL())
    {
      return false;
    }
    else if (is_null($user))
    {
      return $this->isPublic();
    }
    else if ($this->getURLBase() == "users")
    {
      $parts = explode('/', $this->url);
      if (count($parts) == 3 && $user["login"] == $app->config["user_root"])
        return true;
      else
        return ($this->isOwner($user) || $this->isPublic());
    }
    else if ($this->getURLBase() == "projects")
    {
      $parts = explode('/', $this->url);
      if (count($parts) == 5 && $parts[3] == "invitations")
      {
        return ($this->canAdmin($user));
      }
      else
        return ($this->canParticipate($user) || $this->isPublic());
    }
    else
      return false;
  }

  private function isPublic()
  {
    global $app;
    $parts = explode('/', $this->url);
    $auth = json_decode(file_get_contents($app->config["base_dir"].'/'.$this->getURLBase().'/'.$parts[2]."/auth.json"), TRUE);
    return ($auth["can_public"] ==  IS_PUBLIC);
  }

  private function canAdmin($user)
  {
    global $app;
    if ($this->getURLBase() == "users")
    {
      $auth = json_decode(file_get_contents($app->config["base_dir"]."/users/".$user["login"]."/auth.json"), TRUE);
      return ($auth["admin_user"]);
    }
    else  if ($this->getURLBase() == "projects")
    {
      if (!$this->canParticipate($user))
        return false;
      $parts = explode('/', $this->url);
      $auth = json_decode(file_get_contents($app->config["base_dir"]."/projects/".$parts[2]."/auth.json"), TRUE);
      $users = $auth["users"];
      $permissions = $users[$user["login"]];
      return ($permissions["admin_project"]);
    }
    else
      return false;
  }

  private function isOwner($user)
  {
    global $app;
    if ($this->getURLBase() == "users")
    {
      $parts = explode('/', $this->url);
      return ($user["login"] == $parts[2]);
    }
    else
      return false;
  }

  private function getURLBase()
  {
    $parts = explode('/', $this->url);
    return $parts[1];
  }

  private function isRootURL()
  {
    global $app;
    $parts = explode('/', $this->url);
    if ($this->getURLBase() == "users" && $parts[2] == $app->config["user_root"])
      return true;
    else
      return false;
  }

  private function canParticipate($user)
  {
    global $app;
    $parts = explode('/', $this->url);
    $auth = json_decode(file_get_contents($app->config["base_dir"].'/projects/'.$parts[2]."/auth.json"), TRUE);
    $users = $auth["users"];
    return (array_key_exists($user["login"], $users));
  }

  public function file_exists()
  {
    global $app;
    return (file_exists($app->config["base_dir"].$this->url));
  }

  public function link_exists()
  {
    global $app;
    return (is_link($app->config["base_dir"].$this->url));
  }

  public function rrmdir($dir){
    $files = array_diff(scandir($dir), array('.','..'));
    foreach ($files as $file) {
      (is_dir("$dir/$file")) ? $this->rrmdir("$dir/$file") : unlink("$dir/$file");
    }
    return rmdir($dir);
  }
}
?>

h


text:
using System;

namespace org.apache.lucene.analysis.miscellaneous
{

	using BaseTokenStreamFactoryTestCase = org.apache.lucene.analysis.util.BaseTokenStreamFactoryTestCase;

	public class TestLimitTokenCountFilterFactory : BaseTokenStreamFactoryTestCase
	{

//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void test() throws Exception
	  public virtual void test()
	  {
		foreach (bool consumeAll in new bool[]{true, false})
		{
		  Reader reader = new StringReader("A1 B2 C3 D4 E5 F6");
		  MockTokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
		  tokenizer.EnableChecks = consumeAll;
		  TokenStream stream = tokenizer;
		  stream = tokenFilterFactory("LimitTokenCount", LimitTokenCountFilterFactory.MAX_TOKEN_COUNT_KEY, "3", LimitTokenCountFilterFactory.CONSUME_ALL_TOKENS_KEY, Convert.ToString(consumeAll)).create(stream);
		  assertTokenStreamContents(stream, new string[]{"A1", "B2", "C3"});
		}
	  }

//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void testRequired() throws Exception
	  public virtual void testRequired()
	  {
		// param is required
		try
		{
		  tokenFilterFactory("LimitTokenCount");
		  fail();
		}
		catch (System.ArgumentException e)
		{
		  assertTrue("exception doesn't mention param: " + e.Message, 0 < e.Message.indexOf(LimitTokenCountFilterFactory.MAX_TOKEN_COUNT_KEY));
		}
	  }

	  /// <summary>
	  /// Test that bogus arguments result in exception
	  /// </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void testBogusArguments() throws Exception
	  public virtual void testBogusArguments()
	  {
		try
		{
		  tokenFilterFactory("LimitTokenCount", LimitTokenCountFilterFactory.MAX_TOKEN_COUNT_KEY, "3", "bogusArg", "bogusValue");
		  fail();
		}
		catch (System.ArgumentException expected)
		{
		  assertTrue(expected.Message.contains("Unknown parameters"));
		}
	  }
	}

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Administrator Order List</title>

    <link href="css/bootstrap.css" rel="stylesheet">

    <link href="css/small-business.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

                        About

                        Services

                        Contact

                        Registration

                        Login

HW-Race as Administrator

The administrator must check every order made by the costumers and approve or reject each
				sale, in order to get the order into the final step of selling the items selected by the costumer.

                    Welcome to the this interface, here you will be able to check the order requests from every costumer.
					As and admin. you must verify every order made by all our clients, and also approve or reject each order.
					The way you can approve a sale you will only get a click on the "approve button"s from the order you
					want to mark as approved and the status will change into "approved" and by now the costumer will be able to
					buy the items he/she ordered. And if you do not approve the sale, just click on the "rejected" button
					and by doing this, the costumer won't be able to buy the items.

Ordered Products List

Below this text you can see a table containing the different orders of each costumer.

Remember To Approve The Orders

This way the costumers will have the chance to purchase their items.

Update The Stock

Remember that you should and must have the control of the items available at the stock,
				this helps you out by avoiding the lack of items at your stck (making some sales unavailable to proceed).

Orders List

         HRcode
         Costumer's Name
         Sale Status

         #275
         Elvis Tek
         Pending

		 <input type="submit" value="Approve/Reject" class="pass-reset-submit btn btn-default btn-sm btn-mini button"/>

         #341
         Akiles Esquivel Madrazo
         Approved

         #582
         Ana Lisa Meltrozo
         Rejected

         #600
         Neil Anblomee
         Pending

		 <input type="submit" value="Approve/Reject" class="pass-reset-submit btn btn-default btn-sm btn-mini button"/>

Copyright © HW-Race 2015


text:
@class JavaMathBigInteger;
@class OrgBouncycastleMathEcECPoint;

@interface OrgBouncycastleMathEcWNafL2RMultiplier : OrgBouncycastleMathEcAbstractECMultiplier

#pragma mark Public

- (instancetype)init;

#pragma mark Protected

- (jint)getWindowSizeWithInt:(jint)bits;

- (OrgBouncycastleMathEcECPoint *)multiplyPositiveWithOrgBouncycastleMathEcECPoint:(OrgBouncycastleMathEcECPoint *)p
                                                            withJavaMathBigInteger:(JavaMathBigInteger *)k;

@end

J2OBJC_EMPTY_STATIC_INIT(OrgBouncycastleMathEcWNafL2RMultiplier)

FOUNDATION_EXPORT void OrgBouncycastleMathEcWNafL2RMultiplier_init(OrgBouncycastleMathEcWNafL2RMultiplier *self);

FOUNDATION_EXPORT OrgBouncycastleMathEcWNafL2RMultiplier *new_OrgBouncycastleMathEcWNafL2RMultiplier_init() NS_RETURNS_RETAINED;

J2OBJC_TYPE_LITERAL_HEADER(OrgBouncycastleMathEcWNafL2RMultiplier)

#endif // _OrgBouncycastleMathEcWNafL2RMultiplier_H_


text:
package io.vertx.ext.web.api.contract.openapi3.impl;

import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.vertx.core.Handler;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.api.contract.RouterFactoryException;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Francesco Guardiani @slinkydeveloper
 */
class SecurityHandlersStore {

  private class SecurityRequirementKey {
    private String name;
    private String oauth2Scope;

    public SecurityRequirementKey(String name, String oauth2Scope) {
      this.name = name;
      this.oauth2Scope = oauth2Scope;
    }

    public SecurityRequirementKey(String name) {
      this(name, null);
    }

    public String getName() {
      return name;
    }

    public String getScope() {
      return oauth2Scope;
    }

    public boolean hasScope() {
      return oauth2Scope != null;
    }

    @Override
    public boolean equals(Object o) {
      if (this == o) return true;
      if (o == null || getClass() != o.getClass()) return false;

      SecurityRequirementKey that = (SecurityRequirementKey) o;

      if (!name.equals(that.name)) return false;
      return Objects.equals(oauth2Scope, that.oauth2Scope);
    }

    @Override
    public int hashCode() {
      int result = name.hashCode();
      result = 31 * result + (oauth2Scope != null ? oauth2Scope.hashCode() : 0);
      return result;
    }

    private SecurityRequirementKey cloneWithoutScope() {
      return new SecurityRequirementKey(this.getName());
    }
  }

  private final Map<SecurityRequirementKey, List<Handler<RoutingContext>>> securityHandlers;

  SecurityHandlersStore() {
    this.securityHandlers = new HashMap<>();
  }

  protected void addSecurityRequirement(String name, String scope, Handler<RoutingContext> handler) {
    securityHandlers.computeIfAbsent(new SecurityRequirementKey(name, scope), k -> new ArrayList<>()).add(handler);
  }

  protected void addSecurityRequirement(String name, Handler<RoutingContext> handler) {
    securityHandlers.computeIfAbsent(new SecurityRequirementKey(name), k -> new ArrayList<>()).add(handler);
  }

  private List<Handler<RoutingContext>> mapWithFail(SecurityRequirementKey k) throws RouterFactoryException {
    if (k.hasScope())
      return Optional
        .ofNullable((this.securityHandlers.get(k) != null) ? this.securityHandlers.get(k) : this.securityHandlers.get(k.cloneWithoutScope()))
        .orElseThrow(() -> RouterFactoryException.createMissingSecurityHandler(k.getName(), k.getScope()));
    else
      return Optional.ofNullable(this.securityHandlers.get(k)).orElseThrow(() -> RouterFactoryException.createMissingSecurityHandler(k.getName()));
  }

  private List<Handler<RoutingContext>> mapWithoutFail(SecurityRequirementKey k) {
    if (k.hasScope())
      return Optional
        .ofNullable(this.securityHandlers.get(k))
        .orElseGet(() -> this.securityHandlers.get(k.cloneWithoutScope()));
    else
      return this.securityHandlers.get(k);
  }

  protected List<Handler<RoutingContext>> solveSecurityHandlers(List<SecurityRequirement> nonTranslatedKeys, boolean failOnNotFound) {
    List<SecurityRequirementKey> keys = this.translateRequirements(nonTranslatedKeys);
    if (keys != null) {
      if (failOnNotFound)
        return keys.stream().map(this::mapWithFail).flatMap(Collection::stream).collect(Collectors.toList());
      else
        return keys.stream().map(this::mapWithoutFail).filter(Objects::nonNull).flatMap(Collection::stream).collect(Collectors.toList());
    } else
      return new ArrayList<>();
  }

  private List<SecurityRequirementKey> translateRequirements(List<SecurityRequirement> keys) {
    if (keys != null)
      return keys.stream()
        .flatMap(m -> m.entrySet().stream().flatMap(e -> {
          if (e.getValue() == null || e.getValue().size() == 0)
            return Stream.of(new SecurityRequirementKey(e.getKey()));
          else
            return e.getValue().stream().map(s -> new SecurityRequirementKey(e.getKey(), s));
        }))
        .collect(Collectors.toList());
    else
      return new ArrayList<>();
  }

}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using NUnit.Framework;
using SourceIndexingSharp.Indexing.Stash;

namespace SourceIndexingSharp.Tests
{
    [TestFixture]
    public class StashIndexingTests : TestBase
    {
        IStashApi _stashApi;

        [Test, Ignore("A real password is needed to validate this test")]
        public void Can_retrieve_raw_source_file_from_http()
        {
            // arrange
            var destination = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App.xaml");
            if(File.Exists(destination))
                File.Delete(destination);

            // act
            _stashApi.ExtractSource(destination, "stash.medxchange.com", "EVO", "Software", "Src/MedXChange.Evo.Presentation/App.xaml", "5fadaa3dd87b817863253745ae67b1a29efbb1ca", new StashCredentials("pknopf", "youwish!"));

            // assert
            Assert.That(File.Exists(destination));
            Assert.That(File.ReadAllText(destination), Is.StringStarting("<?xml version=\"1.0\" encoding=\"utf-8\"?>"));
        }

        public override void Setup()
        {
            base.Setup();
            _stashApi = new StashApi();
        }
    }
}


text:
package com.vishalaksh.flashlight;

import com.vishalaksh.flashlight.R;

import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class ActivityMain extends Activity {

	private final static String LOG_TAG = "FlashLight";

	private Camera mCamera;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_activity_main);
		mCamera = Camera.open();
		flashOn();

	}

	@Override
	protected void onRestart() {

		mCamera = Camera.open();
		flashOn();
		super.onRestart();
	}

	private void processOffClick() {
		Log.d(LOG_TAG, "processOffClick() called");
		if (mCamera != null) {
			Parameters params = mCamera.getParameters();
			params.setFlashMode(Parameters.FLASH_MODE_OFF);
			mCamera.setParameters(params);
			mCamera.stopPreview();

		}
	}

	private void flashOn() {
		Log.d(LOG_TAG, "processOnClick() called");
		if (mCamera != null) {
			Parameters params = mCamera.getParameters();
			params.setFlashMode(Parameters.FLASH_MODE_ON);
			mCamera.setParameters(params);
			mCamera.startPreview();
			registerCameraAutoFocus(mCamera, new Handler());
			processOffClick();

		}
	}

	@Override
	protected void onStop() {
		if (mCamera != null) {
			mCamera.release();
			mCamera = null;
		}
		super.onStop();
	}

	void registerCameraAutoFocus(Camera camera, Handler h) {
		Log.d(LOG_TAG, "going to register for autofocus");
		AutoFocusCallback autoFocusCallback = new AutoFocusCallback();
		autoFocusCallback.setHandler(h, 0);
		camera.autoFocus(autoFocusCallback);
	}

	class AutoFocusCallback implements Camera.AutoFocusCallback {

		private Handler autoFocusHandler;
		private int autoFocusMessage;

		void setHandler(Handler autoFocusHandler, int autoFocusMessage) {
			this.autoFocusHandler = autoFocusHandler;
			this.autoFocusMessage = autoFocusMessage;
		}

		public void onAutoFocus(boolean success, Camera camera) {
			Log.d(LOG_TAG, "camera autofocussed");
			Message message = autoFocusHandler.obtainMessage(autoFocusMessage,
					success);
			autoFocusHandler.sendMessage(message);

		}
	}
}


text:
package jsystem.runner.agent.mediators;

import java.util.logging.Logger;

import jsystem.framework.report.ExecutionListener;
import jsystem.framework.report.TestInfo;
import jsystem.framework.scenario.JTestContainer;
import jsystem.framework.scenario.RunnerTest;
import jsystem.framework.scenario.flow_control.AntForLoop;
import jsystem.runner.ErrorLevel;
import jsystem.runner.agent.notifications.EndRunNotification;
import jsystem.runner.agent.notifications.ErrorInExecutionNotification;
import jsystem.runner.agent.notifications.ExecutionEndedNotification;
import jsystem.runner.agent.notifications.NotificationLevel;
import jsystem.runner.agent.notifications.RemoteExitNotification;
import jsystem.runner.agent.notifications.RemotePauseNotification;
import jsystem.runner.agent.notifications.StartTestNotification;
import jsystem.runner.agent.server.RunnerAgent;
import junit.framework.AssertionFailedError;
import junit.framework.Test;

/**
 * Listens for general execution events, converts them to JMX notifications
 * and dispatches the notifications.
 * @author goland
 */
public class ExecutionListenerMediator extends BaseMediator implements ExecutionListener {

	private static Logger log = Logger.getLogger(RunnerTest.class.getName());

	public ExecutionListenerMediator(RunnerAgent agent){
		super(agent);
	}

	public void errorOccured(String title, String message, ErrorLevel level) {
		log.finest("errorOccured(String title, String message, ErrorLevel level)");
		sendNotification(new ErrorInExecutionNotification(runnerAgent().getClass().getName(),message,title,level));

	}

	public void executionEnded(String scenarioName) {
		log.finest("executionEnded()");
		sendNotification(new ExecutionEndedNotification(runnerAgent().getClass().getName(),scenarioName));
	}

	public void remoteExit() {
		log.finest("remoteExit()");
		sendNotification(new RemoteExitNotification(runnerAgent().getClass().getName()));
	}

	public void remotePause() {
		log.finest("remotePause()");
		sendNotification(new RemotePauseNotification(runnerAgent().getClass().getName()));
	}

	public void addWarning(Test test) {
		// TODO Auto-generated method stub

	}

	public void endRun() {
		log.finest("endRun()");
		sendNotification(new EndRunNotification(runnerAgent().getClass().getName()));

	}

	public void startTest(TestInfo testInfo) {
		if (NotificationLevel.getCurrentNotificationLevel().equals(NotificationLevel.NO_TEST_INDICATION)){
			return;
		}
		log.finest("startTest(String className, String methodName, String meaningfulName, String comment,String paramString, int count) - sent");
		sendNotification(new StartTestNotification(runnerAgent().getClass().getName(),testInfo));
	}

	public void addError(Test arg0, Throwable arg1) {
	}

	public void addFailure(Test arg0, AssertionFailedError arg1) {
	}

	public void endTest(Test arg0) {
	}

	public void startTest(Test arg0) {

	}

	@Override
	public void endContainer(JTestContainer container) {
		// TODO Auto-generated method stub

	}

	@Override
	public void endLoop(AntForLoop loop, int count) {
		// TODO Auto-generated method stub

	}

	@Override
	public void startContainer(JTestContainer container) {
		// TODO Auto-generated method stub

	}

	@Override
	public void startLoop(AntForLoop loop, int count) {
		// TODO Auto-generated method stub

	}

}


text:
import ThemeSwitcher from "./ThemeSwitcher"

export default ThemeSwitcher


text:
package com.oakhole.auth.entity;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import java.io.Serializable;

/**
 * @author Oakhole
 * @since 1.0
 */
@MappedSuperclass
public abstract class IdEntity implements Serializable {

    private long id;
    private boolean deleted;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public boolean isDeleted() {
        return deleted;
    }

    public void setDeleted(boolean deleted) {
        this.deleted = deleted;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof IdEntity)) return false;

        IdEntity idEntity = (IdEntity) o;

        if (id != idEntity.id) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return (int) (id ^ (id >>> 32));
    }

    @Override
    public String toString() {
        return super.toString();
    }
}


text:
`Node`s, `Path`s and `Step`s, are the three core parts of any VG graph in RDF.
A `Node` in the VG RDF corresponds directly to the Node concept in the VG protobuf serialization.
`Paths` are a number of `Step`s that represent a sequence of Node visits that generate a linear biological sequence.
Each `Step` connects a `Node` into a `Path`

## Annotations on a VG

Path are annotations on the graph, some paths represent a reference genome, others are the genome of a patient.
Yet some represent a gene, regulatory element or any other feature that we can annotate on any biological sequence.

For example lets say we have a small VG graph:

```turtle
node:100 a vg:Node ; vg:linksForwardToForward node:101 ; rdf:value "ACT" .
node:101 a vg:Node ; vg:linksForwardToForward node:102 : rdf:value "TGAAGT" .
node:102 a vg:Node ; vg:linksForwardToForward node:103 ; rdf:value "A" .
node:103 a vg:Node ; vg:linksForwardToForward node:104 ; rdf:value "TGA" .

alternative_node:103 a vg:Node ; vg:linksForwardToForward node:104 ; rdf:value "A" .
node:102 a vg:Node ; vg:linksForwardToForward alternative_node:103 .

```
In this example node:101 to node:104 are on the reference genome path.
They are also annotated to be a gene coding region.

```turtle
@prefix ex:<an  example ontology, could be SO> .

my_example:some_gene a ex:Gene, SO:Gene, vg:Path .
my_example:some_gene_step_1 a vg:Step ; vg:rank 1;vg:node node:101 .
my_example:some_gene_step_2 a vg:Step ; vg:rank 2;vg:node node:102 .
my_example:some_gene_step_3 a vg:Step ; vg:rank 3;vg:node node:103 .
my_example:some_gene_step_4 a vg:Step ; vg:rank 4;vg:node node:104 .

me:example:some_gene rdfs:seeAlso ENSEMBL:ESG00000XXXX . #and then pick up the annotation from the ENSEMBL gene build.
```

## Examples of using VG RDF

[2 ecoli genomes, with ensembl and uniprot annotation](https://github.com/vgteam/vg/wiki/VG-RDF,-the-Ensembl-bacteria-E.-coli-genome-hack-attack)

## VG RDF limitations

At this moment VG RDF wants a fully embedded variation graph. e.g. all positions in vg json have a single edit which covers a whole node. This is to enable easy SPARQL queries where substring operations are rarely used.

## Annotations on Pantograph

On top of VG RDF, we can describe the same path information on Pantograph format as well.

```ttl
<vg/zoom10> a vg:ZoomLevel ;
   vg:components <vg/zoom10/component1>, <vg/zoom10/component2> ;
   vg:zoomFactor 10 .
<vg/zoom1000> a vg:ZoomLevel ;
   vg:components <vg/zoom1000/component1>, <vg/zoom1000/component2> ;
   vg:zoomFactor 1000 . // zoomFactor is binWidth here.
<vg/zoom1000/component1> a vg:Component ;
   vg:componentRank 1 ;   # The order of component is inferred by rank.
   vg:forwardComponentEdge <vg/zoom1000/component2> ;
   vg:bins <vg/zoom1000/component1/bin1>, <vg/zoom1000/component1/bin2> .
<vg/zoom1000/component1/bin1> a vg:Bin ;
   vg:forwardBinEdge <vg/zoom1000/component2/bin2> ;
   vg:binRank 1 ;
   vg:cells <vg/zoom1000/component1/bin1/cell1>, <vg/zoom1000/component1/bin1/cell2> .
<vg/zoom1000/component2/bin2> a vg:Bin ;
   vg:reverseBinEdge <vg/zoom1000/component2/bin3> ;
   vg:forwardBinEdge <vg/zoom1000/component2/bin3> ;
   vg:binRank 2 ;
   vg:cells <vg/zoom1000/component1/bin2/cell1>, <vg/zoom1000/component1/bin2/cell2> .
<vg/zoom1000/component1/bin1/cell1> a vg:Cell ;
   vg:positionPercent 0.04 ;
   vg:inversionPercent 0.98 ;
   vg:cellRegion <path1/region/6-100> .  # To infer firstNucleotide and last Nucleotide. faldo:begin of stepRegion is the first position. faldo:end of cellRegion is the last position.
<vg/zoom1000/link1> a vg:Link ; # This is a non-linear connection between Bins.
   vg:arrival <vg/zoom1000/component1/bin1> ;
   vg:departure <vg/zoom1000/component2/bin2> ;
   vg:forwardLinkEdge <vg/zoom1000/link2> ;
   vg:linkRank 1 ;
   vg:linkPaths <path1> <path2> ; # Participants of the link
   vg:linkZoomLevel <vg/zoom10> .
<path1/region/6-100> a faldo:Region ;
   faldo:begin <path1/position/6>  ;
   faldo:end <path1/position/100>  .
```


text:
Copyright 2004 ludovico magnocavallo

The software is licensed according to the terms of the PSF (Python Software Foundation) license found here: http://www.python.org/psf/license/


text:
package org.apache.jmeter.protocol.http.control;

import java.net.URL;

import org.apache.jmeter.junit.JMeterTestCase;
import org.apache.jmeter.testelement.property.CollectionProperty;

public class TestAuthManager extends JMeterTestCase {
        public TestAuthManager(String name) {
            super(name);
        }

        public void testHttp() throws Exception {
            assertTrue(AuthManager.isSupportedProtocol(new URL("http:")));
        }

        public void testHttps() throws Exception {
            assertTrue(AuthManager.isSupportedProtocol(new URL("https:")));
        }

        public void testFile() throws Exception {
            AuthManager am = new AuthManager();
            CollectionProperty ao = am.getAuthObjects();
            assertEquals(0, ao.size());
            am.addFile(findTestPath("testfiles/TestAuth.txt"));
            assertEquals(9, ao.size());
            Authorization at;
            at = am.getAuthForURL(new URL("http://a.b.c/"));
            assertEquals("login", at.getUser());
            assertEquals("password", at.getPass());
            at = am.getAuthForURL(new URL("http://a.b.c:80/")); // same as above
            assertEquals("login", at.getUser());
            assertEquals("password", at.getPass());
            at = am.getAuthForURL(new URL("http://a.b.c:443/"));// not same
            assertNull(at);
            at = am.getAuthForURL(new URL("http://a.b.c/1"));
            assertEquals("login1", at.getUser());
            assertEquals("password1", at.getPass());
            assertEquals("", at.getDomain());
            assertEquals("", at.getRealm());
            at = am.getAuthForURL(new URL("http://d.e.f/"));
            assertEquals("user", at.getUser());
            assertEquals("pass", at.getPass());
            assertEquals("domain", at.getDomain());
            assertEquals("realm", at.getRealm());
            at = am.getAuthForURL(new URL("https://j.k.l/"));
            assertEquals("jkl", at.getUser());
            assertEquals("pass", at.getPass());
            at = am.getAuthForURL(new URL("https://j.k.l:443/"));
            assertEquals("jkl", at.getUser());
            assertEquals("pass", at.getPass());
            at = am.getAuthForURL(new URL("https://l.m.n/"));
            assertEquals("lmn443", at.getUser());
            assertEquals("pass", at.getPass());
            at = am.getAuthForURL(new URL("https://l.m.n:443/"));
            assertEquals("lmn443", at.getUser());
            assertEquals("pass", at.getPass());
            at = am.getAuthForURL(new URL("https://l.m.n:8443/"));
            assertEquals("lmn8443", at.getUser());
            assertEquals("pass", at.getPass());
        }
}