text:
using namespace llvm;

//
// Enumeration - Emit the specified class as an enumeration.
//
void SubtargetEmitter::Enumeration(raw_ostream &OS,
                                   const char *ClassName,
                                   bool isBits) {
  // Get all records of class and sort
  std::vector<Record*> DefList = Records.getAllDerivedDefinitions(ClassName);
  std::sort(DefList.begin(), DefList.end(), LessRecord());

  unsigned N = DefList.size();
  if (N == 0)
    return;
  if (N > 64) {
    errs() << "Too many (> 64) subtarget features!\n";
    exit(1);
  }

  OS << "namespace " << Target << " {\n";

  // For bit flag enumerations with more than 32 items, emit constants.
  // Emit an enum for everything else.
  if (isBits && N > 32) {
    // For each record
    for (unsigned i = 0; i < N; i++) {
      // Next record
      Record *Def = DefList[i];

      // Get and emit name and expression (1 << i)
      OS << "  const uint64_t " << Def->getName() << " = 1ULL << " << i << ";\n";
    }
  } else {
    // Open enumeration
    OS << "enum {\n";

    // For each record
    for (unsigned i = 0; i < N;) {
      // Next record
      Record *Def = DefList[i];

      // Get and emit name
      OS << "  " << Def->getName();

      // If bit flags then emit expression (1 << i)
      if (isBits)  OS << " = " << " 1ULL << " << i;

      // Depending on 'if more in the list' emit comma
      if (++i < N) OS << ",";

      OS << "\n";
    }

    // Close enumeration
    OS << "};\n";
  }

  OS << "}\n";
}

//
// FeatureKeyValues - Emit data of all the subtarget features.  Used by the
// command line.
//
unsigned SubtargetEmitter::FeatureKeyValues(raw_ostream &OS) {
  // Gather and sort all the features
  std::vector<Record*> FeatureList =
                           Records.getAllDerivedDefinitions("SubtargetFeature");

  if (FeatureList.empty())
    return 0;

  std::sort(FeatureList.begin(), FeatureList.end(), LessRecordFieldName());

  // Begin feature table
  OS << "// Sorted (by key) array of values for CPU features.\n"
     << "extern const llvm::SubtargetFeatureKV " << Target
     << "FeatureKV[] = {\n";

  // For each feature
  unsigned NumFeatures = 0;
  for (unsigned i = 0, N = FeatureList.size(); i < N; ++i) {
    // Next feature
    Record *Feature = FeatureList[i];

    const std::string &Name = Feature->getName();
    const std::string &CommandLineName = Feature->getValueAsString("Name");
    const std::string &Desc = Feature->getValueAsString("Desc");

    if (CommandLineName.empty()) continue;

    // Emit as { "feature", "description", featureEnum, i1 | i2 | ... | in }
    OS << "  { "
       << "\"" << CommandLineName << "\", "
       << "\"" << Desc << "\", "
       << Target << "::" << Name << ", ";

    const std::vector<Record*> &ImpliesList =
      Feature->getValueAsListOfDefs("Implies");

    if (ImpliesList.empty()) {
      OS << "0ULL";
    } else {
      for (unsigned j = 0, M = ImpliesList.size(); j < M;) {
        OS << Target << "::" << ImpliesList[j]->getName();
        if (++j < M) OS << " | ";
      }
    }

    OS << " }";
    ++NumFeatures;

    // Depending on 'if more in the list' emit comma
    if ((i + 1) < N) OS << ",";

    OS << "\n";
  }

  // End feature table
  OS << "};\n";

  return NumFeatures;
}

//
// CPUKeyValues - Emit data of all the subtarget processors.  Used by command
// line.
//
unsigned SubtargetEmitter::CPUKeyValues(raw_ostream &OS) {
  // Gather and sort processor information
  std::vector<Record*> ProcessorList =
                          Records.getAllDerivedDefinitions("Processor");
  std::sort(ProcessorList.begin(), ProcessorList.end(), LessRecordFieldName());

  // Begin processor table
  OS << "// Sorted (by key) array of values for CPU subtype.\n"
     << "extern const llvm::SubtargetFeatureKV " << Target
     << "SubTypeKV[] = {\n";

  // For each processor
  for (unsigned i = 0, N = ProcessorList.size(); i < N;) {
    // Next processor
    Record *Processor = ProcessorList[i];

    const std::string &Name = Processor->getValueAsString("Name");
    const std::vector<Record*> &FeatureList =
      Processor->getValueAsListOfDefs("Features");

    // Emit as { "cpu", "description", f1 | f2 | ... fn },
    OS << "  { "
       << "\"" << Name << "\", "
       << "\"Select the " << Name << " processor\", ";

    if (FeatureList.empty()) {
      OS << "0ULL";
    } else {
      for (unsigned j = 0, M = FeatureList.size(); j < M;) {
        OS << Target << "::" << FeatureList[j]->getName();
        if (++j < M) OS << " | ";
      }
    }

    // The "0" is for the "implies" section of this data structure.
    OS << ", 0ULL }";

    // Depending on 'if more in the list' emit comma
    if (++i < N) OS << ",";

    OS << "\n";
  }

  // End processor table
  OS << "};\n";

  return ProcessorList.size();
}

//
// CollectAllItinClasses - Gathers and enumerates all the itinerary classes.
// Returns itinerary class count.
//
unsigned SubtargetEmitter::
CollectAllItinClasses(raw_ostream &OS,
                      std::map<std::string, unsigned> &ItinClassesMap,
                      std::vector<Record*> &ItinClassList) {
  // For each itinerary class
  unsigned N = ItinClassList.size();
  for (unsigned i = 0; i < N; i++) {
    // Next itinerary class
    const Record *ItinClass = ItinClassList[i];
    // Get name of itinerary class
    // Assign itinerary class a unique number
    ItinClassesMap[ItinClass->getName()] = i;
  }

  // Return itinerary class count
  return N;
}

//
// FormItineraryStageString - Compose a string containing the stage
// data initialization for the specified itinerary.  N is the number
// of stages.
//
void SubtargetEmitter::FormItineraryStageString(const std::string &Name,
                                                Record *ItinData,
                                                std::string &ItinString,
                                                unsigned &NStages) {
  // Get states list
  const std::vector<Record*> &StageList =
    ItinData->getValueAsListOfDefs("Stages");

  // For each stage
  unsigned N = NStages = StageList.size();
  for (unsigned i = 0; i < N;) {
    // Next stage
    const Record *Stage = StageList[i];

    // Form string as ,{ cycles, u1 | u2 | ... | un, timeinc, kind }
    int Cycles = Stage->getValueAsInt("Cycles");
    ItinString += "  { " + itostr(Cycles) + ", ";

    // Get unit list
    const std::vector<Record*> &UnitList = Stage->getValueAsListOfDefs("Units");

    // For each unit
    for (unsigned j = 0, M = UnitList.size(); j < M;) {
      // Add name and bitwise or
      ItinString += Name + "FU::" + UnitList[j]->getName();
      if (++j < M) ItinString += " | ";
    }

    int TimeInc = Stage->getValueAsInt("TimeInc");
    ItinString += ", " + itostr(TimeInc);

    int Kind = Stage->getValueAsInt("Kind");
    ItinString += ", (llvm::InstrStage::ReservationKinds)" + itostr(Kind);

    // Close off stage
    ItinString += " }";
    if (++i < N) ItinString += ", ";
  }
}

//
// FormItineraryOperandCycleString - Compose a string containing the
// operand cycle initialization for the specified itinerary.  N is the
// number of operands that has cycles specified.
//
void SubtargetEmitter::FormItineraryOperandCycleString(Record *ItinData,
                         std::string &ItinString, unsigned &NOperandCycles) {
  // Get operand cycle list
  const std::vector<int64_t> &OperandCycleList =
    ItinData->getValueAsListOfInts("OperandCycles");

  // For each operand cycle
  unsigned N = NOperandCycles = OperandCycleList.size();
  for (unsigned i = 0; i < N;) {
    // Next operand cycle
    const int OCycle = OperandCycleList[i];

    ItinString += "  " + itostr(OCycle);
    if (++i < N) ItinString += ", ";
  }
}

void SubtargetEmitter::FormItineraryBypassString(const std::string &Name,
                                                 Record *ItinData,
                                                 std::string &ItinString,
                                                 unsigned NOperandCycles) {
  const std::vector<Record*> &BypassList =
    ItinData->getValueAsListOfDefs("Bypasses");
  unsigned N = BypassList.size();
  unsigned i = 0;
  for (; i < N;) {
    ItinString += Name + "Bypass::" + BypassList[i]->getName();
    if (++i < NOperandCycles) ItinString += ", ";
  }
  for (; i < NOperandCycles;) {
    ItinString += " 0";
    if (++i < NOperandCycles) ItinString += ", ";
  }
}

