text:
namespace Pythia8 {

//==========================================================================

// Particle class.
// This class holds info on a particle in general.

//--------------------------------------------------------------------------

// Constants: could be changed here if desired, but normally should not.
// These are of technical nature, as described for each.

// Small number to avoid division by zero.
const double Particle::TINY = 1e-20;

//--------------------------------------------------------------------------

// Set pointer to the particle data species of the particle.

void Particle::setPDEPtr(ParticleDataEntry* pdePtrIn) {
  pdePtr = pdePtrIn; if (pdePtrIn != 0 || evtPtr == 0) return;
  pdePtr = (*evtPtr).particleDataPtr->particleDataEntryPtr( idSave);}

//--------------------------------------------------------------------------

// Functions for rapidity and pseudorapidity.

double Particle::y() const {
  double temp = log( ( pSave.e() + abs(pSave.pz()) ) / max( TINY, mT() ) );
  return (pSave.pz() > 0) ? temp : -temp;
}

double Particle::eta() const {
  double temp = log( ( pSave.pAbs() + abs(pSave.pz()) ) / max( TINY, pT() ) );
  return (pSave.pz() > 0) ? temp : -temp;
}

//--------------------------------------------------------------------------

// Method to find the index of the particle in the event record.

int Particle::index() const { if (evtPtr == 0) return -1;
  return (long(this) - long(&((*evtPtr)[0]))) / sizeof(Particle);
}

//--------------------------------------------------------------------------

// Trace the first and last copy of one and the same particle.

int Particle::iTopCopy() const {

  if (evtPtr == 0) return -1;
  int iUp = index();
  while ( iUp > 0 && (*evtPtr)[iUp].mother2() == (*evtPtr)[iUp].mother1()
    && (*evtPtr)[iUp].mother1() > 0) iUp = (*evtPtr)[iUp].mother1();
  return iUp;

}

int Particle::iBotCopy() const {

  if (evtPtr == 0) return -1;
  int iDn = index();
  while ( iDn > 0 && (*evtPtr)[iDn].daughter2() == (*evtPtr)[iDn].daughter1()
    && (*evtPtr)[iDn].daughter1() > 0) iDn = (*evtPtr)[iDn].daughter1();
  return iDn;

}

//--------------------------------------------------------------------------

// Trace the first and last copy of one and the same particle,
// also through shower branchings, making use of flavour matches.
// Stops tracing when this gives ambiguities.

int Particle::iTopCopyId( bool simplify) const {

  // Check that particle belongs to event record. Initialize.
  if (evtPtr == 0) return -1;
  int iUp = index();

  // Simple solution when only first and last mother are studied.
  if (simplify) for ( ; ; ) {
    int mother1up = (*evtPtr)[iUp].mother1();
    int id1up     = (mother1up > 0) ? (*evtPtr)[mother1up].id() : 0;
    int mother2up = (*evtPtr)[iUp].mother2();
    int id2up     = (mother2up > 0) ? (*evtPtr)[mother2up].id() : 0;
    if (mother2up != mother1up && id2up == id1up) return iUp;
    if (id1up != idSave && id2up != idSave) return iUp;
    iUp = (id1up == idSave) ?  mother1up : mother2up;
  }

  // Else full solution where all mothers are studied.
  for ( ; ; ) {
    int iUpTmp  = 0;
    vector<int> mothersTmp = (*evtPtr)[iUp].motherList();
    for (unsigned int i = 0; i < mothersTmp.size(); ++i)
    if ( (*evtPtr)[mothersTmp[i]].id() == idSave) {
      if (iUpTmp != 0) return iUp;
      iUpTmp = mothersTmp[i];
    }
    if (iUpTmp == 0) return iUp;
    iUp = iUpTmp;
  }

}

int Particle::iBotCopyId( bool simplify) const {

  // Check that particle belongs to event record. Initialize.
  if (evtPtr == 0) return -1;
  int iDn = index();

  // Simple solution when only first and last daughter are studied.
  if (simplify) for ( ; ; ) {
    int daughter1dn = (*evtPtr)[iDn].daughter1();
    int id1dn       = (daughter1dn > 0) ? (*evtPtr)[daughter1dn].id() : 0;
    int daughter2dn = (*evtPtr)[iDn].daughter2();
    int id2dn       = (daughter2dn > 0) ? (*evtPtr)[daughter2dn].id() : 0;
    if (daughter2dn != daughter1dn && id2dn == id1dn) return iDn;
    if (id1dn != idSave && id2dn != idSave) return iDn;
    iDn = (id1dn == idSave) ?  daughter1dn : daughter2dn;
  }

  // Else full solution where all daughters are studied.
  for ( ; ; ) {
    int iDnTmp  = 0;
    vector<int> daughtersTmp = (*evtPtr)[iDn].daughterList();
    for (unsigned int i = 0; i < daughtersTmp.size(); ++i)
    if ( (*evtPtr)[daughtersTmp[i]].id() == idSave) {
      if (iDnTmp != 0) return iDn;
      iDnTmp = daughtersTmp[i];
    }
    if (iDnTmp == 0) return iDn;
    iDn = iDnTmp;
  }

}

//--------------------------------------------------------------------------

// Find complete list of mothers.

vector<int> Particle::motherList() const {

  // Vector of all the mothers; created empty. Done if no event pointer.
  vector<int> motherVec;
  if (evtPtr == 0) return motherVec;

  // Special cases in the beginning, where the meaning of zero is unclear.
  int statusSaveAbs = abs(statusSave);
  if  (statusSaveAbs == 11 || statusSaveAbs == 12) ;
  else if (mother1Save == 0 && mother2Save == 0) motherVec.push_back(0);

  // One mother or a carbon copy.
  else if (mother2Save == 0 || mother2Save == mother1Save)
    motherVec.push_back(mother1Save);

  // A range of mothers from string fragmentation.
  else if ( (statusSaveAbs >  80 && statusSaveAbs <  90)
         || (statusSaveAbs > 100 && statusSaveAbs < 107) )
    for (int iRange = mother1Save; iRange <= mother2Save; ++iRange)
      motherVec.push_back(iRange);

  // Two separate mothers.
  else {
    motherVec.push_back( min(mother1Save, mother2Save) );
    motherVec.push_back( max(mother1Save, mother2Save) );
  }

  // Done.
  return motherVec;

}

//--------------------------------------------------------------------------

// Find complete list of daughters.

vector<int> Particle::daughterList() const {

  // Vector of all the daughters; created empty. Done if no event pointer.
  vector<int> daughterVec;
  if (evtPtr == 0) return daughterVec;

  // Simple cases: no or one daughter.
  if (daughter1Save == 0 && daughter2Save == 0) ;
  else if (daughter2Save == 0 || daughter2Save == daughter1Save)
    daughterVec.push_back(daughter1Save);

  // A range of daughters.
  else if (daughter2Save > daughter1Save)
    for (int iRange = daughter1Save; iRange <= daughter2Save; ++iRange)
      daughterVec.push_back(iRange);

  // Two separated daughters.
  else {
    daughterVec.push_back(daughter2Save);
    daughterVec.push_back(daughter1Save);
  }

  // Special case for two incoming beams: attach further
  // initiators and remnants that have beam as mother.
  if (abs(statusSave) == 12 || abs(statusSave) == 13) {
    int i = index();
    for (int iDau = i + 1; iDau < evtPtr->size(); ++iDau)
    if ((*evtPtr)[iDau].mother1() == i) {
      bool isIn = false;
      for (int iIn = 0; iIn < int(daughterVec.size()); ++iIn)
        if (iDau == daughterVec[iIn]) isIn = true;
      if (!isIn) daughterVec.push_back(iDau);
    }
  }

  // Done.
  return daughterVec;

}

//--------------------------------------------------------------------------

// Find complete list of sisters. Optionally traces up with iTopCopy
// and down with iBotCopy to give sisters at same level of evolution.

vector<int> Particle::sisterList(bool traceTopBot) const {

  // Vector of all the sisters; created empty.
  vector<int> sisterVec;
  if (evtPtr == 0 || abs(statusSave) == 11) return sisterVec;

  // Find all daughters of the mother.
  int iUp     = (traceTopBot) ? iTopCopy() : index();
  int iMother = (*evtPtr)[iUp].mother1();
  vector<int> daughterVec = (*evtPtr)[iMother].daughterList();

  // Copy all daughters, excepting the input particle itself.
  for (int j = 0; j < int(daughterVec.size()); ++j) {
    int iDau  = daughterVec[j];
    if (iDau != iUp) {
      int iDn = (traceTopBot) ? (*evtPtr)[iDau].iBotCopy() : iDau;
      sisterVec.push_back( iDn);
    }
  }

  // Done.
  return sisterVec;

}

//--------------------------------------------------------------------------

// Check whether a given particle is an arbitrarily-steps-removed
// mother to another. For the parton -> hadron transition, only
// first-rank hadrons are associated with the respective end quark.

bool Particle::isAncestor(int iAncestor) const {

  // Begin loop to trace upwards from the daughter.
  if (evtPtr == 0) return false;
  int iUp = index();
  int sizeNow = (*evtPtr).size();
  for ( ; ; ) {

    // If positive match then done.
    if (iUp == iAncestor) return true;

    // If out of range then failed to find match.
    if (iUp <= 0 || iUp > sizeNow) return false;

    // If unique mother then keep on moving up the chain.
    int mother1up = (*evtPtr)[iUp].mother1();
    int mother2up = (*evtPtr)[iUp].mother2();
    if (mother2up == mother1up || mother2up == 0) {iUp = mother1up; continue;}

    // If many mothers, except hadronization, then fail tracing.
    int statusUp = (*evtPtr)[iUp].statusAbs();
    if (statusUp < 81 || statusUp > 86) return false;

    // For hadronization step, fail if not first rank, else move up.
    if (statusUp == 82) {
      iUp = (iUp + 1 < sizeNow && (*evtPtr)[iUp + 1].mother1() == mother1up)
          ? mother1up : mother2up; continue;
    }
    if (statusUp == 83) {
      if ((*evtPtr)[iUp - 1].mother1() == mother1up) return false;
      iUp = mother1up; continue;
    }
    if (statusUp == 84) {
      if (iUp + 1 < sizeNow && (*evtPtr)[iUp + 1].mother1() == mother1up)
        return false;
      iUp = mother1up; continue;
    }

    // Fail for ministring -> one hadron and for junctions.
    return false;

  }
  // End of loop. Should never reach beyond here.
  return false;

}

//--------------------------------------------------------------------------

// Convert internal Pythia status codes to the HepMC status conventions.

int Particle::statusHepMC() const {

  // Positive codes are final particles. Status -12 are beam particles.
  if (statusSave > 0)    return 1;
  if (statusSave == -12) return 4;
  if (evtPtr == 0) return 0;

  // Hadrons, muons, taus that decay normally are status 2.
  if (isHadron() || abs(idSave) == 13 || abs(idSave) == 15) {
    // Particle should not decay into itself  (e.g. Bose-Einstein).
    if ( (*evtPtr)[daughter1Save].id() != idSave) {
      int statusDau = (*evtPtr)[daughter1Save].statusAbs();
      if (statusDau > 90 && statusDau < 95) return 2;
    }
  }

  // Other acceptable negative codes as their positive counterpart.
  if (statusSave <= -11 && statusSave >= -200) return -statusSave;

  // Unacceptable codes as 0.
  return 0;

}

//--------------------------------------------------------------------------

// Check if particle belonged to the final state at the Parton Level.

bool Particle::isFinalPartonLevel() const {

  if (index() >= evtPtr->savedPartonLevelSize) return false;
  if (statusSave > 0) return true;
  if (daughter1Save >= evtPtr->savedPartonLevelSize) return true;
  return false;

}

//--------------------------------------------------------------------------

// Recursively remove the decay products of a particle, update it to be
// undecayed, and update all mother/daughter indices to be correct.
// Warning: assumes that decay chains are nicely ordered.

bool Particle::undoDecay() {

  // Do not remove daughters of a parton, i.e. entry carrying colour.
  if (evtPtr == 0) return false;
  int i = index();
  if (i < 0 || i >= int((*evtPtr).size())) return false;
  if (colSave != 0 || acolSave != 0) return false;

  // Find range of daughters to remove.
  int dau1 = daughter1Save;
  if (dau1 == 0) return false;
  int dau2 = daughter2Save;
  if (dau2 == 0) dau2 = dau1;

  // Refuse if any of the daughters have other mothers.
  for (int j = dau1; j <= dau2; ++j) if ((*evtPtr)[j].mother1() != i
    || ((*evtPtr)[j].mother2() != i && (*evtPtr)[j].mother2() != 0) )
    return false;

  // Initialize range arrays for daughters and granddaughters.
  vector<int> dauBeg, dauEnd;
  dauBeg.push_back( dau1);
  dauEnd.push_back( dau2);

  // Begin recursive search through all decay chains.
  int iRange = 0;
  do {
    for (int j = dauBeg[iRange]; j <= dauEnd[iRange]; ++j)
    if ((*evtPtr)[j].status() < 0) {

      // Find new daughter range, if present.
      dau1 = (*evtPtr)[j].daughter1();
      if (dau1 == 0) return false;
      dau2 = (*evtPtr)[j].daughter2();
      if (dau2 == 0) dau2 = dau1;

      // Check if the range duplicates or contradicts existing ones.
      bool isNew = true;
      for (int iR = 0; iR < int(dauBeg.size()); ++iR) {
        if (dau1 == dauBeg[iR] && dau2 == dauEnd[iR]) isNew = false;
        else if (dau1 >= dauBeg[iR] && dau1 <= dauEnd[iR]) return false;
        else if (dau2 >= dauBeg[iR] && dau2 <= dauEnd[iR]) return false;
      }

      // Add new range where relevant. Keep ranges ordered.
      if (isNew) {
        dauBeg.push_back( dau1);
        dauEnd.push_back( dau2);
        for (int iR = int(dauBeg.size()) - 1; iR > 0; --iR) {
          if (dauBeg[iR] < dauBeg[iR - 1]) {
            swap( dauBeg[iR], dauBeg[iR - 1]);
            swap( dauEnd[iR], dauEnd[iR - 1]);
          } else break;
        }
      }

    // End of recursive search all decay chains.
    }
  } while (++iRange < int(dauBeg.size()));

  // Join adjacent ranges to reduce number of erase steps.
  if (int(dauBeg.size()) > 1) {
    int iRJ = 0;
    do {
      if (dauEnd[iRJ] + 1 == dauBeg[iRJ + 1]) {
        for (int iRB = iRJ + 1; iRB < int(dauBeg.size()) - 1; ++iRB)
          dauBeg[iRB] = dauBeg[iRB + 1];
        for (int iRE = iRJ; iRE < int(dauEnd.size()) - 1; ++iRE)
          dauEnd[iRE] = dauEnd[iRE + 1];
        dauBeg.pop_back();
        dauEnd.pop_back();
      } else ++iRJ;
    } while (iRJ < int(dauBeg.size()) - 1);
  }

  // Iterate over relevant ranges, from bottom up.
  for (int iR = int(dauBeg.size()) - 1; iR >= 0; --iR) {
    dau1 = dauBeg[iR];
    dau2 = dauEnd[iR];
    int nRem = dau2 - dau1 + 1;

    // Remove daughters in each range.
    (*evtPtr).remove( dau1, dau2);

    // Update subsequent history to account for removed indices.
    for (int j = 0; j < int((*evtPtr).size()); ++j) {
      if ((*evtPtr)[j].mother1() > dau2)
        (*evtPtr)[j].mother1( (*evtPtr)[j].mother1() - nRem );
      if ((*evtPtr)[j].mother2() > dau2)
        (*evtPtr)[j].mother2( (*evtPtr)[j].mother2() - nRem );
      if ((*evtPtr)[j].daughter1() > dau2)
        (*evtPtr)[j].daughter1( (*evtPtr)[j].daughter1() - nRem );
      if ((*evtPtr)[j].daughter2() > dau2)
        (*evtPtr)[j].daughter2( (*evtPtr)[j].daughter2() - nRem );
    }
  }

  // Update mother that has been undecayed.
  statusSave = abs(statusSave);
  daughter1Save = 0;
  daughter2Save = 0;

  // Done.
  return true;

}

//--------------------------------------------------------------------------

// Particle name, with status but imposed maximum length -> may truncate.

string Particle::nameWithStatus(int maxLen) const {

  if (pdePtr == 0) return " ";
  string temp = (statusSave > 0) ? pdePtr->name(idSave)
    : "(" + pdePtr->name(idSave) + ")";
  while (int(temp.length()) > maxLen) {
    // Remove from end, excluding closing bracket and charge.
    int iRem = temp.find_last_not_of(")+-0");
    temp.erase(iRem, 1);
  }
  return temp;
}

//--------------------------------------------------------------------------

// Add offsets to mother and daughter pointers (must be non-negative).

void Particle::offsetHistory( int minMother, int addMother, int minDaughter,
  int addDaughter) {

  if (addMother < 0 || addDaughter < 0) return;
  if (  mother1Save > minMother  )   mother1Save += addMother;
  if (  mother2Save > minMother  )   mother2Save += addMother;
  if (daughter1Save > minDaughter) daughter1Save += addDaughter;
  if (daughter2Save > minDaughter) daughter2Save += addDaughter;

}

//--------------------------------------------------------------------------

// Add offsets to colour and anticolour (must be positive).

void Particle::offsetCol( int addCol) {

  if (addCol < 0) return;
  if ( colSave > 0)  colSave += addCol;
  if (acolSave > 0) acolSave += addCol;

}

//--------------------------------------------------------------------------

// Invariant mass of a pair and its square.
// (Not part of class proper, but tightly linked.)

double m(const Particle& pp1, const Particle& pp2) {
  double m2 = pow2(pp1.e() + pp2.e()) - pow2(pp1.px() + pp2.px())
     - pow2(pp1.py() + pp2.py()) - pow2(pp1.pz() + pp2.pz());
  return (m2 > 0. ? sqrt(m2) : 0.);
}

double m2(const Particle& pp1, const Particle& pp2) {
  double m2 = pow2(pp1.e() + pp2.e()) - pow2(pp1.px() + pp2.px())
     - pow2(pp1.py() + pp2.py()) - pow2(pp1.pz() + pp2.pz());
  return m2;
}

//==========================================================================

// Event class.
// This class holds info on the complete event record.

//--------------------------------------------------------------------------

// Constants: could be changed here if desired, but normally should not.
// These are of technical nature, as described for each.

// Maxmimum number of mothers or daughter indices per line in listing.
const int Event::IPERLINE = 20;

//--------------------------------------------------------------------------

// Copy all information from one event record to another.

Event& Event::operator=( const Event& oldEvent) {

  // Do not copy if same.
  if (this != &oldEvent) {

    // Reset all current info in the event.
    clear();

    // Copy particle data table; needed for individual particles.
    particleDataPtr     = oldEvent.particleDataPtr;

    // Copy all the particles one by one.
    maxColTag = 100;
    for (int i = 0; i < oldEvent.size(); ++i) append( oldEvent[i] );

    // Copy all the junctions one by one.
    for (int i = 0; i < oldEvent.sizeJunction(); ++i)
      appendJunction( oldEvent.getJunction(i) );

    // Copy all other values.
    startColTag         = oldEvent.startColTag;
    maxColTag           = oldEvent.maxColTag;
    savedSize           = oldEvent.savedSize;
    savedJunctionSize   = oldEvent.savedJunctionSize;
    scaleSave           = oldEvent.scaleSave;
    scaleSecondSave     = oldEvent.scaleSecondSave;
    headerList          = oldEvent.headerList;

  // Done.
  }
  return *this;

}

//--------------------------------------------------------------------------

// Add a copy of an existing particle at the end of the event record;
// return index. Three cases, depending on sign of new status code:
// Positive: copy is viewed as daughter, status of original is negated.
// Negative: copy is viewed as mother, status of original is unchanged.
// Zero: the new is a perfect carbon copy (maybe to be changed later).

int Event::copy(int iCopy, int newStatus) {

  // Protect against attempt to copy negative entries (e.g., junction codes)
  // or entries beyond end of record.
  if (iCopy < 0 || iCopy >= size()) return -1;

  // Simple carbon copy.
  entry.push_back(entry[iCopy]);
  int iNew = entry.size() - 1;

  // Set up to make new daughter of old.
  if (newStatus > 0) {
    entry[iCopy].daughters(iNew,iNew);
    entry[iCopy].statusNeg();
    entry[iNew].mothers(iCopy, iCopy);
    entry[iNew].status(newStatus);

  // Set up to make new mother of old.
  } else if (newStatus < 0) {
    entry[iCopy].mothers(iNew,iNew);
    entry[iNew].daughters(iCopy, iCopy);
    entry[iNew].status(newStatus);
  }

  // Done.
  return iNew;

}

//--------------------------------------------------------------------------

// Print an event - special cases that rely on the general method.
// Not inline to make them directly callable in (some) debuggers.

void Event::list(int precision) const {
  list(false, false, cout, precision);
}

void Event::list(ostream& os, int precision) const {
  list(false, false, os, precision);
}

void Event::list(bool showScaleAndVertex, bool showMothersAndDaughters,
  int precision) const {
  list(showScaleAndVertex, showMothersAndDaughters, cout, precision);
}

//--------------------------------------------------------------------------

// Print an event.

void Event::list(bool showScaleAndVertex, bool showMothersAndDaughters,
  ostream& os, int precision) const {

  // Header.
  os << "\n --------  PYTHIA Event Listing  " << headerList << "----------"
     << "-------------------------------------------------\n \n    no    "
     << "    id   name            status     mothers   daughters     colou"
     << "rs      p_x        p_y        p_z         e          m \n";
  if (showScaleAndVertex)
    os << "                                    scale         pol          "
       << "                   xProd      yProd      zProd      tProd      "
       << " tau\n";

  // Precision. At high energy switch to scientific format for momenta.
  int prec = max( 3, precision);
  bool useFixed = (entry.empty() || entry[0].e() < 1e5);

  // Listing of complete event.
  Vec4 pSum;
  double chargeSum = 0.;
  for (int i = 0; i < int(entry.size()); ++i) {
    const Particle& pt = entry[i];

    // Basic line for a particle, always printed.
    os << setw(6) << i << setw(10) << pt.id() << "   " << left
       << setw(18) << pt.nameWithStatus(18) << right << setw(4)
       << pt.status() << setw(6) << pt.mother1() << setw(6)
       << pt.mother2() << setw(6) << pt.daughter1() << setw(6)
       << pt.daughter2() << setw(6) << pt.col() << setw(6) << pt.acol()
       << ( (useFixed) ? fixed : scientific ) << setprecision(prec)
       << setw(8+prec) << pt.px() << setw(8+prec) << pt.py()
       << setw(8+prec) << pt.pz() << setw(8+prec) << pt.e()
       << setw(8+prec) << pt.m() << "\n";

    // Optional extra line for scale value, polarization and production vertex.
    if (showScaleAndVertex)
      os << "                              " << setw(8+prec) << pt.scale()
         << " " << fixed << setprecision(prec) << setw(8+prec) << pt.pol()
         << "                        " << scientific << setprecision(prec)
         << setw(8+prec) << pt.xProd() << setw(8+prec) << pt.yProd()
         << setw(8+prec) << pt.zProd() << setw(8+prec) << pt.tProd()
         << setw(8+prec) << pt.tau() << "\n";

    // Optional extra line, giving a complete list of mothers and daughters.
    if (showMothersAndDaughters) {
      int linefill = 2;
      os << "                mothers:";
      vector<int> allMothers = pt.motherList();
      for (int j = 0; j < int(allMothers.size()); ++j) {
        os << " " <<  allMothers[j];
        if (++linefill == IPERLINE) {os << "\n                "; linefill = 0;}
      }
      os << ";   daughters:";
      vector<int> allDaughters = pt.daughterList();
      for (int j = 0; j < int(allDaughters.size()); ++j) {
        os << " " <<  allDaughters[j];
        if (++linefill == IPERLINE) {os << "\n                "; linefill = 0;}
      }
      if (linefill !=0) os << "\n";
    }

    // Extra blank separation line when each particle spans more than one line.
    if (showScaleAndVertex || showMothersAndDaughters) os << "\n";

    // Statistics on momentum and charge.
    if (entry[i].status() > 0) {
      pSum += entry[i].p();
      chargeSum += entry[i].charge();
    }
  }

  // Line with sum charge, momentum, energy and invariant mass.
  os << fixed << setprecision(3) << "                                   "
     << "Charge sum:" << setw(7) << chargeSum << "           Momentum sum:"
     << ( (useFixed) ? fixed : scientific ) << setprecision(prec)
     << setw(8+prec) << pSum.px() << setw(8+prec) << pSum.py()
     << setw(8+prec) << pSum.pz() << setw(8+prec) << pSum.e()
     << setw(8+prec) << pSum.mCalc() << "\n";

  // Listing finished.
  os << "\n --------  End PYTHIA Event Listing  ----------------------------"
     << "-------------------------------------------------------------------"
     << endl;
}

//--------------------------------------------------------------------------

// Erase junction stored in specified slot and move up the ones under.

void Event::eraseJunction(int i) {

  for (int j = i; j < int(junction.size()) - 1; ++j)
    junction[j] = junction[j + 1];
  junction.pop_back();

}

//--------------------------------------------------------------------------

// Print the junctions in an event.

void Event::listJunctions(ostream& os) const {

  // Header.
  os << "\n --------  PYTHIA Junction Listing  "
     << headerList.substr(0,30) << "\n \n    no  kind  col0  col1  col2 "
     << "endc0 endc1 endc2 stat0 stat1 stat2\n";

  // Loop through junctions in event and list them.
  for (int i = 0; i < sizeJunction(); ++i)
    os << setw(6) << i << setw(6) << kindJunction(i) << setw(6)
       << colJunction(i, 0) << setw(6) << colJunction(i, 1) << setw(6)
       << colJunction(i, 2) << setw(6) << endColJunction(i, 0) << setw(6)
       << endColJunction(i, 1) << setw(6) << endColJunction(i, 2) << setw(6)
       << statusJunction(i, 0) << setw(6) << statusJunction(i, 1) << setw(6)
       << statusJunction(i, 2) << "\n";

  // Alternative if no junctions. Listing finished.
  if (sizeJunction() == 0) os << "    no junctions present \n";
  os << "\n --------  End PYTHIA Junction Listing  --------------------"
     << "------" << endl;
}

//--------------------------------------------------------------------------

// Operator overloading allows to append one event to an existing one.

Event& Event::operator+=( const Event& addEvent) {

  // Find offsets. One less since won't copy line 0.
  int offsetIdx = entry.size() - 1;
  int offsetCol = maxColTag;

  // Add energy to zeroth line and calculate new invariant mass.
  entry[0].p( entry[0].p() + addEvent[0].p() );
  entry[0].m( entry[0].mCalc() );

  // Read out particles from line 1 (not 0) onwards.
  Particle temp;
  for (int i = 1; i < addEvent.size(); ++i) {
    temp = addEvent[i];

    // Add offset to nonzero mother, daughter and colour indices.
    if (temp.mother1() > 0) temp.mother1( temp.mother1() + offsetIdx );
    if (temp.mother2() > 0) temp.mother2( temp.mother2() + offsetIdx );
    if (temp.daughter1() > 0) temp.daughter1( temp.daughter1() + offsetIdx );
    if (temp.daughter2() > 0) temp.daughter2( temp.daughter2() + offsetIdx );
    if (temp.col() > 0) temp.col( temp.col() + offsetCol );
    if (temp.acol() > 0) temp.acol( temp.acol() + offsetCol );

    // Append particle to summed event.
    append( temp );
  }

  // Read out junctions one by one.
  Junction tempJ;
  int begCol, endCol;
  for (int i = 0; i < addEvent.sizeJunction(); ++i) {
    tempJ = addEvent.getJunction(i);

    // Add colour offsets to all three legs.
    for (int  j = 0; j < 3; ++j) {
      begCol = tempJ.col(j);
      endCol = tempJ.endCol(j);
      if (begCol > 0) begCol += offsetCol;
      if (endCol > 0) endCol += offsetCol;
      tempJ.cols( j, begCol, endCol);
    }

    // Append junction to summed event.
    appendJunction( tempJ );
  }

  // Set header that indicates character as sum of events.
  headerList = "(combination of several events)  -------";

  // Done.
  return *this;

}

//==========================================================================

} // end namespace Pythia8


