text:
//===-- MipsTargetStreamer.cpp - Mips Target Streamer Methods -------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides Mips specific target streamer methods.
//
//===----------------------------------------------------------------------===//

#include "InstPrinter/MipsInstPrinter.h"
#include "MipsELFStreamer.h"
#include "MipsMCTargetDesc.h"
#include "MipsTargetObjectFile.h"
#include "MipsTargetStreamer.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCSectionELF.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/MC/MCSymbolELF.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ELF.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FormattedStream.h"

using namespace llvm;

MipsTargetStreamer::MipsTargetStreamer(MCStreamer &S)
    : MCTargetStreamer(S), ModuleDirectiveAllowed(true) {
  GPRInfoSet = FPRInfoSet = FrameInfoSet = false;
}
void MipsTargetStreamer::emitDirectiveSetMicroMips() {}
void MipsTargetStreamer::emitDirectiveSetNoMicroMips() {}
void MipsTargetStreamer::emitDirectiveSetMips16() {}
void MipsTargetStreamer::emitDirectiveSetNoMips16() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveSetReorder() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveSetNoReorder() {}
void MipsTargetStreamer::emitDirectiveSetMacro() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveSetNoMacro() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveSetMsa() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveSetNoMsa() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveSetAt() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveSetAtWithArg(unsigned RegNo) {
  forbidModuleDirective();
}
void MipsTargetStreamer::emitDirectiveSetNoAt() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveEnd(StringRef Name) {}
void MipsTargetStreamer::emitDirectiveEnt(const MCSymbol &Symbol) {}
void MipsTargetStreamer::emitDirectiveAbiCalls() {}
void MipsTargetStreamer::emitDirectiveNaN2008() {}
void MipsTargetStreamer::emitDirectiveNaNLegacy() {}
void MipsTargetStreamer::emitDirectiveOptionPic0() {}
void MipsTargetStreamer::emitDirectiveOptionPic2() {}
void MipsTargetStreamer::emitDirectiveInsn() { forbidModuleDirective(); }
void MipsTargetStreamer::emitFrame(unsigned StackReg, unsigned StackSize,
                                   unsigned ReturnReg) {}
void MipsTargetStreamer::emitMask(unsigned CPUBitmask, int CPUTopSavedRegOff) {}
void MipsTargetStreamer::emitFMask(unsigned FPUBitmask, int FPUTopSavedRegOff) {
}
void MipsTargetStreamer::emitDirectiveSetArch(StringRef Arch) {
  forbidModuleDirective();
}
void MipsTargetStreamer::emitDirectiveSetMips0() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveSetMips1() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveSetMips2() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveSetMips3() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveSetMips4() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveSetMips5() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveSetMips32() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveSetMips32R2() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveSetMips32R3() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveSetMips32R5() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveSetMips32R6() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveSetMips64() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveSetMips64R2() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveSetMips64R3() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveSetMips64R5() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveSetMips64R6() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveSetPop() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveSetPush() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveSetSoftFloat() {
  forbidModuleDirective();
}
void MipsTargetStreamer::emitDirectiveSetHardFloat() {
  forbidModuleDirective();
}
void MipsTargetStreamer::emitDirectiveSetDsp() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveSetNoDsp() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveCpLoad(unsigned RegNo) {}
void MipsTargetStreamer::emitDirectiveCpRestore(
    SmallVector<MCInst, 3> &StoreInsts, int Offset) {
  forbidModuleDirective();
}
void MipsTargetStreamer::emitDirectiveCpsetup(unsigned RegNo, int RegOrOffset,
                                              const MCSymbol &Sym, bool IsReg) {
}

void MipsTargetStreamer::emitDirectiveModuleFP() {}

void MipsTargetStreamer::emitDirectiveModuleOddSPReg() {
  if (!ABIFlagsSection.OddSPReg && !ABIFlagsSection.Is32BitABI)
    report_fatal_error("+nooddspreg is only valid for O32");
}
void MipsTargetStreamer::emitDirectiveModuleSoftFloat() {}
void MipsTargetStreamer::emitDirectiveModuleHardFloat() {}
void MipsTargetStreamer::emitDirectiveSetFp(
    MipsABIFlagsSection::FpABIKind Value) {
  forbidModuleDirective();
}
void MipsTargetStreamer::emitDirectiveSetOddSPReg() { forbidModuleDirective(); }
void MipsTargetStreamer::emitDirectiveSetNoOddSPReg() {
  forbidModuleDirective();
}

MipsTargetAsmStreamer::MipsTargetAsmStreamer(MCStreamer &S,
                                             formatted_raw_ostream &OS)
    : MipsTargetStreamer(S), OS(OS) {}

void MipsTargetAsmStreamer::emitDirectiveSetMicroMips() {
  OS << "\t.set\tmicromips\n";
  forbidModuleDirective();
}

void MipsTargetAsmStreamer::emitDirectiveSetNoMicroMips() {
  OS << "\t.set\tnomicromips\n";
  forbidModuleDirective();
}

void MipsTargetAsmStreamer::emitDirectiveSetMips16() {
  OS << "\t.set\tmips16\n";
  forbidModuleDirective();
}

void MipsTargetAsmStreamer::emitDirectiveSetNoMips16() {
  OS << "\t.set\tnomips16\n";
  MipsTargetStreamer::emitDirectiveSetNoMips16();
}

void MipsTargetAsmStreamer::emitDirectiveSetReorder() {
  OS << "\t.set\treorder\n";
  MipsTargetStreamer::emitDirectiveSetReorder();
}

void MipsTargetAsmStreamer::emitDirectiveSetNoReorder() {
  OS << "\t.set\tnoreorder\n";
  forbidModuleDirective();
}

void MipsTargetAsmStreamer::emitDirectiveSetMacro() {
  OS << "\t.set\tmacro\n";
  MipsTargetStreamer::emitDirectiveSetMacro();
}

void MipsTargetAsmStreamer::emitDirectiveSetNoMacro() {
  OS << "\t.set\tnomacro\n";
  MipsTargetStreamer::emitDirectiveSetNoMacro();
}

void MipsTargetAsmStreamer::emitDirectiveSetMsa() {
  OS << "\t.set\tmsa\n";
  MipsTargetStreamer::emitDirectiveSetMsa();
}

void MipsTargetAsmStreamer::emitDirectiveSetNoMsa() {
  OS << "\t.set\tnomsa\n";
  MipsTargetStreamer::emitDirectiveSetNoMsa();
}

void MipsTargetAsmStreamer::emitDirectiveSetAt() {
  OS << "\t.set\tat\n";
  MipsTargetStreamer::emitDirectiveSetAt();
}

void MipsTargetAsmStreamer::emitDirectiveSetAtWithArg(unsigned RegNo) {
  OS << "\t.set\tat=$" << Twine(RegNo) << "\n";
  MipsTargetStreamer::emitDirectiveSetAtWithArg(RegNo);
}

void MipsTargetAsmStreamer::emitDirectiveSetNoAt() {
  OS << "\t.set\tnoat\n";
  MipsTargetStreamer::emitDirectiveSetNoAt();
}

void MipsTargetAsmStreamer::emitDirectiveEnd(StringRef Name) {
  OS << "\t.end\t" << Name << '\n';
}

void MipsTargetAsmStreamer::emitDirectiveEnt(const MCSymbol &Symbol) {
  OS << "\t.ent\t" << Symbol.getName() << '\n';
}

void MipsTargetAsmStreamer::emitDirectiveAbiCalls() { OS << "\t.abicalls\n"; }

void MipsTargetAsmStreamer::emitDirectiveNaN2008() { OS << "\t.nan\t2008\n"; }

void MipsTargetAsmStreamer::emitDirectiveNaNLegacy() {
  OS << "\t.nan\tlegacy\n";
}

void MipsTargetAsmStreamer::emitDirectiveOptionPic0() {
  OS << "\t.option\tpic0\n";
}

void MipsTargetAsmStreamer::emitDirectiveOptionPic2() {
  OS << "\t.option\tpic2\n";
}

void MipsTargetAsmStreamer::emitDirectiveInsn() {
  MipsTargetStreamer::emitDirectiveInsn();
  OS << "\t.insn\n";
}

void MipsTargetAsmStreamer::emitFrame(unsigned StackReg, unsigned StackSize,
                                      unsigned ReturnReg) {
  OS << "\t.frame\t$"
     << StringRef(MipsInstPrinter::getRegisterName(StackReg)).lower() << ","
     << StackSize << ",$"
     << StringRef(MipsInstPrinter::getRegisterName(ReturnReg)).lower() << '\n';
}

void MipsTargetAsmStreamer::emitDirectiveSetArch(StringRef Arch) {
  OS << "\t.set arch=" << Arch << "\n";
  MipsTargetStreamer::emitDirectiveSetArch(Arch);
}

void MipsTargetAsmStreamer::emitDirectiveSetMips0() {
  OS << "\t.set\tmips0\n";
  MipsTargetStreamer::emitDirectiveSetMips0();
}

void MipsTargetAsmStreamer::emitDirectiveSetMips1() {
  OS << "\t.set\tmips1\n";
  MipsTargetStreamer::emitDirectiveSetMips1();
}

void MipsTargetAsmStreamer::emitDirectiveSetMips2() {
  OS << "\t.set\tmips2\n";
  MipsTargetStreamer::emitDirectiveSetMips2();
}

void MipsTargetAsmStreamer::emitDirectiveSetMips3() {
  OS << "\t.set\tmips3\n";
  MipsTargetStreamer::emitDirectiveSetMips3();
}

void MipsTargetAsmStreamer::emitDirectiveSetMips4() {
  OS << "\t.set\tmips4\n";
  MipsTargetStreamer::emitDirectiveSetMips4();
}

void MipsTargetAsmStreamer::emitDirectiveSetMips5() {
  OS << "\t.set\tmips5\n";
  MipsTargetStreamer::emitDirectiveSetMips5();
}

void MipsTargetAsmStreamer::emitDirectiveSetMips32() {
  OS << "\t.set\tmips32\n";
  MipsTargetStreamer::emitDirectiveSetMips32();
}

void MipsTargetAsmStreamer::emitDirectiveSetMips32R2() {
  OS << "\t.set\tmips32r2\n";
  MipsTargetStreamer::emitDirectiveSetMips32R2();
}

void MipsTargetAsmStreamer::emitDirectiveSetMips32R3() {
  OS << "\t.set\tmips32r3\n";
  MipsTargetStreamer::emitDirectiveSetMips32R3();
}

void MipsTargetAsmStreamer::emitDirectiveSetMips32R5() {
  OS << "\t.set\tmips32r5\n";
  MipsTargetStreamer::emitDirectiveSetMips32R5();
}

void MipsTargetAsmStreamer::emitDirectiveSetMips32R6() {
  OS << "\t.set\tmips32r6\n";
  MipsTargetStreamer::emitDirectiveSetMips32R6();
}

void MipsTargetAsmStreamer::emitDirectiveSetMips64() {
  OS << "\t.set\tmips64\n";
  MipsTargetStreamer::emitDirectiveSetMips64();
}

void MipsTargetAsmStreamer::emitDirectiveSetMips64R2() {
  OS << "\t.set\tmips64r2\n";
  MipsTargetStreamer::emitDirectiveSetMips64R2();
}

void MipsTargetAsmStreamer::emitDirectiveSetMips64R3() {
  OS << "\t.set\tmips64r3\n";
  MipsTargetStreamer::emitDirectiveSetMips64R3();
}

void MipsTargetAsmStreamer::emitDirectiveSetMips64R5() {
  OS << "\t.set\tmips64r5\n";
  MipsTargetStreamer::emitDirectiveSetMips64R5();
}

void MipsTargetAsmStreamer::emitDirectiveSetMips64R6() {
  OS << "\t.set\tmips64r6\n";
  MipsTargetStreamer::emitDirectiveSetMips64R6();
}