//
// EmitStageAndOperandCycleData - Generate unique itinerary stages and
// operand cycle tables.  Record itineraries for processors.
//
void SubtargetEmitter::EmitStageAndOperandCycleData(raw_ostream &OS,
       unsigned NItinClasses,
       std::map<std::string, unsigned> &ItinClassesMap,
       std::vector<Record*> &ItinClassList,
       std::vector<std::vector<InstrItinerary> > &ProcList) {
  // Gather processor iteraries
  std::vector<Record*> ProcItinList =
                       Records.getAllDerivedDefinitions("ProcessorItineraries");

  // If just no itinerary then don't bother
  if (ProcItinList.size() < 2) return;

  // Emit functional units for all the itineraries.
  for (unsigned i = 0, N = ProcItinList.size(); i < N; ++i) {
    // Next record
    Record *Proc = ProcItinList[i];

    std::vector<Record*> FUs = Proc->getValueAsListOfDefs("FU");
    if (FUs.empty())
      continue;

    const std::string &Name = Proc->getName();
    OS << "\n// Functional units for itineraries \"" << Name << "\"\n"
       << "namespace " << Name << "FU {\n";

    for (unsigned j = 0, FUN = FUs.size(); j < FUN; ++j)
      OS << "  const unsigned " << FUs[j]->getName()
         << " = 1 << " << j << ";\n";

    OS << "}\n";

    std::vector<Record*> BPs = Proc->getValueAsListOfDefs("BP");
    if (BPs.size()) {
      OS << "\n// Pipeline forwarding pathes for itineraries \"" << Name
         << "\"\n" << "namespace " << Name << "Bypass {\n";

      OS << "  const unsigned NoBypass = 0;\n";
      for (unsigned j = 0, BPN = BPs.size(); j < BPN; ++j)
        OS << "  const unsigned " << BPs[j]->getName()
           << " = 1 << " << j << ";\n";

      OS << "}\n";
    }
  }

  // Begin stages table
  std::string StageTable = "\nextern const llvm::InstrStage " + Target +
                           "Stages[] = {\n";
  StageTable += "  { 0, 0, 0, llvm::InstrStage::Required }, // No itinerary\n";

  // Begin operand cycle table
  std::string OperandCycleTable = "extern const unsigned " + Target +
    "OperandCycles[] = {\n";
  OperandCycleTable += "  0, // No itinerary\n";

  // Begin pipeline bypass table
  std::string BypassTable = "extern const unsigned " + Target +
    "ForwardingPathes[] = {\n";
  BypassTable += "  0, // No itinerary\n";

  unsigned StageCount = 1, OperandCycleCount = 1;
  std::map<std::string, unsigned> ItinStageMap, ItinOperandMap;
  for (unsigned i = 0, N = ProcItinList.size(); i < N; i++) {
    // Next record
    Record *Proc = ProcItinList[i];

    // Get processor itinerary name
    const std::string &Name = Proc->getName();

    // Skip default
    if (Name == "NoItineraries") continue;

    // Create and expand processor itinerary to cover all itinerary classes
    std::vector<InstrItinerary> ItinList;
    ItinList.resize(NItinClasses);

    // Get itinerary data list
    std::vector<Record*> ItinDataList = Proc->getValueAsListOfDefs("IID");

    // For each itinerary data
    for (unsigned j = 0, M = ItinDataList.size(); j < M; j++) {
      // Next itinerary data
      Record *ItinData = ItinDataList[j];

      // Get string and stage count
      std::string ItinStageString;
      unsigned NStages;
      FormItineraryStageString(Name, ItinData, ItinStageString, NStages);

      // Get string and operand cycle count
      std::string ItinOperandCycleString;
      unsigned NOperandCycles;
      FormItineraryOperandCycleString(ItinData, ItinOperandCycleString,
                                      NOperandCycles);

      std::string ItinBypassString;
      FormItineraryBypassString(Name, ItinData, ItinBypassString,
                                NOperandCycles);

      // Check to see if stage already exists and create if it doesn't
      unsigned FindStage = 0;
      if (NStages > 0) {
        FindStage = ItinStageMap[ItinStageString];
        if (FindStage == 0) {
          // Emit as { cycles, u1 | u2 | ... | un, timeinc }, // indices
          StageTable += ItinStageString + ", // " + itostr(StageCount);
          if (NStages > 1)
            StageTable += "-" + itostr(StageCount + NStages - 1);
          StageTable += "\n";
          // Record Itin class number.
          ItinStageMap[ItinStageString] = FindStage = StageCount;
          StageCount += NStages;
        }
      }

      // Check to see if operand cycle already exists and create if it doesn't
      unsigned FindOperandCycle = 0;
      if (NOperandCycles > 0) {
        std::string ItinOperandString = ItinOperandCycleString+ItinBypassString;
        FindOperandCycle = ItinOperandMap[ItinOperandString];
        if (FindOperandCycle == 0) {
          // Emit as  cycle, // index
          OperandCycleTable += ItinOperandCycleString + ", // ";
          std::string OperandIdxComment = itostr(OperandCycleCount);
          if (NOperandCycles > 1)
            OperandIdxComment += "-"
              + itostr(OperandCycleCount + NOperandCycles - 1);
          OperandCycleTable += OperandIdxComment + "\n";
          // Record Itin class number.
          ItinOperandMap[ItinOperandCycleString] =
            FindOperandCycle = OperandCycleCount;
          // Emit as bypass, // index
          BypassTable += ItinBypassString + ", // " + OperandIdxComment + "\n";
          OperandCycleCount += NOperandCycles;
        }
      }

      // Locate where to inject into processor itinerary table
      const std::string &Name = ItinData->getValueAsDef("TheClass")->getName();
      unsigned Find = ItinClassesMap[Name];

      // Set up itinerary as location and location + stage count
      unsigned NumUOps = ItinClassList[Find]->getValueAsInt("NumMicroOps");
      InstrItinerary Intinerary = { NumUOps, FindStage, FindStage + NStages,
                                    FindOperandCycle,
                                    FindOperandCycle + NOperandCycles};

      // Inject - empty slots will be 0, 0
      ItinList[Find] = Intinerary;
    }

    // Add process itinerary to list
    ProcList.push_back(ItinList);
  }

  // Closing stage
  StageTable += "  { 0, 0, 0, llvm::InstrStage::Required } // End itinerary\n";
  StageTable += "};\n";

  // Closing operand cycles
  OperandCycleTable += "  0 // End itinerary\n";
  OperandCycleTable += "};\n";

  BypassTable += "  0 // End itinerary\n";
  BypassTable += "};\n";

  // Emit tables.
  OS << StageTable;
  OS << OperandCycleTable;
  OS << BypassTable;
}

//
// EmitProcessorData - Generate data for processor itineraries.
//
void SubtargetEmitter::
EmitProcessorData(raw_ostream &OS,
                  std::vector<Record*> &ItinClassList,
                  std::vector<std::vector<InstrItinerary> > &ProcList) {
  // Get an iterator for processor itinerary stages
  std::vector<std::vector<InstrItinerary> >::iterator
      ProcListIter = ProcList.begin();

  // For each processor itinerary
  std::vector<Record*> Itins =
                       Records.getAllDerivedDefinitions("ProcessorItineraries");
  for (unsigned i = 0, N = Itins.size(); i < N; i++) {
    // Next record
    Record *Itin = Itins[i];

    // Get processor itinerary name
    const std::string &Name = Itin->getName();

    // Skip default
    if (Name == "NoItineraries") continue;

    // Begin processor itinerary table
    OS << "\n";
    OS << "static const llvm::InstrItinerary " << Name << "[] = {\n";

    // For each itinerary class
    std::vector<InstrItinerary> &ItinList = *ProcListIter++;
    assert(ItinList.size() == ItinClassList.size() && "bad itinerary");
    for (unsigned j = 0, M = ItinList.size(); j < M; ++j) {
      InstrItinerary &Intinerary = ItinList[j];

      // Emit in the form of
      // { firstStage, lastStage, firstCycle, lastCycle } // index
      if (Intinerary.FirstStage == 0) {
        OS << "  { 1, 0, 0, 0, 0 }";
      } else {
        OS << "  { " <<
          Intinerary.NumMicroOps << ", " <<
          Intinerary.FirstStage << ", " <<
          Intinerary.LastStage << ", " <<
          Intinerary.FirstOperandCycle << ", " <<
          Intinerary.LastOperandCycle << " }";
      }

      OS << ", // " << j << " " << ItinClassList[j]->getName() << "\n";
    }

    // End processor itinerary table
    OS << "  { 1, ~0U, ~0U, ~0U, ~0U } // end marker\n";
    OS << "};\n";
  }
}

//
// EmitProcessorLookup - generate cpu name to itinerary lookup table.
//
void SubtargetEmitter::EmitProcessorLookup(raw_ostream &OS) {
  // Gather and sort processor information
  std::vector<Record*> ProcessorList =
                          Records.getAllDerivedDefinitions("Processor");
  std::sort(ProcessorList.begin(), ProcessorList.end(), LessRecordFieldName());

  // Begin processor table
  OS << "\n";
  OS << "// Sorted (by key) array of itineraries for CPU subtype.\n"
     << "extern const llvm::SubtargetInfoKV "
     << Target << "ProcItinKV[] = {\n";

  // For each processor
  for (unsigned i = 0, N = ProcessorList.size(); i < N;) {
    // Next processor
    Record *Processor = ProcessorList[i];

    const std::string &Name = Processor->getValueAsString("Name");
    const std::string &ProcItin =
      Processor->getValueAsDef("ProcItin")->getName();

    // Emit as { "cpu", procinit },
    OS << "  { "
       << "\"" << Name << "\", "
       << "(void *)&" << ProcItin;

    OS << " }";

    // Depending on ''if more in the list'' emit comma
    if (++i < N) OS << ",";

    OS << "\n";
  }

  // End processor table
  OS << "};\n";
}

//
// EmitData - Emits all stages and itineries, folding common patterns.
//
void SubtargetEmitter::EmitData(raw_ostream &OS) {
  std::map<std::string, unsigned> ItinClassesMap;
  // Gather and sort all itinerary classes
  std::vector<Record*> ItinClassList =
    Records.getAllDerivedDefinitions("InstrItinClass");
  std::sort(ItinClassList.begin(), ItinClassList.end(), LessRecord());

  // Enumerate all the itinerary classes
  unsigned NItinClasses = CollectAllItinClasses(OS, ItinClassesMap,
                                                ItinClassList);
  // Make sure the rest is worth the effort
  HasItineraries = NItinClasses != 1;   // Ignore NoItinerary.

  if (HasItineraries) {
    std::vector<std::vector<InstrItinerary> > ProcList;
    // Emit the stage data
    EmitStageAndOperandCycleData(OS, NItinClasses, ItinClassesMap,
                                 ItinClassList, ProcList);
    // Emit the processor itinerary data
    EmitProcessorData(OS, ItinClassList, ProcList);
    // Emit the processor lookup data
    EmitProcessorLookup(OS);
  }
}

//
// ParseFeaturesFunction - Produces a subtarget specific function for parsing
// the subtarget features string.
//
void SubtargetEmitter::ParseFeaturesFunction(raw_ostream &OS,
                                             unsigned NumFeatures,
                                             unsigned NumProcs) {
  std::vector<Record*> Features =
                       Records.getAllDerivedDefinitions("SubtargetFeature");
  std::sort(Features.begin(), Features.end(), LessRecord());

  OS << "// ParseSubtargetFeatures - Parses features string setting specified\n"
     << "// subtarget options.\n"
     << "void llvm::";
  OS << Target;
  OS << "Subtarget::ParseSubtargetFeatures(StringRef CPU, StringRef FS) {\n"
     << "  DEBUG(dbgs() << \"\\nFeatures:\" << FS);\n"
     << "  DEBUG(dbgs() << \"\\nCPU:\" << CPU);\n";

  if (Features.empty()) {
    OS << "}\n";
    return;
  }

  OS << "  uint64_t Bits = ReInitMCSubtargetInfo(CPU, FS);\n";

  for (unsigned i = 0; i < Features.size(); i++) {
    // Next record
    Record *R = Features[i];
    const std::string &Instance = R->getName();
    const std::string &Value = R->getValueAsString("Value");
    const std::string &Attribute = R->getValueAsString("Attribute");

    if (Value=="true" || Value=="false")
      OS << "  if ((Bits & " << Target << "::"
         << Instance << ") != 0) "
         << Attribute << " = " << Value << ";\n";
    else
      OS << "  if ((Bits & " << Target << "::"
         << Instance << ") != 0 && "
         << Attribute << " < " << Value << ") "
         << Attribute << " = " << Value << ";\n";
  }

  OS << "}\n";
}