text:
using System;

namespace Org.Mentalis.Security.Ssl.Shared {
	internal class RecordMessage {
		public RecordMessage(MessageType messageType, ContentType contentType, ProtocolVersion version, byte[] bytes) {
			this.messageType = messageType;
			this.contentType = contentType;
			this.version = version;
			if (bytes != null)
				this.fragment = bytes;
			else
				this.fragment = new byte[0];
			this.length = (ushort)this.fragment.Length;
		}
		public RecordMessage(byte[] bytes, int offset) {
			if (bytes == null)
				throw new ArgumentNullException();
			if (offset < 0 || offset >= bytes.Length)
				throw new ArgumentException();
			this.messageType = MessageType.Encrypted;
			this.contentType = (ContentType)bytes[offset];
			this.version = new ProtocolVersion(bytes[offset + 1], bytes[offset + 2]);
			this.length = (ushort)(bytes[offset + 3] * 256 + bytes[offset + 4]);
			this.fragment = new byte[this.length];
			Array.Copy(bytes, offset + 5, this.fragment, 0, this.length);
		}
		public byte[] ToBytes() {
			byte[] ret = new byte[fragment.Length + 5];
			ret[0] = (byte)contentType;
			ret[1] = version.major;
			ret[2] = version.minor;
			ret[3] = (byte)(length / 256);
			ret[4] = (byte)(length % 256);
			Array.Copy(fragment, 0, ret, 5, fragment.Length);
			return ret;
		}
		public MessageType messageType;
		public ContentType contentType;
		public ProtocolVersion version;
		public ushort length;
		public byte[] fragment;
	}
}