void MipsTargetAsmStreamer::emitDirectiveSetDsp() {
  OS << "\t.set\tdsp\n";
  MipsTargetStreamer::emitDirectiveSetDsp();
}

void MipsTargetAsmStreamer::emitDirectiveSetNoDsp() {
  OS << "\t.set\tnodsp\n";
  MipsTargetStreamer::emitDirectiveSetNoDsp();
}

void MipsTargetAsmStreamer::emitDirectiveSetPop() {
  OS << "\t.set\tpop\n";
  MipsTargetStreamer::emitDirectiveSetPop();
}

void MipsTargetAsmStreamer::emitDirectiveSetPush() {
 OS << "\t.set\tpush\n";
 MipsTargetStreamer::emitDirectiveSetPush();
}

void MipsTargetAsmStreamer::emitDirectiveSetSoftFloat() {
  OS << "\t.set\tsoftfloat\n";
  MipsTargetStreamer::emitDirectiveSetSoftFloat();
}

void MipsTargetAsmStreamer::emitDirectiveSetHardFloat() {
  OS << "\t.set\thardfloat\n";
  MipsTargetStreamer::emitDirectiveSetHardFloat();
}

// Print a 32 bit hex number with all numbers.
static void printHex32(unsigned Value, raw_ostream &OS) {
  OS << "0x";
  for (int i = 7; i >= 0; i--)
    OS.write_hex((Value & (0xF << (i * 4))) >> (i * 4));
}

void MipsTargetAsmStreamer::emitMask(unsigned CPUBitmask,
                                     int CPUTopSavedRegOff) {
  OS << "\t.mask \t";
  printHex32(CPUBitmask, OS);
  OS << ',' << CPUTopSavedRegOff << '\n';
}

void MipsTargetAsmStreamer::emitFMask(unsigned FPUBitmask,
                                      int FPUTopSavedRegOff) {
  OS << "\t.fmask\t";
  printHex32(FPUBitmask, OS);
  OS << "," << FPUTopSavedRegOff << '\n';
}

void MipsTargetAsmStreamer::emitDirectiveCpLoad(unsigned RegNo) {
  OS << "\t.cpload\t$"
     << StringRef(MipsInstPrinter::getRegisterName(RegNo)).lower() << "\n";
  forbidModuleDirective();
}

void MipsTargetAsmStreamer::emitDirectiveCpRestore(
    SmallVector<MCInst, 3> &StoreInsts, int Offset) {
  MipsTargetStreamer::emitDirectiveCpRestore(StoreInsts, Offset);
  OS << "\t.cprestore\t" << Offset << "\n";
}

void MipsTargetAsmStreamer::emitDirectiveCpsetup(unsigned RegNo,
                                                 int RegOrOffset,
                                                 const MCSymbol &Sym,
                                                 bool IsReg) {
  OS << "\t.cpsetup\t$"
     << StringRef(MipsInstPrinter::getRegisterName(RegNo)).lower() << ", ";

  if (IsReg)
    OS << "$"
       << StringRef(MipsInstPrinter::getRegisterName(RegOrOffset)).lower();
  else
    OS << RegOrOffset;

  OS << ", ";

  OS << Sym.getName() << "\n";
  forbidModuleDirective();
}

void MipsTargetAsmStreamer::emitDirectiveModuleFP() {
  OS << "\t.module\tfp=";
  OS << ABIFlagsSection.getFpABIString(ABIFlagsSection.getFpABI()) << "\n";
}

void MipsTargetAsmStreamer::emitDirectiveSetFp(
    MipsABIFlagsSection::FpABIKind Value) {
  MipsTargetStreamer::emitDirectiveSetFp(Value);

  OS << "\t.set\tfp=";
  OS << ABIFlagsSection.getFpABIString(Value) << "\n";
}

void MipsTargetAsmStreamer::emitDirectiveModuleOddSPReg() {
  MipsTargetStreamer::emitDirectiveModuleOddSPReg();

  OS << "\t.module\t" << (ABIFlagsSection.OddSPReg ? "" : "no") << "oddspreg\n";
}

void MipsTargetAsmStreamer::emitDirectiveSetOddSPReg() {
  MipsTargetStreamer::emitDirectiveSetOddSPReg();
  OS << "\t.set\toddspreg\n";
}

void MipsTargetAsmStreamer::emitDirectiveSetNoOddSPReg() {
  MipsTargetStreamer::emitDirectiveSetNoOddSPReg();
  OS << "\t.set\tnooddspreg\n";
}

void MipsTargetAsmStreamer::emitDirectiveModuleSoftFloat() {
  OS << "\t.module\tsoftfloat\n";
}

void MipsTargetAsmStreamer::emitDirectiveModuleHardFloat() {
  OS << "\t.module\thardfloat\n";
}

// This part is for ELF object output.
MipsTargetELFStreamer::MipsTargetELFStreamer(MCStreamer &S,
                                             const MCSubtargetInfo &STI)
    : MipsTargetStreamer(S), MicroMipsEnabled(false), STI(STI) {
  MCAssembler &MCA = getStreamer().getAssembler();
  Pic = MCA.getContext().getObjectFileInfo()->getRelocM() == Reloc::PIC_;

  const FeatureBitset &Features = STI.getFeatureBits();

  // Set the header flags that we can in the constructor.
  // FIXME: This is a fairly terrible hack. We set the rest
  // of these in the destructor. The problem here is two-fold:
  //
  // a: Some of the eflags can be set/reset by directives.
  // b: There aren't any usage paths that initialize the ABI
  //    pointer until after we initialize either an assembler
  //    or the target machine.
  // We can fix this by making the target streamer construct
  // the ABI, but this is fraught with wide ranging dependency
  // issues as well.
  unsigned EFlags = MCA.getELFHeaderEFlags();

  // Architecture
  if (Features[Mips::FeatureMips64r6])
    EFlags |= ELF::EF_MIPS_ARCH_64R6;
  else if (Features[Mips::FeatureMips64r2] ||
           Features[Mips::FeatureMips64r3] ||
           Features[Mips::FeatureMips64r5])
    EFlags |= ELF::EF_MIPS_ARCH_64R2;
  else if (Features[Mips::FeatureMips64])
    EFlags |= ELF::EF_MIPS_ARCH_64;
  else if (Features[Mips::FeatureMips5])
    EFlags |= ELF::EF_MIPS_ARCH_5;
  else if (Features[Mips::FeatureMips4])
    EFlags |= ELF::EF_MIPS_ARCH_4;
  else if (Features[Mips::FeatureMips3])
    EFlags |= ELF::EF_MIPS_ARCH_3;
  else if (Features[Mips::FeatureMips32r6])
    EFlags |= ELF::EF_MIPS_ARCH_32R6;
  else if (Features[Mips::FeatureMips32r2] ||
           Features[Mips::FeatureMips32r3] ||
           Features[Mips::FeatureMips32r5])
    EFlags |= ELF::EF_MIPS_ARCH_32R2;
  else if (Features[Mips::FeatureMips32])
    EFlags |= ELF::EF_MIPS_ARCH_32;
  else if (Features[Mips::FeatureMips2])
    EFlags |= ELF::EF_MIPS_ARCH_2;
  else
    EFlags |= ELF::EF_MIPS_ARCH_1;

  // Other options.
  if (Features[Mips::FeatureNaN2008])
    EFlags |= ELF::EF_MIPS_NAN2008;

  // -mabicalls and -mplt are not implemented but we should act as if they were
  // given.
  EFlags |= ELF::EF_MIPS_CPIC;

  MCA.setELFHeaderEFlags(EFlags);
}

void MipsTargetELFStreamer::emitLabel(MCSymbol *S) {
  auto *Symbol = cast<MCSymbolELF>(S);
  if (!isMicroMipsEnabled())
    return;
  getStreamer().getAssembler().registerSymbol(*Symbol);
  uint8_t Type = Symbol->getType();
  if (Type != ELF::STT_FUNC)
    return;

  Symbol->setOther(ELF::STO_MIPS_MICROMIPS);
}

void MipsTargetELFStreamer::finish() {
  MCAssembler &MCA = getStreamer().getAssembler();
  const MCObjectFileInfo &OFI = *MCA.getContext().getObjectFileInfo();

  // .bss, .text and .data are always at least 16-byte aligned.
  MCSection &TextSection = *OFI.getTextSection();
  MCA.registerSection(TextSection);
  MCSection &DataSection = *OFI.getDataSection();
  MCA.registerSection(DataSection);
  MCSection &BSSSection = *OFI.getBSSSection();
  MCA.registerSection(BSSSection);

  TextSection.setAlignment(std::max(16u, TextSection.getAlignment()));
  DataSection.setAlignment(std::max(16u, DataSection.getAlignment()));
  BSSSection.setAlignment(std::max(16u, BSSSection.getAlignment()));

  const FeatureBitset &Features = STI.getFeatureBits();

  // Update e_header flags. See the FIXME and comment above in
  // the constructor for a full rundown on this.
  unsigned EFlags = MCA.getELFHeaderEFlags();

  // ABI
  // N64 does not require any ABI bits.
  if (getABI().IsO32())
    EFlags |= ELF::EF_MIPS_ABI_O32;
  else if (getABI().IsN32())
    EFlags |= ELF::EF_MIPS_ABI2;

  if (Features[Mips::FeatureGP64Bit]) {
    if (getABI().IsO32())
      EFlags |= ELF::EF_MIPS_32BITMODE; /* Compatibility Mode */
  } else if (Features[Mips::FeatureMips64r2] || Features[Mips::FeatureMips64])
    EFlags |= ELF::EF_MIPS_32BITMODE;

  // If we've set the cpic eflag and we're n64, go ahead and set the pic
  // one as well.
  if (EFlags & ELF::EF_MIPS_CPIC && getABI().IsN64())
    EFlags |= ELF::EF_MIPS_PIC;

  MCA.setELFHeaderEFlags(EFlags);

  // Emit all the option records.
  // At the moment we are only emitting .Mips.options (ODK_REGINFO) and
  // .reginfo.
  MipsELFStreamer &MEF = static_cast<MipsELFStreamer &>(Streamer);
  MEF.EmitMipsOptionRecords();

  emitMipsAbiFlags();
}

void MipsTargetELFStreamer::emitAssignment(MCSymbol *S, const MCExpr *Value) {
  auto *Symbol = cast<MCSymbolELF>(S);
  // If on rhs is micromips symbol then mark Symbol as microMips.
  if (Value->getKind() != MCExpr::SymbolRef)
    return;
  const auto &RhsSym = cast<MCSymbolELF>(
      static_cast<const MCSymbolRefExpr *>(Value)->getSymbol());

  if (!(RhsSym.getOther() & ELF::STO_MIPS_MICROMIPS))
    return;

  Symbol->setOther(ELF::STO_MIPS_MICROMIPS);
}

MCELFStreamer &MipsTargetELFStreamer::getStreamer() {
  return static_cast<MCELFStreamer &>(Streamer);
}

void MipsTargetELFStreamer::emitDirectiveSetMicroMips() {
  MicroMipsEnabled = true;

  MCAssembler &MCA = getStreamer().getAssembler();
  unsigned Flags = MCA.getELFHeaderEFlags();
  Flags |= ELF::EF_MIPS_MICROMIPS;
  MCA.setELFHeaderEFlags(Flags);
  forbidModuleDirective();
}

void MipsTargetELFStreamer::emitDirectiveSetNoMicroMips() {
  MicroMipsEnabled = false;
  forbidModuleDirective();
}

void MipsTargetELFStreamer::emitDirectiveSetMips16() {
  MCAssembler &MCA = getStreamer().getAssembler();
  unsigned Flags = MCA.getELFHeaderEFlags();
  Flags |= ELF::EF_MIPS_ARCH_ASE_M16;
  MCA.setELFHeaderEFlags(Flags);
  forbidModuleDirective();
}