//
// SubtargetEmitter::run - Main subtarget enumeration emitter.
//
void SubtargetEmitter::run(raw_ostream &OS) {
  Target = CodeGenTarget(Records).getName();

  EmitSourceFileHeader("Subtarget Enumeration Source Fragment", OS);

  OS << "\n#ifdef GET_SUBTARGETINFO_ENUM\n";
  OS << "#undef GET_SUBTARGETINFO_ENUM\n";

  OS << "namespace llvm {\n";
  Enumeration(OS, "SubtargetFeature", true);
  OS << "} // End llvm namespace \n";
  OS << "#endif // GET_SUBTARGETINFO_ENUM\n\n";

  OS << "\n#ifdef GET_SUBTARGETINFO_MC_DESC\n";
  OS << "#undef GET_SUBTARGETINFO_MC_DESC\n";

  OS << "namespace llvm {\n";
#if 0
  OS << "namespace {\n";
#endif
  unsigned NumFeatures = FeatureKeyValues(OS);
  OS << "\n";
  unsigned NumProcs = CPUKeyValues(OS);
  OS << "\n";
  EmitData(OS);
  OS << "\n";
#if 0
  OS << "}\n";
#endif

  // MCInstrInfo initialization routine.
  OS << "static inline void Init" << Target
     << "MCSubtargetInfo(MCSubtargetInfo *II, "
     << "StringRef TT, StringRef CPU, StringRef FS) {\n";
  OS << "  II->InitMCSubtargetInfo(TT, CPU, FS, ";
  if (NumFeatures)
    OS << Target << "FeatureKV, ";
  else
    OS << "0, ";
  if (NumProcs)
    OS << Target << "SubTypeKV, ";
  else
    OS << "0, ";
  if (HasItineraries) {
    OS << Target << "ProcItinKV, "
       << Target << "Stages, "
       << Target << "OperandCycles, "
       << Target << "ForwardingPathes, ";
  } else
    OS << "0, 0, 0, 0, ";
  OS << NumFeatures << ", " << NumProcs << ");\n}\n\n";

  OS << "} // End llvm namespace \n";

  OS << "#endif // GET_SUBTARGETINFO_MC_DESC\n\n";

  OS << "\n#ifdef GET_SUBTARGETINFO_TARGET_DESC\n";
  OS << "#undef GET_SUBTARGETINFO_TARGET_DESC\n";

  OS << "#include \"llvm/Support/Debug.h\"\n";
  OS << "#include \"llvm/Support/raw_ostream.h\"\n";
  ParseFeaturesFunction(OS, NumFeatures, NumProcs);

  OS << "#endif // GET_SUBTARGETINFO_TARGET_DESC\n\n";

  // Create a TargetSubtargetInfo subclass to hide the MC layer initialization.
  OS << "\n#ifdef GET_SUBTARGETINFO_HEADER\n";
  OS << "#undef GET_SUBTARGETINFO_HEADER\n";

  std::string ClassName = Target + "GenSubtargetInfo";
  OS << "namespace llvm {\n";
  OS << "class DFAPacketizer;\n";
  OS << "struct " << ClassName << " : public TargetSubtargetInfo {\n"
     << "  explicit " << ClassName << "(StringRef TT, StringRef CPU, "
     << "StringRef FS);\n"
     << "public:\n"
     << "  DFAPacketizer *createDFAPacketizer(const InstrItineraryData *IID)"
     << " const;\n"
     << "};\n";
  OS << "} // End llvm namespace \n";

  OS << "#endif // GET_SUBTARGETINFO_HEADER\n\n";

  OS << "\n#ifdef GET_SUBTARGETINFO_CTOR\n";
  OS << "#undef GET_SUBTARGETINFO_CTOR\n";

  OS << "namespace llvm {\n";
  OS << "extern const llvm::SubtargetFeatureKV " << Target << "FeatureKV[];\n";
  OS << "extern const llvm::SubtargetFeatureKV " << Target << "SubTypeKV[];\n";
  if (HasItineraries) {
    OS << "extern const llvm::SubtargetInfoKV " << Target << "ProcItinKV[];\n";
    OS << "extern const llvm::InstrStage " << Target << "Stages[];\n";
    OS << "extern const unsigned " << Target << "OperandCycles[];\n";
    OS << "extern const unsigned " << Target << "ForwardingPathes[];\n";
  }

  OS << ClassName << "::" << ClassName << "(StringRef TT, StringRef CPU, "
     << "StringRef FS)\n"
     << "  : TargetSubtargetInfo() {\n"
     << "  InitMCSubtargetInfo(TT, CPU, FS, ";
  if (NumFeatures)
    OS << Target << "FeatureKV, ";
  else
    OS << "0, ";
  if (NumProcs)
    OS << Target << "SubTypeKV, ";
  else
    OS << "0, ";
  if (HasItineraries) {
    OS << Target << "ProcItinKV, "
       << Target << "Stages, "
       << Target << "OperandCycles, "
       << Target << "ForwardingPathes, ";
  } else
    OS << "0, 0, 0, 0, ";
  OS << NumFeatures << ", " << NumProcs << ");\n}\n\n";
  OS << "} // End llvm namespace \n";

  OS << "#endif // GET_SUBTARGETINFO_CTOR\n\n";
}


text:
using Microsoft.AspNetCore.Html;

namespace Cofoundry.Samples.SimpleSite;

/// <summary>
/// Each blcck type must have a display model that is marked with
/// IPageBlockTypeDisplayModel. This is the model that is rendered
/// in the view. In simple scenarios you can simply mark up the data
/// model as the display model, but here we want to transform the
/// HtmlText property so we need to define a separate model.
///
/// See https://www.cofoundry.org/docs/content-management/page-block-types
/// for more information
/// </summary>
public class ContentSplitSectionDisplayModel : IPageBlockTypeDisplayModel
{
    public string Title { get; set; }

    public IHtmlContent HtmlText { get; set; }

    public ImageAssetRenderDetails Image { get; set; }
}

redpajama_set_name: RedPajamaGithub


text:
package de.knoobie.project.ryou.filesystem.utils;

import de.knoobie.project.clannadutils.common.FileUtils;
import de.knoobie.project.clannadutils.common.NetUtils;
import de.knoobie.project.clannadutils.common.StringUtils;
import de.knoobie.project.fuko.database.domain.Product;
import de.knoobie.project.fuko.database.domain.embeddable.AlbumLink;
import de.knoobie.project.fuko.database.domain.embeddable.Picture;
import de.knoobie.project.fuko.database.domain.embeddable.ProductLink;
import de.knoobie.project.fuko.database.service.FukoDB;
import de.knoobie.project.ryou.filesystem.domain.FileOperationResult;
import de.knoobie.project.ryou.filesystem.domain.RyouPath;
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class ProductFileSystem {

    private static final String PATH_PRODUCTS = "I:\\ClannadProject\\Product";
    private static final String FOLDER_NAME_ALBUMS = "Albums";
    private static final String FOLDER_NAME_TITLES = "Titles";
    private static final String FOLDER_NAME_FRANCHISES = "Franchises";
    private static final String FOLDER_NAME_EXTRA = "Extra";

    public static boolean hasLocalFolder(ProductLink product) {
        if (product == null) {
            return false;
        }
        return FileUtils.exists(
                RyouPath.create(PATH_PRODUCTS,
                        createFolderName(product)).getPath());
    }

    public static String createFolderName(ProductLink product) {
        return FileUtils.normalizeName(
                product.getPrimaryName().getName() + " [" + product.getVgmdbID() + "]");
    }

    public static Path createProductDirectory(ProductLink product) throws IOException {
        return FileUtils.createDirectory(RyouPath.create(PATH_PRODUCTS,
                createFolderName(product)).getPath());
    }

    public static Path getProductDirectory(ProductLink product, boolean createIfNotExists) throws IOException {
        if (createIfNotExists) {
            if (!hasLocalFolder(product)) {
                return createProductDirectory(product);
            }
        }
        return RyouPath.create(PATH_PRODUCTS, createFolderName(product)).getPath();
    }

    public static boolean hasLocalFolder(Product product) {
        if (product == null) {
            return false;
        }
        return FileUtils.exists(
                RyouPath.create(PATH_PRODUCTS,
                        createFolderName(product)).getPath());
    }

    public static String createFolderName(Product product) {
        return FileUtils.normalizeName(
                product.getName() + " [" + product.getVgmdbID() + "]");
    }

    public static Path createProductDirectory(Product product) throws IOException {
        return FileUtils.createDirectory(RyouPath.create(PATH_PRODUCTS,
                createFolderName(product)).getPath());
    }

    public static Path getProductDirectory(Product product, boolean createIfNotExists) throws IOException {
        if (createIfNotExists) {
            if (!hasLocalFolder(product)) {
                return createProductDirectory(product);
            }
        }
        return RyouPath.create(PATH_PRODUCTS, createFolderName(product)).getPath();
    }

    public static FileOperationResult createCompleteProductStructure(Product product, boolean force) {
        FileOperationResult result = new FileOperationResult();

        if (product == null) {
            result.setSuccess(false);
            result.setMessage("Can't create a artist structure without an album.");
            return result;
        }

        Path productDir;
        try {
            productDir = getProductDirectory(product, true);
        } catch (IOException ex) {
            result.setSuccess(false);
            result.setMessage("Coudn't get productDir -  IOExpcetion " + ex.getMessage());
            result.setException(ex);
            return result;
        }
        if (StringUtils.isEmpty(product.getFolderName()) || force) {
            product.setFolderName(createFolderName(product));

            RyouPath picturePath = RyouPath.create(productDir.toAbsolutePath().toString(), "Pictures");
            if (!FileUtils.exists(picturePath.getPath())) {
                try {
                    FileUtils.createDirectory(picturePath.getPath());
                } catch (IOException ex) {
                    result.getSubOperations().add(new FileOperationResult(
                            true, "Couldn't create directory '"
                            + picturePath.getPath().toAbsolutePath().toString() + "' IO Exception.", ex));
                }
            }
            RyouPath extraPath = RyouPath.create(productDir.toAbsolutePath().toString(), FOLDER_NAME_EXTRA);
            if (!FileUtils.exists(extraPath.getPath())) {
                try {
                    FileUtils.createDirectory(extraPath.getPath());
                } catch (IOException ex) {
                    result.getSubOperations().add(new FileOperationResult(
                            true, "Couldn't create directory '"
                            + extraPath.getPath().toAbsolutePath().toString() + "' IO Exception.", ex));
                }
            }
            RyouPath discographyPath = RyouPath.create(productDir.toAbsolutePath().toString(), FOLDER_NAME_ALBUMS);
            if (!FileUtils.exists(discographyPath.getPath())) {
                try {
                    FileUtils.createDirectory(discographyPath.getPath());
                } catch (IOException ex) {
                    result.getSubOperations().add(new FileOperationResult(
                            true, "Couldn't create directory '"
                            + discographyPath.getPath().toAbsolutePath().toString() + "' IO Exception.", ex));
                }
            }
            updateRelatedAlbums(product, product.getRelatedAlbums(), FOLDER_NAME_ALBUMS);
            RyouPath titles = RyouPath.create(productDir.toAbsolutePath().toString(), FOLDER_NAME_TITLES);
            if (!FileUtils.exists(titles.getPath())) {
                try {
                    FileUtils.createDirectory(titles.getPath());
                } catch (IOException ex) {
                    result.getSubOperations().add(new FileOperationResult(
                            true, "Couldn't create directory '"
                            + titles.getPath().toAbsolutePath().toString() + "' IO Exception.", ex));
                }
            }
            updateRelatedProducts(product, product.getTitles(), FOLDER_NAME_TITLES);
            RyouPath franchises = RyouPath.create(productDir.toAbsolutePath().toString(), FOLDER_NAME_FRANCHISES);
            if (!FileUtils.exists(franchises.getPath())) {
                try {
                    FileUtils.createDirectory(franchises.getPath());
                } catch (IOException ex) {
                    result.getSubOperations().add(new FileOperationResult(
                            true, "Couldn't create directory '"
                            + franchises.getPath().toAbsolutePath().toString() + "' IO Exception.", ex));
                }
            }
            updateRelatedProducts(product, product.getFranchises(), FOLDER_NAME_FRANCHISES);

            if (product.getPicture() != null) {
                Picture picture = product.getPicture();
                try {
                    if (NetUtils.downloadFromUrl(StringUtils.isEmpty(picture.getUrlFull())
                            ? picture.getUrlSmall()
                            : picture.getUrlFull(),
                            productDir.toAbsolutePath().toString()
                            + FileUtils.getFileSystem().getSeparator() + "product.jpg")) {
                        picture.setPictureLocaleStorage(true);
                        picture.setPictureExtension("jpg");
                        picture.setPictureLocation("product.jpg");
                    }
                } catch (IOException ex) {
                    result.getSubOperations().add(new FileOperationResult(
                            true, "Couldn't download artist.jpg IO Exception.", ex));
                }

            }

            FukoDB.getInstance().getProductService().updateFileSystem(product);
        }

        return result;
    }

    public static FileOperationResult updateRelatedProducts(Product product, List<ProductLink> products, String folderName) {
        FileOperationResult result = new FileOperationResult();

        Path productDir;
        try {
            productDir = getProductDirectory(product, true);
        } catch (IOException ex) {
            result.setSuccess(false);
            result.setMessage("Coudn't get ArtistDir -  IOExpcetion " + ex.getMessage());
            result.setException(ex);
            return result;
        }

        for (ProductLink link : products) {
            try {
                Path albumDir = getProductDirectory(link, true);
                Files.createSymbolicLink(RyouPath.create(productDir.toAbsolutePath().toString(),
                        folderName,
                        createFolderName(link)).getPath(),
                        albumDir);
            } catch (FileAlreadyExistsException ex) {
                ex.printStackTrace();
                result.getSubOperations().add(new FileOperationResult(
                        true, "Couldn't create link FileAlreadyExistsException Exception.", ex));
            } catch (IOException ex) {
                ex.printStackTrace();
                result.getSubOperations().add(new FileOperationResult(
                        true, "Couldn't create link IO Exception.", ex));
            }

        }

        return result;
    }

    public static FileOperationResult updateRelatedAlbums(Product product, List<AlbumLink> albums, String folderName) {
        FileOperationResult result = new FileOperationResult();

        Path artistDir;
        try {
            artistDir = getProductDirectory(product, true);
        } catch (IOException ex) {
            result.setSuccess(false);
            result.setMessage("Coudn't get ArtistDir -  IOExpcetion " + ex.getMessage());
            result.setException(ex);
            return result;
        }

        for (AlbumLink link : albums) {
            try {
                Path albumDir = AlbumFileSystem.getAlbumDirectory(link, true);
                Files.createSymbolicLink(RyouPath.create(artistDir.toAbsolutePath().toString(),
                        folderName,
                        AlbumFileSystem.createFolderName(link)).getPath(),
                        albumDir);
            } catch (FileAlreadyExistsException ex) {
                ex.printStackTrace();
                result.getSubOperations().add(new FileOperationResult(
                        true, "Couldn't create link FileAlreadyExistsException Exception.", ex));
            } catch (IOException ex) {
                ex.printStackTrace();
                result.getSubOperations().add(new FileOperationResult(
                        true, "Couldn't create link IO Exception.", ex));
            }

        }

        return result;
    }

}