redpajama_set_name: RedPajamaGithub


text:
#include "config.h"

int unused;

#ifndef HAVE_PLEDGE

int
pledge(const char *promises __attribute__((__unused__)),
    const char *execpromises __attribute__((__unused__)))
{
	return 0;
}

#endif /* !HAVE_PLEDGE */


text:
using System;
using System.Collections.Generic;
using Umbraco.Core.ObjectResolution;
using umbraco.interfaces;

namespace Umbraco.Core
{
	/// <summary>
	/// A resolver to return all IDataType objects
	/// </summary>
	internal sealed class DataTypesResolver : LegacyTransientObjectsResolver<DataTypesResolver, IDataType>
	{
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="dataTypes"></param>
		internal DataTypesResolver(Func<IEnumerable<Type>> dataTypes)
			: base(dataTypes)
		{

		}

		/// <summary>
		/// Gets the <see cref="ICacheRefresher"/> implementations.
		/// </summary>
		public IEnumerable<IDataType> DataTypes
		{
			get
			{
				EnsureIsInitialized();
				return Values;
			}
		}

		protected override Guid GetUniqueIdentifier(IDataType obj)
		{
			return obj.Id;
		}
	}
}


text:
class CreateQuestions < ActiveRecord::Migration[4.2]
  def self.up
    create_table :questions do |t|
      t.integer :user_id, :null => false
      t.text :body
      t.boolean :shared, :default => true, :null => false
      t.integer :answers_count, :default => 0, :null => false
      t.datetime :deleted_at
      t.string :state
      t.boolean :solved, :null => false, :default => false
      t.text :note

      t.timestamps
    end
    add_index :questions, :user_id
  end

  def self.down
    drop_table :questions
  end