void MipsTargetELFStreamer::emitDirectiveSetNoReorder() {
  MCAssembler &MCA = getStreamer().getAssembler();
  unsigned Flags = MCA.getELFHeaderEFlags();
  Flags |= ELF::EF_MIPS_NOREORDER;
  MCA.setELFHeaderEFlags(Flags);
  forbidModuleDirective();
}

void MipsTargetELFStreamer::emitDirectiveEnd(StringRef Name) {
  MCAssembler &MCA = getStreamer().getAssembler();
  MCContext &Context = MCA.getContext();
  MCStreamer &OS = getStreamer();

  MCSectionELF *Sec = Context.getELFSection(".pdr", ELF::SHT_PROGBITS,
                                            ELF::SHF_ALLOC | ELF::SHT_REL);

  const MCSymbolRefExpr *ExprRef =
      MCSymbolRefExpr::create(Name, MCSymbolRefExpr::VK_None, Context);

  MCA.registerSection(*Sec);
  Sec->setAlignment(4);

  OS.PushSection();

  OS.SwitchSection(Sec);

  OS.EmitValueImpl(ExprRef, 4);

  OS.EmitIntValue(GPRInfoSet ? GPRBitMask : 0, 4); // reg_mask
  OS.EmitIntValue(GPRInfoSet ? GPROffset : 0, 4);  // reg_offset

  OS.EmitIntValue(FPRInfoSet ? FPRBitMask : 0, 4); // fpreg_mask
  OS.EmitIntValue(FPRInfoSet ? FPROffset : 0, 4);  // fpreg_offset

  OS.EmitIntValue(FrameInfoSet ? FrameOffset : 0, 4); // frame_offset
  OS.EmitIntValue(FrameInfoSet ? FrameReg : 0, 4);    // frame_reg
  OS.EmitIntValue(FrameInfoSet ? ReturnReg : 0, 4);   // return_reg

  // The .end directive marks the end of a procedure. Invalidate
  // the information gathered up until this point.
  GPRInfoSet = FPRInfoSet = FrameInfoSet = false;

  OS.PopSection();
}

void MipsTargetELFStreamer::emitDirectiveEnt(const MCSymbol &Symbol) {
  GPRInfoSet = FPRInfoSet = FrameInfoSet = false;
}

void MipsTargetELFStreamer::emitDirectiveAbiCalls() {
  MCAssembler &MCA = getStreamer().getAssembler();
  unsigned Flags = MCA.getELFHeaderEFlags();
  Flags |= ELF::EF_MIPS_CPIC | ELF::EF_MIPS_PIC;
  MCA.setELFHeaderEFlags(Flags);
}

void MipsTargetELFStreamer::emitDirectiveNaN2008() {
  MCAssembler &MCA = getStreamer().getAssembler();
  unsigned Flags = MCA.getELFHeaderEFlags();
  Flags |= ELF::EF_MIPS_NAN2008;
  MCA.setELFHeaderEFlags(Flags);
}

void MipsTargetELFStreamer::emitDirectiveNaNLegacy() {
  MCAssembler &MCA = getStreamer().getAssembler();
  unsigned Flags = MCA.getELFHeaderEFlags();
  Flags &= ~ELF::EF_MIPS_NAN2008;
  MCA.setELFHeaderEFlags(Flags);
}

void MipsTargetELFStreamer::emitDirectiveOptionPic0() {
  MCAssembler &MCA = getStreamer().getAssembler();
  unsigned Flags = MCA.getELFHeaderEFlags();
  // This option overrides other PIC options like -KPIC.
  Pic = false;
  Flags &= ~ELF::EF_MIPS_PIC;
  MCA.setELFHeaderEFlags(Flags);
}

void MipsTargetELFStreamer::emitDirectiveOptionPic2() {
  MCAssembler &MCA = getStreamer().getAssembler();
  unsigned Flags = MCA.getELFHeaderEFlags();
  Pic = true;
  // NOTE: We are following the GAS behaviour here which means the directive
  // 'pic2' also sets the CPIC bit in the ELF header. This is different from
  // what is stated in the SYSV ABI which consider the bits EF_MIPS_PIC and
  // EF_MIPS_CPIC to be mutually exclusive.
  Flags |= ELF::EF_MIPS_PIC | ELF::EF_MIPS_CPIC;
  MCA.setELFHeaderEFlags(Flags);
}

void MipsTargetELFStreamer::emitDirectiveInsn() {
  MipsTargetStreamer::emitDirectiveInsn();
  MipsELFStreamer &MEF = static_cast<MipsELFStreamer &>(Streamer);
  MEF.createPendingLabelRelocs();
}

void MipsTargetELFStreamer::emitFrame(unsigned StackReg, unsigned StackSize,
                                      unsigned ReturnReg_) {
  MCContext &Context = getStreamer().getAssembler().getContext();
  const MCRegisterInfo *RegInfo = Context.getRegisterInfo();

  FrameInfoSet = true;
  FrameReg = RegInfo->getEncodingValue(StackReg);
  FrameOffset = StackSize;
  ReturnReg = RegInfo->getEncodingValue(ReturnReg_);
}

void MipsTargetELFStreamer::emitMask(unsigned CPUBitmask,
                                     int CPUTopSavedRegOff) {
  GPRInfoSet = true;
  GPRBitMask = CPUBitmask;
  GPROffset = CPUTopSavedRegOff;
}

void MipsTargetELFStreamer::emitFMask(unsigned FPUBitmask,
                                      int FPUTopSavedRegOff) {
  FPRInfoSet = true;
  FPRBitMask = FPUBitmask;
  FPROffset = FPUTopSavedRegOff;
}

void MipsTargetELFStreamer::emitDirectiveCpLoad(unsigned RegNo) {
  // .cpload $reg
  // This directive expands to:
  // lui   $gp, %hi(_gp_disp)
  // addui $gp, $gp, %lo(_gp_disp)
  // addu  $gp, $gp, $reg
  // when support for position independent code is enabled.
  if (!Pic || (getABI().IsN32() || getABI().IsN64()))
    return;

  // There's a GNU extension controlled by -mno-shared that allows
  // locally-binding symbols to be accessed using absolute addresses.
  // This is currently not supported. When supported -mno-shared makes
  // .cpload expand to:
  //   lui     $gp, %hi(__gnu_local_gp)
  //   addiu   $gp, $gp, %lo(__gnu_local_gp)

  StringRef SymName("_gp_disp");
  MCAssembler &MCA = getStreamer().getAssembler();
  MCSymbol *GP_Disp = MCA.getContext().getOrCreateSymbol(SymName);
  MCA.registerSymbol(*GP_Disp);

  MCInst TmpInst;
  TmpInst.setOpcode(Mips::LUi);
  TmpInst.addOperand(MCOperand::createReg(Mips::GP));
  const MCSymbolRefExpr *HiSym = MCSymbolRefExpr::create(
      "_gp_disp", MCSymbolRefExpr::VK_Mips_ABS_HI, MCA.getContext());
  TmpInst.addOperand(MCOperand::createExpr(HiSym));
  getStreamer().EmitInstruction(TmpInst, STI);

  TmpInst.clear();

  TmpInst.setOpcode(Mips::ADDiu);
  TmpInst.addOperand(MCOperand::createReg(Mips::GP));
  TmpInst.addOperand(MCOperand::createReg(Mips::GP));
  const MCSymbolRefExpr *LoSym = MCSymbolRefExpr::create(
      "_gp_disp", MCSymbolRefExpr::VK_Mips_ABS_LO, MCA.getContext());
  TmpInst.addOperand(MCOperand::createExpr(LoSym));
  getStreamer().EmitInstruction(TmpInst, STI);

  TmpInst.clear();

  TmpInst.setOpcode(Mips::ADDu);
  TmpInst.addOperand(MCOperand::createReg(Mips::GP));
  TmpInst.addOperand(MCOperand::createReg(Mips::GP));
  TmpInst.addOperand(MCOperand::createReg(RegNo));
  getStreamer().EmitInstruction(TmpInst, STI);

  forbidModuleDirective();
}

void MipsTargetELFStreamer::emitDirectiveCpRestore(
    SmallVector<MCInst, 3> &StoreInsts, int Offset) {
  MipsTargetStreamer::emitDirectiveCpRestore(StoreInsts, Offset);
  // .cprestore offset
  // When PIC mode is enabled and the O32 ABI is used, this directive expands
  // to:
  //    sw $gp, offset($sp)
  // and adds a corresponding LW after every JAL.

  // Note that .cprestore is ignored if used with the N32 and N64 ABIs or if it
  // is used in non-PIC mode.
  if (!Pic || (getABI().IsN32() || getABI().IsN64()))
    return;

  for (const MCInst &Inst : StoreInsts)
    getStreamer().EmitInstruction(Inst, STI);
}

void MipsTargetELFStreamer::emitDirectiveCpsetup(unsigned RegNo,
                                                 int RegOrOffset,
                                                 const MCSymbol &Sym,
                                                 bool IsReg) {
  // Only N32 and N64 emit anything for .cpsetup iff PIC is set.
  if (!Pic || !(getABI().IsN32() || getABI().IsN64()))
    return;

  MCAssembler &MCA = getStreamer().getAssembler();
  MCInst Inst;

  // Either store the old $gp in a register or on the stack
  if (IsReg) {
    // move $save, $gpreg
    Inst.setOpcode(Mips::OR64);
    Inst.addOperand(MCOperand::createReg(RegOrOffset));
    Inst.addOperand(MCOperand::createReg(Mips::GP));
    Inst.addOperand(MCOperand::createReg(Mips::ZERO));
  } else {
    // sd $gpreg, offset($sp)
    Inst.setOpcode(Mips::SD);
    Inst.addOperand(MCOperand::createReg(Mips::GP));
    Inst.addOperand(MCOperand::createReg(Mips::SP));
    Inst.addOperand(MCOperand::createImm(RegOrOffset));
  }
  getStreamer().EmitInstruction(Inst, STI);
  Inst.clear();

  const MCSymbolRefExpr *HiExpr = MCSymbolRefExpr::create(
      &Sym, MCSymbolRefExpr::VK_Mips_GPOFF_HI, MCA.getContext());
  const MCSymbolRefExpr *LoExpr = MCSymbolRefExpr::create(
      &Sym, MCSymbolRefExpr::VK_Mips_GPOFF_LO, MCA.getContext());

  // lui $gp, %hi(%neg(%gp_rel(funcSym)))
  Inst.setOpcode(Mips::LUi);
  Inst.addOperand(MCOperand::createReg(Mips::GP));
  Inst.addOperand(MCOperand::createExpr(HiExpr));
  getStreamer().EmitInstruction(Inst, STI);
  Inst.clear();

  // addiu  $gp, $gp, %lo(%neg(%gp_rel(funcSym)))
  Inst.setOpcode(Mips::ADDiu);
  Inst.addOperand(MCOperand::createReg(Mips::GP));
  Inst.addOperand(MCOperand::createReg(Mips::GP));
  Inst.addOperand(MCOperand::createExpr(LoExpr));
  getStreamer().EmitInstruction(Inst, STI);
  Inst.clear();

  // daddu  $gp, $gp, $funcreg
  Inst.setOpcode(Mips::DADDu);
  Inst.addOperand(MCOperand::createReg(Mips::GP));
  Inst.addOperand(MCOperand::createReg(Mips::GP));
  Inst.addOperand(MCOperand::createReg(RegNo));
  getStreamer().EmitInstruction(Inst, STI);

  forbidModuleDirective();
}

void MipsTargetELFStreamer::emitMipsAbiFlags() {
  MCAssembler &MCA = getStreamer().getAssembler();
  MCContext &Context = MCA.getContext();
  MCStreamer &OS = getStreamer();
  MCSectionELF *Sec = Context.getELFSection(
      ".MIPS.abiflags", ELF::SHT_MIPS_ABIFLAGS, ELF::SHF_ALLOC, 24, "");
  MCA.registerSection(*Sec);
  Sec->setAlignment(8);
  OS.SwitchSection(Sec);

  OS << ABIFlagsSection;
}