text:
/**
 * @file
 * @brief This file contains the method declarations to translate
 *        SCSI Log Sense command based of the SATv2 spec.
 */

#ifndef _SATI_LOG_SENSE_H_
#define _SATI_LOG_SENSE_H_

#include <dev/isci/scil/intel_scsi.h>
#include <dev/isci/scil/sati_types.h>
#include <dev/isci/scil/sati_translator_sequence.h>

#define SATI_LOG_SENSE_GET_PC_FIELD(cdb) \
   (( sati_get_cdb_byte((cdb), 2) & SCSI_LOG_SENSE_PC_FIELD_MASK ) \
   >> SCSI_LOG_SENSE_PC_FIELD_SHIFT )

#define SATI_LOG_SENSE_GET_PAGE_CODE(cdb) \
   (( sati_get_cdb_byte((cdb), 2) & SCSI_LOG_SENSE_PAGE_CODE_FIELD_MASK ) \
   >> SCSI_LOG_SENSE_PAGE_CODE_FIELD_SHIFT )

SATI_STATUS sati_log_sense_translate_command(
   SATI_TRANSLATOR_SEQUENCE_T * sequence,
   void                       * scsi_io,
   void                       * ata_io
);

SATI_STATUS sati_log_sense_translate_response(
   SATI_TRANSLATOR_SEQUENCE_T * sequence,
   void                       * scsi_io,
   void                       * ata_io
);
#endif // _SATI_LOG_SENSE_H_


text:
<?xml version='1.0' encoding='UTF-8'?>
<extensions xmlns:atom="http://www.w3.org/2005/Atom" xmlns="http://docs.openstack.org/common/api/v1.0">
  <extension alias="NMN" updated="2011-06-09T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/multinic/api/v1.1" name="Multinic">
    <description>Multiple network support</description>
  </extension>
  <extension alias="OS-DCF" updated="2011-09-27T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/disk_config/api/v1.1" name="DiskConfig">
    <description>Disk Management Extension</description>
  </extension>
  <extension alias="OS-EXT-SRV-ATTR" updated="2011-11-03T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/extended_status/api/v1.1" name="ExtendedServerAttributes">
    <description>Extended Server Attributes support.</description>
  </extension>
  <extension alias="OS-EXT-STS" updated="2011-11-03T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/extended_status/api/v1.1" name="ExtendedStatus">
    <description>Extended Status support</description>
  </extension>
  <extension alias="OS-FLV-DISABLED" updated="2012-08-29T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/flavor_disabled/api/v1.1" name="FlavorDisabled">
    <description>Support to show the disabled status of a flavor</description>
  </extension>
  <extension alias="OS-FLV-EXT-DATA" updated="2011-09-14T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/flavor_extra_data/api/v1.1" name="FlavorExtraData">
    <description>Provide additional data for flavors</description>
  </extension>
  <extension alias="OS-SCH-HNT" updated="2011-07-19T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/scheduler-hints/api/v2" name="SchedulerHints">
    <description>Pass arbitrary key/value pairs to the scheduler</description>
  </extension>
  <extension alias="os-admin-actions" updated="2011-09-20T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/admin-actions/api/v1.1" name="AdminActions">
    <description>Enable admin-only server actions

    Actions include: pause, unpause, suspend, resume, migrate,
    resetNetwork, injectNetworkInfo, lock, unlock, createBackup
    </description>
  </extension>
  <extension alias="os-agents" updated="2012-10-28T00:00:00-00:00" namespace="http://docs.openstack.org/compute/ext/agents/api/v2" name="Agents">
    <description>Agents support</description>
  </extension>
  <extension alias="os-aggregates" updated="2012-01-12T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/aggregates/api/v1.1" name="Aggregates">
    <description>Admin-only aggregate administration</description>
  </extension>
  <extension alias="os-availability-zone" updated="2012-08-09T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/availabilityzone/api/v1.1" name="AvailabilityZone">
    <description>Add availability_zone to the Create Server v1.1 API</description>
  </extension>
  <extension alias="os-certificates" updated="2012-01-19T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/certificates/api/v1.1" name="Certificates">
    <description>Certificates support</description>
  </extension>
  <extension alias="os-cloudpipe" updated="2011-12-16T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/cloudpipe/api/v1.1" name="Cloudpipe">
    <description>Adds actions to create cloudpipe instances.

    When running with the Vlan network mode, you need a mechanism to route
    from the public Internet to your vlans.  This mechanism is known as a
    cloudpipe.

    At the time of creating this class, only OpenVPN is supported.  Support for
    a SSH Bastion host is forthcoming.
    </description>
  </extension>
  <extension alias="os-cloudpipe-update" updated="2012-11-14T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/cloudpipe-update/api/v2" name="CloudpipeUpdate">
    <description>Adds the ability to set the vpn ip/port for cloudpipe instances.</description>
  </extension>
  <extension alias="os-config-drive" updated="2012-07-16T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/config_drive/api/v1.1" name="ConfigDrive">
    <description>Config Drive Extension</description>
  </extension>
  <extension alias="os-console-output" updated="2011-12-08T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/os-console-output/api/v2" name="ConsoleOutput">
    <description>Console log output support, with tailing ability.</description>
  </extension>
  <extension alias="os-consoles" updated="2011-12-23T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/os-consoles/api/v2" name="Consoles">
    <description>Interactive Console support.</description>
  </extension>
  <extension alias="os-coverage" updated="2012-10-15T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/coverage/api/v2" name="Coverage">
    <description>Enable Nova Coverage</description>
  </extension>
  <extension alias="os-create-server-ext" updated="2011-07-19T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/createserverext/api/v1.1" name="Createserverext">
    <description>Extended support to the Create Server v1.1 API</description>
  </extension>
  <extension alias="os-deferred-delete" updated="2011-09-01T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/deferred-delete/api/v1.1" name="DeferredDelete">
    <description>Instance deferred delete</description>
  </extension>
  <extension alias="os-fixed-ips" updated="2012-10-18T13:25:27-06:00" namespace="http://docs.openstack.org/compute/ext/fixed_ips/api/v2" name="FixedIPs">
    <description>Fixed IPs support</description>
  </extension>
  <extension alias="os-flavor-access" updated="2012-08-01T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/flavor_access/api/v2" name="FlavorAccess">
    <description>Flavor access supprt</description>
  </extension>
  <extension alias="os-flavor-extra-specs" updated="2011-06-23T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/flavor_extra_specs/api/v1.1" name="FlavorExtraSpecs">
    <description>Instance type (flavor) extra specs</description>
  </extension>
  <extension alias="os-flavor-manage" updated="2012-01-19T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/flavor_manage/api/v1.1" name="FlavorManage">
    <description>
    Flavor create/delete API support
    </description>
  </extension>
  <extension alias="os-flavor-rxtx" updated="2012-08-29T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/flavor_rxtx/api/v1.1" name="FlavorRxtx">
    <description>Support to show the rxtx status of a flavor</description>
  </extension>
  <extension alias="os-flavor-swap" updated="2012-08-29T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/flavor_swap/api/v1.1" name="FlavorSwap">
    <description>Support to show the swap status of a flavor</description>
  </extension>
  <extension alias="os-floating-ip-dns" updated="2011-12-23T00:00:00+00:00" namespace="http://docs.openstack.org/ext/floating_ip_dns/api/v1.1" name="FloatingIpDns">
    <description>Floating IP DNS support</description>
  </extension>
  <extension alias="os-floating-ip-pools" updated="2012-01-04T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/floating_ip_pools/api/v1.1" name="FloatingIpPools">
    <description>Floating IPs support</description>
  </extension>
  <extension alias="os-floating-ips" updated="2011-06-16T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/floating_ips/api/v1.1" name="FloatingIps">
    <description>Floating IPs support</description>
  </extension>
  <extension alias="os-floating-ips-bulk" updated="2012-10-29T13:25:27-06:00" namespace="http://docs.openstack.org/compute/ext/floating_ips_bulk/api/v2" name="FloatingIpsBulk">
    <description>Bulk handling of Floating IPs</description>
  </extension>
  <extension alias="os-fping" updated="2012-07-06T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/fping/api/v1.1" name="Fping">
    <description>Fping Management Extension.</description>
  </extension>
  <extension alias="os-hide-server-addresses" updated="2012-12-11T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/hide_server_addresses/api/v1.1" name="HideServerAddresses">
    <description>Support hiding server addresses in certain states.</description>
  </extension>
  <extension alias="os-hosts" updated="2011-06-29T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/hosts/api/v1.1" name="Hosts">
    <description>Admin-only host administration</description>
  </extension>
  <extension alias="os-hypervisors" updated="2012-06-21T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/hypervisors/api/v1.1" name="Hypervisors">
    <description>Admin-only hypervisor administration</description>
  </extension>
  <extension alias="os-instance_usage_audit_log" updated="2012-07-06T01:00:00+00:00" namespace="http://docs.openstack.org/ext/services/api/v1.1" name="OSInstanceUsageAuditLog">
    <description>Admin-only Task Log Monitoring</description>
  </extension>
  <extension alias="os-keypairs" updated="2011-08-08T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/keypairs/api/v1.1" name="Keypairs">
    <description>Keypair Support</description>
  </extension>
  <extension alias="os-multiple-create" updated="2012-08-07T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/multiplecreate/api/v1.1" name="MultipleCreate">
    <description>Allow multiple create in the Create Server v1.1 API</description>
  </extension>
  <extension alias="os-networks" updated="2011-12-23T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/networks/api/v1.1" name="Networks">
    <description>Admin-only Network Management Extension</description>
  </extension>
  <extension alias="os-networks-associate" updated="2012-11-19T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/networks_associate/api/v2" name="NetworkAssociationSupport">
    <description>Network association support</description>
  </extension>
  <extension alias="os-quota-class-sets" updated="2012-03-12T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/quota-classes-sets/api/v1.1" name="QuotaClasses">
    <description>Quota classes management support</description>
  </extension>
  <extension alias="os-quota-sets" updated="2011-08-08T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/quotas-sets/api/v1.1" name="Quotas">
    <description>Quotas management support</description>
  </extension>
  <extension alias="os-rescue" updated="2011-08-18T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/rescue/api/v1.1" name="Rescue">
    <description>Instance rescue mode</description>
  </extension>
  <extension alias="os-security-groups" updated="2011-07-21T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/securitygroups/api/v1.1" name="SecurityGroups">
    <description>Security group support</description>
  </extension>
  <extension alias="os-server-diagnostics" updated="2011-12-21T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/server-diagnostics/api/v1.1" name="ServerDiagnostics">
    <description>Allow Admins to view server diagnostics through server action</description>
  </extension>
  <extension alias="os-server-password" updated="2012-11-29T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/server-password/api/v2" name="ServerPassword">
    <description>Server password support</description>
  </extension>
  <extension alias="os-server-start-stop" updated="2012-01-23T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/servers/api/v1.1" name="ServerStartStop">
    <description>Start/Stop instance compute API support</description>
  </extension>
  <extension alias="os-services" updated="2012-10-28T00:00:00-00:00" namespace="http://docs.openstack.org/compute/ext/services/api/v2" name="Services">
    <description>Services support</description>
  </extension>
  <extension alias="os-simple-tenant-usage" updated="2011-08-19T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/os-simple-tenant-usage/api/v1.1" name="SimpleTenantUsage">
    <description>Simple tenant usage extension</description>
  </extension>
  <extension alias="os-used-limits" updated="2012-07-13T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/used_limits/api/v1.1" name="UsedLimits">
    <description>Provide data on limited resources that are being used.</description>
  </extension>
  <extension alias="os-user-data" updated="2012-08-07T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/userdata/api/v1.1" name="UserData">
    <description>Add user_data to the Create Server v1.1 API</description>
  </extension>
  <extension alias="os-virtual-interfaces" updated="2011-08-17T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/virtual_interfaces/api/v1.1" name="VirtualInterfaces">
    <description>Virtual interface support</description>
  </extension>
  <extension alias="os-volumes" updated="2011-03-25T00:00:00+00:00" namespace="http://docs.openstack.org/compute/ext/volumes/api/v1.1" name="Volumes">
    <description>Volumes support</description>
  </extension>