end


text:
package org.multibit.hd.core.sntp;

import com.google.common.base.Charsets;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class NtpMessage {

  /**
   * This is a two-bit code warning of an impending leap second to be
   * inserted/deleted in the last minute of the current day.  It's values
   * may be as follows:
   *
   * Value     Meaning
   * -----     -------
   * 0         no warning
   * 1         last minute has 61 seconds
   * 2         last minute has 59 seconds)
   * 3         alarm condition (clock not synchronized)
   */
  public byte leapIndicator = 0;

  /**
   * This value indicates the NTP/SNTP version number.  The version number
   * is 3 for Version 3 (IPv4 only) and 4 for Version 4 (IPv4, IPv6 and OSI).
   * If necessary to distinguish between IPv4, IPv6 and OSI, the
   * encapsulating context must be inspected.
   */
  public byte version = 3;

  /**
   * This value indicates the mode, with values defined as follows:
   *
   * Mode     Meaning
   * ----     -------
   * 0        reserved
   * 1        symmetric active
   * 2        symmetric passive
   * 3        client
   * 4        server
   * 5        broadcast
   * 6        reserved for NTP control message
   * 7        reserved for private use
   *
   * In unicast and anycast modes, the client sets this field to 3 (client)
   * in the request and the server sets it to 4 (server) in the reply. In
   * multicast mode, the server sets this field to 5 (broadcast).
   */
  public byte mode = 0;

  /**
   * This value indicates the stratum level of the local clock, with values
   * defined as follows:
   *
   * Stratum  Meaning
   * ----------------------------------------------
   * 0        unspecified or unavailable
   * 1        primary reference (e.g., radio clock)
   * 2-15     secondary reference (via NTP or SNTP)
   * 16-255   reserved
   */
  public short stratum = 0;

  /**
   * This value indicates the maximum interval between successive messages,
   * in seconds to the nearest power of two. The values that can appear in
   * this field presently range from 4 (16 s) to 14 (16284 s); however, most
   * applications use only the sub-range 6 (64 s) to 10 (1024 s).
   */
  public byte pollInterval = 0;

  /**
   * This value indicates the precision of the local clock, in seconds to
   * the nearest power of two.  The values that normally appear in this field
   * range from -6 for mains-frequency clocks to -20 for microsecond clocks
   * found in some workstations.
   */
  public byte precision = 0;

  /**
   * This value indicates the total round trip delay to the primary reference
   * source, in seconds.  Note that this variable can take on both positive
   * and negative values, depending on the relative time and frequency
   * offsets. The values that normally appear in this field range from
   * negative values of a few milliseconds to positive values of several
   * hundred milliseconds.
   */
  public double rootDelay = 0;

  /**
   * This value indicates the nominal error relative to the primary reference
   * source, in seconds.  The values  that normally appear in this field
   * range from 0 to several hundred milliseconds.
   */
  public double rootDispersion = 0;

  /**
   * This is a 4-byte array identifying the particular reference source.
   * In the case of NTP Version 3 or Version 4 stratum-0 (unspecified) or
   * stratum-1 (primary) servers, this is a four-character ASCII string, left
   * justified and zero padded to 32 bits. In NTP Version 3 secondary
   * servers, this is the 32-bit IPv4 address of the reference source. In NTP
   * Version 4 secondary servers, this is the low order 32 bits of the latest
   * transmit timestamp of the reference source. NTP primary (stratum 1)
   * servers should set this field to a code identifying the external
   * reference source according to the following list. If the external
   * reference is one of those listed, the associated code should be used.
   * Codes for sources not listed can be contrived as appropriate.
   *
   * Code     External Reference Source
   * ----     -------------------------
   * LOCL     uncalibrated local clock used as a primary reference for
   * a subnet without external means of synchronization
   * PPS      atomic clock or other pulse-per-second source individually
   * calibrated to national standards
   * ACTS     NIST dialup modem service
   * USNO     USNO modem service
   * PTB      PTB (Germany) modem service
   * TDF      Allouis (France) Radio 164 kHz
   * DCF      Mainflingen (Germany) Radio 77.5 kHz
   * MSF      Rugby (UK) Radio 60 kHz
   * WWV      Ft. Collins (US) Radio 2.5, 5, 10, 15, 20 MHz
   * WWVB     Boulder (US) Radio 60 kHz
   * WWVH     Kaui Hawaii (US) Radio 2.5, 5, 10, 15 MHz
   * CHU      Ottawa (Canada) Radio 3330, 7335, 14670 kHz
   * LORC     LORAN-C radionavigation system
   * OMEG     OMEGA radionavigation system
   * GPS      Global Positioning Service
   * GOES     Geostationary Orbit Environment Satellite
   */
  public byte[] referenceIdentifier = {0, 0, 0, 0};

  /**
   * This is the time at which the local clock was last set or corrected, in
   * seconds since 00:00 1-Jan-1900.
   */
  public double referenceTimestamp = 0;

  /**
   * This is the time at which the request departed the client for the
   * server, in seconds since 00:00 1-Jan-1900.
   */
  public double originateTimestamp = 0;

  /**
   * This is the time at which the request arrived at the server, in seconds
   * since 00:00 1-Jan-1900.
   */
  public double receiveTimestamp = 0;

  /**
   * This is the time at which the reply departed the server for the client,
   * in seconds since 00:00 1-Jan-1900.
   */
  public double transmitTimestamp = 0;

  /**
   * Lightweight random number generator for use with LSB filling
   */
  private static final Random random = new Random();

  /**
   * Constructs a new NtpMessage from an array of bytes.
   */
  public NtpMessage(byte[] array) {

    // See the packet format diagram in RFC 2030 for details
    leapIndicator = (byte) ((array[0] >> 6) & 0x3);
    version = (byte) ((array[0] >> 3) & 0x7);
    mode = (byte) (array[0] & 0x7);
    stratum = unsignedByteToShort(array[1]);
    pollInterval = array[2];
    precision = array[3];

    rootDelay = (array[4] * 256.0) +
      unsignedByteToShort(array[5]) +
      (unsignedByteToShort(array[6]) / 256.0) +
      (unsignedByteToShort(array[7]) / 65536.0);

    rootDispersion = (unsignedByteToShort(array[8]) * 256.0) +
      unsignedByteToShort(array[9]) +
      (unsignedByteToShort(array[10]) / 256.0) +
      (unsignedByteToShort(array[11]) / 65536.0);

    referenceIdentifier[0] = array[12];
    referenceIdentifier[1] = array[13];
    referenceIdentifier[2] = array[14];
    referenceIdentifier[3] = array[15];

    referenceTimestamp = decodeTimestamp(array, 16);
    originateTimestamp = decodeTimestamp(array, 24);
    receiveTimestamp = decodeTimestamp(array, 32);
    transmitTimestamp = decodeTimestamp(array, 40);

  }

  /**
   * Constructs a new NtpMessage in client -> server mode, and sets the
   * transmit timestamp to the current time.
   */
  public NtpMessage() {

    // Note that all the other member variables are already set with
    // appropriate default values.
    this.mode = 3;
    this.transmitTimestamp = (System.currentTimeMillis() / 1000.0) + 2208988800.0;

  }

  /**
   * This method constructs the data bytes of a raw NTP packet.
   */
  public byte[] toByteArray() {

    // All bytes are automatically set to 0
    byte[] p = new byte[48];

    p[0] = (byte) (leapIndicator << 6 | version << 3 | mode);
    p[1] = (byte) stratum;
    p[2] = pollInterval;
    p[3] = precision;

    // root delay is a signed 16.16-bit FP, in Java an int is 32-bits
    int l = (int) (rootDelay * 65536.0);
    p[4] = (byte) ((l >> 24) & 0xFF);
    p[5] = (byte) ((l >> 16) & 0xFF);
    p[6] = (byte) ((l >> 8) & 0xFF);
    p[7] = (byte) (l & 0xFF);

    // root dispersion is an unsigned 16.16-bit FP, in Java there are no
    // unsigned primitive types, so we use a long which is 64-bits
    long ul = (long) (rootDispersion * 65536.0);
    p[8] = (byte) ((ul >> 24) & 0xFF);
    p[9] = (byte) ((ul >> 16) & 0xFF);
    p[10] = (byte) ((ul >> 8) & 0xFF);
    p[11] = (byte) (ul & 0xFF);

    p[12] = referenceIdentifier[0];
    p[13] = referenceIdentifier[1];
    p[14] = referenceIdentifier[2];
    p[15] = referenceIdentifier[3];

    encodeTimestamp(p, 16, referenceTimestamp);
    encodeTimestamp(p, 24, originateTimestamp);
    encodeTimestamp(p, 32, receiveTimestamp);
    encodeTimestamp(p, 40, transmitTimestamp);

    return p;
  }

  /**
   * Returns a string representation of a NtpMessage
   */
  public String toString() {

    String precisionStr =
      new DecimalFormat("0.#E0").format(Math.pow(2, precision));

    return "Leap indicator: " + leapIndicator + "\n" +
      "Version: " + version + "\n" +
      "Mode: " + mode + "\n" +
      "Stratum: " + stratum + "\n" +
      "Poll: " + pollInterval + "\n" +
      "Precision: " + precision + " (" + precisionStr + " seconds)\n" +
      "Root delay: " + new DecimalFormat("0.00").format(rootDelay * 1000) + " ms\n" +
      "Root dispersion: " + new DecimalFormat("0.00").format(rootDispersion * 1000) + " ms\n" +
      "Reference identifier: " + referenceIdentifierToString(referenceIdentifier, stratum, version) + "\n" +
      "Reference timestamp: " + timestampToString(referenceTimestamp) + "\n" +
      "Originate timestamp: " + timestampToString(originateTimestamp) + "\n" +
      "Receive timestamp:   " + timestampToString(receiveTimestamp) + "\n" +
      "Transmit timestamp:  " + timestampToString(transmitTimestamp);
  }

  /**
   * Converts an unsigned byte to a short.  By default, Java assumes that
   * a byte is signed.
   */
  public static short unsignedByteToShort(byte b) {

    if ((b & 0x80) == 0x80) {
      return (short) (128 + (b & 0x7f));
    } else {
      return (short) b;
    }
  }

  /**
   * Will read 8 bytes of a message beginning at pointer
   * and return it as a double, according to the NTP 64-bit timestamp
   * format.
   */
  public static double decodeTimestamp(byte[] array, int pointer) {

    double r = 0.0;

    for (int i = 0; i < 8; i++) {
      r += unsignedByteToShort(array[pointer + i]) * Math.pow(2, (3 - i) * 8);
    }

    return r;

  }

  /**
   * Encodes a timestamp in the specified position in the message
   */
  public static void encodeTimestamp(byte[] array, int pointer, double timestamp) {

    // Converts a double into a 64-bit fixed point
    for (int i = 0; i < 8; i++) {
      // 2^24, 2^16, 2^8, .. 2^-32
      double base = Math.pow(2, (3 - i) * 8);

      // Capture byte value
      array[pointer + i] = (byte) (timestamp / base);

      // Subtract captured value from remaining total
      timestamp = timestamp - unsignedByteToShort(array[pointer + i]) * base;
    }

    // From RFC 2030: It is advisable to fill the non-significant
    // low order bits of the timestamp with a random, unbiased
    // bitstring, both to avoid systematic rounding errors and as
    // a means of loop detection and replay detection
    array[7] = (byte) random.nextInt(256);

  }

  /**
   * Returns a timestamp (number of seconds since 00:00 1-Jan-1900) as a
   * formatted date/time string.
   */
  public static String timestampToString(double timestamp) {

    if (timestamp == 0) return "0";

    // timestamp is relative to 1900, utc is used by Java and is relative
    // to 1970
    double utc = timestamp - (2208988800.0);

    // milliseconds
    long ms = (long) (utc * 1000.0);

    // date/time
    String date = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss").format(new Date(ms));

    // fraction
    double fraction = timestamp - ((long) timestamp);
    String fractionSting = new DecimalFormat(".000000").format(fraction);

    return date + fractionSting;
  }

  /**
   * Returns a string representation of a reference identifier according
   * to the rules set out in RFC 2030.
   */
  public static String referenceIdentifierToString(byte[] ref, short stratum, byte version) {

    // From the RFC 2030:
    // In the case of NTP Version 3 or Version 4 stratum-0 (unspecified)
    // or stratum-1 (primary) servers, this is a four-character ASCII
    // string, left justified and zero padded to 32 bits.
    if (stratum == 0 || stratum == 1) {
      return new String(ref, Charsets.UTF_8);
    }

    // In NTP Version 3 secondary servers, this is the 32-bit IPv4
    // address of the reference source.
    else if (version == 3) {
      return unsignedByteToShort(ref[0]) + "." +
        unsignedByteToShort(ref[1]) + "." +
        unsignedByteToShort(ref[2]) + "." +
        unsignedByteToShort(ref[3]);
    }

    // In NTP Version 4 secondary servers, this is the low order 32 bits
    // of the latest transmit timestamp of the reference source.
    else if (version == 4) {
      return "" + ((unsignedByteToShort(ref[0]) / 256.0) +
        (unsignedByteToShort(ref[1]) / 65536.0) +
        (unsignedByteToShort(ref[2]) / 16777216.0) +
        (unsignedByteToShort(ref[3]) / 4294967296.0));
    }

    return "";
  }

}