text:
<?php
class ip2more
{

  ///////////////////
  // CLASS OPTIONS //
  ///////////////////

  /**
  * IP Address
  */
  var $ip              = '';

  /*
  * Country Info Array
  * Holds each piece of information about current IP's Country

  *         'name'                  : country name

  *         'iso2'                  : ISO2 code

  *         'iso3'                  : ISO3 code

  *         'fibs104'               : FIBS104 code

  *         'isono'                 : ISO Number

  *         'capital'               : Capital City

  *         'region'                : Region

  *         'currency'              : Currency

  *         'currency_code'         : Currency Code

  *         'flag_small'            : Small Flag Picture

  *         'flag_big'              : Big Flag Picture

  */
  var $country         = array();

  /*
  * Flags Dir
  */
  var $flags_dir       = 'flags';

  /*
  * IPs Database Index File
  */
  var $idx_file        = 'data/ips.idx';

  /*
  * IPs Database File
  */
  var $db_file         = 'data/ips.db';

  /*
  * Countries List File
  */
  var $countries_file  = 'data/countries.php';

  /*
  * Countries List Array
  */
  var $countries_list  = array();

  /*
  * What Should Be Returned If Couldn't Find IP's Country
  */
  var $null_country = array('name'=>"Spain", 'iso2'=>"ES", 'iso3'=>"ESP", 'fips104'=>"SP", 'isono'=>"724.00", 'capital'=>"Madrid", 'region'=>"Europe", 'currency'=>"Euro", 'currency_code'=>"EUR");
  /*
  * WHOIS Service URL
  */
  var $whois_url = 'http://www.dnsstuff.com/tools/whois.ch?ip=%s';

  /*
  * WHOIS Service Request Method (GET OR POST)
  */
  var $whois_method = 'GET';

  /*
  * WHOIS Service Timeout
  */
  var $whois_timeout = '20';

  /*
  * WHOIS Regex Which Will Match Country
  */
  var $whois_regex = '/Location\<\/A\>:\s+([^\r\n\<\[\(\{]+)/i';

  /*
  * WHOIS Return Type (name OR iso2 OR iso3 OR fips104 OR isono)
  */
  var $whois_return = 'name';

  /////////////////
  // CONSTRUCTOR //
  /////////////////

  /**
  * CONSTRUCTOR Functions
  *
  * IF IP address not passed, Current user's IP will be used
  *
  * @param      string      $ip             If null, current user's ip will be used. If false, no IP lookup will be made
  * @param      bool        $whois_lookup   If true, and the IP couldn't be found in the local database, a search will be done by using Whois Service
  * @see        get_ip
  * @see        whois_lookup
  */
  function ip2more($ip = null, $whois_lookup = false)
  {
    if(file_exists(dirname(__FILE__).'/'.$this->countries_file)){
      include(dirname(__FILE__).'/'.$this->countries_file);
      $this->countries_list = $i2m_countries_list;
      unset($i2m_countries_list);
    }

    if($ip === null) $this->set_ip($this->get_ip(), $whois_lookup);
    elseif($ip !== false && $this->is_valid_ip($ip)) $this->set_ip($ip, $whois_lookup);
  }

  //////////////////////
  // PUBLIC FUNCTIONS //
  //////////////////////

  /**
  * Check if IP Address Is Valid Or Not
  *
  * This function will validate the passed IP address. It returns true if the IP is valid. and false if not valid
  *
  * @return     bool
  * @param      string      $ip         The IP address to check
  * @access     public
  */
  function is_valid_ip($ip)
  {
    $ip = explode('.', $ip);
    if(count($ip) != 4) return false;
    for($i=0;$i<4;$i++)
      if(!is_numeric($ip[$i]) || $ip[$i] > 255) return false;
    return true;
  }

  /**
  * Get User's Real IP
  *
  * This function will try to find user's real ip address
  * even if he is behind proxy server or firewall
  * NOTE: Almost all anonymous proxies will hide real user's ip
  *
  * @return     string              User's Real IP Address
  * @access     public
  * @see        set_ip
  */
  function get_ip()
  {
   // No IP found (will be overwritten by for
   // if any IP is found behind a firewall)
   $ip = FALSE;

   // If HTTP_CLIENT_IP is set, then give it priority
   if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
       $ip = $_SERVER["HTTP_CLIENT_IP"];
   }

   // User is behind a proxy and check that we discard RFC1918 IP addresses
   // if they are behind a proxy then only figure out which IP belongs to the
   // user.  Might not need any more hackin if there is a squid reverse proxy
   // infront of apache.
   if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {

       // Put the IP's into an array which we shall work with shortly.
       $ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
       if ($ip) { array_unshift($ips, $ip); $ip = FALSE; }

       for ($i = 0; $i < count($ips); $i++) {
           // Skip RFC 1918 IP's 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16
           if (!eregi ("^(10|172\.16|192\.168)\.", $ips[$i])) {
               if (version_compare(phpversion(), "5.0.0", ">=")) {
                   if (ip2long($ips[$i]) != false) {
                       $ip = $ips[$i];
                       break;
                   }
               } else {
                   if (ip2long($ips[$i]) != -1) {
                       $ip = $ips[$i];
                       break;
                   }
               }
           }
       }
   }