</extensions>


text:
#include "ant_search_uplink.h"
#include <stdint.h>
#include "ant_interface.h"
#include "ant_parameters.h"
#include "app_error.h"
#include "app_util.h"
#include "boards.h"
#include "sdk_config.h"
#include "ant_channel_config.h"
#include "ant_search_config.h"
#include "nrf_soc.h"

#define WILDCARD_DEVICE_NUMBER          0x00                    /**< Wildcard device number. */
// Miscellaneous defines.
#define ANT_CHANNEL_DEFAULT_NETWORK     0x00                    /**< ANT Channel Network. */
#define ANT_CHANNEL_NUMBER              0x00                    /**< ANT Channel Number. */

// Operation modes
static enum
{
    MODE_NONE,                                                  /**< Do not send any uplink messages. */
    MODE_SEND_UPLINK_ANY,                                       /**< Send uplink messages to any devices. */
    MODE_SEND_UPLINK_SPECIFIC,                                  /**< Send a single uplink message to a specific device. */
} m_mode;

static uint8_t m_tx_buffer[ANT_STANDARD_DATA_PAYLOAD_SIZE];     /**< Transmit buffer. */
static uint8_t m_counter;                                       /**< Counter to include in transmit data. */
static bool    m_sent;

/**@brief Send uplink message
 * @param[in] device_number Device number of intended destination of message. Set to WILDCARD_DEVICE_NUMBER for any node.
 */
static void uplink_message_send(uint16_t device_number)
{
    uint8_t err_code;

    m_tx_buffer[0] = 0xFF;
    m_tx_buffer[1] = 0xFF;
    m_tx_buffer[2] = 0xFF;
    m_tx_buffer[3] = 0xFF;
    m_tx_buffer[4] = 0xFF;
    m_tx_buffer[5] = 0xFF;
    m_tx_buffer[6] = 0xFF;
    m_tx_buffer[7] = m_counter;

    if (device_number != WILDCARD_DEVICE_NUMBER)
    {
        // Set the channel ID of the specific device to send message to
        err_code = sd_ant_channel_id_set(ANT_CHANNEL_NUMBER,
                                         device_number,
                                         CHAN_ID_DEV_TYPE,
                                         CHAN_ID_TRANS_TYPE);
        APP_ERROR_CHECK(err_code);
    }

    err_code = sd_ant_broadcast_message_tx(ANT_CHANNEL_NUMBER,
                                           ANT_STANDARD_DATA_PAYLOAD_SIZE,
                                           m_tx_buffer);
    APP_ERROR_CHECK(err_code);

    m_counter++;
}

void ant_search_uplink_setup(void)
{
    uint32_t err_code;

    m_mode    = MODE_NONE;
    m_counter = 0;

    ant_channel_config_t channel_config =
    {
        .channel_number    = ANT_CHANNEL_NUMBER,
        .channel_type      = CHANNEL_TYPE_SLAVE,
        .ext_assign        = EXT_PARAM_ALWAYS_SEARCH,
        .rf_freq           = RF_FREQ,
        .transmission_type = CHAN_ID_TRANS_TYPE,
        .device_type       = CHAN_ID_DEV_TYPE,
        .device_number     = WILDCARD_DEVICE_NUMBER,
        .network_number    = ANT_CHANNEL_DEFAULT_NETWORK,
    };

    ant_search_config_t search_config = DEFAULT_ANT_SEARCH_CONFIG(ANT_CHANNEL_NUMBER);

    // Keep searching always
    search_config.low_priority_timeout = ANT_LOW_PRIORITY_TIMEOUT_DISABLE;

    // Disable high priority search to minimize disruption to other channels while searching
    search_config.high_priority_timeout = ANT_HIGH_PRIORITY_SEARCH_DISABLE;

    // Configure the channel
    err_code = ant_channel_init(&channel_config);
    APP_ERROR_CHECK(err_code);

    // Configure search parameters
    err_code = ant_search_init(&search_config);
    APP_ERROR_CHECK(err_code);

    // Enable extended rx messages, including the channel ID
    err_code = sd_ant_lib_config_set(ANT_LIB_CONFIG_MESG_OUT_INC_DEVICE_ID);
    APP_ERROR_CHECK(err_code);

    // Open background scanning channel
    err_code = sd_ant_channel_open(ANT_CHANNEL_NUMBER);
    APP_ERROR_CHECK(err_code);
}

void ant_search_uplink_bsp_evt_handler(bsp_event_t evt)
{
    switch (evt)
    {
        case BSP_EVENT_KEY_0:
            m_mode = MODE_SEND_UPLINK_ANY;
            uplink_message_send(WILDCARD_DEVICE_NUMBER);
            bsp_board_led_off(BSP_BOARD_LED_1);
            break;

        case BSP_EVENT_KEY_1:
            m_mode = MODE_SEND_UPLINK_SPECIFIC;
            m_sent = false;
            bsp_board_led_off(BSP_BOARD_LED_1);
            break;

        default:
            break; // No implementation needed
    }
}

void ant_search_uplink_event_handler(ant_evt_t * p_ant_evt)
{
    switch (p_ant_evt->event)
    {
        case EVENT_TX:
            bsp_board_led_invert(BSP_BOARD_LED_1);
            if (m_mode == MODE_SEND_UPLINK_ANY)
            {
                uplink_message_send(WILDCARD_DEVICE_NUMBER);
            }
            else if (m_mode == MODE_SEND_UPLINK_SPECIFIC)
            {
                // Reset the channel ID to wild card to continue receiving messages from any device
                uint32_t err_code = sd_ant_channel_id_set(ANT_CHANNEL_NUMBER,
                                                          WILDCARD_DEVICE_NUMBER,
                                                          CHAN_ID_DEV_TYPE,
                                                          CHAN_ID_TRANS_TYPE);
                APP_ERROR_CHECK(err_code);
            }
            break;

        case EVENT_RX:
            bsp_board_led_invert(BSP_BOARD_LED_0);
            if (m_mode == MODE_SEND_UPLINK_SPECIFIC && !m_sent)
            {
                ANT_MESSAGE * p_message = (ANT_MESSAGE *) p_ant_evt->msg.evt_buffer;
                // Decode extended data to get channel ID of the received message and send message to that specific device
                if (p_message->ANT_MESSAGE_stExtMesgBF.bANTDeviceID)
                {
                    uint16_t device_number = uint16_decode(p_message->ANT_MESSAGE_aucExtData);
                    uplink_message_send(device_number);
                    m_sent = true;
                }
            }
            break;

        default:
            break; // No implementation needed
    }
}


text:
class DinnersController < ApplicationController
  before_filter :authorize_invitee_host, only: :show
  include DinnersHelper

  def authorize_invitee_host

    if get_user_id == nil
      render :error
    else
      @dinner = Dinner.find(params[:id])
      @user = get_user_reference
      @invite = @dinner.invites.find_by(user: @user)
      unless @dinner.host == @user || @invite
        render :error
      end
    end
  end

  ##

  def show
    @dinner = Dinner.find(params[:id])
    @course = Course.new
    @drink = Drink.new
    @user = get_user_reference
    @invite = Invite.new

    @uninvited = User.uninvited(@dinner, @user)
    @invited = User.invited(@dinner)

    @comment = Comment.new
  end

  def new
    @owner = get_user_reference
    @other_users = User.other_users(get_user_id)
    @dinner = Dinner.new
    @dinner.invites.build
  end

  def create
    @dinner = Dinner.new(dinner_params)

    if @dinner.save
      params[:dinner][:user_ids].each do |id|
        @dinner.users << User.find(id) unless id==""
      end
      redirect_to dinner_path(@dinner)
    else
      @owner = get_user_reference
      @other_users = User.other_users(get_user_id)
      render :new
    end
  end

  def edit
    @dinner = Dinner.find(params[:id])
  end

  def update
    @dinner = Dinner.find(params[:id])
    @dinner.assign_attributes(dinner_params)
    if @dinner.save
      redirect_to dinner_path(@dinner)
    else
      render :edit
    end
  end

  def uninvite
    @dinner = Dinner.find(params[:dinner_id])
    @invite = Invite.find_by(invite_params, dinner_inv_params)
    @invite.destroy_related_courses
    @invite.destroy
    redirect_to dinner_path(@dinner)
  end

  def destroy
    @dinner = Dinner.find(params[:id])
    Invite.destroy_without_dinner(params[:id])
    Course.destroy_without_dinner(params[:id])
    @dinner.destroy
    redirect_to my_profile_path
  end

  private

  def dinner_params
    params.require(:dinner).permit(:location, :date, :host_id, :name, :attire)
  end

  def invite_params
    params.require(:invite).permit(:user_id)
  end

  def dinner_inv_params
    params.permit(:dinner_id)
  end

end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Bjd.Configurations.Attributes
{
    public class TextBoxAttribute : ControlAttribute
    {
        public TextBoxAttribute() : base(Controls.CtrlType.TextBox) { }
        public TextBoxAttribute(Crlf crlfType) : base(Controls.CtrlType.TextBox, crlfType) { }

    }
}


text:
package landmaster.landcraft.crafttweaker;

import crafttweaker.*;
import crafttweaker.annotations.*;
import crafttweaker.api.item.*;
import crafttweaker.api.liquid.*;
import crafttweaker.api.oredict.*;
import stanhebben.zenscript.annotations.*;

@ZenClass("mods.landcraft.machines")
@ZenRegister
public class Machines {
	@ZenMethod
	public static void setFeedstock(IOreDictEntry entry, int mass, int temp) {
		CraftTweakerAPI.apply(new AddFeedstockAction(entry.getName(), mass, temp));
	}