text:
#pragma once

#include <vector>
#include <string>
#include "libusb.h"

struct command_status_wrapper
{
	uint8_t dCSWSignature[4];
	uint32_t dCSWTag;
	uint32_t dCSWDataResidue;
	uint8_t bCSWStatus;
};

class DevicesHandler
{
	public:
		DevicesHandler();
		~DevicesHandler();

		std::vector<std::string> PrintDevicesList();
		void OpenDevice(int vid, int pid);

	private:
		libusb_context* context;

		void InitLibUSB();
		void CloseLibUSB();
};


text:
(function() {
  'use strict';

  angular
    .module("canon.button.group")
    .directive("canonButtonGroup", canonButtonGroup);

    canonButtonGroup.$inject = ['requestCountfactory'];

  /****** Loading Buttons Directive ******/
  function canonButtonGroup(requestCountfactory) {
    return {
      restrict: "E",
      transclude: true,
      scope: {},
      template: '
<ng-transclude></ng-transclude>
',
      link: function(scope, element) {
        scope.requestCount = 0;
        scope.$watch(function() {
          return requestCountfactory.getRequestCount();
        }, function(requestCount) {
          scope.requestCount = requestCount;
          if (requestCount > 0) { //outstanding request present
            disableElements(scope, element[0]); //de-reference to unwrap jQLite object
          } else {
            enableElements(scope, element[0]);
          }
        });
      }
    };
  }

  var disableElements = function(scope, element) {
    $(element).find('a.rs-btn').not('.rs-btn-link').addClass('disabled').attr('disabled', 'disabled');
    $(element).find('a.rs-btn-link').hide();
    $(element).find('.rs-processing-indicator').show();
  }
  var enableElements = function(scope, element) {
    $(element).find('a.rs-btn').removeClass('disabled').removeAttr('disabled');
    $(element).find('a.rs-btn-link').show();
    $(element).find('.rs-processing-indicator').hide();
  }

  /****** End Loading Buttons Directive ******/
  }());


text:
<!DOCTYPE html>

  <title>Tyler Sharp's Cars</title>
  <link rel="stylesheet" type="text/css" href="styles.css">

Tyler Sharp's Cars

    510
    Galaxie
    Eclipse
    MR2 Turbo
    M3
    Boxster
    335i
    911
    FJ40
    About Me

Cars I have owned

Make and Model List

      Datsun 510

      Ford Galaxie 500

      Mitsubishi Eclipse

      Toyota MR2 Turbo

      BMW M3

      Porsche Boxster

      BMW 335i

      Porsche 911 C4S

      Toyota Landcruiser

All car logo images used with permission from https://commons.wikimedia.org.

© 2016 Tyler Sharp. All rights reserved.