   return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
  }

  /**
  * Set Active IP Address
  *
  * This will set the active ip address, and fetches
  * all available informations about it.
  * after calling this function, the public variable 'caountry'
  * will hold all the info about the ip address
  *
  * @param      string      $ip             User's Real IP Address
  * @param      bool        $whois_lookup   If true, and the IP couldn't be found in the local database, a search will be done by using Whois Service
  * @return     bool                        always return true
  * @access     public
  * @see        get_ip
  * @see        whois_lookup
  */
  function set_ip($ip, $whois_lookup=false)
  {
    $this->ip = $ip;
    if($ip == '127.0.0.1') $this->country = $this->null_country;
    else $this->_get_country($whois_lookup);
    $this->_set_flags();
    return true;
  }

  /**
  * Sort Countries List
  *
  * This will sort countries list on the passed order
  *
  * @param      int         $order      COUNTRY_ORDER default , REGION_ORDER, ISO2_ORDER, ISO3_ORDER
  * @return     bool                    always returns true
  * @access     public
  * @see        print_countries_list
  * @see        return_countries_list
  */
  function sort_countries_list($order)
  {
    if($order == COUNTRY_ORDER){
      uasort($this->countries_list, array($this, '_sort_by_country'));
    }
    elseif($order == REGION_ORDER){
      uasort($this->countries_list, array($this, '_sort_by_region'));
    }
    elseif($order == ISO2_ORDER){
      uasort($this->countries_list, array($this, '_sort_by_iso2'));
    }
    elseif($order == ISO3_ORDER){
      uasort($this->countries_list, array($this, '_sort_by_iso3'));
    }
    return true;
  }

  /**
  *
  * Print Countries List
  *
  * This will print countries list as drop down list options
  * the value of the option can passed in the first param
  * and can be any valid key in $this->country array (like iso2 , iso3 or name)
  *
  * @param      string      $value          Drop Down List Options values key (default iso3)
  * @param      bool        $auto_select    if true , the active country will be selected (default true)
  * @param      string      $selected_value if $auto_select is false, then the option having its value equal to $selected_value will be selected
  * @return     bool                        always returns true
  * @access     public
  * @see        return_countries_list
  * @see        sort_countries_list
  *
  */
  function print_countries_list($value='iso3', $auto_select=true, $selected_value='')
  {
    if($auto_select) // more faster than checking it in the loop
    {
      foreach($this->countries_list as $key=>$val)
      {
        echo '<option value="' . $this->countries_list[$key][$value] . '"' . (($this->countries_list[$key]['iso3']==$this->country['iso3']) ? ' SELECTED' : '') . '>' . $val['name'] . "</option>\r\n";
      }
    }
    else
    {
      foreach($this->countries_list as $key=>$val)
      {
        echo '<option value="' . $this->countries_list[$key][$value] . '"' . (($this->countries_list[$key]['iso3']==$selected_value) ? ' SELECTED' : '') . '>' . $val['name'] . "</option>\r\n";
      }
    }
    return true;
  }

  /**
  *
  * Return Countries List
  *
  * This will return countries list as string containing drop down list options
  * the value of the option can passed in the first param
  * and can be any valid key in $this->country array (like iso2 , iso3 or name)
  *
  * @param      string      $value          Drop Down List Options values key (default iso3)
  * @param      bool        $auto_select    if true , the active country will be selected (default true)
  * @param      string      $selected_value if $auto_select is false, then the option having its value equal to $selected_value will be selected
  * @return     string                      Drop Down List Options
  * @access     public
  * @see        print_countries_list
  * @see        sort_countries_list
  *
  */
  function return_countries_list($value='iso3', $auto_select=true, $selected_value='')
  {
    $return = '';
    if($auto_select) // more faster than checking it in the loop
    {
      foreach($this->countries_list as $key=>$val)
      {
        $return .= '<option value="' . $this->countries_list[$key][$value] . '"' . (($this->countries_list[$key]['iso3']==$this->country['iso3']) ? ' SELECTED' : '') . '>' . $val['name'] . "</option>\r\n";
      }
    }
    else
    {
      foreach($this->countries_list as $key=>$val)
      {
        $return .= '<option value="' . $this->countries_list[$key][$value] . '"' . (($this->countries_list[$key]['iso3']==$selected_value) ? ' SELECTED' : '') . '>' . $val['name'] . "</option>\r\n";
      }
    }
    return $return;
  }

  /**
  * Search for a country
  *
  * This function was suggested by 'Nizam <info AT singlesburg DOT com>'. It can be used to find a country by providing any info about it
  * like name, iso2, iso3, fips104 or even the Capital
  *
  * @param      string      $needle     The info you know about the country
  * @param      string      $type       Type of needle. it must be on of the following: (name, iso2, iso3, fips104, isono, capital)
  * @return     array                   An array containing all the info about the found country.
  * @access     public
  */
  function find_country($needle, $type)
  {
    $type = strtolower($type);
    if(!in_array($type, array('name','iso2','iso3','fips104','isono','capital'))) return false;

    $needle = strtolower($needle);
    foreach($this->countries_list as $key=>$val)
    {
      if(strtolower($val[$type]) == $needle) return $val;
    }
    return $this->null_country;
  }

  /**
  * Whois Service Lookup
  *
  * This function will open a socket to WHOIS service server and fetches all available info about the passed IP address.
  * It's useful if the we are looking for IP address that's not stored in the local flat database
  *
  * @param      string      $ip         The IP address to find its country
  * @return     array                   An array containing all the info about the found country.
  * @access     public
  */
  function whois_lookup($ip)
  {
    $URL = parse_url( sprintf($this->whois_url, $ip) );
    if(($this->whois_method = strtoupper($this->whois_method)) && ($this->whois_method == 'GET' || $this->whois_method == 'POST'))
    {
        ;
    }
    else
    {
      return $this->null_country;
    }
    $req = '';
    if ($this->whois_method == 'GET')
    {
      $URL['path'] .= '?' . $URL['query'];
    }
    $req .= "GET $URL[path] HTTP/1.1\r\n".
            "Connection: Close\r\n".
            "Accept: */*\r\n".
            "Accept-Language: en-gb\r\n".
            "Host: $URL[host]\r\n".
            "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.0; en-GB; rv:0.9.4) Gecko/20011019 Netscape6/6.2\r\n";
    if($this->whois_method == 'POST')
    {
      $req .= "Content-Type: application/x-www-form-urlencoded\r\n";
      $req .= 'Content-Length: '.strlen($URL['query']);
      $req .= "\r\n\r\n$URL[query]";
    }
    else
    {
      $req .= "\r\n";
    }

    if(empty($URL['port'])) $URL['port'] = 80;
    $fp = @fsockopen($URL['host'], $URL['port'], $errno, $errstr, $this->whois_timeout);
    if(!$fp)
    {
      //echo "Whois Lookup Failed To Open $URL[host]:$URL[port] ($errno - $errstr)";
      return $this->null_country;
    }

    fwrite($fp, $req);
    $result = '';
    while(!feof($fp))
    {
      $result .= fgets($fp, 1024);
    }

    @fclose($fp);

    if(!preg_match($this->whois_regex, $result, $match)) return $this->null_country;
    else return $this->find_country(trim($match[1]), $this->whois_return);
  }

  ///////////////////////
  // PRIVATE FUNCTIONS //
  ///////////////////////

  /**
  * Get IP's Info
  *
  * This is the main function which translate IP address
  * to country's ISO3 code and then sets $this->country
  * if country not found, or IP in not listed in database,
  * UNKOWN country with UNKOWN info and -- ISO Codes will be used instead
  *
  * @param      bool        $whois_lookup   If true, and the IP couldn't be found in the local database, a search will be done by using Whois Service
  * @return     bool        always return true
  * @access     private
  * @see        _search_in_index
  * @see        _search_in_db
  * @see        whois_lookup
  */
  function _get_country($whois_lookup=false)
  {

   // Convert the IP number to some useable form for searching
   $ipn = (float) sprintf("%u", ip2long($this->ip));

   // Find the index to start search from
   $idx = $this->_search_in_index($ipn);

   // If we were unable to find any helpful entry
   // in the index do not search, as it would take
   // a very long time. It is an error, if we have
   // not found anything in the index
   if ($idx !== FALSE) {
       $country = $this->_search_in_db($ipn, $idx);
   } else {
       $country = 'NA';
   }
   if($country != 'NA'){
       if(isset($this->countries_list[$country]))
         $this->country = $this->countries_list[$country];
       else
         $this->country = $this->null_country;
   }
   elseif($whois_lookup) $this->country = $this->whois_lookup($this->ip);
   else $this->country = $this->null_country;
   return true;
  }

  /**
   * Find Nearest Database Index
   *
   * Find nearest index entry for IP number (not address)
   *
   * @param     long        $ip         IP address in long format see ip2long
   * @return    array                   containing the min & max record numbers IP address could be between
   * @access    private
   * @see       _search_in_db
   */
  function _search_in_index($ip)
  {
   // Indexed part and record number to jump to
   $idxpart = 0; $recnum = 0;

   // Open the index file for reading
   $dbidx = fopen(dirname(__FILE__).'/'.$this->idx_file, "r");
   if (!$dbidx) { return FALSE; }

   // Read in granularity from index file and
   // convert current IP to something useful
   $granularity = intval(fgets($dbidx, 64));
   $ip_chunk = intval($ip / $granularity);

   // Loop till we can read the file
   while (!feof($dbidx)) {

       // Get CSV data from index file
       $data = fgetcsv($dbidx, 100);

       // Compare current index part with our IP
       if ($ip_chunk >= $idxpart && $ip_chunk < (int) $data[0]) {
           return array($recnum, (int) $data[1]);
       }

       // Store for next compare
       $idxpart = (int) $data[0];
       $recnum  = (int) $data[1];
   }

   // Return record number found
   return array($recnum, -1);
  }

  /**
   * Find Country ISO3 Code IN Database
   *
   * Find the ISO3 Code by searching from record $idx[0] to record $idx[1]
   *
   * @param     long        $ip         IP address in long format see ip2long
   * @param     array       $idx        containing the min & max record numbers IP address could be between
   * @return    string                  ISO3 Code  OR  NA  if not found
   * @access    private
   * @see       _search_in_index
   */
  function _search_in_db($ip, $idx)
  {
   // Default range and country
   $range_start = 0; $range_end = 0;
   $country = "NA";

   // Open DB for reading
   $ipdb = fopen(dirname(__FILE__).'/'.$this->db_file,"r");

   // Return with "NA" in case of we cannot open the db
   if (!$ipdb) { return $country; }

   // Jump to record $idx
   fseek($ipdb, ($idx[0]-1)*24);

   // Read records until we hit the end of the file,
   // or we find the range where this IP is, or we
   // reach the next indexed part [where the IP should
   // not be found, so there is no point in searching further]
   while (!feof($ipdb) && !($range_start <= $ip && $range_end >= $ip)) {

       // We had run out of the indexed region,
       // where we expected to find the IP
       if ($idx[1] != -1 && $idx[0] > $idx[1]) {
           $country = "NA"; break;
       }

       // Try to read record
       $record = fread($ipdb, 24);

       // Unable to read the record => error
       if (strlen($record) != 24) { $country = "NA"; break; }

       // Split the record to it's parts
       $range_start = (float) substr($record, 0, 10);
       $range_end  = (float) substr($record, 10, 10);
       $country    = substr($record, 20, 3);

       // Getting closer to the end of the indexed region
       $idx[0] += 1;
   }

   // Close datafile
   fclose($ipdb);

   // Return with the country found
   return $country;
  }

  /**
  * Set Country Flags Pictures
  *
  * After calling this function, $this->country['flag_small']
  * and $this->country['flag_small'] will be set to pictures files
  * NOTE: if the flags dir has been changed, you have to set it first
  *       $i2m->flags_dir = './flags/';
  *       $i2m->flags_dir = 'http://domain-name/flags/';
  *
  * @return     bool                always returns true
  * @access     private
  */
  function _set_flags()
  {
    // Add trailing slash to flags_dir if there's no 1 already
    if(substr($this->flags_dir,-1) != '/') $this->flags_dir .= '/';

    $this->country['flag_small'] = $this->flags_dir . 's/' . strtolower($this->country['iso2']) . '.png';
    $this->country['flag_big']   = $this->flags_dir . 'b/' . strtolower($this->country['iso2']) . '.png';
    return true;
  }

  /**
  * Sort Countries List By Country Name
  *
  * Private function used in uasort to sort countries list based on country name
  *
  * @param      array           $country1       an array containing country info
  * @param      array           $country2       an array containing country info
  * @return     int                             the returned value will be used by uasort function to sort countries list
  * @access     private
  * @see        sort_countries_list
  * @see        print_countries_list
  */
  function _sort_by_country($country1, $country2)
  {
    return strcmp($country1['name'], $country2['name']);
  }

  /**
  * Sort Countries List By Region
  *
  * Private function used in uasort to sort countries list based on region
  *
  * @param      array           $country1       an array containing country info
  * @param      array           $country2       an array containing country info
  * @return     int                             the returned value will be used by uasort function to sort countries list
  * @access     private
  * @see        sort_countries_list
  * @see        print_countries_list
  */
  function _sort_by_region($country1, $country2)
  {
    return strcmp($country1['region'], $country2['region']);
  }

  /**
  * Sort Countries List By ISO2 Code
  *
  * Private function used in uasort to sort countries list based on ISO2 Code
  *
  * @param      array           $country1       an array containing country info
  * @param      array           $country2       an array containing country info
  * @return     int                             the returned value will be used by uasort function to sort countries list
  * @access     private
  * @see        sort_countries_list
  * @see        print_countries_list
  */
  function _sort_by_iso2($country1, $country2)
  {
    return strcmp($country1['iso2'], $country2['iso2']);
  }

  /**
  * Sort Countries List By ISO3 Code
  *
  * Private function used in uasort to sort countries list based on ISO3 Code
  *
  * @param      array           $country1       an array containing country info
  * @param      array           $country2       an array containing country info
  * @return     int                             the returned value will be used by uasort function to sort countries list
  * @access     private
  * @see        sort_countries_list
  * @see        print_countries_list
  */
  function _sort_by_iso3($country1, $country2)
  {
    return strcmp($country1['iso3'], $country2['iso3']);
  }

}

define('COUNTRY_ORDER', 1);
define('REGION_ORDER', 2);
define('ISO3_ORDER', 3);
define('ISO2_ORDER', 4);
?>

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="CP850"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta content="text/html; charset=CP850" http-equiv="Content-Type" />

  <title>Class: Open4::SpawnError</title>

  <link rel="stylesheet" href="../rdoc.css" type="text/css" media="screen" />

          Home
          Classes
          Methods

In Files

lib/open4.rb

Parent

Open4::Error

Methods

::new

#exitstatus

Class/Module Index

        <form action="#" method="get" accept-charset="utf-8" class="initially-hidden">
        <fieldset>
          <legend>Quicksearch</legend>
          <input type="text" name="quicksearch" value=""
            class="quicksearch-field" />
        </fieldset>
        </form>

Open4

Open4::Error

Open4::SpawnError

Open4::ThreadEnsemble

Object

No matching classes.

Open4::SpawnError

Attributes

            cmd[R]

            signals[R]

            status[R]

Public Class Methods

            new(cmd, status)
            click to toggle source

# File lib/open4.rb, line 144
def initialize cmd, status
  @cmd, @status = cmd, status
  @signals = {}
  if status.signaled?
    @signals['termsig'] = status.termsig
    @signals['stopsig'] = status.stopsig
  end
  sigs = @signals.map{|k,v| "#{ k }:#{ v.inspect }"}.join(' ')
  super "cmd <#{ cmd }> failed with status <#{ exitstatus.inspect }> signals <#{ sigs }>"
end

Public Instance Methods

            exitstatus()
            click to toggle source

# File lib/open4.rb, line 141
def exitstatus
  @status.exitstatus
end

[Validate]

Generated with the Darkfish
      Rdoc Generator 2.


text:
#include <wiisprite.h>
#include "button.h"  // header file
#include "resourcemanager.h"

using namespace wsp;

void Button::initUsing(int x, int y, ResourceManager* rm) {

	selected = false;					// Initialize the selected-ness

	button_sprite.SetPosition(x, y);	// Tell the sprite where to draw itself

	resources = rm;						// Remember where the Resource Manager lives.

	button_sprite.SetImage( & resources->getImage(ResourceManager::button_hover) );
}

// Default constructor
Button::Button() { }

// Destructor
Button::~Button() { }

/* Button operations: */

// Sets the button selected-ness
void Button::setSelected(bool setting) {

	selected = setting;
}

// Returns a pointer to the sprite.
Sprite * Button::getSprite() {
	return &button_sprite;
}

// Draws the button
void Button::draw() {

	if (selected)
		button_sprite.Draw();

}


text:
class BaseView < UIImageView

  def self.stylesheet stylesheet
    @stylesheet = stylesheet
  end

  def self.setStylesheet(instance)
    instance.stylesheet = @stylesheet if @stylesheet
  end

  def initWithFrame(rect)
    if super
      self.class.setStylesheet(self)
      self.render
    end
    self
  end

end


text:
namespace starboard {
namespace loader_app {

// Returns an application key extracted from |url|. This function is not meant
// to validate a URL, and operates assuming the URL provided is valid. This
// should not be used for anything other than a best-effort attempt.
std::string ExtractAppKey(const std::string& url);

// Returns a base64 encoded |app_key|.
std::string EncodeAppKey(const std::string& app_key);

}  // namespace loader_app
}  // namespace starboard

#endif  // STARBOARD_LOADER_APP_APP_KEY_INTERNAL_H_


text:
using System.Collections.Generic;

namespace _6.Book_Library_Modification
{
    class Library
    {
        public string Name { get; set; }
        public List<Book> Books { get; set; }
    }
}


text:
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.skylark.skylint;

import com.google.devtools.build.lib.packages.BazelLibrary;
import com.google.devtools.build.lib.skylarkinterface.SkylarkSignature;
import com.google.devtools.build.lib.syntax.ASTNode;
import com.google.devtools.build.lib.syntax.Comment;
import com.google.devtools.build.lib.syntax.Identifier;
import com.google.devtools.build.lib.syntax.MethodLibrary;
import com.google.devtools.skylark.skylint.Environment.NameInfo.Kind;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;