	@ZenMethod
	public static void removeFeedstock(IOreDictEntry entry) {
		CraftTweakerAPI.apply(new RemoveFeedstockAction(entry.getName()));
	}

	@ZenMethod
	public static void addPotRecipe(IItemStack output, IIngredient ingredient1, IIngredient ingredient2, IIngredient ingredient3, ILiquidStack fluid, int energyPerTick, int time) {
		CraftTweakerAPI.apply(new AddPotRecipeAction(output, ingredient1, ingredient2, ingredient3, fluid, energyPerTick, time));
	}

	@ZenMethod
	public static void removePotRecipe(IIngredient output) {
		CraftTweakerAPI.apply(new RemovePotRecipeAction(output));
	}

	@ZenMethod
	public static void addAltarRecipeEntityDeathTrigger(IItemStack output, int minPyramidSize, IIngredient[] ingredients, String entity) {
		CraftTweakerAPI.apply(new AddAltarRecipeEntityDeathTriggerAction(output, minPyramidSize, ingredients, entity));
	}

	@ZenMethod
	public static void removeAltarRecipeEntityDeathTrigger(IIngredient output) {
		CraftTweakerAPI.apply(new RemoveAltarRecipeEntityDeathTriggerAction(output));
	}
}


text:
.header .menu {
  border-radius: 5px;
}
.no-borderradius .header .menu {
  background-image: url('images/button-background.png');
}


text:
from tools.isType import is_type
from datetime import datetime
from datetime import timedelta

class ILimitator:
    def clear(self):
        raise NotImplementedError()

    def next(self, user, amout=1):
        raise NotImplementedError()

class Limitator(ILimitator):
    ALL_USER = {"id": -1}

    def __init__(self, per_time_unit, time_unit_seconds, per_user=False):
        is_type(int, per_time_unit, "per_time_unit")
        is_type(int, time_unit_seconds, "time_unit_seconds")
        is_type(int, per_user, "per_user")
        self.delta = timedelta(seconds=time_unit_seconds)
        self.per_time_unit = per_time_unit
        self.per_user = per_user
        self.users = None
        self.allUser = None
        self.clear()

    def clear(self):
        if self.per_user:
            self.users = []
        else:
            self.allUser = LimitatorUser(self.ALL_USER)

    def next(self, user, amount=1):
        is_type(dict, user, "user")
        is_type(int, amount, "amout")
        u = self.get_user(user)

        #clear old tiems
        now = datetime.now()
        u.items = list([i for i in u.items if now - i <= self.delta])

        if len(u.items) + amount > self.per_time_unit:
            raise LimitatorLimitted()
        else:
            for i in range(amount):
                u.items.append(now)

    def get_user(self, user):
        if self.per_user:
            users = [u for u in self.users if u.is_user(user)]
            if len(users) > 0:
                return users[0]
            else:
                u = LimitatorUser(user)
                self.users.append(u)
                return u
        else:
            return self.allUser

class LimitatorUser:
    def __init__(self, user):
        self.id = self.get_user_id(user)
        self.items = []

    def is_user(self, user):
        return self.id == self.get_user_id(user)

    @staticmethod
    def get_user_id(user):
        return user["id"]

class LimitatorMultiple(ILimitator):
    def __init__(self, *args):
        [is_type(ILimitator, a, "args") for a in args]
        self.limitators = list(args)

    def next(self, user, amout=1):
        error = False
        for limitator in self.limitators:
            try:
                limitator.next(user, amout)
            except LimitatorLimitted:
                error = True
        if error:
            raise LimitatorLimitted()

    def clear(self):
        for limitator in self.limitators:
            limitator.clear()

class LimitatorLimitted(Exception): pass


text:
import React from 'react';
import { Trans } from '@lingui/react';
import { View, Text, Image, ImageSourcePropType, TouchableOpacity, ScrollView } from 'react-native';
import { colors, textStyles, imageStyles } from '../../application/styles';
import { Icon } from 'native-base';
import { EmptyComponent } from '../empty_component/empty_component';
import { useTheme } from '../main/context_component';

type ErrorScreenComponentProps = {
    readonly refreshScreen: () => void;
    readonly imageSource: ImageSourcePropType;
    readonly title: JSX.Element;
    readonly header?: JSX.Element;
    readonly subTitle?: JSX.Element;
    readonly additionalContent?: JSX.Element;
};

export const ErrorScreenComponent = (props: ErrorScreenComponentProps): JSX.Element => (
    <ScrollView style={{ flex: 1, backgroundColor: colors.lightGrey }}>
        {props.header}
        <View
            style={{
                flex: 1,
                alignItems: 'center',
                paddingTop: 50,
                paddingHorizontal: 20,
            }}
        >
            <ErrorScreenImage imageSource={props.imageSource} />
            <ErrorScreenTitle title={props.title} hasSubTitle={!!props.subTitle} />
            <ErrorScreenSubTitle subTitle={props.subTitle} />
            <ErrorScreenAdditionalContent additionalContent={props.additionalContent} />
            <ErrorScreenRefreshButton refreshScreen={props.refreshScreen} />
        </View>
    </ScrollView>
);

const ErrorScreenImage = (props: { readonly imageSource: ImageSourcePropType }): JSX.Element => (
    <Image
        source={props.imageSource}
        resizeMode={'contain'}
        style={imageStyles.emptyOrErrorComponentImage}
    />
);

const ErrorScreenTitle = (props: { readonly title: JSX.Element, readonly hasSubTitle: boolean }): JSX.Element => {
    const marginBottom = props.hasSubTitle ? 10 : 20;
    return (
        <Text style={[textStyles.headlineH2StyleBlackCenter, { marginBottom }]}>
            {props.title}
        </Text>
    );
};

const ErrorScreenSubTitle = (props: { readonly subTitle?: JSX.Element  }): JSX.Element => {
    if (!props.subTitle) {
        return <EmptyComponent />;
    }
    return (
        <Text style={[textStyles.paragraphStyleBrownCenter, { marginBottom: 20 }]}>
            {props.subTitle}
        </Text>
    );
};

const ErrorScreenAdditionalContent = (props: { readonly additionalContent?: JSX.Element  }): JSX.Element => {
    if (!props.additionalContent) {
        return <EmptyComponent />;
    }
    return (
        <View style={{ marginBottom: 20 }}>
            {props.additionalContent}
        </View>
    );
};

const ErrorScreenRefreshButton = (props: { readonly refreshScreen: () => void }): JSX.Element => {
    const theme = useTheme();
    return <TouchableOpacity onPress={props.refreshScreen} style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 20 }}>
        <Icon name={'refresh'} type={'FontAwesome'} style={{ color: theme.mainColour, fontSize: 17, marginRight: 10 }} />
        <Text style={[textStyles.paragraphBoldBlackLeft, { color: theme.mainColour }]}>
            <Trans>Try again</Trans>
        </Text>
    </TouchableOpacity>;
};


text:
require 'test_helper'

class UsersControllerTest < ActionDispatch::IntegrationTest
  setup do
    @user = users(:me)
  end

  test "should get index" do
    get users_url
    assert_response :success
  end

  test "should get new" do
    get new_user_url
    assert_response :success
  end

  test "should create user" do
    assert_difference('User.count') do
      post users_url, params: { user: { email: 'test@test.fr', firstname: @user.firstname, lastname: @user.lastname, password: 20462046, password_confirmation: 20462046 } }
    end

    created_user = User.last
    assert_redirected_to user_url(User.last)
    assert_not created_user.activated
  end

  test "should create activated user when logged as super_user" do
    login(users(:super_user))
    assert_difference('User.count') do
      post users_url, params: { user: { email: 'test@test.fr', firstname: @user.firstname, lastname: @user.lastname, password: 20462046, password_confirmation: 20462046 } }
    end
    created_user = User.last
    assert_redirected_to user_url(created_user)
    assert created_user.activated
  end

  test "should not create user because password don't match" do
    assert_no_difference('User.count') do
      post users_url, params: { user: { email: 'test@test.fr', firstname: @user.firstname, lastname: @user.lastname } }
    end
  end

  test "should show connected user" do
    login(users(:me))
    get user_url(@user)
    assert_response :success
  end

  test "should show user" do
    get user_url(@user)
    assert_response :success
  end

  test "should redirect on get edit" do
    get edit_user_url(@user)
    assert_response 302
  end

  test "should get edit" do
    login(users(:me))
    get edit_user_url(@user)
    assert_response :success
  end

  test "should redirect update user" do
    patch user_url(@user), params: { user: { email: @user.email, firstname: @user.firstname, lastname: @user.lastname } }
    assert_redirected_to root_url
  end

  test "should update user" do
    login(users(:me))
    patch user_url(@user), params: { user: { email: @user.email, firstname: @user.firstname, lastname: @user.lastname } }
    assert_redirected_to user_url(@user)
  end

  test "should not destroy user" do
    assert_no_difference('User.count') do
      delete user_url(@user)
    end

    assert_redirected_to root_url
  end

  test "should destroy user" do
    login(users(:me))
    assert_difference('User.count', -1) do
      delete user_url(@user)
    end

    assert_redirected_to users_url
  end

  test "should not confirm email" do
    # get email & reset password
    my_girlfriend = users(:my_girlfriend)
    my_girlfriend.reset_email_token!
    assert_not my_girlfriend.activated
    my_girlfriend.reset_email_token!
    # send GET request to confirm email
    get confirm_email_url(token: 'bad_token')
    my_girlfriend.reload
    # check if user is confirmed
    assert_not my_girlfriend.activated
  end

  test "should confirm email" do
    # get email & reset password
    my_girlfriend = users(:my_girlfriend)
    my_girlfriend.reset_email_token!
    assert_not my_girlfriend.activated
    # send GET request to confirm email
    get confirm_email_url(token: my_girlfriend.email_token)
    my_girlfriend.reload
    # check if user is confirmed
    assert my_girlfriend.activated
  end
end


text:
package com.redhat.ceylon.model.loader;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.redhat.ceylon.model.loader.mirror.AnnotationMirror;
import com.redhat.ceylon.model.typechecker.model.Annotation;

/**
 * Enumerates the language module annotations and allows them to be loaded from mirrors
 */
public enum LanguageAnnotation {
    /* modifier annotations */
    ANNOTATION("annotation", 1L<<0, AbstractModelLoader.CEYLON_LANGUAGE_ANNOTATION_ANNOTATION),
    SHARED("shared", 1L<<1, AbstractModelLoader.CEYLON_LANGUAGE_SHARED_ANNOTATION),
    VARIABLE("variable", 1L<<2, AbstractModelLoader.CEYLON_LANGUAGE_VARIABLE_ANNOTATION),
    ABSTRACT("abstract", 1L<<3, AbstractModelLoader.CEYLON_LANGUAGE_ABSTRACT_ANNOTATION),
    SEALED("sealed", 1L<<4, AbstractModelLoader.CEYLON_LANGUAGE_SEALED_ANNOTATION),
    FINAL("final", 1L<<5, AbstractModelLoader.CEYLON_LANGUAGE_FINAL_ANNOTATION),
    ACTUAL("actual", 1L<<6, AbstractModelLoader.CEYLON_LANGUAGE_ACTUAL_ANNOTATION),
    FORMAL("formal", 1L<<7, AbstractModelLoader.CEYLON_LANGUAGE_FORMAL_ANNOTATION),
    DEFAULT("default", 1L<<8, AbstractModelLoader.CEYLON_LANGUAGE_DEFAULT_ANNOTATION),
    LATE("late", 1L<<9, AbstractModelLoader.CEYLON_LANGUAGE_LATE_ANNOTATION),
    OPTIONAL("optional", 1L<<11, AbstractModelLoader.CEYLON_LANGUAGE_OPTIONAL_ANNOTATION),
    SERIALIZABLE("serializable", 1L<<12, AbstractModelLoader.CEYLON_LANGUAGE_SERIALIZABLE_ANNOTATION),