The website that I looked at for comparison's sake can be seen here. I liked the responsive nature of the website, the imagery (even though i'm not a huge   old Cadillac guy), and some of the jquery animations/effects of the website. As a simple, template car collection website goes, I would say this one is not bad.


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
     File created by the Android Action Bar Style Generator

     Copyright (C) 2011 The Android Open Source Project
     Copyright (C) 2012 readyState Software Ltd

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

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

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<resources xmlns:android="http://schemas.android.com/apk/res/android">

    <style name="Theme.Configstyle" parent="@android:style/Theme.Holo.Light.DarkActionBar">
        <item name="android:actionBarItemBackground">@drawable/selectable_background_configstyle</item>
        <item name="android:popupMenuStyle">@style/PopupMenu.Configstyle</item>
        <item name="android:dropDownListViewStyle">@style/DropDownListView.Configstyle</item>
        <item name="android:actionBarTabStyle">@style/ActionBarTabStyle.Configstyle</item>
        <item name="android:actionDropDownStyle">@style/DropDownNav.Configstyle</item>
        <item name="android:actionBarStyle">@style/ActionBar.Solid.Configstyle</item>
        <item name="android:actionModeBackground">@drawable/cab_background_top_configstyle</item>
        <item name="android:actionModeSplitBackground">@drawable/cab_background_bottom_configstyle</item>
        <item name="android:actionModeCloseButtonStyle">@style/ActionButton.CloseMode.Configstyle</item>

        <!-- Light.DarkActionBar specific -->
        <item name="android:actionBarWidgetTheme">@style/Theme.Configstyle.Widget</item>
        <item name="android:spinnerStyle">@style/SpinnerAppTheme</item>
        <item name="android:dropDownSpinnerStyle">@style/SpinnerAppTheme.DropDown</item>
        <item name="android:spinnerDropDownItemStyle">@style/SpinnerDropDownItemAppTheme</item>

        <!-- For changing spinner textview(not drop down) style -->
        <item name="android:spinnerItemStyle">@style/SpinnerTextViewStyles</item>
        <item name="android:buttonStyle">@style/ConfigApplyBtn</item>
        <item name="android:windowBackground">@color/lightLightGrey</item>
        <item name="android:textViewStyle">@style/ConfigTitle</item>
    </style>

    <style name="ActionBar.Solid.Configstyle" parent="@android:style/Widget.Holo.Light.ActionBar.Solid.Inverse">
        <item name="android:background">@drawable/ab_solid_configstyle</item>
        <item name="android:backgroundStacked">@drawable/ab_stacked_solid_configstyle</item>
        <item name="android:backgroundSplit">@drawable/ab_bottom_solid_configstyle</item>
        <item name="android:progressBarStyle">@style/ProgressBar.Configstyle</item>
        <item name="android:titleTextStyle">@style/WidgetHeading1</item>
        <item name="android:displayOptions">showHome|homeAsUp|showTitle</item>
        <item name="android:icon">@android:color/transparent</item>
    </style>

    <style name="ActionBar.Transparent.Configstyle" parent="@android:style/Widget.Holo.ActionBar">
        <item name="android:background">@drawable/ab_transparent_configstyle</item>
        <item name="android:progressBarStyle">@style/ProgressBar.Configstyle</item>
    </style>

    <style name="PopupMenu.Configstyle" parent="@android:style/Widget.Holo.ListPopupWindow">
        <item name="android:popupBackground">@drawable/menu_dropdown_panel_configstyle</item>
    </style>

    <style name="DropDownListView.Configstyle" parent="@android:style/Widget.Holo.ListView.DropDown">
        <item name="android:listSelector">@drawable/selectable_background_configstyle</item>
    </style>

    <style name="ActionBarTabStyle.Configstyle" parent="@android:style/Widget.Holo.ActionBar.TabView">
        <item name="android:background">@drawable/tab_indicator_ab_configstyle</item>
    </style>

    <style name="DropDownNav.Configstyle" parent="@android:style/Widget.Holo.Spinner">
        <item name="android:background">@drawable/spinner_background_ab_configstyle</item>
        <item name="android:popupBackground">@drawable/menu_dropdown_panel_configstyle</item>
        <item name="android:dropDownSelector">@drawable/selectable_background_configstyle</item>
        <item name="android:spinnerItemStyle">@style/SpinnerTextViewStyle</item>
    </style>

    <style name="ProgressBar.Configstyle" parent="@android:style/Widget.Holo.ProgressBar.Horizontal">
        <item name="android:progressDrawable">@drawable/progress_horizontal_configstyle</item>
    </style>

    <style name="ActionButton.CloseMode.Configstyle" parent="@android:style/Widget.Holo.ActionButton.CloseMode">
        <item name="android:background">@drawable/btn_cab_done_configstyle</item>
    </style>

    <!-- this style is only referenced in a Light.DarkActionBar based theme -->
    <style name="Theme.Configstyle.Widget" parent="@android:style/Theme.Holo">
        <item name="android:popupMenuStyle">@style/PopupMenu.Configstyle</item>
        <item name="android:dropDownListViewStyle">@style/DropDownListView.Configstyle</item>
    </style>

    <!-- Styles for configuration fragments -->

    <style name="ConfigTitle" parent="@android:style/TextAppearance">
        <item name="android:textColor">@android:color/black</item>
        <item name="android:textSize">18sp</item>
        <item name="android:textStyle">bold</item>
        <item name="android:shadowColor">@android:color/white</item>
        <item name="android:shadowDx">0</item>
        <item name="android:shadowDy">1</item>
        <item name="android:typeface">sans</item>
        <item name="android:shadowRadius">1</item>
    </style>

    <style name="ConfigApplyBtn" parent="@android:style/Widget.Button">
        <item name="android:background">@drawable/btn_green</item>
        <item name="android:textAppearance">@style/ConfigTitle</item>
        <item name="android:textColor">@android:color/white</item>
        <item name="android:shadowColor">@android:color/black</item>
    </style>

    <style name="SpinnerTextViewStyles" parent="android:TextAppearance.Holo.Widget.TextView.SpinnerItem">
        <item name="android:textColor">@android:color/black</item>
        <item name="android:textSize">16sp</item>
        <item name="android:textStyle">normal</item>
        <item name="android:typeface">sans</item>
    </style>

    <style name="AdListTitleTextStyle" parent="@android:style/Widget.TextView">
        <item name="android:textColor">@color/ad_list_item_title_text_color</item>
        <item name="android:textStyle">bold</item>
        <item name="android:shadowColor">@android:color/white</item>
        <item name="android:shadowRadius">1</item>
        <item name="android:shadowDx">0</item>
        <item name="android:shadowDy">1</item>
        <item name="android:textSize">15sp</item>
    </style>

    <style name="AdListDescTextStyle" parent="@android:style/Widget.TextView">
        <item name="android:textColor">@color/ad_list_item_desc_text_color</item>
        <item name="android:textSize">14sp</item>
    </style>

</resources>


text:
const Counter = Recompose.componentFromStream(props$ => {
  const {
    handler: onClick,
    stream: btnClick$
  } = Recompose.createEventHandler();

  // Stream logic
  const count$ = btnClick$
    .mapTo(1)
    .scan((count, n) => count + n, 0)
    .startWith(0);

  // Statless functional component.
  return props$.combineLatest(count$,
    (props, count) => (
      <div>
        Count: {count}
        <button onClick={onClick}>+</button>
      </div>
    )
  );
});

render(<Counter />, mountNode);


text:
{% extends "layout.html" %}
{% block body %}

Force Example

This a simple dynamic visualization of a connected graph.

        <svg viewBox="0 0 600 600"></svg>

{% endblock %}


text:
#ifndef ALIUNFOLDING_H
#define ALIUNFOLDING_H

/// \class AliUnfolding
/// \brief class that implements several unfolding methods
///
/// I.e. chi2 minimization and bayesian unfolding
/// The whole class is static and not thread-safe (due to the fact that MINUIT unfolding is not thread-safe)
///
/// Methods that are implemented are chi2 minimization and bayesian unfolding.
///
/// \author Jan Fiete Grosse-Oetringhaus <Jan.Fiete.Grosse-Oetringhaus@cern.ch>

#include "TObject.h"
#include <TMatrixD.h>
#include <TVectorD.h>

class TH1;
class TH2;
class TF1;
class TCanvas;
class TVirtualPad;
class TAxis;

class AliUnfolding : public TObject
{
  public:
  enum RegularizationType { kNone = 0, kPol0, kPol1, kLog, kEntropy, kCurvature, kRatio, kPowerLaw, kLogLog };
    enum MethodType { kInvalid = -1, kChi2Minimization = 0, kBayesian = 1, kFunction = 2};

    virtual ~AliUnfolding() {};

    static void SetUnfoldingMethod(MethodType methodType);
    static void SetCreateOverflowBin(Float_t overflowBinLimit);
    static void SetSkipBinsBegin(Int_t nBins);
    static void SetNbins(Int_t nMeasured, Int_t nUnfolded);
    static void SetChi2Regularization(RegularizationType type, Float_t weight);
    static void SetMinuitStepSize(Float_t stepSize) { fgMinuitStepSize = stepSize; }
    static void SetMinuitPrecision(Float_t pres) {fgMinuitPrecision = pres;}
    static void SetMinuitMaxIterations(Int_t iter) {fgMinuitMaxIterations = iter;}
    static void SetMinuitStrategy(Double_t strat) {fgMinuitStrategy = strat;}
    static void SetMinimumInitialValue(Bool_t flag, Float_t value = -1) { fgMinimumInitialValue = flag; fgMinimumInitialValueFix = value; }
    static void SetNormalizeInput(Bool_t flag) { fgNormalizeInput = flag; }
    static void SetNotFoundEvents(Float_t notFoundEvents) { fgNotFoundEvents = notFoundEvents; }
    static void SetSkip0BinInChi2(Bool_t flag) { fgSkipBin0InChi2 = flag; }
    static void SetBayesianParameters(Float_t smoothing, Int_t nIterations);
    static void SetFunction(TF1* function);
    static void SetDebug(Bool_t flag) { fgDebug = flag; }
    static void SetPowern(Int_t n) {fgPowern = -1*n;}

    static Int_t Unfold(TH2* correlation, TH1* efficiency, TH1* measured, TH1* initialConditions, TH1* result, Bool_t check = kFALSE);
    static Int_t UnfoldGetBias(TH2* correlation, TH1* efficiency, TH1* measured, TH1* initialConditions, TH1* result);

    static TH1* GetPenaltyPlot(Double_t* params);
    static TH1* GetPenaltyPlot(TH1* corrected);

    static TH1* GetResidualsPlot(Double_t* params);
    static TH1* GetResidualsPlot(TH1* corrected);

    static Double_t GetChi2FromFit() {return fChi2FromFit;}
    static Double_t GetPenaltyVal()  {return fPenaltyVal;}
    static Double_t GetAvgResidual() {return fAvgResidual;}

    static void DrawResults(TH2* correlation, TH1* efficiency, TH1* measured, TH1* initialConditions, TCanvas *canvas = 0, Int_t reuseHists = kFALSE,TH1 *unfolded=0);
    static void InteractiveUnfold(TH2* correlation, TH1* efficiency, TH1* measured, TH1* initialConditions);
    static void RedrawInteractive();

  protected:
    AliUnfolding() {};

    static Int_t UnfoldWithMinuit(TH2* correlation, TH1* efficiency, TH1* measured, TH1* initialConditions, TH1* result, Bool_t check);
    static Int_t UnfoldWithBayesian(TH2* correlation, TH1* aEfficiency, TH1* measured, TH1* initialConditions, TH1* aResult);
    static Int_t UnfoldWithFunction(TH2* correlation, TH1* efficiency, TH1* measured, TH1* /* initialConditions */, TH1* aResult);

    static void CreateOverflowBin(TH2* correlation, TH1* measured);
    static void SetStaticVariables(TH2* correlation, TH1* measured, TH1* efficiency);

    static void MakePads();
    static void DrawGuess(Double_t *params, TVirtualPad *pfolded=0, TVirtualPad *pres=0, TVirtualPad *ppen=0, Int_t reuseHists = kFALSE, TH1* unfolded=0);

    static Double_t RegularizationPol0(TVectorD& params);
    static Double_t RegularizationPol1(TVectorD& params);
    static Double_t RegularizationTotalCurvature(TVectorD& params);
    static Double_t RegularizationEntropy(TVectorD& params);
    static Double_t RegularizationLog(TVectorD& params);
    static Double_t RegularizationRatio(TVectorD& params);
    static Double_t RegularizationPowerLaw(TVectorD& params);
    static Double_t RegularizationLogLog(TVectorD& params);

    static void Chi2Function(Int_t&, Double_t*, Double_t& chi2, Double_t *params, Int_t);
    static void TF1Function(Int_t& unused1, Double_t* unused2, Double_t& chi2, Double_t *params, Int_t unused3);