/** Holds the information about which symbols are in scope during AST traversal. */
public class Environment {
  private final List<LexicalBlock> blocks = new ArrayList<>();
  private final Map<Integer, NameInfo> idToNameInfo = new HashMap<>();
  private int nextId = 0;
  private static final int BUILTINS_INDEX = 0; // index of the block containing builtins
  private static final int GLOBALS_INDEX = 1; // index of the block containing globals

  public static Environment empty() {
    Environment env = new Environment();
    env.blocks.add(new LexicalBlock()); // for builtins
    return env;
  }

  public static Environment defaultBazel() {
    Environment env = empty();
    env.addBuiltin("None");
    env.addBuiltin("True");
    env.addBuiltin("False");
    env.setupFunctions(MethodLibrary.class, BazelLibrary.class);
    return env;
  }

  private void setupFunctions(Class<?>... classes) {
    // Iterate through the skylark functions declared inline within the classes
    // retrieving and storing their names.
    for (Class<?> c : classes) {
      for (Field field : c.getDeclaredFields()) {
        // Skylark functions are defined inline as fields within the class, annotated
        // by @SkylarkSignature.
        SkylarkSignature builtinFuncSignature = field.getAnnotation(SkylarkSignature.class);
        if (builtinFuncSignature != null && builtinFuncSignature.objectType() == Object.class) {
          addBuiltin(builtinFuncSignature.name());
        }
      }
    }
  }

  public void enterBlock() {
    blocks.add(new LexicalBlock());
  }

  public Collection<Integer> exitBlock() {
    if (blocks.size() <= GLOBALS_INDEX) {
      throw new IllegalStateException("no blocks to exit from");
    }
    return blocks.remove(blocks.size() - 1).getAllSymbols();
  }

  public boolean inGlobalBlock() {
    return blocks.size() - 1 == GLOBALS_INDEX;
  }

  public boolean isDefined(String name) {
    return resolveName(name) != null;
  }

  public boolean isDefinedInCurrentScope(String name) {
    return blocks.get(blocks.size() - 1).resolve(name) != null;
  }

  @Nullable
  public NameInfo resolveName(String name) {
    for (int i = blocks.size() - 1; i >= 0; i--) {
      Integer id = blocks.get(i).resolve(name);
      if (id != null) {
        return idToNameInfo.get(id);
      }
    }
    return null;
  }

  public NameInfo resolveExistingName(String name) {
    NameInfo info = resolveName(name);
    if (info == null) {
      throw new IllegalArgumentException("name '" + name + "' doesn't exist");
    }
    return info;
  }

  private void addName(int block, NameInfo nameInfo) {
    NameInfo prev = idToNameInfo.putIfAbsent(nameInfo.id, nameInfo);
    if (prev != null) {
      throw new IllegalStateException("id " + nameInfo.id + " is already used!");
    }
    blocks.get(block).add(nameInfo.name, nameInfo.id);
  }

  private void addBuiltin(String name) {
    addName(BUILTINS_INDEX, createNameInfo(name, new Comment("builtin"), Kind.BUILTIN));
  }

  public void addImported(String name, Identifier node) {
    addName(GLOBALS_INDEX, createNameInfo(name, node, Kind.IMPORTED));
  }

  public void addIdentifier(String name, ASTNode node) {
    Kind kind = blocks.size() - 1 == GLOBALS_INDEX ? Kind.GLOBAL : Kind.LOCAL;
    addName(blocks.size() - 1, createNameInfo(name, node, kind));
  }

  public void addFunction(String name, ASTNode node) {
    addName(GLOBALS_INDEX, createNameInfo(name, node, Kind.FUNCTION));
  }

  public void addParameter(String name, ASTNode param) {
    addName(blocks.size() - 1, createNameInfo(name, param, Kind.PARAMETER));
  }

  private NameInfo createNameInfo(String name, ASTNode definition, Kind kind) {
    return new NameInfo(name, definition, newId(), kind);
  }

  private int newId() {
    int ret = nextId;
    nextId++;
    return ret;
  }

  public Collection<Integer> getNameIdsInCurrentBlock() {
    return getNameIdsInBlock(blocks.size() - 1);
  }

  private Collection<Integer> getNameIdsInBlock(int block) {
    return Collections.unmodifiableCollection(blocks.get(block).nameToId.values());
  }

  public NameInfo getNameInfo(int id) {
    NameInfo info = idToNameInfo.get(id);
    if (info == null) {
      throw new IllegalArgumentException("id " + id + " doesn't exist");
    }
    return info;
  }

  /**
   * Represents a lexical block, e.g. global, function-local or further nested (in a comprehension).
   */
  private static class LexicalBlock {
    private final Map<String, Integer> nameToId = new HashMap<>();

    @Nullable
    private Integer resolve(String name) {
      return nameToId.get(name);
    }

    private void add(String name, int id) {
      Integer entry = nameToId.putIfAbsent(name, id);
      if (entry != null) {
        throw new IllegalArgumentException("name '" + name + "' is already defined");
      }
    }

    public Collection<Integer> getAllSymbols() {
      return nameToId.values();
    }
  }

  /** Holds information about a name/symbol. */
  public static class NameInfo {
    final int id;
    final String name;
    final ASTNode definition;
    final Kind kind;

    /** Kind of definition where the name was declared. */
    public enum Kind {
      BUILTIN,
      IMPORTED,
      GLOBAL,
      FUNCTION,
      PARAMETER,
      LOCAL,
    }

    private NameInfo(String name, ASTNode definition, int id, Kind kind) {
      this.id = id;
      this.name = name;
      this.definition = definition;
      this.kind = kind;
    }
  }
}


text:
<?php

namespace Backend\Modules\Mailmotor\Domain\Settings\Command;

use Backend\Core\Language\Language;
use Common\ModulesSettings;

final class SaveSettingsHandler
{
    private const MODULE_NAME = 'Mailmotor';

    /**
     * @var ModulesSettings
     */
    private $modulesSettings;

    public function __construct(
        ModulesSettings $modulesSettings
    ) {
        $this->modulesSettings = $modulesSettings;
    }

    public function handle(SaveSettings $settings): void
    {
        $this->modulesSettings->set(self::MODULE_NAME, 'mail_engine', $settings->mailEngine);
        $this->modulesSettings->set(self::MODULE_NAME, 'double_opt_in', $settings->doubleOptIn);
        $this->modulesSettings->set(self::MODULE_NAME, 'overwrite_interests', $settings->overwriteInterests);

        // mail engine is empty
        if ($settings->mailEngine === 'not_implemented') {
            $this->modulesSettings->delete(self::MODULE_NAME, 'api_key');
            $this->modulesSettings->delete(self::MODULE_NAME, 'list_id');

            foreach (Language::getActiveLanguages() as $language) {
                $this->modulesSettings->delete(self::MODULE_NAME, 'list_id_' . $language);
            }

            return;
        }

        $this->modulesSettings->set(self::MODULE_NAME, 'api_key', $settings->apiKey);
        $this->modulesSettings->set(self::MODULE_NAME, 'list_id', $settings->listId);
        $this->saveLanguageListIds($settings->languageListIds);
    }

    private function saveLanguageListIds(array $languageListIds): void
    {
        foreach ($languageListIds as $language => $languageListId) {
            if (empty($languageListId) || !Language::isActiveLanguage($language)) {
                $this->modulesSettings->delete(self::MODULE_NAME, 'list_id_' . $language);

                continue;
            }

            $this->modulesSettings->set(self::MODULE_NAME, 'list_id_' . $language, $languageListId);
        }
    }
}


text:
<?php

namespace Kronos\Tests\Log\Writer;

use Kronos\Log\Writer\TriggerError;
use Psr\Log\LogLevel;

class TriggerErrorTest extends \PHPUnit\Framework\TestCase
{
    const ANY_LOG_LEVEL = LogLevel::INFO;
    const LOG_MESSAGE = 'log message';
    const MESSAGE_WITH_INTERPOLATION = 'message with {interpolation}';
    const INTERPOLATION_KEY = 'interpolation';
    const INTERPOLATED_VALUE = 'interpolated value';
    const INVALID_LOG_LEVEL = 'invalid log level';

    /**
     * @var TriggerError
     */
    private $writer;

    public function setUp(): void
    {
        $this->writer = new TriggerError();
    }

    public function test_AnyLogLevel_log_ShouldTriggerErrorWithMessage()
    {
        $triggeredErrors = [];
        $previousErrorHandler = $this->setUpErrorHandler($triggeredErrors);

        try {
            $this->writer->log(self::ANY_LOG_LEVEL, self::LOG_MESSAGE);

            $this->assertEquals(1, count($triggeredErrors));
            $this->assertEquals(self::LOG_MESSAGE, $triggeredErrors[0]['errstr']);
        }
        finally {
            set_error_handler($previousErrorHandler);
        }
    }

    public function test_MessageWithInterpolation_log_ShouldInterpolateMessage()
    {
        $triggeredErrors = [];
        $previousErrorHandler = $this->setUpErrorHandler($triggeredErrors);

        try {
            $this->writer->log(self::ANY_LOG_LEVEL, self::MESSAGE_WITH_INTERPOLATION,
                [self::INTERPOLATION_KEY => self::INTERPOLATED_VALUE]);

            $this->assertEquals(1, count($triggeredErrors));
            $this->assertEquals(str_replace('{' . self::INTERPOLATION_KEY . '}', self::INTERPOLATED_VALUE,
                self::MESSAGE_WITH_INTERPOLATION), $triggeredErrors[0]['errstr']);
        }
        finally {
            set_error_handler($previousErrorHandler);
        }
    }

    public function test_Emergency_log_ShouldTriggerUserWarning()
    {
        $triggeredErrors = [];
        $previousErrorHandler = $this->setUpErrorHandler($triggeredErrors);

        try {
            $this->writer->log(LogLevel::EMERGENCY, self::LOG_MESSAGE);

            $this->assertEquals(1, count($triggeredErrors));
            $this->assertEquals(E_USER_WARNING, $triggeredErrors[0]['errno']);
        }
        finally {
            set_error_handler($previousErrorHandler);
        }
    }

    public function test_Alert_log_ShouldTriggerUserWarning()
    {
        $triggeredErrors = [];
        $previousErrorHandler = $this->setUpErrorHandler($triggeredErrors);

        try {
            $this->writer->log(LogLevel::ALERT, self::LOG_MESSAGE);

            $this->assertEquals(1, count($triggeredErrors));
            $this->assertEquals(E_USER_WARNING, $triggeredErrors[0]['errno']);
        }
        finally {
            set_error_handler($previousErrorHandler);
        }
    }

    public function test_Critical_log_ShouldTriggerUserWarning()
    {
        $triggeredErrors = [];
        $previousErrorHandler = $this->setUpErrorHandler($triggeredErrors);

        try {
            $this->writer->log(LogLevel::CRITICAL, self::LOG_MESSAGE);

            $this->assertEquals(1, count($triggeredErrors));
            $this->assertEquals(E_USER_WARNING, $triggeredErrors[0]['errno']);
        }
        finally {
            set_error_handler($previousErrorHandler);
        }
    }

    public function test_Error_log_ShouldTriggerUserWarning()
    {
        $triggeredErrors = [];
        $previousErrorHandler = $this->setUpErrorHandler($triggeredErrors);

        try {
            $this->writer->log(LogLevel::ERROR, self::LOG_MESSAGE);

            $this->assertEquals(1, count($triggeredErrors));
            $this->assertEquals(E_USER_WARNING, $triggeredErrors[0]['errno']);
        }
        finally {
            set_error_handler($previousErrorHandler);
        }
    }

    public function test_Warning_log_ShouldTriggerUserWarning()
    {
        $triggeredErrors = [];
        $previousErrorHandler = $this->setUpErrorHandler($triggeredErrors);

        try {
            $this->writer->log(LogLevel::WARNING, self::LOG_MESSAGE);

            $this->assertEquals(1, count($triggeredErrors));
            $this->assertEquals(E_USER_WARNING, $triggeredErrors[0]['errno']);
        }
        finally {
            set_error_handler($previousErrorHandler);
        }
    }