    /* documentation annotations */
    DOC("doc", 0, AbstractModelLoader.CEYLON_LANGUAGE_DOC_ANNOTATION) {
        public List<Annotation> makeFromCeylonAnnotation(AnnotationMirror mirror) {
            Annotation anno = new Annotation(name);
            anno.addPositionalArgument((String)mirror.getValue("description"));
            return Collections.singletonList(anno);
        }
    },
    THROWS("throws", 0, AbstractModelLoader.CEYLON_LANGUAGE_THROWS_ANNOTATIONS) {
        public List<Annotation> makeFromCeylonAnnotation(AnnotationMirror mirror) {
            @SuppressWarnings("unchecked")
            List<AnnotationMirror> thrownExceptions = (List<AnnotationMirror>)mirror.getValue("value");
            List<Annotation> result = new ArrayList<Annotation>(thrownExceptions.size());
            for (AnnotationMirror thrown : thrownExceptions) {
                Annotation anno = new Annotation(name);
                // can't decode the declaration
                anno.addPositionalArgument(parseMetamodelReference((String)thrown.getValue("type")));
                anno.addPositionalArgument((String)thrown.getValue("when"));
                result.add(anno);
            }
            return result;
        }
    },
    BY("by", 0, AbstractModelLoader.CEYLON_LANGUAGE_AUTHORS_ANNOTATION) {
        public List<Annotation> makeFromCeylonAnnotation(AnnotationMirror mirror) {
            Annotation anno = new Annotation(name);
            @SuppressWarnings("unchecked")
            List<String> authors = (List<String>)mirror.getValue("authors");
            for (String author : authors) {
                anno.addPositionalArgument(author);
            }
            return Collections.singletonList(anno);
        }
    },
    NATIVE("native", 0, AbstractModelLoader.CEYLON_LANGUAGE_NATIVE_ANNOTATION) {
        public List<Annotation> makeFromCeylonAnnotation(AnnotationMirror mirror) {
            Annotation anno = new Annotation(name);
            @SuppressWarnings("unchecked")
            List<String> backends = (List<String>)mirror.getValue("backends");
            if (backends != null) {
                for (String backend : backends) {
                    anno.addPositionalArgument(backend);
                }
            }
            return Collections.singletonList(anno);
        }
    },
    SEE("see", 0, AbstractModelLoader.CEYLON_LANGUAGE_SEE_ANNOTATIONS) {
        public List<Annotation> makeFromCeylonAnnotation(AnnotationMirror mirror) {
            @SuppressWarnings("unchecked")
            List<AnnotationMirror> sees = (List<AnnotationMirror>)mirror.getValue("value");
            List<Annotation> result = new ArrayList<Annotation>(sees.size());
            for (AnnotationMirror see : sees) {
                Annotation anno = new Annotation(name);
                // can't decode the declaration
                @SuppressWarnings("unchecked")
                List<String> elements = (List<String>)see.getValue("programElements");
                for (String s : elements) {
                    anno.addPositionalArgument(parseMetamodelReference(s));
                }
                result.add(anno);
            }
            return result;
        }

    },
    LICENSE("license", 0, AbstractModelLoader.CEYLON_LANGUAGE_LICENSE_ANNOTATION) {
        public List<Annotation> makeFromCeylonAnnotation(AnnotationMirror mirror) {
            Annotation anno = new Annotation(name);
            anno.addPositionalArgument((String)mirror.getValue("description"));
            return Collections.singletonList(anno);
        }
    },
    DEPRECATED("deprecated", 0, AbstractModelLoader.CEYLON_LANGUAGE_DEPRECATED_ANNOTATION) {
        public List<Annotation> makeFromCeylonAnnotation(AnnotationMirror mirror) {
            Annotation anno = new Annotation(name);
            anno.addPositionalArgument((String)mirror.getValue("description"));
            return Collections.singletonList(anno);
        }
    },
    TAGGED("tagged", 0, AbstractModelLoader.CEYLON_LANGUAGE_TAGS_ANNOTATION) {
        public List<Annotation> makeFromCeylonAnnotation(AnnotationMirror mirror) {
            Annotation anno = new Annotation(name);
            @SuppressWarnings("unchecked")
            List<String> tags = (List<String>)mirror.getValue("tags");
            for (String tag : tags) {
                anno.addPositionalArgument(tag);
            }
            return Collections.singletonList(anno);
        }
    },
    SUPPRESS_WARNINGS("suppressWarnings", 0, AbstractModelLoader.CEYLON_LANGUAGE_SUPPRESS_WARNINGS_ANNOTATION) {
        public List<Annotation> makeFromCeylonAnnotation(AnnotationMirror mirror) {
            Annotation anno = new Annotation(name);
            @SuppressWarnings("unchecked")
            List<String> warnings = (List<String>)mirror.getValue("warnings");
            for (String tag : warnings) {
                anno.addPositionalArgument(tag);
            }
            return Collections.singletonList(anno);
        }
    },
    // the name of the function is "aliased" but its type is "AliasesAnnotation"
    ALIASES("aliased", 0, AbstractModelLoader.CEYLON_LANGUAGE_ALIASES_ANNOTATION){
        public List<Annotation> makeFromCeylonAnnotation(AnnotationMirror mirror) {
            Annotation anno = new Annotation(name);
            @SuppressWarnings("unchecked")
            List<String> aliases = (List<String>)mirror.getValue("aliases");
            for (String alias : aliases) {
                anno.addPositionalArgument(alias);
            }
            return Collections.singletonList(anno);
        }
    };

    /**
     * The unqualified Ceylon name of the annotation, e.g. {@code shared}
     */
    public final String name;

    /**
     * The mask used to address this modifier when encoded as a long.
     * zero if this annotation is not a model annotation
     */
    public final long mask;
    /**
     * The qualifier Java name of the annotation type, e.g. {@code ceylon.language.Shared$annotation$}
     */
    public final String annotationType;

    LanguageAnnotation(String name, long mask, String annotationType) {
        this.name = name;
        this.mask = mask;
        this.annotationType = annotationType;
    }

    /**
     * Whether this annotation is a modifier annotation
     * (i.e. one whose annotation class is nullary, and
     * therefore whose presence/absence is all that matters)
     */
    public boolean isModifier() {
        return mask != 0;
    }

    /**
     * Construct a Ceylon annotation model from the information stored in
     * the mirror of the Ceylon annotation.
     * @param mirror The mirror of the Ceylon annotation.
     * @return
     */
    public List<Annotation> makeFromCeylonAnnotation(AnnotationMirror mirror) {
        return Collections.singletonList(new Annotation(name));
    }

    protected String parseMetamodelReference(String s) {
        // Ugly hack to save us having to actually parse the output of
        // ExpressionTransfomer.serializeReferenceable() in order to get the
        // unqualified name
        return s.replaceAll("^.*::[CIAVFP]", "").replaceAll("^.*\\.[CIAVFP]", "");
    }
}


text:
sap.ui.define([], function () {
	"use strict";

	/**
	 *
	 * @constructor
	 */
	function Shape() {
		this.oContainer = null;
	}

	Shape.extend = function () {
		var fnConstructor = function () {};
		fnConstructor.prototype = new Shape();
		fnConstructor.prototype.constructor = fnConstructor;

		return fnConstructor;
	};

	/**
	 *
	 * @param sSvgNamespace {string} namespace to the svg library
	 * @param sShape {string} shape type
	 * @return {Shape} SVGSVGElement
	 */
	Shape.prototype.createShape = function (sSvgNamespace, sShape) {
		this.oContainer = document.createElementNS(sSvgNamespace, sShape);
		this.oContainer.setAttribute("class", ['shape', sShape].join(" ")) ;

		return this;
	};

	/**
	 * Changes the shape coordinates
	 * @param sCoords {string} shape's new coordinates
	 */
	Shape.prototype.setPosition = function (sCoords) {
		// override
	};

	Shape.prototype.show = function () {
		this.oContainer.style.opacity = '1';
	};

	Shape.prototype.hide = function () {
		this.oContainer.style.opacity = '0';
	};

	return Shape;
});


text:
Report basic metrics summarizing the log volume. See [docs] for more information.

[docs]: https://netflix.github.io/spectator/en/latest/ext/log4j1/

## Gradle

```
compile "com.netflix.spectator:spectator-ext-log4j1:${version}"
```


text:
@implementation DCReleaseTrack

@end


text:
/**
 * Removes last tab from an Element (e.g. hit Back button)
 *
 * @param  {Object} obj Element containing the tab(s)
 * @param  {Mixed}  arg Array of routes or route to destroy, e.g. "/blog"
 * @return {Object}     Element which contained the tab(s)
 */
var destroy = function ( obj, arg ) {
	if ( !( obj instanceof Element ) || arg === undefined ) {
		throw Error( $.label.error.invalidArguments );
	}

	if ( !( arg instanceof Array ) ) {
		arg = arg.toString().explode();
	}

	// Removing tab(s) if found
	arg.forEach( function ( i ) {
		var root = false,
		    li, section;

		if ( i === undefined ) {
			return;
		}
		else {
			i  = i.toLowerCase().replace( /^\/{1,1}/, "" );
			li = obj.find( "a[data-route=\"/" + i + "\"]" ).last().parentNode;

			if ( li !== undefined ) {
				section = li.parentNode.parentNode.find( "section[data-hash=\"" + i + "\"]" ).last();
				section.destroy();
				li.destroy();

				// Loading initial route if the current one was just destroyed
				if ( $.route.hash() === i ) {
					$.route.hash( $.route.initial );
				}
			}
		}
	});

	return obj;
};


text:
import numpy as np
from scipy import interp
import matplotlib.pyplot as plt
import sys
import os

from sklearn import svm, datasets
from sklearn.metrics import roc_curve, auc
from sklearn.cross_validation import StratifiedKFold

###############################################################################
# prepare dataset
###############################################################################

kfold = int(sys.argv[3])
prefix = sys.argv[4]

dat_fh = open(sys.argv[1], 'rb')
tar_fh = open(sys.argv[2], 'rb')
dat = []
while True:
    l = dat_fh.readline()
    if len(l) == 0:
        break
    lc = l.strip("\n").split("\t")
    dat.append([float(i) for i in lc])

X = np.array(dat)

tar = []
while True:
    l = tar_fh.readline()
    if len(l) == 0:
        break
    lc = l.strip("\n").split("\t")
    tar.append(float(lc[0]))

y = np.array(tar)

###############################################################################
# Classification and ROC analysis
#
# Run classifier with cross-validation and plot ROC curves
print "Training data count: " + str(len(y))
cv = StratifiedKFold(y, n_folds=kfold)

#for train, test in cv:
#    print("%s %s" % (train, test))

####################
# your classifier
####################

if prefix == "LR":
	from sklearn.linear_model import LogisticRegression
	classifier = LogisticRegression(penalty='l2', C=1)
elif prefix == "GBDT":
	from sklearn.ensemble import GradientBoostingClassifier
	classifier = GradientBoostingClassifier(n_estimators=200)
elif prefix == "RF":
	from sklearn.ensemble import RandomForestClassifier
	classifier = RandomForestClassifier(n_estimators=10)
elif prefix == "SVM":
	from sklearn.svm import SVC
	classifier = SVC(kernel='linear', probability=True)
elif prefix == "NB":
	from sklearn.naive_bayes import MultinomialNB
	classifier = MultinomialNB(alpha=0.01)