    // static variable to be accessed by MINUIT
    static TMatrixD* fgCorrelationMatrix;            ///< contains fCurrentCorrelation in matrix form
    static TMatrixD* fgCorrelationMatrixSquared;     ///< contains squared fCurrentCorrelation in matrix form
    static TMatrixD* fgCorrelationCovarianceMatrix;  ///< contains the errors of fCurrentESD
    static TVectorD* fgCurrentESDVector;             ///< contains fCurrentESD
    static TVectorD* fgEntropyAPriori;               ///< a-priori distribution for entropy regularization
    static TVectorD* fgEfficiency;                   ///< efficiency
    /*
    static TVectorD* fgBinWidths;                    // bin widths to be taken into account in regularization
    static TVectorD* fgBinPos;                       // bin positions of unfolded
    */
    static TAxis *fgUnfoldedAxis;                    ///< bin widths and positions for unfolded
    static TAxis *fgMeasuredAxis;                    ///< bin widths and positions for measured

    static TF1* fgFitFunction;                       ///< fit function

    // --- configuration params follow ---
    static MethodType fgMethodType;                  ///< unfolding method to be used
    static Int_t fgMaxParams;                        ///< bins in unfolded histogram = number of fit params
    static Int_t fgMaxInput;                         ///< bins in measured histogram
    static Float_t fgOverflowBinLimit;               ///< to fix fluctuations at high multiplicities, all entries above the limit are summarized in one bin

    static RegularizationType fgRegularizationType;  ///< regularization that is used during Chi2 method
    static Float_t fgRegularizationWeight;           ///< factor for regularization term
    static Int_t fgSkipBinsBegin;                    ///< (optional) skip the given number of bins in the regularization
    static Float_t fgMinuitStepSize;                 ///< (usually not needed to be changed) step size in minimization
    static Float_t fgMinuitPrecision;                ///< precision used by minuit. default = 1e-6
    static Int_t   fgMinuitMaxIterations;            ///< maximum number of iterations used by minuit. default = 5000
    static Double_t fgMinuitStrategy;                ///< minuit strategy: 0 (low), 1 (default), 2 (high)
    static Bool_t fgMinimumInitialValue;             ///< set all initial values at least to the smallest value among the initial values
    static Float_t fgMinimumInitialValueFix;         ///< use this as the minimum initial value instead of determining it automatically
    static Bool_t fgNormalizeInput;                  ///< normalize input spectrum
    static Float_t fgNotFoundEvents;                 ///< constraint on the total number of not found events sum(guess * (1/eff -1))
    static Bool_t fgSkipBin0InChi2;                  ///< skip bin 0 (= 0 measured) in chi2 function

    static Float_t fgBayesianSmoothing;              ///< smoothing parameter (0 = no smoothing)
    static Int_t   fgBayesianIterations;             ///< number of iterations in Bayesian method

    static Bool_t fgDebug;                           ///< debug flag
    // --- end of configuration ---

    static Int_t fgCallCount;                        ///< call count to chi2 function

    static Int_t fgPowern;                           ///< power of power law for regularization with power law

    static Double_t fChi2FromFit;                    ///< Chi2 from fit at current iteration
    static Double_t fPenaltyVal;                     ///< Penalty value at current iteration (\beta * PU)
    static Double_t fAvgResidual;                    ///< Sum residuals / nbins

    static Int_t fgPrintChi2Details;                 ///< debug for chi2 calc

    // Pointers for interactive unfolder
    static TCanvas *fgCanvas;                        ///< Canvas for interactive unfolder
    static TH1 *fghUnfolded;                         ///< Unfolding result for interactive unfolder
    static TH2 *fghCorrelation;                      ///< Response matrix for interactive unfolder
    static TH1 *fghEfficiency;                       ///< Efficiency histo for interactive unfolder
    static TH1 *fghMeasured;                         ///< Measured distribution for interactive unfolder

private:
    AliUnfolding(const AliUnfolding&);
    AliUnfolding& operator=(const AliUnfolding&);

  ClassDef(AliUnfolding, 0);
};

#endif


text:
module EY
  class EYRC
    attr_reader :path

    DEFAULT_PATH = "~/.eyrc"

    def self.load
      new(ENV['EYRC'] || DEFAULT_PATH)
    end

    def initialize(path)
      @path = Pathname.new(path).expand_path
    end

    def exist?
      path.exist?
    end

    def delete_api_token
      delete('api_token')
    end

    def api_token
      self['api_token']
    end

    def api_token=(token)
      self['api_token'] = token
    end

    private

    def [](key)
      read_data[key.to_s]
    end

    def []=(key,val)
      new_data = read_data.merge(key.to_s => val)
      write_data new_data
      val
    end

    def delete(key)
      data = read_data.dup
      res = data.delete(key)
      write_data data
      res
    end

    def read_data
      exist? && YAML.load(path.read) || {}
    end

    def write_data(new_data)
      path.open("w") {|f| YAML.dump(new_data, f) }
    end

  end
end


text:
require 'nkf'