    public function test_Notice_log_ShouldTriggerUserNotice()
    {
        $triggeredErrors = [];
        $previousErrorHandler = $this->setUpErrorHandler($triggeredErrors);

        try {
            $this->writer->log(LogLevel::NOTICE, self::LOG_MESSAGE);

            $this->assertEquals(1, count($triggeredErrors));
            $this->assertEquals(E_USER_NOTICE, $triggeredErrors[0]['errno']);
        }
        finally {
            set_error_handler($previousErrorHandler);
        }
    }

    public function test_Info_log_ShouldTriggerUserNotice()
    {
        $triggeredErrors = [];
        $previousErrorHandler = $this->setUpErrorHandler($triggeredErrors);

        try {
            $this->writer->log(LogLevel::INFO, self::LOG_MESSAGE);

            $this->assertEquals(1, count($triggeredErrors));
            $this->assertEquals(E_USER_NOTICE, $triggeredErrors[0]['errno']);
        }
        finally {
            set_error_handler($previousErrorHandler);
        }
    }

    public function test_Debug_log_ShouldTriggerUserNotice()
    {
        $triggeredErrors = [];
        $previousErrorHandler = $this->setUpErrorHandler($triggeredErrors);

        try {
            $this->writer->log(LogLevel::DEBUG, self::LOG_MESSAGE);

            $this->assertEquals(1, count($triggeredErrors));
            $this->assertEquals(E_USER_NOTICE, $triggeredErrors[0]['errno']);
        }
        finally {
            set_error_handler($previousErrorHandler);
        }
    }

    public function test_InvalidLogLevel_log_ShouldTriggerUserWarning()
    {
        $triggeredErrors = [];
        $previousErrorHandler = $this->setUpErrorHandler($triggeredErrors);

        try {
            $this->writer->log(self::INVALID_LOG_LEVEL, self::LOG_MESSAGE);

            $this->assertEquals(1, count($triggeredErrors));
            $this->assertEquals(E_USER_WARNING, $triggeredErrors[0]['errno']);
        }
        finally {
            set_error_handler($previousErrorHandler);
        }
    }

    /**
     * @return array
     */
    private function setUpErrorHandler(&$triggeredErrors)
    {
        return set_error_handler(function ($errno, $errstr) use (&$triggeredErrors) {
            $triggeredErrors[] = ['errno' => $errno, 'errstr' => $errstr];
        });
    }
}


text:
from django.core.management.base import BaseCommand
from django.conf import settings
from django.utils.translation import ugettext as _, ugettext_lazy

from odk_viewer.models import DataDictionary
from utils.model_tools import queryset_iterator

class Command(BaseCommand):
    help = ugettext_lazy("Insert UUID into XML of all existing XForms")

    def handle(self, *args, **kwargs):
        print (_('%(nb)d XForms to update')
               % {'nb': DataDictionary.objects.count()})
        for i, dd in enumerate(queryset_iterator(DataDictionary.objects.all())):
            if dd.xls:
                dd._set_uuid_in_xml()
                super(DataDictionary, dd).save()
            if (i + 1) % 10 == 0:
                print _('Updated %(nb)d XForms...') % {'nb': i}


text:
namespace mojo {
class ApplicationImpl;
}

namespace resource_provider {

class ResourceProviderApp : public mojo::ApplicationDelegate,
                            public mojo::InterfaceFactory<ResourceProvider> {
 public:
  ResourceProviderApp();
  ~ResourceProviderApp() override;

 private:
  // ApplicationDelegate:
  void Initialize(mojo::ApplicationImpl* app) override;
  bool ConfigureIncomingConnection(
      mojo::ApplicationConnection* connection) override;

  // mojo::InterfaceFactory<ResourceProvider>:
  void Create(mojo::ApplicationConnection* connection,
              mojo::InterfaceRequest<ResourceProvider> request) override;

  mojo::WeakBindingSet<ResourceProvider> bindings_;

  DISALLOW_COPY_AND_ASSIGN(ResourceProviderApp);
};

}  // namespace resource_provider

#endif  // COMPONENTS_RESOURCE_PROVIDER_RESOURCE_PROVIDER_APP_H_


text:
Read ME!
----------

tiny_Blog is a very simple blogging system using the Nancy framework, This is a new approach to blogging and so here,
you don't go through the troubles of creating a post with the help of add/edit/manage pages. To create a post, just
create a YAML (.yml) file within the Posts folder in the Nancy.Demo.TinyBlog web application's folder
in your file system! So whenever you create a new post or modify (or delete) a post, you just have to copy over the
updated files to the server hosting the application :)

It should use the following format - there should be a "title", "date_created",
"date_edited", "content" and "tags"! That's it!!! The file name will act as the url :) So, if the file name
is "Lorem Ipsum Dolor.yml", the url will be "http://<base_url>/blog/lorem-ipsum-dolor" !

For more information about YAML, refer the wikipedia page: http://en.wikipedia.org/wiki/Yaml. Given below is a
sample YAML file.