elif prefix == "KNN":
	from sklearn.neighbors import KNeighborsClassifier
	classifier = KNeighborsClassifier()
elif prefix == "DT":
	from sklearn import tree
	classifier = tree.DecisionTreeClassifier()
else:
	print >>sys.stderr, "Wrong prefix: " % (prefix)

mean_tpr = 0.0
mean_fpr = np.linspace(0, 1, 100)
all_tpr = []
model_save = {}
best_model_auc = 0
best_model_index = 0
from sklearn import metrics
for i, (train, test) in enumerate(cv):
    classifier.fit(X[train], y[train])
    a = classifier.fit(X[train], y[train])
    #print a.coef_
    probas_ = classifier.fit(X[train], y[train]).predict_proba(X[test])
    # Compute ROC curve and area the curve
    fpr, tpr, thresholds = roc_curve(y[test], probas_[:, 1], pos_label=1)
    predict = classifier.fit(X[train], y[train]).predict(X[test])
    precision = metrics.precision_score(y[test], predict)
    recall = metrics.recall_score(y[test], predict)
    print str(precision) + "\t" + str(recall)
    mean_tpr += interp(mean_fpr, fpr, tpr)
    mean_tpr[0] = 0.0
    roc_auc = auc(fpr, tpr)
    model_save[i] = classifier
    if roc_auc > best_model_auc:
        best_model_auc = roc_auc
        best_model_index = i
    plt.plot(fpr, tpr, lw=1, label='ROC fold %d (area = %0.2f)' % (i, roc_auc))

from sklearn.externals import joblib
print best_model_index

print "################\nCoef_\n";
print model_save[best_model_index].coef_[0]
print "###############\n";

coef_normalized_arr = []
coef_sum = sum(model_save[best_model_index].coef_[0])
for coef in model_save[best_model_index].coef_[0]:
	coef_normalized = coef/float(coef_sum)
	coef_normalized_arr.append(coef_normalized)

out = open("./" + prefix + ".weight.value.lst", 'wb')
print >>out,"miRNA_weight\t%.2f\nTF_weight\t%.2f\nPCG_weight\t%.2f" % (coef_normalized_arr[0], coef_normalized_arr[1], coef_normalized_arr[2])
out.close()

try:
	os.makedirs("./" + prefix)
except OSError:
	if not os.path.isdir("./" + prefix):
		raise

joblib.dump(model_save[best_model_index], "./" + prefix + "/" + prefix + ".pkl")

if prefix == "LR" or prefix == "SVM" or prefix == "KNN":
	print model_save[best_model_index].coef_
	print model_save[best_model_index].intercept_
else:
	print model_save[best_model_index].feature_importances_

#plt.plot([0, 1], [0, 1], '--', color=(0.6, 0.6, 0.6), label='Luck')

plt.plot([0, 1], [0, 1], '--', color=(0.6, 0.6, 0.6))
mean_tpr /= len(cv)
mean_tpr[-1] = 1.0
mean_auc = auc(mean_fpr, mean_tpr)

out = open("./" + prefix + ".tpr.fpr.txt", 'wb')
for i in range(0,len(mean_fpr), 1):
         print >>out, "%.4f\t%.4f" % (mean_tpr[i], mean_fpr[i])
out.close()

plt.plot(mean_fpr, mean_tpr, 'k--',
         label='Mean ROC (area = %0.2f)' % mean_auc, lw=2)

plt.xlim([-0.05, 1.05])
plt.ylim([-0.05, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic by ' + prefix)
plt.legend(loc="lower right")
plt.savefig("./" + prefix + ".png")


text:
URL: https://leetcode.com/problems/majority-element-ii/</br>
Given an integer array of size _n_, find all elements that appear more than `⌊ n/3 ⌋` times. The algorithm should run in linear time and in O(1) space.

####Hint:

1. How many majority elements could it possibly have?
2. Do you have a better hint? Suggest it!

__Code:__

	class Solution {
	public:

	    //O(n) Space compexity
	    vector<int> majorityElement01(vector<int>& nums) {
	        vector<int> result;
	        unordered_map<int, int> counts;
	        int n = nums.size();
	        for(auto item : nums){
	            counts[item]++;
	            if (counts[item] > n/3 ){
	               result.push_back(item);
	               //Tricky: make sure the item only can be put into result once.
	               counts[item] = -n;
	            }
	        }
	        return result;
	    }
	    //We know, there could be at most two numbers can be more than 1/3
	    //so, same as Majority Element I problem, we can have two counters.
	    vector<int> majorityElement02(vector<int>& nums) {
	        if(nums.size()<=1) return nums;

	        //the same algorithm as Majority Element I problem
	        int majority1=0, majority2=0, cnt1=0, cnt2=0;
	        for(auto item: nums) {
	            if (cnt1 == 0) {
	                majority1 = item;
	                cnt1 = 1;
	            } else if (majority1 == item) {
	                cnt1++;
	            } else if (cnt2 == 0) {
	                majority2 = item;
	                cnt2 = 1;
	            } else if (majority2 == item) {
	                cnt2++;
	            } else {
	                cnt1--;
	                cnt2--;
	            }
	        }
	        //re-check it again, in case there has less than two numbers of majority
	        cnt1 = cnt2 = 0;
	        for (auto item : nums) {
	            if (majority1 == item) cnt1++;
	            else if (majority2 == item) cnt2++;
	        }
	        vector<int> result;
	        if (cnt1 > nums.size()/3) result.push_back(majority1);
	        if (cnt2 > nums.size()/3) result.push_back(majority2);
	        return result;

	    }
	};


text:
import logging
from collections import defaultdict

import progressbar
import structlog
from django.core.management.base import BaseCommand

from ...actions.invoices import pay_with_account_credit_cards
from ...models import CreditCard, Invoice

def set_debug(logger_name):
    logger = logging.getLogger(logger_name)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(logging.StreamHandler())

logger = structlog.get_logger()

class Command(BaseCommand):
    help = """Pay pending invoices with credit cards registered on accounts.
              Pass v2 to see sql queries"""

    def add_arguments(self, parser):
        parser.add_argument(
            '--dry-run',
            action='store_true',
            dest='dry_run',
            help="Displays the payable invoices but doesn't perform any action."
        )
        parser.add_argument(
            '--progress',
            action='store_true',
            dest='progress',
            help='Displays a progress bar'
        )

    def handle(self, *args, **options):
        if options['verbosity'] >= 2:
            set_debug('django.db.backends')

        dry_run = options['dry_run']

        all_payable_invoices = Invoice.objects.payable()

        logger.debug(
            'pay-invoice-select',
            dry_run=dry_run,
            payable=len(all_payable_invoices)
        )

        # Should replace by a filter, to run in a single sql query
        invoices = [
            invoice
            for invoice in all_payable_invoices
            if CreditCard.objects.valid().filter(account_id=invoice.account_id).exists()
        ]

        logger.info(
            'pay-invoices-start',
            dry_run=dry_run,
            payable_with_valid_cc=len(invoices)
        )

        if dry_run:
            return

        if options['progress']:
            bar = progressbar.ProgressBar()
            invoices = bar(invoices)

        try:
            stats = defaultdict(lambda: 0)
            for invoice in invoices:
                try:
                    maybe_transaction = pay_with_account_credit_cards(invoice.pk)
                    if maybe_transaction is not None:
                        stats['success'] += 1
                    else:
                        stats['failure'] += 1
                except Exception as ex:
                    logger.error('pay-invoices-error', invoice_id=invoice.pk, ex=ex)
                    stats['error'] += 1
        finally:
            logger.info('pay-invoices-done', **stats)


text:
package io.github.luiseduardobrito.androidboilerplate.fragment;

import io.github.luiseduardobrito.androidboilerplate.R;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EFragment;

import android.app.Fragment;

@EFragment(R.layout.fragment_groups)
public class GroupsFragment extends Fragment {

	@AfterViews
	void initViews() {

	}
}


text:
namespace search {
namespace expression {

class AndFunctionNode : public BitFunctionNode
{
public:
    DECLARE_EXPRESSIONNODE(AndFunctionNode);
    AndFunctionNode() { }
private:
    ResultNode::CP getInitialValue() const override { return  ResultNode::CP(new Int64ResultNode(-1)); }
    ResultNode & flatten(const ResultNodeVector & v, ResultNode & result) const override { return v.flattenAnd(result); }
    void onArgument(const ResultNode & arg, Int64ResultNode & result) const override;
};

}
}


text:
<?php

namespace Sabre\DAV;

use Sabre\DAVServerTest;
use Sabre\HTTP;

class HttpMoveTest extends DAVServerTest {

    /**
     * Sets up the DAV tree.
     *
     * @return void
     */
    function setUpTree() {

        $this->tree = new Mock\Collection('root', [
            'file1' => 'content1',
            'file2' => 'content2',
        ]);

    }

    function testMoveToSelf() {

        $request = new HTTP\Request('MOVE', '/file1', [
            'Destination' => '/file1'
        ]);
        $response = $this->request($request);
        $this->assertEquals(403, $response->getStatus());
        $this->assertEquals('content1', $this->tree->getChild('file1')->get());

    }

    function testMove() {

        $request = new HTTP\Request('MOVE', '/file1', [
            'Destination' => '/file3'
        ]);
        $response = $this->request($request);
        $this->assertEquals(201, $response->getStatus(), print_r($response,true));
        $this->assertEquals('content1', $this->tree->getChild('file3')->get());
        $this->assertFalse($this->tree->childExists('file1'));

    }

    function testMoveToExisting() {

        $request = new HTTP\Request('MOVE', '/file1', [
            'Destination' => '/file2'
        ]);
        $response = $this->request($request);
        $this->assertEquals(204, $response->getStatus(), print_r($response,true));
        $this->assertEquals('content1', $this->tree->getChild('file2')->get());
        $this->assertFalse($this->tree->childExists('file1'));

    }

    function testMoveToExistingOverwriteT() {

        $request = new HTTP\Request('MOVE', '/file1', [
            'Destination' => '/file2',
            'Overwrite' => 'T',
        ]);
        $response = $this->request($request);
        $this->assertEquals(204, $response->getStatus(), print_r($response,true));
        $this->assertEquals('content1', $this->tree->getChild('file2')->get());
        $this->assertFalse($this->tree->childExists('file1'));

    }

    function testMoveToExistingOverwriteF() {

        $request = new HTTP\Request('MOVE', '/file1', [
            'Destination' => '/file2',
            'Overwrite' => 'F',
        ]);
        $response = $this->request($request);
        $this->assertEquals(412, $response->getStatus(), print_r($response,true));
        $this->assertEquals('content1', $this->tree->getChild('file1')->get());
        $this->assertEquals('content2', $this->tree->getChild('file2')->get());
        $this->assertTrue($this->tree->childExists('file1'));
        $this->assertTrue($this->tree->childExists('file2'));

    }

    /**
     * If we MOVE to an existing file, but a plugin prevents the original from
     * being deleted, we need to make sure that the server does not delete
     * the destination.
     */
    function testMoveToExistingBlockedDeleteSource() {

        $this->server->on('beforeUnbind', function($path) {

            if ($path==='file1') {
                throw new \Sabre\DAV\Exception\Forbidden('uh oh');
            }

        });
        $request = new HTTP\Request('MOVE', '/file1', [
            'Destination' => '/file2'
        ]);
        $response = $this->request($request);
        $this->assertEquals(403, $response->getStatus(), print_r($response,true));
        $this->assertEquals('content1', $this->tree->getChild('file1')->get());
        $this->assertEquals('content2', $this->tree->getChild('file2')->get());
        $this->assertTrue($this->tree->childExists('file1'));
        $this->assertTrue($this->tree->childExists('file2'));

    }
}