RSpec.describe OAuth2::Client do
  subject do
    described_class.new('abc', 'def', :site => 'https://api.example.com') do |builder|
      builder.adapter :test do |stub|
        stub.get('/success')             { |env| [200, {'Content-Type' => 'text/awesome'}, 'yay'] }
        stub.get('/reflect')             { |env| [200, {}, env[:body]] }
        stub.post('/reflect')            { |env| [200, {}, env[:body]] }
        stub.get('/unauthorized')        { |env| [401, {'Content-Type' => 'application/json'}, MultiJson.encode(:error => error_value, :error_description => error_description_value)] }
        stub.get('/conflict')            { |env| [409, {'Content-Type' => 'text/plain'}, 'not authorized'] }
        stub.get('/redirect')            { |env| [302, {'Content-Type' => 'text/plain', 'location' => '/success'}, ''] }
        stub.post('/redirect')           { |env| [303, {'Content-Type' => 'text/plain', 'location' => '/reflect'}, ''] }
        stub.get('/error')               { |env| [500, {'Content-Type' => 'text/plain'}, 'unknown error'] }
        stub.get('/empty_get')           { |env| [204, {}, nil] }
        stub.get('/different_encoding')  { |env| [500, {'Content-Type' => 'application/json'}, NKF.nkf('-We', MultiJson.encode(:error => error_value, :error_description => '∞'))] }
        stub.get('/ascii_8bit_encoding') { |env| [500, {'Content-Type' => 'application/json'}, MultiJson.encode(:error => 'invalid_request', :error_description => 'é').force_encoding('ASCII-8BIT')] }
      end
    end
  end

  let!(:error_value) { 'invalid_token' }
  let!(:error_description_value) { 'bad bad token' }

  describe '#initialize' do
    it 'assigns id and secret' do
      expect(subject.id).to eq('abc')
      expect(subject.secret).to eq('def')
    end

    it 'assigns site from the options hash' do
      expect(subject.site).to eq('https://api.example.com')
    end

    it 'assigns Faraday::Connection#host' do
      expect(subject.connection.host).to eq('api.example.com')
    end

    it 'leaves Faraday::Connection#ssl unset' do
      expect(subject.connection.ssl).to be_empty
    end

    it 'is able to pass a block to configure the connection' do
      builder = double('builder')

      allow(Faraday).to receive(:new).and_yield(builder)
      allow(builder).to receive(:response)

      expect(builder).to receive(:adapter).with(:test)

      described_class.new('abc', 'def') do |client|
        client.adapter :test
      end.connection
    end

    it 'defaults raise_errors to true' do
      expect(subject.options[:raise_errors]).to be true
    end

    it 'allows true/false for raise_errors option' do
      client = described_class.new('abc', 'def', :site => 'https://api.example.com', :raise_errors => false)
      expect(client.options[:raise_errors]).to be false
      client = described_class.new('abc', 'def', :site => 'https://api.example.com', :raise_errors => true)
      expect(client.options[:raise_errors]).to be true
    end

    it 'allows override of raise_errors option' do
      client = described_class.new('abc', 'def', :site => 'https://api.example.com', :raise_errors => true) do |builder|
        builder.adapter :test do |stub|
          stub.get('/notfound') { |env| [404, {}, nil] }
        end
      end
      expect(client.options[:raise_errors]).to be true
      expect { client.request(:get, '/notfound') }.to raise_error(OAuth2::Error)
      response = client.request(:get, '/notfound', :raise_errors => false)
      expect(response.status).to eq(404)
    end

    it 'allows get/post for access_token_method option' do
      client = described_class.new('abc', 'def', :site => 'https://api.example.com', :access_token_method => :get)
      expect(client.options[:access_token_method]).to eq(:get)
      client = described_class.new('abc', 'def', :site => 'https://api.example.com', :access_token_method => :post)
      expect(client.options[:access_token_method]).to eq(:post)
    end

    it 'does not mutate the opts hash argument' do
      opts = {:site => 'http://example.com/'}
      opts2 = opts.dup
      described_class.new 'abc', 'def', opts
      expect(opts).to eq(opts2)
    end
  end

  %w[authorize token].each do |url_type|
    describe ":#{url_type}_url option" do
      it "defaults to a path of /oauth/#{url_type}" do
        expect(subject.send("#{url_type}_url")).to eq("https://api.example.com/oauth/#{url_type}")
      end

      it "is settable via the :#{url_type}_url option" do
        subject.options[:"#{url_type}_url"] = '/oauth/custom'
        expect(subject.send("#{url_type}_url")).to eq('https://api.example.com/oauth/custom')
      end

      it 'allows a different host than the site' do
        subject.options[:"#{url_type}_url"] = 'https://api.foo.com/oauth/custom'
        expect(subject.send("#{url_type}_url")).to eq('https://api.foo.com/oauth/custom')
      end
    end
  end

  describe ':redirect_uri option' do
    let(:auth_code_params) do
      {
        'client_id' => 'abc',
        'client_secret' => 'def',
        'code' => 'code',
        'grant_type' => 'authorization_code',
      }
    end

    context 'when blank' do
      it 'there is no redirect_uri param added to authorization URL' do
        expect(subject.authorize_url('a' => 'b')).to eq('https://api.example.com/oauth/authorize?a=b')
      end

      it 'does not add the redirect_uri param to the auth_code token exchange request' do
        client = described_class.new('abc', 'def', :site => 'https://api.example.com', :auth_scheme => :request_body) do |builder|
          builder.adapter :test do |stub|
            stub.post('/oauth/token', auth_code_params) do
              [200, {'Content-Type' => 'application/json'}, '{"access_token":"token"}']
            end
          end
        end
        client.auth_code.get_token('code')
      end
    end

    context 'when set' do
      before { subject.options[:redirect_uri] = 'https://site.com/oauth/callback' }

      it 'adds the redirect_uri param to authorization URL' do
        expect(subject.authorize_url('a' => 'b')).to eq('https://api.example.com/oauth/authorize?a=b&redirect_uri=https%3A%2F%2Fsite.com%2Foauth%2Fcallback')
      end

      it 'adds the redirect_uri param to the auth_code token exchange request' do
        client = described_class.new('abc', 'def', :redirect_uri => 'https://site.com/oauth/callback', :site => 'https://api.example.com', :auth_scheme => :request_body) do |builder|
          builder.adapter :test do |stub|
            stub.post('/oauth/token', auth_code_params.merge('redirect_uri' => 'https://site.com/oauth/callback')) do
              [200, {'Content-Type' => 'application/json'}, '{"access_token":"token"}']
            end
          end
        end
        client.auth_code.get_token('code')
      end
    end
  end

  describe '#connection' do
    context 'when debugging' do
      include_context 'with stubbed env'
      before do
        stub_env('OAUTH_DEBUG' => debug_value)
      end
      context 'when OAUTH_DEBUG=true' do
        let(:debug_value) { 'true' }

        it 'smoothly handles successive requests' do
          capture_output do
            # first request (always goes smoothly)
            subject.request(:get, '/success')
          end

          expect do
            # second request (used to throw Faraday::RackBuilder::StackLocked)
            subject.request(:get, '/success')
          end.not_to raise_error
        end
        it 'prints both request and response bodies to STDOUT' do
          printed = capture_output do
            subject.request(:get, '/success')
            subject.request(:get, '/reflect', :body => 'this is magical')
          end
          expect(printed).to match(/DEBUG -- request: User-Agent: "Faraday v.+"/)
          expect(printed).to match 'DEBUG -- response: Content-Type: "text/awesome'
          expect(printed).to match 'DEBUG -- response: yay'
          expect(printed).to match 'DEBUG -- request: this is magical'
          expect(printed).to match 'DEBUG -- response: this is magical'
        end
      end
      context 'when OAUTH_DEBUG=false' do
        let(:debug_value) { 'false' }

        it 'smoothly handles successive requests' do
          capture_output do
            # first request (always goes smoothly)
            subject.request(:get, '/success')
          end

          expect do
            # second request (used to throw Faraday::RackBuilder::StackLocked)
            subject.request(:get, '/success')
          end.not_to raise_error
        end
        it 'prints nothing to STDOUT' do
          printed = capture_output do
            subject.request(:get, '/success')
            subject.request(:get, '/reflect', :body => 'this is magical')
          end
          expect(printed).to eq ''
        end
      end
    end
  end

  describe '#request' do
    it 'works with a null response body' do
      expect(subject.request(:get, 'empty_get').body).to eq('')
    end

    it 'returns on a successful response' do
      response = subject.request(:get, '/success')
      expect(response.body).to eq('yay')
      expect(response.status).to eq(200)
      expect(response.headers).to eq('Content-Type' => 'text/awesome')
    end

    context 'when OAUTH_DEBUG=true' do
      around do |example|
        begin
          original = ENV['OAUTH_DEBUG']
          ENV['OAUTH_DEBUG'] = 'true'

          example.call
        ensure
          if original.nil?
            ENV.delete('OAUTH_DEBUG')
          else
            ENV['OAUTH_DEBUG'] = original
          end
        end
      end

      it 'outputs to $stdout when OAUTH_DEBUG=true' do
        output = capture_output do
          subject.request(:get, '/success')
        end

        expect(output).to include 'INFO -- : get https://api.example.com/success', 'INFO -- : get https://api.example.com/success'
      end
    end

    it 'posts a body' do
      response = subject.request(:post, '/reflect', :body => 'foo=bar')
      expect(response.body).to eq('foo=bar')
    end

    it 'follows redirects properly' do
      response = subject.request(:get, '/redirect')
      expect(response.body).to eq('yay')
      expect(response.status).to eq(200)
      expect(response.headers).to eq('Content-Type' => 'text/awesome')
    end

    it 'redirects using GET on a 303' do
      response = subject.request(:post, '/redirect', :body => 'foo=bar')
      expect(response.body).to be_empty
      expect(response.status).to eq(200)
    end

    it 'obeys the :max_redirects option' do
      max_redirects = subject.options[:max_redirects]
      subject.options[:max_redirects] = 0
      response = subject.request(:get, '/redirect')
      expect(response.status).to eq(302)
      subject.options[:max_redirects] = max_redirects
    end

    it 'returns if raise_errors is false' do
      subject.options[:raise_errors] = false
      response = subject.request(:get, '/unauthorized')

      expect(response.status).to eq(401)
      expect(response.headers).to eq('Content-Type' => 'application/json')
      expect(response.error).not_to be_nil
    end

    %w[/unauthorized /conflict /error /different_encoding /ascii_8bit_encoding].each do |error_path|
      it "raises OAuth2::Error on error response to path #{error_path}" do
        expect { subject.request(:get, error_path) }.to raise_error(OAuth2::Error)
      end
    end

    it 're-encodes response body in the error message' do
      expect { subject.request(:get, '/ascii_8bit_encoding') }.to raise_error do |ex|
        expect(ex.message).to eq("invalid_request: é\n{\"error\":\"invalid_request\",\"error_description\":\"��\"}")
        expect(ex.message.encoding.name).to eq('UTF-8')
      end
    end

    it 'parses OAuth2 standard error response' do
      begin
        subject.request(:get, '/unauthorized')
      rescue StandardError => e
        expect(e.code).to eq(error_value)
        expect(e.description).to eq(error_description_value)
        expect(e.to_s).to match(/#{error_value}/)
        expect(e.to_s).to match(/#{error_description_value}/)
      end
    end

    it 'provides the response in the Exception' do
      begin
        subject.request(:get, '/error')
      rescue StandardError => e
        expect(e.response).not_to be_nil
        expect(e.to_s).to match(/unknown error/)
      end
    end
  end

  describe '#get_token' do
    it 'returns a configured AccessToken' do
      client = stubbed_client do |stub|
        stub.post('/oauth/token') do
          [200, {'Content-Type' => 'application/json'}, MultiJson.encode('access_token' => 'the-token')]
        end
      end

      token = client.get_token({})
      expect(token).to be_a OAuth2::AccessToken
      expect(token.token).to eq('the-token')
    end

    it 'authenticates with request parameters' do
      client = stubbed_client(:auth_scheme => :request_body) do |stub|
        stub.post('/oauth/token', 'client_id' => 'abc', 'client_secret' => 'def') do |env|
          [200, {'Content-Type' => 'application/json'}, MultiJson.encode('access_token' => 'the-token')]
        end
      end
      client.get_token({})
    end

    it 'authenticates with Basic auth' do
      client = stubbed_client(:auth_scheme => :basic_auth) do |stub|
        stub.post('/oauth/token') do |env|
          raise Faraday::Adapter::Test::Stubs::NotFound unless env[:request_headers]['Authorization'] == OAuth2::Authenticator.encode_basic_auth('abc', 'def')
          [200, {'Content-Type' => 'application/json'}, MultiJson.encode('access_token' => 'the-token')]
        end
      end
      client.get_token({})
    end

    it 'sets the response object on the access token' do
      client = stubbed_client do |stub|
        stub.post('/oauth/token') do
          [200, {'Content-Type' => 'application/json'}, MultiJson.encode('access_token' => 'the-token')]
        end
      end

      token = client.get_token({})
      expect(token.response).to be_a OAuth2::Response
      expect(token.response.parsed).to eq('access_token' => 'the-token')
    end

    it 'forwards given token parameters' do
      client = stubbed_client(:auth_scheme => :request_body) do |stub|
        stub.post('/oauth/token', 'arbitrary' => 'parameter', 'client_id' => 'abc', 'client_secret' => 'def') do |env|
          [200, {'Content-Type' => 'application/json'}, MultiJson.encode('access_token' => 'the-token')]
        end
      end
      client.get_token('arbitrary' => 'parameter')
    end

    def stubbed_client(params = {}, &stubs)
      params = {:site => 'https://api.example.com'}.merge(params)
      OAuth2::Client.new('abc', 'def', params) do |builder|
        builder.adapter :test, &stubs
      end
    end
  end

  it 'instantiates an AuthCode strategy with this client' do
    expect(subject.auth_code).to be_kind_of(OAuth2::Strategy::AuthCode)
  end

  it 'instantiates an Implicit strategy with this client' do
    expect(subject.implicit).to be_kind_of(OAuth2::Strategy::Implicit)
  end

  context 'with SSL options' do
    subject do
      cli = described_class.new('abc', 'def', :site => 'https://api.example.com', :ssl => {:ca_file => 'foo.pem'})
      cli.connection.build do |b|
        b.adapter :test
      end
      cli
    end

    it 'passes the SSL options along to Faraday::Connection#ssl' do
      expect(subject.connection.ssl.fetch(:ca_file)).to eq('foo.pem')
    end
  end

  context 'without a connection-configuration block' do
    subject do
      described_class.new('abc', 'def', :site => 'https://api.example.com')
    end

    it 'applies default faraday middleware to the connection' do
      expect(subject.connection.builder.handlers).to eq([Faraday::Request::UrlEncoded, Faraday::Adapter::Test])
    end
  end
end


text:
/**
 * Created by bobtian on 16/2/3.
 */

function routes($stateProvider) {
    $stateProvider.state('scrollXY', {
        url: '/scroll-x',
        templateUrl: './components/basic/scroll-xy/sxy.tpl.html',
        controller: 'ScrollXYController',
        controllerAs: 'sxy'
    })
}

routes.$inject = ['$stateProvider'];

export default routes;