```yaml
---
title: Lorem Ipsum Dolor
date_created: 2013-05-18
date_edited: 2013-05-18
content: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed orci ante, tincidunt vitae hendrerit.
tags:
    - ASP.Net
    - C#
    - IronRuby


text:
<!DOCTYPE html>

		<title>Clip-One - Front End</title>

		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">
		<meta content="" name="description" />
		<meta content="" name="author" />

		<link href="assets/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
		<link rel="stylesheet" href="assets/plugins/font-awesome/css/font-awesome.min.css">
		<link rel="stylesheet" href="assets/fonts/style.css">
		<link rel="stylesheet" href="assets/plugins/animate.css/animate.min.css">
		<link rel="stylesheet" href="assets/css/main.css">
		<link rel="stylesheet" href="assets/css/main-responsive.css">
		<link rel="stylesheet" href="assets/css/theme_blue.css" type="text/css" id="skin_color">

		<link rel="stylesheet" href="assets/plugins/revolution_slider/rs-plugin/css/settings.css">
		<link rel="stylesheet" href="assets/plugins/flex-slider/flexslider.css">
		<link rel="stylesheet" href="assets/plugins/colorbox/example2/colorbox.css">

About Clip-One

							Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.
							Nulla consequat massa quis enim.
							Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu.
							In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo.

Recent Works

Contact Us

						<address class="margin-bottom-40">
							Clip-One

							12345 Street Name, City Name, United States

							P: (641)-734-4763

							Email:

								info@example.com

						</address>

								Call Us: (641)-734-4763 - Mail:

									info@example.com

											Twitter

											Dribbble

											Facebook

											Google+

											LinkedIn

											YouTube

											RSS

						<button data-target=".navbar-collapse" data-toggle="collapse" class="navbar-toggle" type="button">
							Toggle navigation

						</button>

							CLIPONE

									Home

									Pages

											About Us

											Team

											Services

											Careers

											Faq

											Contact Us

									Features

															Main Features

																		Icons

																		Buttons

																		Animations

																		Typograpy

																		Grid System

															Headers and Footers

																		Header Version 1

																		Header Version 2

																		Header Version 3

																		Footer Version 1

																		Footer Version 2

															Extra

																		Search Result

																		Pricing Tables

																		404

																		500

															Blog

																		Blog Page

																		Blog Post

									Portfolio

											4 Columns Portfolio

											3 Columns Portfolio

											2 Columns Portfolio

											Portfolio Item

									Admin Theme

										<form class="" id="searchform" action="#">

												<input type="text" class="form-control" placeholder="Search">

													<button class="btn btn-main-color btn-squared" type="button">

													</button>

										</form>

						Style Selector

						Predefined Color Schemes

							Clear Styles

							Save Styles

								Free your creative spirit

								Super Clean Admin Theme

								Lorem ipsum dolor sit amet, dolore eiusmod

								quis tempor incididunt. Sed unde omnis iste.

								Purchase Now!

								100% Fully Responsive

								This is what you were looking for

								Lorem ipsum dolor sit amet, dolore eiusmod

								quis tempor incididunt. Sed unde omnis iste.

								Purchase Now!

								Super Flexible Layout

								This is what you were looking for

								Lorem ipsum dolor sit amet, dolore eiusmod

								quis tempor incididunt. Sed unde omnis iste.

								Purchase Now!

Responsive Design

									Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

									View More

Free updates & support

									Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

									View More

Incredibly Flexible

									Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

									View More

Take a look at some of our work

								Nulla consequat massa quis enim. Donec pede justo fringilla vel, aliquet nec, vulputate eget, arcu.

								In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium.

												4 Columns Portfolio

												3 Columns Portfolio

												2 Columns Portfolio

												Single Project

									View the Full Portfolio here

About Us

								Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.

								Nulla consequat massa quis enim.

								Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu.

								In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium.

								Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi.

								Aenean vulputate eleifend tellus.

							 Learn more...

HTML5 / CSS3 / JS

											Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in.

Awesome Sliders

											Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in.

Clean Design

											Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in.

Why Choose Us

									Lid est laborum dolo rumes fugats untras. Etha rums ser quidem rerum facilis dolores nemis onis fugats vitaes nemo minima rerums unsers sadips amets.

									Ut enim ad minim veniam, quis nostrud Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci amets uns.

									Etharums ser quidem rerum facilis dolores nemis omnis fugats vitaes nemo minima rerums unsers sadips ameet quasi architecto beatae vitae dicta sunt explicabo

										Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim.

										Nulla consequat massa quis enim.
										Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu.

										Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy.

										Ut enim ad minim veniam, quis nostrud Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci amets uns.

										Etharums ser quidem rerum facilis dolores nemis omnis fugats vitaes nemo minima rerums unsers sadips ameet quasi architecto beatae vitae dicta sunt explicabo.

								 Learn more...

Our Happy Clients

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

Ultra-Responsive Design

								Lid est laborum dolo rumes fugats untras. Etha rums ser quidem rerum facilis dolores nemis onis fugats vitaes nemo minima rerums unsers sadips amets.

								Ut enim ad minim veniam, quis nostrud Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci amets uns.

								Etharums ser quidem rerum facilis dolores nemis omnis fugats vitaes nemo minima rerums unsers sadips ameet quasi architecto beatae vitae dicta sunt explicabo.

							 Learn more...

 WE WORK HARD FOR YOU

								Try new wxperience with Clip-One

Design

										Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.

											Learn more

Develop

										Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.

											Learn more

Support

										Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.

											Learn more

Latest Blog Posts

													 January 11, 2014

														Lorem ipsum dolor sit amet, consectetur adipiscing elit.

														Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec hendrerit vehicula est, in consequat libero.

														 By

																Peter Clark

																Design
															,

																Lifestyle

																36 Comments

														Read more...

													 January 11, 2014

														Lorem ipsum dolor sit amet, consectetur adipiscing elit.

														Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec hendrerit vehicula est, in consequat libero.

														 By

																Peter Clark

																Design
															,

																Lifestyle

																36 Comments

														Read more...

													 January 11, 2014

														Lorem ipsum dolor sit amet, consectetur adipiscing elit.

														Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec hendrerit vehicula est, in consequat libero.

														 By

																Peter Clark

																Design
															,

																Lifestyle

																36 Comments

														Read more...

What Client's Say

														Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec hendrerit vehicula est, in consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec hendrerit vehicula est, in consequat.  Donec hendrerit vehicula est, in consequat.  Donec hendrerit vehicula est, in consequat.

														Peter ClarkUI Designer - Cliptheme

														Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec hendrerit vehicula est, in consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

														Nicole BellContent Designer - Cliptheme

Welcome

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eu pulvinar magna. Phasellus semper scelerisque purus, et semper nisl lacinia sit amet. Praesent venenatis turpis vitae purus semper, eget sagittis velit venenatis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos... View More

Follow Us

										Twitter

										Facebook

										LinkedIn

								CLIPONE

								© Copyright 2014 by Clip-One. All Rights Reserved.

											FAQ's

											Sitemap

											Contact


text:
layout: book
title: "Chapter 15"
tagline: "The Van"
lastReviewedOn: "2016-10-03 00:00:00 -0500"
status: stub
---

{pagebreak}

# Chapter Fifteen: The Van

- Darnell waits for the van outside Mad Canopy
- Darnell tails van, runs plates
- Introduce Valerie Williams in this chapter, she's the one who comes to trust Darnell and invite him into her cell.
- Thinking on his feet when presented with an opportunity, he helps Valerie, gains her trust,
- Asks her out? Coffee at Mad Canopy? She doesn't like that place. They settle on another, then.
- [Later Chapter: Valerie introduces him into her cell – Archie's cell! Archie is a rebel? (Yep.)]
- [Later Chapter: Prue suspects Darnell is having affair with Valerie. Good luck explaining that one, Darnell.]


text:
package sprout.crypto;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import sprout.crypto.CryptoException;
import sprout.util.Util;

import java.math.BigInteger;

public class PRG {

	private SecureRandom rand;
	private int l;

	public PRG(int l) throws NoSuchAlgorithmException {
		this.rand = SecureRandom.getInstance("SHA1PRNG");
		this.l = l;
	}

	public PRG(int l, byte[] seed) throws NoSuchAlgorithmException {
		this.rand = SecureRandom.getInstance("SHA1PRNG");
		this.rand.setSeed(seed);
		this.l = l;
	}

	public byte[] generateBytes(int m) {
		byte[] bytes = new byte[(m + 7) / 8];
		this.rand.nextBytes(bytes);
		return bytes;
	}

	public byte[] generateBytes(int m, byte[] seed) {
		this.rand.setSeed(seed);
		return generateBytes(m);
	}

	public byte[] generateBytes(int m, BigInteger seed) {
		return generateBytes(m, seed.toByteArray());
	}

	public String generateBitString(int m) {
		byte[] bytes = generateBytes(m);
		String s = new BigInteger(1, bytes).toString(2);
		if (s.length() < m)
			return Util.addZero(s, m);
		return s.substring(0, m); // bit string of length m
	}

	public String generateBitString(int m, byte[] seed) {
		byte[] bytes = generateBytes(m, seed);
		String s = new BigInteger(1, bytes).toString(2);
		if (s.length() < m)
			return Util.addZero(s, m);
		return s.substring(0, m); // bit string of length m
	}

	public String generateBitString(int m, BigInteger seed) {
		byte[] bytes = generateBytes(m, seed);
		String s = new BigInteger(1, bytes).toString(2);
		if (s.length() < m)
			return Util.addZero(s, m);
		return s.substring(0, m); // bit string of length m
	}
}


text:
from django.db import models
from localflavor.us.models import PhoneNumberField, USStateField
from django.utils.translation import ugettext_lazy as _
from django.db.models import permalink
from django_extensions.db.models import (TitleSlugDescriptionModel,
                                         TimeStampedModel)
from django.contrib.gis.db import models as gis_models
from django.contrib.gis.geos import GEOSGeometry
from django.contrib.auth import get_user_model
from django.db.models.signals import post_save
from taggit.managers import TaggableManager
from taggit.models import TaggedItemBase
from .utils import get_lat_long

class Location(TimeStampedModel):
    slug = models.SlugField(_('slug'))
    address = models.CharField(_('address'),
                               max_length=255, blank=True, null=True)
    city = models.CharField(_('city'), max_length=100, blank=True, null=True)
    state = USStateField(_('state'), blank=True, null=True)
    zipcode = models.CharField(_('zip'), max_length=5, blank=True, null=True)
    lat_long = models.CharField(_('lat and long coords'),
                                max_length=255, blank=True, null=True)
    point = gis_models.PointField(blank=True, null=True)

    def __unicode__(self):
        return u'{0}, {1}, {2}'.format(self.address, self.city, self.state)

    @property
    def latitude(self):
        return float(self.lat_long.split(',')[0])

    @property
    def longitude(self):
        return float(self.lat_long.split(',')[1])

    @permalink
    def get_absolute_url(self):
        return ('location-detail', None, {'slug': self.slug})

    def save(self):
        location = "%s+%s+%s+%s" % (self.address.replace(' ', '+'),
                                    self.city,
                                    self.state,
                                    self.zipcode)
        self.lat_long = get_lat_long(location)
        if not self.lat_long:
            location = "%s+%s+%s" % (self.city, self.state, self.zipcode)
            self.lat_long = get_lat_long(location)
        self.point = GEOSGeometry(
            'POINT(%s)' % self.lat_long.replace(',', ' '))

        super(Location, self).save()

#class Skill(TaggedItemBase):
#    pass

class Organization(TimeStampedModel, TitleSlugDescriptionModel):
    phone = PhoneNumberField(blank=True, null=True)
    website = models.CharField(max_length=255, blank=True, null=True)
    managers = models.ManyToManyField(get_user_model(),
                                      blank=True,
                                      null=True)

    objects = gis_models.GeoManager()

    @permalink
    def get_absolute_url(self):
        return ('project-list', None, {})

    def __unicode__(self):
        return u'{0}'.format(self.title)

class LaborType(TitleSlugDescriptionModel):
    pass

    @permalink
    def get_absolute_url(self):
        return ('opportunity-type', None, {'slug': self.slug})

    def __unicode__(self):
        return u'{0}'.format(self.title)

class Project(TimeStampedModel, TitleSlugDescriptionModel):
    lead_volunteers = models.ManyToManyField(get_user_model(),
                                             blank=True,
                                             null=True)
    organization = models.ForeignKey(Organization, related_name='projects')
    image = models.ImageField(upload_to="project_images",
                              blank=True,
                              null=True)

    @permalink
    def get_absolute_url(self):
        return ('project-detail', None, {'slug': self.slug})

    def __unicode__(self):
        return u'{0} at {1}'.format(self.title, self.organization)

class OpenOpportunityManager(models.Manager):
    def get_queryset(self):
        return super(OpenOpportunityManager, self).get_queryset().filter(
            fulfilled=False)

class Opportunity(TimeStampedModel, TitleSlugDescriptionModel):
    project = models.ForeignKey(Project)
    location = models.ForeignKey(Location, blank=True, null=True)
    date = models.DateField(blank=True, null=True)
    time = models.TimeField(blank=True, null=True)
    labor_type = models.ForeignKey(LaborType, blank=True, null=True)
    fulfilled = models.BooleanField(default=False)
    max_applicants = models.IntegerField(_('Max applicants'), blank=True,
                                         null=True)

    requirements = TaggableManager()

    objects = gis_models.GeoManager()
    open_objects = OpenOpportunityManager()

    @permalink
    def get_absolute_url(self):
        return (
            'opportunity-detail', None,
            {'project_slug': self.project.slug, 'slug': self.slug})

    def __unicode__(self):
        return u'{0} for {1}'.format(self.title, self.project)

    @property
    def location(self):
        if len(self.locations.all()) == 1:
            return self.locations.all()[0]
        else:
            return False

    @property
    def app_count(self):
        return len(VolunteerApplication.objects.filter(
            opportunity=self))

class Volunteer(TimeStampedModel):
    '''
    '''
    name = models.CharField(_('Name'), max_length=255)
    phone_number = PhoneNumberField(blank=True, null=True)
    address = models.CharField(blank=True, null=True,
                               max_length=255)
    user = models.ForeignKey(get_user_model(), blank=True, null=True)

    opportunities_completed = models.ManyToManyField(Opportunity,
                                                     blank=True,
                                                     null=True)

    @property
    def is_manager(self):
        if self.organization_set.all():
            return True
        else:
            return False

    def __unicode__(self):
        return u'{0}'.format(self.name)

    @permalink
    def get_absolute_url(self):
        return ('dashboard')

APP_STATUSES = (('pending', 'Pending'),
                ('approved', 'Approved'),
                ('denied', 'Denied'))

def create_volunteer_profile(sender, instance, created, **kwargs):
    if created:
        Volunteer.objects.create(user=instance)

post_save.connect(create_volunteer_profile, sender=get_user_model())

class VolunteerApplication(TimeStampedModel):

    user = models.ForeignKey(get_user_model())
    opportunity = models.ForeignKey(Opportunity)
    status = models.CharField(_('Status'),
                              choices=APP_STATUSES,
                              default='pending',
                              max_length=15)

    def __unicode__(self):
        return u'Application for {0}: {1}'.format(self.opportunity, self.user)


text:
package com.cloudera.util;

import java.util.Map;

import com.cloudera.flume.core.Attributes;
import com.cloudera.flume.reporter.ReportEvent;
import com.cloudera.flume.reporter.ReportUtil;
import com.cloudera.flume.reporter.Reportable;

/**
 * Simple class that retries a fixed number of times, then fails.
 */
public class FixedRetryPolicy implements BackoffPolicy {

  protected int numRetries;
  protected int retryCount = 0;

  final static public String A_MAX_ATTEMPTS = "fixedmaxAttempts";
  final static public String A_COUNT = "fixedRetryCount";

  public FixedRetryPolicy(int numRetries) {
    this.numRetries = numRetries;
  }

  /**
   * Increment the retry count.
   */
  @Override
  public void backoff() {
    retryCount++;
  }

  /**
   * Returns true when the number of retry attempts exceeds the maximum.
   */
  @Override
  public boolean isFailed() {
    return retryCount >= numRetries;
  }

  /**
   * Returns true if number of retry attempts is less than the maximum allowed.
   */
  @Override
  public boolean isRetryOk() {
    return retryCount < numRetries;
  }

  @Override
  public void reset() {
    retryCount = 0;
  }

  /**
   * Returns immediately - there are no external conditions to wait for.
   */
  @Override
  public void waitUntilRetryOk() throws InterruptedException {
    // We can always retry
  }

  @Override
  public long sleepIncrement() {
    return 0;
  }

  @Override
  public String getName() {
    return "FixedRetryPolicy";
  }

  @Override
  public ReportEvent getMetrics() {
    ReportEvent rpt = new ReportEvent(getName());
    Attributes.setLong(rpt, A_MAX_ATTEMPTS, numRetries);
    Attributes.setLong(rpt, A_COUNT, retryCount);
    return rpt;
  }

  @Override
  public Map<String, Reportable> getSubMetrics() {
    return ReportUtil.noChildren();
  }
}


text:
package com.crawljax.plugins.savecrawlsession;

/**
 * Default values for basic variables.
 */
public class Utils {

	public static final String OUTPUTFOLDER = "crawlsession/";
	public static final String SESSION_XML = "session.xml";
	public static final String URL = "http://spci.st.ewi.tudelft.nl/demo/crawljax/";

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:padding="20dp"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/situation_title"
        android:textSize="18sp"
        android:drawablePadding="10dp"
        tools:text = "SituationName" />

</LinearLayout>


text:
import { ParameterInvocation } from '../../TypeInvocations';
import { ParameterInfo } from '../../Reflection/ParameterInfo';
import { Arguments } from '../../Arguments';

/**
 * @ignore
 * @hidden
 */
export class MethodParameterInvocation implements ParameterInvocation {
  constructor(readonly design: ParameterInfo) {}

  // parameters[0] = value of index
  // parameters[1] = index of this parameter
  // parameters[2] = all parameters
  invoke(params: Arguments, receiver: unknown): any {
    return params[this.design.index];
  }
}


text:
This crate contains the functionality necessary for loading and managing AWS
credentials for API requests. It was designed for use in
[Rusoto](https://github.com/rusoto/rusoto).

## Development

The Rusoto credential crate is packaged and published separately from the Rusoto
crate itself. The crate does not depend on Rusoto itself. The credential crate
is published as a versioned dependency of Rusoto on crates.io.