text:
var Calendar = function () {

    return {
        //main function to initiate the module
        init: function () {

            App.addResponsiveHandler(function () {
                Calendar.initCalendar();
            });

            $('.page-sidebar .sidebar-toggler').click(function () {
                Calendar.initCalendar();
            });

            Calendar.initCalendar();
        },

        initCalendar: function () {

            if (!jQuery().fullCalendar) {
                return;
            }

            var date = new Date();
            var d = date.getDate();
            var m = date.getMonth();
            var y = date.getFullYear();

            var h = {};

            if (App.isRTL()) {
                 if ($('#calendar').parents(".portlet").width() <= 720) {
                    $('#calendar').addClass("mobile");
                    h = {
                        right: 'title, prev, next',
                        center: '',
                        right: 'agendaDay, agendaWeek, month, today'
                    };
                } else {
                    $('#calendar').removeClass("mobile");
                    h = {
                        right: 'title',
                        center: '',
                        left: 'agendaDay, agendaWeek, month, today, prev,next'
                    };
                }
            } else {
                 if ($('#calendar').parents(".portlet").width() <= 720) {
                    $('#calendar').addClass("mobile");
                    h = {
                        left: 'title, prev, next',
                        center: '',
                        right: 'today,month,agendaWeek,agendaDay'
                    };
                } else {
                    $('#calendar').removeClass("mobile");
                    h = {
                        left: 'title',
                        center: '',
                        right: 'prev,next,today,month,agendaWeek,agendaDay'
                    };
                }
            }

            var initDrag = function (el) {
                // create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
                // it doesn't need to have a start or end
                var eventObject = {
                    title: $.trim(el.text()) // use the element's text as the event title
                };
                // store the Event Object in the DOM element so we can get to it later
                el.data('eventObject', eventObject);
                // make the event draggable using jQuery UI
                el.draggable({
                    zIndex: 999,
                    revert: true, // will cause the event to go back to its
                    revertDuration: 0 //  original position after the drag
                });
            }

            var addEvent = function (title) {
                title = title.length == 0 ? "Untitled Event" : title;
                var html = $('
' + title + '
');
                jQuery('#event_box').append(html);
                initDrag(html);
            }

            $('#external-events div.external-event').each(function () {
                initDrag($(this))
            });

            $('#event_add').unbind('click').click(function () {
                var title = $('#event_title').val();
                addEvent(title);
            });

            //predefined events
            $('#event_box').html("");
            addEvent("My Event 1");
            addEvent("My Event 2");
            addEvent("My Event 3");
            addEvent("My Event 4");
            addEvent("My Event 5");
            addEvent("My Event 6");

            $('#calendar').fullCalendar('destroy'); // destroy the calendar
            $('#calendar').fullCalendar({ //re-initialize the calendar
                header: h,
                slotMinutes: 15,
                editable: true,
                droppable: true, // this allows things to be dropped onto the calendar !!!
                drop: function (date, allDay) { // this function is called when something is dropped

                    // retrieve the dropped element's stored Event Object
                    var originalEventObject = $(this).data('eventObject');
                    // we need to copy it, so that multiple events don't have a reference to the same object
                    var copiedEventObject = $.extend({}, originalEventObject);

                    // assign it the date that was reported
                    copiedEventObject.start = date;
                    copiedEventObject.allDay = allDay;
                    copiedEventObject.className = $(this).attr("data-class");

                    // render the event on the calendar
                    // the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
                    $('#calendar').fullCalendar('renderEvent', copiedEventObject, true);

                    // is the "remove after drop" checkbox checked?
                    if ($('#drop-remove').is(':checked')) {
                        // if so, remove the element from the "Draggable Events" list
                        $(this).remove();
                    }
                },
                events: [{
                        title: 'All Day Event',
                        start: new Date(y, m, 1),
                        backgroundColor: App.getLayoutColorCode('yellow')
                    }, {
                        title: 'Long Event',
                        start: new Date(y, m, d - 5),
                        end: new Date(y, m, d - 2),
                        backgroundColor: App.getLayoutColorCode('green')
                    }, {
                        title: 'Repeating Event',
                        start: new Date(y, m, d - 3, 16, 0),
                        allDay: false,
                        backgroundColor: App.getLayoutColorCode('red')
                    }, {
                        title: 'Repeating Event',
                        start: new Date(y, m, d + 4, 16, 0),
                        allDay: false,
                        backgroundColor: App.getLayoutColorCode('green')
                    }, {
                        title: 'Meeting',
                        start: new Date(y, m, d, 10, 30),
                        allDay: false,
                    }, {
                        title: 'Lunch',
                        start: new Date(y, m, d, 12, 0),
                        end: new Date(y, m, d, 14, 0),
                        backgroundColor: App.getLayoutColorCode('grey'),
                        allDay: false,
                    }, {
                        title: 'Birthday Party',
                        start: new Date(y, m, d + 1, 19, 0),
                        end: new Date(y, m, d + 1, 22, 30),
                        backgroundColor: App.getLayoutColorCode('purple'),
                        allDay: false,
                    }, {
                        title: 'Click for Google',
                        start: new Date(y, m, 28),
                        end: new Date(y, m, 29),
                        backgroundColor: App.getLayoutColorCode('yellow'),
                        url: 'http://google.com/',
                    }
                ]
            });

        }

    };

}();


text:
using namespace llvm;

#define FIXUPLEA_DESC "X86 LEA Fixup"
#define FIXUPLEA_NAME "x86-fixup-LEAs"

#define DEBUG_TYPE FIXUPLEA_NAME

STATISTIC(NumLEAs, "Number of LEA instructions created");

namespace {
class FixupLEAPass : public MachineFunctionPass {
  enum RegUsageState { RU_NotUsed, RU_Write, RU_Read };

  /// Given a machine register, look for the instruction
  /// which writes it in the current basic block. If found,
  /// try to replace it with an equivalent LEA instruction.
  /// If replacement succeeds, then also process the newly created
  /// instruction.
  void seekLEAFixup(MachineOperand &p, MachineBasicBlock::iterator &I,
                    MachineBasicBlock &MBB);

  /// Given a memory access or LEA instruction
  /// whose address mode uses a base and/or index register, look for
  /// an opportunity to replace the instruction which sets the base or index
  /// register with an equivalent LEA instruction.
  void processInstruction(MachineBasicBlock::iterator &I,
                          MachineBasicBlock &MBB);

  /// Given a LEA instruction which is unprofitable
  /// on SlowLEA targets try to replace it with an equivalent ADD instruction.
  void processInstructionForSlowLEA(MachineBasicBlock::iterator &I,
                                    MachineBasicBlock &MBB);

  /// Given a LEA instruction which is unprofitable
  /// on SNB+ try to replace it with other instructions.
  /// According to Intel's Optimization Reference Manual:
  /// " For LEA instructions with three source operands and some specific
  ///   situations, instruction latency has increased to 3 cycles, and must
  ///   dispatch via port 1:
  /// - LEA that has all three source operands: base, index, and offset
  /// - LEA that uses base and index registers where the base is EBP, RBP,
  ///   or R13
  /// - LEA that uses RIP relative addressing mode
  /// - LEA that uses 16-bit addressing mode "
  /// This function currently handles the first 2 cases only.
  void processInstrForSlow3OpLEA(MachineBasicBlock::iterator &I,
                                 MachineBasicBlock &MBB, bool OptIncDec);

  /// Look for LEAs that are really two address LEAs that we might be able to
  /// turn into regular ADD instructions.
  bool optTwoAddrLEA(MachineBasicBlock::iterator &I,
                     MachineBasicBlock &MBB, bool OptIncDec,
                     bool UseLEAForSP) const;

  /// Determine if an instruction references a machine register
  /// and, if so, whether it reads or writes the register.
  RegUsageState usesRegister(MachineOperand &p, MachineBasicBlock::iterator I);

  /// Step backwards through a basic block, looking
  /// for an instruction which writes a register within
  /// a maximum of INSTR_DISTANCE_THRESHOLD instruction latency cycles.
  MachineBasicBlock::iterator searchBackwards(MachineOperand &p,
                                              MachineBasicBlock::iterator &I,
                                              MachineBasicBlock &MBB);

  /// if an instruction can be converted to an
  /// equivalent LEA, insert the new instruction into the basic block
  /// and return a pointer to it. Otherwise, return zero.
  MachineInstr *postRAConvertToLEA(MachineBasicBlock &MBB,
                                   MachineBasicBlock::iterator &MBBI) const;

public:
  static char ID;

  StringRef getPassName() const override { return FIXUPLEA_DESC; }

  FixupLEAPass() : MachineFunctionPass(ID) { }

  /// Loop over all of the basic blocks,
  /// replacing instructions by equivalent LEA instructions
  /// if needed and when possible.
  bool runOnMachineFunction(MachineFunction &MF) override;

  // This pass runs after regalloc and doesn't support VReg operands.
  MachineFunctionProperties getRequiredProperties() const override {
    return MachineFunctionProperties().set(
        MachineFunctionProperties::Property::NoVRegs);
  }

private:
  TargetSchedModel TSM;
  const X86InstrInfo *TII = nullptr;
  const X86RegisterInfo *TRI = nullptr;
};
}

char FixupLEAPass::ID = 0;

INITIALIZE_PASS(FixupLEAPass, FIXUPLEA_NAME, FIXUPLEA_DESC, false, false)

MachineInstr *
FixupLEAPass::postRAConvertToLEA(MachineBasicBlock &MBB,
                                 MachineBasicBlock::iterator &MBBI) const {
  MachineInstr &MI = *MBBI;
  switch (MI.getOpcode()) {
  case X86::MOV32rr:
  case X86::MOV64rr: {
    const MachineOperand &Src = MI.getOperand(1);
    const MachineOperand &Dest = MI.getOperand(0);
    MachineInstr *NewMI =
        BuildMI(MBB, MBBI, MI.getDebugLoc(),
                TII->get(MI.getOpcode() == X86::MOV32rr ? X86::LEA32r
                                                        : X86::LEA64r))
            .add(Dest)
            .add(Src)
            .addImm(1)
            .addReg(0)
            .addImm(0)
            .addReg(0);
    return NewMI;
  }
  }

  if (!MI.isConvertibleTo3Addr())
    return nullptr;

  switch (MI.getOpcode()) {
  default:
    // Only convert instructions that we've verified are safe.
    return nullptr;
  case X86::ADD64ri32:
  case X86::ADD64ri8:
  case X86::ADD64ri32_DB:
  case X86::ADD64ri8_DB:
  case X86::ADD32ri:
  case X86::ADD32ri8:
  case X86::ADD32ri_DB:
  case X86::ADD32ri8_DB:
    if (!MI.getOperand(2).isImm()) {
      // convertToThreeAddress will call getImm()
      // which requires isImm() to be true
      return nullptr;
    }
    break;
  case X86::SHL64ri:
  case X86::SHL32ri:
  case X86::INC64r:
  case X86::INC32r:
  case X86::DEC64r:
  case X86::DEC32r:
  case X86::ADD64rr:
  case X86::ADD64rr_DB:
  case X86::ADD32rr:
  case X86::ADD32rr_DB:
    // These instructions are all fine to convert.
    break;
  }
  MachineFunction::iterator MFI = MBB.getIterator();
  return TII->convertToThreeAddress(MFI, MI, nullptr);
}

FunctionPass *llvm::createX86FixupLEAs() { return new FixupLEAPass(); }

static bool isLEA(unsigned Opcode) {
  return Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
         Opcode == X86::LEA64_32r;
}

bool FixupLEAPass::runOnMachineFunction(MachineFunction &MF) {
  if (skipFunction(MF.getFunction()))
    return false;

  const X86Subtarget &ST = MF.getSubtarget<X86Subtarget>();
  bool IsSlowLEA = ST.slowLEA();
  bool IsSlow3OpsLEA = ST.slow3OpsLEA();
  bool LEAUsesAG = ST.LEAusesAG();

  bool OptIncDec = !ST.slowIncDec() || MF.getFunction().hasOptSize();
  bool UseLEAForSP = ST.useLeaForSP();

  TSM.init(&ST);
  TII = ST.getInstrInfo();
  TRI = ST.getRegisterInfo();

  LLVM_DEBUG(dbgs() << "Start X86FixupLEAs\n";);
  for (MachineBasicBlock &MBB : MF) {
    // First pass. Try to remove or optimize existing LEAs.
    for (MachineBasicBlock::iterator I = MBB.begin(); I != MBB.end(); ++I) {
      if (!isLEA(I->getOpcode()))
        continue;

      if (optTwoAddrLEA(I, MBB, OptIncDec, UseLEAForSP))
        continue;

      if (IsSlowLEA)
        processInstructionForSlowLEA(I, MBB);
      else if (IsSlow3OpsLEA)
        processInstrForSlow3OpLEA(I, MBB, OptIncDec);
    }

    // Second pass for creating LEAs. This may reverse some of the
    // transformations above.
    if (LEAUsesAG) {
      for (MachineBasicBlock::iterator I = MBB.begin(); I != MBB.end(); ++I)
        processInstruction(I, MBB);
    }
  }

  LLVM_DEBUG(dbgs() << "End X86FixupLEAs\n";);

  return true;
}

FixupLEAPass::RegUsageState
FixupLEAPass::usesRegister(MachineOperand &p, MachineBasicBlock::iterator I) {
  RegUsageState RegUsage = RU_NotUsed;
  MachineInstr &MI = *I;

  for (unsigned i = 0; i < MI.getNumOperands(); ++i) {
    MachineOperand &opnd = MI.getOperand(i);
    if (opnd.isReg() && opnd.getReg() == p.getReg()) {
      if (opnd.isDef())
        return RU_Write;
      RegUsage = RU_Read;
    }
  }
  return RegUsage;
}

/// getPreviousInstr - Given a reference to an instruction in a basic
/// block, return a reference to the previous instruction in the block,
/// wrapping around to the last instruction of the block if the block
/// branches to itself.
static inline bool getPreviousInstr(MachineBasicBlock::iterator &I,
                                    MachineBasicBlock &MBB) {
  if (I == MBB.begin()) {
    if (MBB.isPredecessor(&MBB)) {
      I = --MBB.end();
      return true;
    } else
      return false;
  }
  --I;
  return true;
}

MachineBasicBlock::iterator
FixupLEAPass::searchBackwards(MachineOperand &p, MachineBasicBlock::iterator &I,
                              MachineBasicBlock &MBB) {
  int InstrDistance = 1;
  MachineBasicBlock::iterator CurInst;
  static const int INSTR_DISTANCE_THRESHOLD = 5;

  CurInst = I;
  bool Found;
  Found = getPreviousInstr(CurInst, MBB);
  while (Found && I != CurInst) {
    if (CurInst->isCall() || CurInst->isInlineAsm())
      break;
    if (InstrDistance > INSTR_DISTANCE_THRESHOLD)
      break; // too far back to make a difference
    if (usesRegister(p, CurInst) == RU_Write) {
      return CurInst;
    }
    InstrDistance += TSM.computeInstrLatency(&*CurInst);
    Found = getPreviousInstr(CurInst, MBB);
  }
  return MachineBasicBlock::iterator();
}

static inline bool isInefficientLEAReg(unsigned Reg) {
  return Reg == X86::EBP || Reg == X86::RBP ||
         Reg == X86::R13D || Reg == X86::R13;
}

/// Returns true if this LEA uses base an index registers, and the base register
/// is known to be inefficient for the subtarget.
// TODO: use a variant scheduling class to model the latency profile
// of LEA instructions, and implement this logic as a scheduling predicate.
static inline bool hasInefficientLEABaseReg(const MachineOperand &Base,
                                            const MachineOperand &Index) {
  return Base.isReg() && isInefficientLEAReg(Base.getReg()) && Index.isReg() &&
         Index.getReg() != X86::NoRegister;
}

static inline bool hasLEAOffset(const MachineOperand &Offset) {
  return (Offset.isImm() && Offset.getImm() != 0) || Offset.isGlobal();
}

static inline unsigned getADDrrFromLEA(unsigned LEAOpcode) {
  switch (LEAOpcode) {
  default:
    llvm_unreachable("Unexpected LEA instruction");
  case X86::LEA32r:
  case X86::LEA64_32r:
    return X86::ADD32rr;
  case X86::LEA64r:
    return X86::ADD64rr;
  }
}

static inline unsigned getADDriFromLEA(unsigned LEAOpcode,
                                       const MachineOperand &Offset) {
  bool IsInt8 = Offset.isImm() && isInt<8>(Offset.getImm());
  switch (LEAOpcode) {
  default:
    llvm_unreachable("Unexpected LEA instruction");
  case X86::LEA32r:
  case X86::LEA64_32r:
    return IsInt8 ? X86::ADD32ri8 : X86::ADD32ri;
  case X86::LEA64r:
    return IsInt8 ? X86::ADD64ri8 : X86::ADD64ri32;
  }
}

static inline unsigned getINCDECFromLEA(unsigned LEAOpcode, bool IsINC) {
  switch (LEAOpcode) {
  default:
    llvm_unreachable("Unexpected LEA instruction");
  case X86::LEA32r:
  case X86::LEA64_32r:
    return IsINC ? X86::INC32r : X86::DEC32r;
  case X86::LEA64r:
    return IsINC ? X86::INC64r : X86::DEC64r;
  }
}

bool FixupLEAPass::optTwoAddrLEA(MachineBasicBlock::iterator &I,
                                 MachineBasicBlock &MBB, bool OptIncDec,
                                 bool UseLEAForSP) const {
  MachineInstr &MI = *I;

  const MachineOperand &Base =    MI.getOperand(1 + X86::AddrBaseReg);
  const MachineOperand &Scale =   MI.getOperand(1 + X86::AddrScaleAmt);
  const MachineOperand &Index =   MI.getOperand(1 + X86::AddrIndexReg);
  const MachineOperand &Disp =    MI.getOperand(1 + X86::AddrDisp);
  const MachineOperand &Segment = MI.getOperand(1 + X86::AddrSegmentReg);

  if (Segment.getReg() != 0 || !Disp.isImm() || Scale.getImm() > 1 ||
      !TII->isSafeToClobberEFLAGS(MBB, I))
    return false;

  Register DestReg = MI.getOperand(0).getReg();
  Register BaseReg = Base.getReg();
  Register IndexReg = Index.getReg();

  // Don't change stack adjustment LEAs.
  if (UseLEAForSP && (DestReg == X86::ESP || DestReg == X86::RSP))
    return false;

  // LEA64_32 has 64-bit operands but 32-bit result.
  if (MI.getOpcode() == X86::LEA64_32r) {
    if (BaseReg != 0)
      BaseReg = TRI->getSubReg(BaseReg, X86::sub_32bit);
    if (IndexReg != 0)
      IndexReg = TRI->getSubReg(IndexReg, X86::sub_32bit);
  }

  MachineInstr *NewMI = nullptr;

  // Look for lea(%reg1, %reg2), %reg1 or lea(%reg2, %reg1), %reg1
  // which can be turned into add %reg2, %reg1
  if (BaseReg != 0 && IndexReg != 0 && Disp.getImm() == 0 &&
      (DestReg == BaseReg || DestReg == IndexReg)) {
    unsigned NewOpcode = getADDrrFromLEA(MI.getOpcode());
    if (DestReg != BaseReg)
      std::swap(BaseReg, IndexReg);

    if (MI.getOpcode() == X86::LEA64_32r) {
      // TODO: Do we need the super register implicit use?
      NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpcode), DestReg)
        .addReg(BaseReg).addReg(IndexReg)
        .addReg(Base.getReg(), RegState::Implicit)
        .addReg(Index.getReg(), RegState::Implicit);
    } else {
      NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpcode), DestReg)
        .addReg(BaseReg).addReg(IndexReg);
    }
  } else if (DestReg == BaseReg && IndexReg == 0) {
    // This is an LEA with only a base register and a displacement,
    // We can use ADDri or INC/DEC.

    // Does this LEA have one these forms:
    // lea  %reg, 1(%reg)
    // lea  %reg, -1(%reg)
    if (OptIncDec && (Disp.getImm() == 1 || Disp.getImm() == -1)) {
      bool IsINC = Disp.getImm() == 1;
      unsigned NewOpcode = getINCDECFromLEA(MI.getOpcode(), IsINC);

      if (MI.getOpcode() == X86::LEA64_32r) {
        // TODO: Do we need the super register implicit use?
        NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpcode), DestReg)
          .addReg(BaseReg).addReg(Base.getReg(), RegState::Implicit);
      } else {
        NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpcode), DestReg)
          .addReg(BaseReg);
      }
    } else {
      unsigned NewOpcode = getADDriFromLEA(MI.getOpcode(), Disp);
      if (MI.getOpcode() == X86::LEA64_32r) {
        // TODO: Do we need the super register implicit use?
        NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpcode), DestReg)
          .addReg(BaseReg).addImm(Disp.getImm())
          .addReg(Base.getReg(), RegState::Implicit);
      } else {
        NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpcode), DestReg)
          .addReg(BaseReg).addImm(Disp.getImm());
      }
    }
  } else
    return false;

  MBB.erase(I);
  I = NewMI;
  return true;
}

void FixupLEAPass::processInstruction(MachineBasicBlock::iterator &I,
                                      MachineBasicBlock &MBB) {
  // Process a load, store, or LEA instruction.
  MachineInstr &MI = *I;
  const MCInstrDesc &Desc = MI.getDesc();
  int AddrOffset = X86II::getMemoryOperandNo(Desc.TSFlags);
  if (AddrOffset >= 0) {
    AddrOffset += X86II::getOperandBias(Desc);
    MachineOperand &p = MI.getOperand(AddrOffset + X86::AddrBaseReg);
    if (p.isReg() && p.getReg() != X86::ESP) {
      seekLEAFixup(p, I, MBB);
    }
    MachineOperand &q = MI.getOperand(AddrOffset + X86::AddrIndexReg);
    if (q.isReg() && q.getReg() != X86::ESP) {
      seekLEAFixup(q, I, MBB);
    }
  }
}

void FixupLEAPass::seekLEAFixup(MachineOperand &p,
                                MachineBasicBlock::iterator &I,
                                MachineBasicBlock &MBB) {
  MachineBasicBlock::iterator MBI = searchBackwards(p, I, MBB);
  if (MBI != MachineBasicBlock::iterator()) {
    MachineInstr *NewMI = postRAConvertToLEA(MBB, MBI);
    if (NewMI) {
      ++NumLEAs;
      LLVM_DEBUG(dbgs() << "FixLEA: Candidate to replace:"; MBI->dump(););
      // now to replace with an equivalent LEA...
      LLVM_DEBUG(dbgs() << "FixLEA: Replaced by: "; NewMI->dump(););
      MBB.erase(MBI);
      MachineBasicBlock::iterator J =
          static_cast<MachineBasicBlock::iterator>(NewMI);
      processInstruction(J, MBB);
    }
  }
}

void FixupLEAPass::processInstructionForSlowLEA(MachineBasicBlock::iterator &I,
                                                MachineBasicBlock &MBB) {
  MachineInstr &MI = *I;
  const unsigned Opcode = MI.getOpcode();

  const MachineOperand &Dst =     MI.getOperand(0);
  const MachineOperand &Base =    MI.getOperand(1 + X86::AddrBaseReg);
  const MachineOperand &Scale =   MI.getOperand(1 + X86::AddrScaleAmt);
  const MachineOperand &Index =   MI.getOperand(1 + X86::AddrIndexReg);
  const MachineOperand &Offset =  MI.getOperand(1 + X86::AddrDisp);
  const MachineOperand &Segment = MI.getOperand(1 + X86::AddrSegmentReg);

  if (Segment.getReg() != 0 || !Offset.isImm() ||
      !TII->isSafeToClobberEFLAGS(MBB, I))
    return;
  const Register DstR = Dst.getReg();
  const Register SrcR1 = Base.getReg();
  const Register SrcR2 = Index.getReg();
  if ((SrcR1 == 0 || SrcR1 != DstR) && (SrcR2 == 0 || SrcR2 != DstR))
    return;
  if (Scale.getImm() > 1)
    return;
  LLVM_DEBUG(dbgs() << "FixLEA: Candidate to replace:"; I->dump(););
  LLVM_DEBUG(dbgs() << "FixLEA: Replaced by: ";);
  MachineInstr *NewMI = nullptr;
  // Make ADD instruction for two registers writing to LEA's destination
  if (SrcR1 != 0 && SrcR2 != 0) {
    const MCInstrDesc &ADDrr = TII->get(getADDrrFromLEA(Opcode));
    const MachineOperand &Src = SrcR1 == DstR ? Index : Base;
    NewMI =
        BuildMI(MBB, I, MI.getDebugLoc(), ADDrr, DstR).addReg(DstR).add(Src);
    LLVM_DEBUG(NewMI->dump(););
  }
  // Make ADD instruction for immediate
  if (Offset.getImm() != 0) {
    const MCInstrDesc &ADDri =
        TII->get(getADDriFromLEA(Opcode, Offset));
    const MachineOperand &SrcR = SrcR1 == DstR ? Base : Index;
    NewMI = BuildMI(MBB, I, MI.getDebugLoc(), ADDri, DstR)
                .add(SrcR)
                .addImm(Offset.getImm());
    LLVM_DEBUG(NewMI->dump(););
  }
  if (NewMI) {
    MBB.erase(I);
    I = NewMI;
  }
}

void FixupLEAPass::processInstrForSlow3OpLEA(MachineBasicBlock::iterator &I,
                                             MachineBasicBlock &MBB,
                                             bool OptIncDec) {
  MachineInstr &MI = *I;
  const unsigned LEAOpcode = MI.getOpcode();

  const MachineOperand &Dest =    MI.getOperand(0);
  const MachineOperand &Base =    MI.getOperand(1 + X86::AddrBaseReg);
  const MachineOperand &Scale =   MI.getOperand(1 + X86::AddrScaleAmt);
  const MachineOperand &Index =   MI.getOperand(1 + X86::AddrIndexReg);
  const MachineOperand &Offset =  MI.getOperand(1 + X86::AddrDisp);
  const MachineOperand &Segment = MI.getOperand(1 + X86::AddrSegmentReg);

  if (!(TII->isThreeOperandsLEA(MI) || hasInefficientLEABaseReg(Base, Index)) ||
      !TII->isSafeToClobberEFLAGS(MBB, MI) ||
      Segment.getReg() != X86::NoRegister)
    return;

  Register DestReg = Dest.getReg();
  Register BaseReg = Base.getReg();
  Register IndexReg = Index.getReg();

  if (MI.getOpcode() == X86::LEA64_32r) {
    if (BaseReg != 0)
      BaseReg = TRI->getSubReg(BaseReg, X86::sub_32bit);
    if (IndexReg != 0)
      IndexReg = TRI->getSubReg(IndexReg, X86::sub_32bit);
  }

  bool IsScale1 = Scale.getImm() == 1;
  bool IsInefficientBase = isInefficientLEAReg(BaseReg);
  bool IsInefficientIndex = isInefficientLEAReg(IndexReg);

  // Skip these cases since it takes more than 2 instructions
  // to replace the LEA instruction.
  if (IsInefficientBase && DestReg == BaseReg && !IsScale1)
    return;

  LLVM_DEBUG(dbgs() << "FixLEA: Candidate to replace:"; MI.dump(););
  LLVM_DEBUG(dbgs() << "FixLEA: Replaced by: ";);

  MachineInstr *NewMI = nullptr;

  // First try to replace LEA with one or two (for the 3-op LEA case)
  // add instructions:
  // 1.lea (%base,%index,1), %base => add %index,%base
  // 2.lea (%base,%index,1), %index => add %base,%index
  if (IsScale1 && (DestReg == BaseReg || DestReg == IndexReg)) {
    unsigned NewOpc = getADDrrFromLEA(MI.getOpcode());
    if (DestReg != BaseReg)
      std::swap(BaseReg, IndexReg);

    if (MI.getOpcode() == X86::LEA64_32r) {
      // TODO: Do we need the super register implicit use?
      NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpc), DestReg)
                  .addReg(BaseReg)
                  .addReg(IndexReg)
                  .addReg(Base.getReg(), RegState::Implicit)
                  .addReg(Index.getReg(), RegState::Implicit);
    } else {
      NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpc), DestReg)
                  .addReg(BaseReg)
                  .addReg(IndexReg);
    }
  } else if (!IsInefficientBase || (!IsInefficientIndex && IsScale1)) {
    // If the base is inefficient try switching the index and base operands,
    // otherwise just break the 3-Ops LEA inst into 2-Ops LEA + ADD instruction:
    // lea offset(%base,%index,scale),%dst =>
    // lea (%base,%index,scale); add offset,%dst
    NewMI = BuildMI(MBB, MI, MI.getDebugLoc(), TII->get(LEAOpcode))
                .add(Dest)
                .add(IsInefficientBase ? Index : Base)
                .add(Scale)
                .add(IsInefficientBase ? Base : Index)
                .addImm(0)
                .add(Segment);
    LLVM_DEBUG(NewMI->dump(););
  }

  // If either replacement succeeded above, add the offset if needed, then
  // replace the instruction.
  if (NewMI) {
    // Create ADD instruction for the Offset in case of 3-Ops LEA.
    if (hasLEAOffset(Offset)) {
      if (OptIncDec && Offset.isImm() &&
          (Offset.getImm() == 1 || Offset.getImm() == -1)) {
        unsigned NewOpc =
            getINCDECFromLEA(MI.getOpcode(), Offset.getImm() == 1);
        NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpc), DestReg)
                    .addReg(DestReg);
        LLVM_DEBUG(NewMI->dump(););
      } else {
        unsigned NewOpc = getADDriFromLEA(MI.getOpcode(), Offset);
        NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpc), DestReg)
                    .addReg(DestReg)
                    .add(Offset);
        LLVM_DEBUG(NewMI->dump(););
      }
    }

    MBB.erase(I);
    I = NewMI;
    return;
  }

  // Handle the rest of the cases with inefficient base register:
  assert(DestReg != BaseReg && "DestReg == BaseReg should be handled already!");
  assert(IsInefficientBase && "efficient base should be handled already!");

  // FIXME: Handle LEA64_32r.
  if (LEAOpcode == X86::LEA64_32r)
    return;

  // lea (%base,%index,1), %dst => mov %base,%dst; add %index,%dst
  if (IsScale1 && !hasLEAOffset(Offset)) {
    bool BIK = Base.isKill() && BaseReg != IndexReg;
    TII->copyPhysReg(MBB, MI, MI.getDebugLoc(), DestReg, BaseReg, BIK);
    LLVM_DEBUG(MI.getPrevNode()->dump(););

    unsigned NewOpc = getADDrrFromLEA(MI.getOpcode());
    NewMI = BuildMI(MBB, MI, MI.getDebugLoc(), TII->get(NewOpc), DestReg)
                .addReg(DestReg)
                .add(Index);
    LLVM_DEBUG(NewMI->dump(););

    MBB.erase(I);
    I = NewMI;
    return;
  }

  // lea offset(%base,%index,scale), %dst =>
  // lea offset( ,%index,scale), %dst; add %base,%dst
  NewMI = BuildMI(MBB, MI, MI.getDebugLoc(), TII->get(LEAOpcode))
              .add(Dest)
              .addReg(0)
              .add(Scale)
              .add(Index)
              .add(Offset)
              .add(Segment);
  LLVM_DEBUG(NewMI->dump(););

  unsigned NewOpc = getADDrrFromLEA(MI.getOpcode());
  NewMI = BuildMI(MBB, MI, MI.getDebugLoc(), TII->get(NewOpc), DestReg)
              .addReg(DestReg)
              .add(Base);
  LLVM_DEBUG(NewMI->dump(););

  MBB.erase(I);
  I = NewMI;
}

redpajama_set_name: RedPajamaGithub


text:
from datetime import datetime

from twisted.trial.unittest import TestCase

from apns.utils import datetime_to_timestamp

class DatetimeToTimestampTestCase(TestCase):

    def test_datetime(self):
        now = datetime.now()

        timestamp = datetime_to_timestamp(now)

        self.assertEqual(datetime.fromtimestamp(timestamp),
                         now.replace(microsecond=0))


text:
/*
 * Do not modify this file. This file is generated from the monitoring-2010-08-01.normal.json service model.
 */

using System;
using System.Collections.Generic;

using Amazon.CloudWatch.Model;

namespace Amazon.CloudWatch
{
    ///
    /// Interface for accessing CloudWatch
    ///
    /// This is the Amazon CloudWatch API Reference. This guide provides detailed information
    /// about Amazon CloudWatch actions, data types, parameters, and errors. For detailed
    /// information about Amazon CloudWatch features and their associated API calls, go to
    /// the Amazon
    /// CloudWatch Developer Guide.
    ///
    ///
    /// <para>
    /// Amazon CloudWatch is a web service that enables you to publish, monitor, and manage
    /// various metrics, as well as configure alarm actions based on data from metrics. For
    /// more information about this product go to http://aws.amazon.com/cloudwatch.
    ///
    /// </para>
    ///
    /// <para>
    ///  For information about the namespace, metric names, and dimensions that other Amazon
    /// Web Services products use to send metrics to Cloudwatch, go to Amazon
    /// CloudWatch Metrics, Namespaces, and Dimensions Reference in the Amazon CloudWatch
    /// Developer Guide.
    /// </para>
    ///
    /// <para>
    /// Use the following links to get started using the Amazon CloudWatch API Reference:
    /// </para>
    ///

 Actions:
    /// An alphabetical list of all Amazon CloudWatch actions.

 Data
    /// Types: An alphabetical list of all Amazon CloudWatch data types.

 Common
    /// Parameters: Parameters that all Query actions can use.

 Common
    /// Errors: Client and server errors that all actions can return.

 Regions
    /// and Endpoints: Itemized regions and endpoints for all AWS products.

    /// WSDL Location:
    /// http://monitoring.amazonaws.com/doc/2010-08-01/CloudWatch.wsdl

    /// <para>
    /// In addition to using the Amazon CloudWatch API, you can also use the following SDKs
    /// and third-party libraries to access Amazon CloudWatch programmatically.
    /// </para>
    ///

AWS SDK for Java
    /// Documentation

AWS
    /// SDK for .NET Documentation

AWS
    /// SDK for PHP Documentation

AWS
    /// SDK for Ruby Documentation

    /// <para>
    /// Developers in the AWS developer community also provide their own libraries, which
    /// you can find at the following AWS developer centers:
    /// </para>
    ///

AWS Java Developer Center

    ///
AWS PHP Developer Center

AWS Python Developer Center

AWS
    /// Ruby Developer Center

AWS Windows
    /// and .NET Developer Center

    ///
    public partial interface IAmazonCloudWatch : IDisposable
    {

        #region  DeleteAlarms

        ///
        /// Deletes all specified alarms. In the event of an error, no alarms are deleted.
        ///
        /// <param name="request">Container for the necessary parameters to execute the DeleteAlarms service method.</param>
        ///
        /// <returns>The response from the DeleteAlarms service method, as returned by CloudWatch.</returns>
        /// <exception cref="Amazon.CloudWatch.Model.ResourceNotFoundException">
        /// The named resource does not exist.
        /// </exception>
        DeleteAlarmsResponse DeleteAlarms(DeleteAlarmsRequest request);

        ///
        /// Initiates the asynchronous execution of the DeleteAlarms operation.
        ///
        ///
        /// <param name="request">Container for the necessary parameters to execute the DeleteAlarms operation on AmazonCloudWatchClient.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
        /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
        ///          procedure using the AsyncState property.</param>
        ///
        /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteAlarms
        ///         operation.</returns>
        IAsyncResult BeginDeleteAlarms(DeleteAlarmsRequest request, AsyncCallback callback, object state);

        ///
        /// Finishes the asynchronous execution of the  DeleteAlarms operation.
        ///
        ///
        /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteAlarms.</param>
        ///
        /// <returns>Returns a  DeleteAlarmsResult from CloudWatch.</returns>
        DeleteAlarmsResponse EndDeleteAlarms(IAsyncResult asyncResult);

        #endregion

        #region  DescribeAlarmHistory

        ///
        /// Retrieves history for the specified alarm. Filter alarms by date range or item type.
        /// If an alarm name is not specified, Amazon CloudWatch returns histories for all of
        /// the owner's alarms.
        ///
        ///
        /// <returns>The response from the DescribeAlarmHistory service method, as returned by CloudWatch.</returns>
        /// <exception cref="Amazon.CloudWatch.Model.InvalidNextTokenException">
        /// The next token specified is invalid.
        /// </exception>
        DescribeAlarmHistoryResponse DescribeAlarmHistory();

        ///
        /// Retrieves history for the specified alarm. Filter alarms by date range or item type.
        /// If an alarm name is not specified, Amazon CloudWatch returns histories for all of
        /// the owner's alarms.
        ///
        /// <param name="request">Container for the necessary parameters to execute the DescribeAlarmHistory service method.</param>
        ///
        /// <returns>The response from the DescribeAlarmHistory service method, as returned by CloudWatch.</returns>
        /// <exception cref="Amazon.CloudWatch.Model.InvalidNextTokenException">
        /// The next token specified is invalid.
        /// </exception>
        DescribeAlarmHistoryResponse DescribeAlarmHistory(DescribeAlarmHistoryRequest request);

        ///
        /// Initiates the asynchronous execution of the DescribeAlarmHistory operation.
        ///
        ///
        /// <param name="request">Container for the necessary parameters to execute the DescribeAlarmHistory operation on AmazonCloudWatchClient.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
        /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
        ///          procedure using the AsyncState property.</param>
        ///
        /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeAlarmHistory
        ///         operation.</returns>
        IAsyncResult BeginDescribeAlarmHistory(DescribeAlarmHistoryRequest request, AsyncCallback callback, object state);

        ///
        /// Finishes the asynchronous execution of the  DescribeAlarmHistory operation.
        ///
        ///
        /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeAlarmHistory.</param>
        ///
        /// <returns>Returns a  DescribeAlarmHistoryResult from CloudWatch.</returns>
        DescribeAlarmHistoryResponse EndDescribeAlarmHistory(IAsyncResult asyncResult);

        #endregion

        #region  DescribeAlarms

        ///
        /// Retrieves alarms with the specified names. If no name is specified, all alarms for
        /// the user are returned. Alarms can be retrieved by using only a prefix for the alarm
        /// name, the alarm state, or a prefix for any action.
        ///
        ///
        /// <returns>The response from the DescribeAlarms service method, as returned by CloudWatch.</returns>
        /// <exception cref="Amazon.CloudWatch.Model.InvalidNextTokenException">
        /// The next token specified is invalid.
        /// </exception>
        DescribeAlarmsResponse DescribeAlarms();

        ///
        /// Retrieves alarms with the specified names. If no name is specified, all alarms for
        /// the user are returned. Alarms can be retrieved by using only a prefix for the alarm
        /// name, the alarm state, or a prefix for any action.
        ///
        /// <param name="request">Container for the necessary parameters to execute the DescribeAlarms service method.</param>
        ///
        /// <returns>The response from the DescribeAlarms service method, as returned by CloudWatch.</returns>
        /// <exception cref="Amazon.CloudWatch.Model.InvalidNextTokenException">
        /// The next token specified is invalid.
        /// </exception>
        DescribeAlarmsResponse DescribeAlarms(DescribeAlarmsRequest request);

        ///
        /// Initiates the asynchronous execution of the DescribeAlarms operation.
        ///
        ///
        /// <param name="request">Container for the necessary parameters to execute the DescribeAlarms operation on AmazonCloudWatchClient.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
        /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
        ///          procedure using the AsyncState property.</param>
        ///
        /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeAlarms
        ///         operation.</returns>
        IAsyncResult BeginDescribeAlarms(DescribeAlarmsRequest request, AsyncCallback callback, object state);

        ///
        /// Finishes the asynchronous execution of the  DescribeAlarms operation.
        ///
        ///
        /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeAlarms.</param>
        ///
        /// <returns>Returns a  DescribeAlarmsResult from CloudWatch.</returns>
        DescribeAlarmsResponse EndDescribeAlarms(IAsyncResult asyncResult);

        #endregion

        #region  DescribeAlarmsForMetric

        ///
        /// Retrieves all alarms for a single metric. Specify a statistic, period, or unit to
        /// filter the set of alarms further.
        ///
        /// <param name="request">Container for the necessary parameters to execute the DescribeAlarmsForMetric service method.</param>
        ///
        /// <returns>The response from the DescribeAlarmsForMetric service method, as returned by CloudWatch.</returns>
        DescribeAlarmsForMetricResponse DescribeAlarmsForMetric(DescribeAlarmsForMetricRequest request);

        ///
        /// Initiates the asynchronous execution of the DescribeAlarmsForMetric operation.
        ///
        ///
        /// <param name="request">Container for the necessary parameters to execute the DescribeAlarmsForMetric operation on AmazonCloudWatchClient.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
        /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
        ///          procedure using the AsyncState property.</param>
        ///
        /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeAlarmsForMetric
        ///         operation.</returns>
        IAsyncResult BeginDescribeAlarmsForMetric(DescribeAlarmsForMetricRequest request, AsyncCallback callback, object state);

        ///
        /// Finishes the asynchronous execution of the  DescribeAlarmsForMetric operation.
        ///
        ///
        /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeAlarmsForMetric.</param>
        ///
        /// <returns>Returns a  DescribeAlarmsForMetricResult from CloudWatch.</returns>
        DescribeAlarmsForMetricResponse EndDescribeAlarmsForMetric(IAsyncResult asyncResult);

        #endregion

        #region  DisableAlarmActions

        ///
        /// Disables actions for the specified alarms. When an alarm's actions are disabled the
        /// alarm's state may change, but none of the alarm's actions will execute.
        ///
        /// <param name="request">Container for the necessary parameters to execute the DisableAlarmActions service method.</param>
        ///
        /// <returns>The response from the DisableAlarmActions service method, as returned by CloudWatch.</returns>
        DisableAlarmActionsResponse DisableAlarmActions(DisableAlarmActionsRequest request);

        ///
        /// Initiates the asynchronous execution of the DisableAlarmActions operation.
        ///
        ///
        /// <param name="request">Container for the necessary parameters to execute the DisableAlarmActions operation on AmazonCloudWatchClient.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
        /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
        ///          procedure using the AsyncState property.</param>
        ///
        /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDisableAlarmActions
        ///         operation.</returns>
        IAsyncResult BeginDisableAlarmActions(DisableAlarmActionsRequest request, AsyncCallback callback, object state);

        ///
        /// Finishes the asynchronous execution of the  DisableAlarmActions operation.
        ///
        ///
        /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDisableAlarmActions.</param>
        ///
        /// <returns>Returns a  DisableAlarmActionsResult from CloudWatch.</returns>
        DisableAlarmActionsResponse EndDisableAlarmActions(IAsyncResult asyncResult);

        #endregion

        #region  EnableAlarmActions

        ///
        /// Enables actions for the specified alarms.
        ///
        /// <param name="request">Container for the necessary parameters to execute the EnableAlarmActions service method.</param>
        ///
        /// <returns>The response from the EnableAlarmActions service method, as returned by CloudWatch.</returns>
        EnableAlarmActionsResponse EnableAlarmActions(EnableAlarmActionsRequest request);

        ///
        /// Initiates the asynchronous execution of the EnableAlarmActions operation.
        ///
        ///
        /// <param name="request">Container for the necessary parameters to execute the EnableAlarmActions operation on AmazonCloudWatchClient.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
        /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
        ///          procedure using the AsyncState property.</param>
        ///
        /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndEnableAlarmActions
        ///         operation.</returns>
        IAsyncResult BeginEnableAlarmActions(EnableAlarmActionsRequest request, AsyncCallback callback, object state);

        ///
        /// Finishes the asynchronous execution of the  EnableAlarmActions operation.
        ///
        ///
        /// <param name="asyncResult">The IAsyncResult returned by the call to BeginEnableAlarmActions.</param>
        ///
        /// <returns>Returns a  EnableAlarmActionsResult from CloudWatch.</returns>
        EnableAlarmActionsResponse EndEnableAlarmActions(IAsyncResult asyncResult);

        #endregion

        #region  GetMetricStatistics

        ///
        /// Gets statistics for the specified metric.
        ///
        ///
        /// <para>
        ///  The maximum number of data points returned from a single GetMetricStatistics
        /// request is 1,440, wereas the maximum number of data points that can be queried is
        /// 50,850. If you make a request that generates more than 1,440 data points, Amazon CloudWatch
        /// returns an error. In such a case, you can alter the request by narrowing the specified
        /// time range or increasing the specified period. Alternatively, you can make multiple
        /// requests across adjacent time ranges.
        /// </para>
        ///
        /// <para>
        ///  Amazon CloudWatch aggregates data points based on the length of the period
        /// that you specify. For example, if you request statistics with a one-minute granularity,
        /// Amazon CloudWatch aggregates data points with time stamps that fall within the same
        /// one-minute period. In such a case, the data points queried can greatly outnumber the
        /// data points returned.
        /// </para>
        ///
        /// <para>
        ///  The following examples show various statistics allowed by the data point query maximum
        /// of 50,850 when you call GetMetricStatistics on Amazon EC2 instances with
        /// detailed (one-minute) monitoring enabled:
        /// </para>
        ///

Statistics for up to 400 instances for a span of one hour

Statistics
        /// for up to 35 instances over a span of 24 hours

Statistics for up to 2 instances
        /// over a span of 2 weeks

        /// <para>
        ///  For information about the namespace, metric names, and dimensions that other Amazon
        /// Web Services products use to send metrics to Cloudwatch, go to Amazon
        /// CloudWatch Metrics, Namespaces, and Dimensions Reference in the Amazon CloudWatch
        /// Developer Guide.
        /// </para>
        ///
        /// <param name="request">Container for the necessary parameters to execute the GetMetricStatistics service method.</param>
        ///
        /// <returns>The response from the GetMetricStatistics service method, as returned by CloudWatch.</returns>
        /// <exception cref="Amazon.CloudWatch.Model.InternalServiceException">
        /// Indicates that the request processing has failed due to some unknown error, exception,
        /// or failure.
        /// </exception>
        /// <exception cref="Amazon.CloudWatch.Model.InvalidParameterCombinationException">
        /// Parameters that must not be used together were used together.
        /// </exception>
        /// <exception cref="Amazon.CloudWatch.Model.InvalidParameterValueException">
        /// Bad or out-of-range value was supplied for the input parameter.
        /// </exception>
        /// <exception cref="Amazon.CloudWatch.Model.MissingRequiredParameterException">
        /// An input parameter that is mandatory for processing the request is not supplied.
        /// </exception>
        GetMetricStatisticsResponse GetMetricStatistics(GetMetricStatisticsRequest request);

        ///
        /// Initiates the asynchronous execution of the GetMetricStatistics operation.
        ///
        ///
        /// <param name="request">Container for the necessary parameters to execute the GetMetricStatistics operation on AmazonCloudWatchClient.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
        /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
        ///          procedure using the AsyncState property.</param>
        ///
        /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetMetricStatistics
        ///         operation.</returns>
        IAsyncResult BeginGetMetricStatistics(GetMetricStatisticsRequest request, AsyncCallback callback, object state);

        ///
        /// Finishes the asynchronous execution of the  GetMetricStatistics operation.
        ///
        ///
        /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetMetricStatistics.</param>
        ///
        /// <returns>Returns a  GetMetricStatisticsResult from CloudWatch.</returns>
        GetMetricStatisticsResponse EndGetMetricStatistics(IAsyncResult asyncResult);

        #endregion

        #region  ListMetrics

        ///
        /// Returns a list of valid metrics stored for the AWS account owner. Returned metrics
        /// can be used with GetMetricStatistics to obtain statistical data for a given
        /// metric.
        ///
        ///
        /// <returns>The response from the ListMetrics service method, as returned by CloudWatch.</returns>
        /// <exception cref="Amazon.CloudWatch.Model.InternalServiceException">
        /// Indicates that the request processing has failed due to some unknown error, exception,
        /// or failure.
        /// </exception>
        /// <exception cref="Amazon.CloudWatch.Model.InvalidParameterValueException">
        /// Bad or out-of-range value was supplied for the input parameter.
        /// </exception>
        ListMetricsResponse ListMetrics();

        ///
        /// Returns a list of valid metrics stored for the AWS account owner. Returned metrics
        /// can be used with GetMetricStatistics to obtain statistical data for a given
        /// metric.
        ///
        /// <param name="request">Container for the necessary parameters to execute the ListMetrics service method.</param>
        ///
        /// <returns>The response from the ListMetrics service method, as returned by CloudWatch.</returns>
        /// <exception cref="Amazon.CloudWatch.Model.InternalServiceException">
        /// Indicates that the request processing has failed due to some unknown error, exception,
        /// or failure.
        /// </exception>
        /// <exception cref="Amazon.CloudWatch.Model.InvalidParameterValueException">
        /// Bad or out-of-range value was supplied for the input parameter.
        /// </exception>
        ListMetricsResponse ListMetrics(ListMetricsRequest request);

        ///
        /// Initiates the asynchronous execution of the ListMetrics operation.
        ///
        ///
        /// <param name="request">Container for the necessary parameters to execute the ListMetrics operation on AmazonCloudWatchClient.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
        /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
        ///          procedure using the AsyncState property.</param>
        ///
        /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListMetrics
        ///         operation.</returns>
        IAsyncResult BeginListMetrics(ListMetricsRequest request, AsyncCallback callback, object state);

        ///
        /// Finishes the asynchronous execution of the  ListMetrics operation.
        ///
        ///
        /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListMetrics.</param>
        ///
        /// <returns>Returns a  ListMetricsResult from CloudWatch.</returns>
        ListMetricsResponse EndListMetrics(IAsyncResult asyncResult);

        #endregion

        #region  PutMetricAlarm

        ///
        /// Creates or updates an alarm and associates it with the specified Amazon CloudWatch
        /// metric. Optionally, this operation can associate one or more Amazon Simple Notification
        /// Service resources with the alarm.
        ///
        ///
        /// <para>
        ///  When this operation creates an alarm, the alarm state is immediately set to INSUFFICIENT_DATA.
        /// The alarm is evaluated and its StateValue is set appropriately. Any actions
        /// associated with the StateValue is then executed.
        /// </para>
        ///
        /// <param name="request">Container for the necessary parameters to execute the PutMetricAlarm service method.</param>
        ///
        /// <returns>The response from the PutMetricAlarm service method, as returned by CloudWatch.</returns>
        /// <exception cref="Amazon.CloudWatch.Model.LimitExceededException">
        /// The quota for alarms for this customer has already been reached.
        /// </exception>
        PutMetricAlarmResponse PutMetricAlarm(PutMetricAlarmRequest request);

        ///
        /// Initiates the asynchronous execution of the PutMetricAlarm operation.
        ///
        ///
        /// <param name="request">Container for the necessary parameters to execute the PutMetricAlarm operation on AmazonCloudWatchClient.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
        /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
        ///          procedure using the AsyncState property.</param>
        ///
        /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPutMetricAlarm
        ///         operation.</returns>
        IAsyncResult BeginPutMetricAlarm(PutMetricAlarmRequest request, AsyncCallback callback, object state);

        ///
        /// Finishes the asynchronous execution of the  PutMetricAlarm operation.
        ///
        ///
        /// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutMetricAlarm.</param>
        ///
        /// <returns>Returns a  PutMetricAlarmResult from CloudWatch.</returns>
        PutMetricAlarmResponse EndPutMetricAlarm(IAsyncResult asyncResult);

        #endregion

        #region  PutMetricData

        ///
        /// Publishes metric data points to Amazon CloudWatch. Amazon Cloudwatch associates the
        /// data points with the specified metric. If the specified metric does not exist, Amazon
        /// CloudWatch creates the metric. It can take up to fifteen minutes for a new metric
        /// to appear in calls to the ListMetrics action.
        ///
        ///
        /// <para>
        ///  The size of a PutMetricData request is limited to 8 KB for HTTP GET requests and
        /// 40 KB for HTTP POST requests.
        /// </para>
        ///  <important> Although the Value parameter accepts numbers of type Double,
        /// Amazon CloudWatch truncates values with very large exponents. Values with base-10
        /// exponents greater than 126 (1 x 10^126) are truncated. Likewise, values with base-10
        /// exponents less than -130 (1 x 10^-130) are also truncated. </important>
        /// <para>
        /// Data that is timestamped 24 hours or more in the past may take in excess of 48 hours
        /// to become available from submission time using GetMetricStatistics.
        /// </para>
        ///
        /// <param name="request">Container for the necessary parameters to execute the PutMetricData service method.</param>
        ///
        /// <returns>The response from the PutMetricData service method, as returned by CloudWatch.</returns>
        /// <exception cref="Amazon.CloudWatch.Model.InternalServiceException">
        /// Indicates that the request processing has failed due to some unknown error, exception,
        /// or failure.
        /// </exception>
        /// <exception cref="Amazon.CloudWatch.Model.InvalidParameterCombinationException">
        /// Parameters that must not be used together were used together.
        /// </exception>
        /// <exception cref="Amazon.CloudWatch.Model.InvalidParameterValueException">
        /// Bad or out-of-range value was supplied for the input parameter.
        /// </exception>
        /// <exception cref="Amazon.CloudWatch.Model.MissingRequiredParameterException">
        /// An input parameter that is mandatory for processing the request is not supplied.
        /// </exception>
        PutMetricDataResponse PutMetricData(PutMetricDataRequest request);

        ///
        /// Initiates the asynchronous execution of the PutMetricData operation.
        ///
        ///
        /// <param name="request">Container for the necessary parameters to execute the PutMetricData operation on AmazonCloudWatchClient.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
        /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
        ///          procedure using the AsyncState property.</param>
        ///
        /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPutMetricData
        ///         operation.</returns>
        IAsyncResult BeginPutMetricData(PutMetricDataRequest request, AsyncCallback callback, object state);

        ///
        /// Finishes the asynchronous execution of the  PutMetricData operation.
        ///
        ///
        /// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutMetricData.</param>
        ///
        /// <returns>Returns a  PutMetricDataResult from CloudWatch.</returns>
        PutMetricDataResponse EndPutMetricData(IAsyncResult asyncResult);

        #endregion

        #region  SetAlarmState

        ///
        /// Temporarily sets the state of an alarm. When the updated StateValue
        /// differs from the previous value, the action configured for the appropriate state is
        /// invoked. This is not a permanent change. The next periodic alarm check (in about a
        /// minute) will set the alarm to its actual state.
        ///
        /// <param name="request">Container for the necessary parameters to execute the SetAlarmState service method.</param>
        ///
        /// <returns>The response from the SetAlarmState service method, as returned by CloudWatch.</returns>
        /// <exception cref="Amazon.CloudWatch.Model.InvalidFormatException">
        /// Data was not syntactically valid JSON.
        /// </exception>
        /// <exception cref="Amazon.CloudWatch.Model.ResourceNotFoundException">
        /// The named resource does not exist.
        /// </exception>
        SetAlarmStateResponse SetAlarmState(SetAlarmStateRequest request);

        ///
        /// Initiates the asynchronous execution of the SetAlarmState operation.
        ///
        ///
        /// <param name="request">Container for the necessary parameters to execute the SetAlarmState operation on AmazonCloudWatchClient.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
        /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
        ///          procedure using the AsyncState property.</param>
        ///
        /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndSetAlarmState
        ///         operation.</returns>
        IAsyncResult BeginSetAlarmState(SetAlarmStateRequest request, AsyncCallback callback, object state);

        ///
        /// Finishes the asynchronous execution of the  SetAlarmState operation.
        ///
        ///
        /// <param name="asyncResult">The IAsyncResult returned by the call to BeginSetAlarmState.</param>
        ///
        /// <returns>Returns a  SetAlarmStateResult from CloudWatch.</returns>
        SetAlarmStateResponse EndSetAlarmState(IAsyncResult asyncResult);

        #endregion

    }
}


text:
import json

from django import http
from django.utils.encoding import force_text
from django.utils.safestring import mark_safe

from horizon import messages
from horizon import middleware
from horizon.test import helpers as test

class MessageTests(test.TestCase):
    def test_middleware_header(self):
        req = self.request
        string = "Giant ants are attacking San Francisco!"
        expected = ["error", force_text(string), ""]
        self.assertTrue("async_messages" in req.horizon)
        self.assertItemsEqual(req.horizon['async_messages'], [])
        req.META['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
        messages.error(req, string)
        self.assertItemsEqual(req.horizon['async_messages'], [expected])
        res = http.HttpResponse()
        res = middleware.HorizonMiddleware().process_response(req, res)
        self.assertEqual(res['X-Horizon-Messages'],
                         json.dumps([expected]))

    def test_safe_message(self):
        req = self.request
        string = mark_safe("We are now safe from ants! Go here!")
        expected = ["error", force_text(string), " safe"]
        self.assertTrue("async_messages" in req.horizon)
        self.assertItemsEqual(req.horizon['async_messages'], [])
        req.META['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
        messages.error(req, string)
        self.assertItemsEqual(req.horizon['async_messages'], [expected])
        res = http.HttpResponse()
        res = middleware.HorizonMiddleware().process_response(req, res)
        self.assertEqual(res['X-Horizon-Messages'],
                         json.dumps([expected]))


text:
using DelegateAndEvent.Event;
using DelegateAndEvent.Publisher;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DelegateAndEvent.Observer
{
    // A second subscriber whose job is to write to a file
    public class LogTimeOfClock
    {
        public void Subscribe(Clock theClock)
        {
            Console.WriteLine("LogTimeOfClock will now observer Clock for its event SecondChangeEvent");
            theClock.SecondChangeEvent += new Clock.SecondChangeHandler(WriteLogEntry);
        }

        public void Unsubscribe(Clock theClock)
        {
            Console.WriteLine("LogTimeOfClock will now stop observing Clock for its event SecondChangeEvent");
            theClock.SecondChangeEvent -= new Clock.SecondChangeHandler(WriteLogEntry);
        }

        // This method should write to a file
        // we write to the console to see the effect
        // this object keeps no state
        public void WriteLogEntry(object theClock, TimeInfoEventArgs ti)
        {
            Console.WriteLine("Subscriber DisplayTimeOfClock, received notify from Clock that second changed, log to console: {0}:{1}:{2}",
                               ti.hour.ToString(),
                               ti.minute.ToString(),
                               ti.second.ToString());
        }
    }
}


text:
????? ????? ????

on 2012-05-06 09:31:09

This is a very informative article. I was looking for these things and here I found it. I am doing a project and this information is very useful me. Some things in here I have not thought about before

Kevin van Zonneveld

on 2008-03-03 11:49:59

@ Michael White: Good point, added!

Michael White

on 2008-03-03 02:44:54

Why do I make things more complicated than they really are? Here is a much more sensible version that based on the content of the is_array() method. I apologize for polluting your message boards with the previous post.

function is_object( mixed_var ){
	if(mixed_var instanceof Array) {
		return false;
	} else {
		return (mixed_var !== null) &amp;&amp; (typeof( mixed_var ) == 'object');
	}
}

http://crestidg.com

Michael White

on 2008-03-03 02:37:48

I found a way to detect the difference between objects and arrays. There is an incredibly slight change that you pass an array to this function and it still returns true but I'll explain that after the code.

alert(&quot;Obj: &quot; + is_object({foo: &quot;bar&quot;}));
alert(&quot;Arr: &quot; + is_object([&quot;foo&quot;, &quot;bar&quot;]));

function is_object( mixed_var ){
	if(typeof(mixed_var.join) != &quot;function&quot;) {
	    return (mixed_var !== null) &amp;&amp; (typeof( mixed_var ) == 'object');
	} else {
		return false;
	}
}

Ok, this works by checking to see if there is a property of the array named &quot;join&quot; that contains a function object. If not then we know this is an object. If it is then we can reasonably assume that it is an array. I chose the join() method of arrays simply because it has been implemented since Netscape 3.0 and IE 3.0 and so should exist if you are working with an array.

http://crestidg.com

Kevin van Zonneveld

on 2008-03-01 20:52:46

@ Legaev Andrey: updated, thanks again Legaev!

Legaev Andrey

on 2008-03-01 19:39:30

Hi
I found few errors:
1. typeof null returns 'object', but this is not an object.
2. Original PHP function returns false if you pass array as parameter, but in JS returns 'object'. If we want fully emulate PHP function we should handle this case.

function is_object( mixed_var ){
    return (mixed_var !== null) &amp;&amp; (typeof( mixed_var ) == 'object');
}


text:
<?php

namespace Jul\Lib\Tests\String\Property;

use Jul\Lib\String\Property\ClosureProperty;

/**
 * @author Julien <youlweb@hotmail.com>
 */
class ClosurePropertyTest extends \PHPUnit_Framework_TestCase
{
    public function testValue()
    {
        $length = new ClosureProperty(function ($string) {
            return strlen($string);
        });
        $this->assertEquals(3, $length->value('foo'));
    }

    public function testValueWithMultipleArguments()
    {
        $hash = new ClosureProperty(function ($string, $algo = 'sha512') {
            return hash($algo, $string);
        });
        $this->assertEquals('acbd18db4cc2f85cedef654fccc4a4d8', $hash->value('foo', 'md5'));
    }
}


text:
package com.haoxitech.canzhaopin.app;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.text.TextUtils;
import android.widget.CheckBox;

import com.haoxitech.HaoConnect.HaoConnect;
import com.haoxitech.HaoConnect.HaoUtility;
import com.haoxitech.canzhaopin.R;
import com.haoxitech.canzhaopin.base.BaseApplication;
import com.haoxitech.canzhaopin.database.DataBaseHelper;
import com.haoxitech.canzhaopin.ui.activity.MainActivity;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by wangtao on 15/11/17.
 */
public class AppContext extends BaseApplication {
    private static AppContext instance;

    public String userId = "";

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        initImageLoader();
//        initUmeng();
        dealXGPush();
        HaoConnect.init(this, AppContext.getInstance().getVersionName());

        initDataBase();
    }

    public void initDataBase() {
        try {
            DataBaseHelper.copyDataBase(this, "zipArea.db");
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    public static AppContext getInstance() {
        return instance;
    }

    public String getUserId() {
        if (userId == null || userId.equals("")) {
            try {
                userId = HaoConnect.getString("userID");
            } catch (Exception e) {

            }
        }
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    /**
     * 初始化图片加载类
     */
    private void initImageLoader() {
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .cacheInMemory(true).cacheOnDisc(true)
                .bitmapConfig(Bitmap.Config.RGB_565)// 防止内存溢出的,图片太多就这这个。还有其他设置
                        // 如Bitmap.Config.ARGB_8888
                .showImageOnLoading(R.drawable.image_default) // 默认图片
                .showImageForEmptyUri(R.drawable.image_default) //
                        // url爲空會显示该图片,自己放在drawable里面的
                .showImageOnFail(R.drawable.image_default)// 加载失败显示的图片
                .build();

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                this).memoryCacheExtraOptions(480, 800)
                // 缓存在内存的图片的宽和高度
//                .discCacheExtraOptions(480, 800, CompressFormat.PNG, 70, null)
                        // CompressFormat.PNG类型,70质量(0-100)
                .memoryCache(new WeakMemoryCache())
                .memoryCacheSize(2 * 1024 * 1024) // 缓存到内存的最大数据
                .discCacheSize(50 * 1024 * 1024). // 缓存到文件的最大数据
                        discCacheFileCount(1000) // 文件数量
                .defaultDisplayImageOptions(options). // 上面的options对象,一些属性配置
                        build();
        ImageLoader.getInstance().init(config); // 初始化
    }

    private void dealXGPush() {
        if (isMainProcess()) {
            // 为保证弹出通知前一定调用本方法,需要在application的onCreate注册
            // 收到通知时,会调用本回调函数。
            // 相当于这个回调会拦截在信鸽的弹出通知之前被截取
            // 一般上针对需要获取通知内容、标题,设置通知点击的跳转逻辑等等
//            XGPushManager
//                    .setNotifactionCallback(new XGPushNotifactionCallback() {
//
//                        @Override
//                        public void handleNotify(XGNotifaction xGNotifaction) {
//
//                            // 获取标签、内容、自定义内容
//                            String title = xGNotifaction.getTitle();
//                            String content = xGNotifaction.getContent();
//                            String customContent = xGNotifaction
//                                    .getCustomContent();
//                            // 其它的处理
//                            // 如果还要弹出通知,可直接调用以下代码或自己创建Notifaction,否则,本通知将不会弹出在通知栏中。
//                            xGNotifaction.doNotify();
//                        }
//                    });
        }
    }

    public int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    private void initUmeng() {
//        PlatformConfig.setWeixin(Constant.WXAPPID, Constant.WXAPPKEY);
//        //微信 appid appsecret
//        PlatformConfig.setSinaWeibo(Constant.SINAAPPID, Constant.SINAAPPKEY);
//        //新浪微博 appkey appsecret
//        PlatformConfig.setQQZone(Constant.QQAPPID, Constant.QQAPPKEY);
//         QQ和Qzone appid appkey

        HaoUtility.print("getDeviceInfo-->" + getDeviceInfo(this));
    }

    @SuppressLint("NewApi")
    public static boolean checkPermission(Context context, String permission) {
        boolean result = false;
        if (Build.VERSION.SDK_INT >= 23) {
            if (context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) {
                result = true;
            }
        } else {
            PackageManager pm = context.getPackageManager();
            if (pm.checkPermission(permission, context.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
                result = true;
            }
        }
        return result;
    }

    public static String getDeviceInfo(Context context) {
        try {
            org.json.JSONObject json = new org.json.JSONObject();
            android.telephony.TelephonyManager tm = (android.telephony.TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            String device_id = null;
            if (checkPermission(context, Manifest.permission.READ_PHONE_STATE)) {
                device_id = tm.getDeviceId();
            }
            android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) context
                    .getSystemService(Context.WIFI_SERVICE);
            String mac = wifi.getConnectionInfo().getMacAddress();
            json.put("mac", mac);
            if (TextUtils.isEmpty(device_id)) {
                device_id = mac;
            }
            if (TextUtils.isEmpty(device_id)) {
                device_id = android.provider.Settings.Secure.getString(context.getContentResolver(),
                        android.provider.Settings.Secure.ANDROID_ID);
            }
            json.put("device_id", device_id);
            return json.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/drawer_header_content"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:adjustViewBounds="true"
        android:scaleType="fitCenter"
        android:src="@drawable/header_bg"/>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:paddingTop="25dp"
        android:layout_centerVertical="true">

        <ImageView
            android:id="@+id/profile_image"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:src="@drawable/ic_contact_picture"/>

        <TextView
            android:id="@+id/user_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/profile_image"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="12dp"
            android:gravity="center"
            android:text="@string/user_name"
            android:textColor="@android:color/white"
            android:textStyle="bold"/>
    </RelativeLayout>
</RelativeLayout>


text:
package com.online.market.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.online.market.common.Constant;
import com.online.market.model.Goods;
import com.online.market.model.Needs;
import com.online.market.model.User;
import com.online.market.model.UserMsg;
import com.online.market.service.IGoodsManager;
import com.online.market.service.INeedsManager;
import com.online.market.service.IUserManager;
import com.online.market.service.IUserMsgManager;
import com.opensymphony.xwork2.ActionContext;

public class MsgAction extends BaseAction{

	/**
	 * 用于用户之间发送消息,但是1.2版没有用到这个功能,也就是说这个action从未被执行。
	 */
	private static final long serialVersionUID = -3868656860407759353L;
	private String pre;
	private String id;
	private String msg;
	private IUserManager userManager;
	private IGoodsManager goodsManager;
	private INeedsManager needsManager;
	private IUserMsgManager userMsgManager;
	public String getPre() {
		return pre;
	}
	public void setPre(String pre) {
		this.pre = pre;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public IUserManager getUserManager() {
		return userManager;
	}
	public void setUserManager(IUserManager userManager) {
		this.userManager = userManager;
	}
	public IGoodsManager getGoodsManager() {
		return goodsManager;
	}
	public void setGoodsManager(IGoodsManager goodsManager) {
		this.goodsManager = goodsManager;
	}
	public INeedsManager getNeedsManager() {
		return needsManager;
	}
	public void setNeedsManager(INeedsManager needsManager) {
		this.needsManager = needsManager;
	}
	public IUserMsgManager getUserMsgManager() {
		return userMsgManager;
	}
	public void setUserMsgManager(IUserMsgManager userMsgManager) {
		this.userMsgManager = userMsgManager;
	}

	public String msg(){
		User user=(User) ActionContext.getContext().getSession().get(Constant.KEY_LOGIN_USER);
		if(user.equals(null)){
			return "login";
		}
		if("g".equals(pre)){
			String dqQuery="GoodsManager.findGoodsByGid.query";
			Map<String,Object>map = new HashMap<String,Object>();
			map.put("id", id);
			List<Goods> goodses=(List<Goods>)goodsManager.findListByDynamicQuery(dqQuery,map);
			UserMsg userMsg = new UserMsg();
			userMsg.setSendId(user.getUid());
			userMsg.setUmMsg(msg);
			userMsg.setUmIsNew(true);
			userMsg.setUser(goodses.get(0).getUser());
			userMsgManager.save(userMsg);
		}
		if("n".equals(pre)){
			String dqQuery="NeedsManager.findNeedsByNid.query";
			Map<String,Object>map = new HashMap<String,Object>();
			map.put("id", id);
			List<Needs> needses=(List<Needs>)needsManager.findListByDynamicQuery(dqQuery,map);
			UserMsg userMsg = new UserMsg();
			userMsg.setSendId(user.getUid());
			userMsg.setUmMsg(msg);
			userMsg.setUmIsNew(true);
			userMsg.setUser(needses.get(0).getUser());
			userMsgManager.save(userMsg);
		}

		return "toItemDetailsAction";
	}
}


text:
package registration

import (
	"fmt"

	"github.com/docker/machine/libmachine/host"
	"github.com/docker/machine/libmachine/log"
	"github.com/docker/machine/libmachine/provision"
	"github.com/pkg/errors"
)

type RegistrationParameters struct {
	Username string
	Password string
}

// Register host VM
func RegisterHostVM(host *host.Host, param *RegistrationParameters) error {
	commander := provision.GenericSSHCommander{Driver: host.Driver}
	registrator, supportRegistration, err := DetectRegistrator(commander)
	if !supportRegistration {
		log.Debug("Distribution doesn't support registration")
	}

	if err != nil && err != ErrDetectionFailed {
		return err
	}

	if registrator != nil {
		fmt.Println("Registering machine using subscription-manager")
		if param.Username == "" || param.Password == "" {
			return errors.New("This virtual machine requires registration. " +
				"Credentials must either be passed via the environment variables " +
				"MINISHIFT_USERNAME and MINISHIFT_PASSWORD " +
				" or the --username and --password flags\n")
		}

		if err := registrator.Register(param); err != nil {
			return err
		}
	}
	return nil
}

// Unregister host VM
func UnregisterHostVM(host *host.Host, param *RegistrationParameters) error {
	commander := provision.GenericSSHCommander{Driver: host.Driver}
	registrator, supportUnregistration, err := DetectRegistrator(commander)

	if !supportUnregistration {
		log.Debug("Distribution doesn't support unregistration")
	}

	if err != nil && err != ErrDetectionFailed {
		return err
	}

	if registrator != nil {
		fmt.Println("Unregistering machine")
		if err := registrator.Unregister(param); err != nil {
			return err
		}
	}
	return nil
}


text:
Tanequil: Translates SQL-92 to CouchDB Map/Reduce Queires
=========================================================

An Erlang server that exposes a SQLite-like database
interface.

Tanequil attempts to create an intelligent bridge between
the strict world of relational databases and the flexible
world of NoSQL. Whenever possible, Tanequil will precompute
generic Map/Reduce functions that can be queired at a later
date.


text:
layout: post
title:  "'Looping' and 'Branching' with Pipes"
date:   2020-09-03 13:15:02 -0700
categories: Post
tags: R
image: "/img/loopandbranch.png"
---

Whilst programming, I am a Don't Repeat Yourself (DRY) devotee. I am also frequently side-tracked by ancillary exploration: "Hmmm, what about this instead?" "What if I tried this really quick?" "Ohhhh should I check this variable too?" My point is this: exploratory data analysis is seldom linear; I often want to *loop back* or *branch off* from my pipes, preferably with minimal syntactical friction, and definitely without repeating myself. In this blog I'll show two ways to 'loop' and 'branch' with pipes.

<img src="/img/loopandbranch.png" alt="pipeflow" align="center"/>

## 'Looping' with hacksaw

For example: I neither enjoy writing nor seeing code like this:

{% highlight r %}
library(palmerpenguins)
library(tidyverse)

penguins %>%
  count(species)

penguins %>%
  count(island)

penguins %>%
  count(year, sex)
{% endhighlight %}

This irksome repetition was the primary motivation for [my hacksaw package.](https://github.com/daranzolin/hacksaw) Rather than re-type `penguins %>% count(...)` N amount of times, I can write this instead:

{% highlight r %}
library(hacksaw)

penguins %>%
    count_split(
        species,
        island,
        across(c(year, sex))
    )

# Or
# penguins %>%
#    eval_split(
#        count(species),
#        count(island),
#        count(year, sex)
#    )
{% endhighlight %}

```
[[1]]
# A tibble: 3 x 2
  species       n
  <fct>     <int>
1 Adelie      152
2 Gentoo      124
3 Chinstrap    68

[[2]]
# A tibble: 3 x 2
  island        n
  <fct>     <int>
1 Biscoe      168
2 Dream       124
3 Torgersen    52

[[3]]
# A tibble: 9 x 3
   year sex        n
  <int> <fct>  <int>
1  2009 male      59
2  2009 female    58
3  2008 male      57
4  2008 female    56
5  2007 male      52
6  2007 female    51
7  2007 NA         7
8  2009 NA         3
9  2008 NA         1
```

Now *that's* DRY! Note how `count_split` and `eval_split` recycle the original data frame. hacksaw provides this 'looping' `*_split` construct with most dplyr verbs, and for me, this saves some time, keystrokes, and mild annoyance.

## 'Branching' with nakedpipe

Again, I sometimes wish to 'branch' off from my main pipeline rather than assign an intermediate object. The reason is threefold: (1) Because naming things is hard; (2) I prefer fewer objects in my environment; and (3) I want to be DRY.

Consider the following example from [the excellent infer package:](https://github.com/tidymodels/infer)

{% highlight r %}
library(infer)

# Calculate observed statistic
d_hat <- offshore %>%
  specify(response ~ college_grad, success = "no opinion") %>%
  calculate(stat = "diff in props", order = c("yes", "no"))

# Simulated null distribution
null_distn_two_props <- offshore %>%
  specify(response ~ college_grad, success = "no opinion") %>%
  hypothesize(null = "independence") %>%
  generate(reps = 10000) %>%
  calculate(stat = "diff in props", order = c("yes", "no"))

# Bootstrap distribution
boot_distn_two_props <- offshore %>%
  specify(response ~ college_grad, success = "no opinion") %>%
  generate(reps = 10000) %>%
  calculate(stat = "diff in props", order = c("yes", "no"))

{% endhighlight %}

Note how `offshore %>% specify(response ~ college_grad, success = "no opinion")` is called *three* times. Not a bad thing, but wouldn't it be nice to do it only once and then branch off mid-piping? This is possible with [the nakedpipe package:](https://github.com/moodymudskipper/nakedpipe)

{% highlight r %}
library(nakedpipe)

offshore %.% {
  specify(response ~ college_grad, success = "no opinion")

  # BRANCH OFF
  ~~calculate(., stat = "diff in props", order = c("yes", "no")) -> d_hat

  # BRANCH OFF
  ~~. %.% {
    generate(reps = 1000, type = "bootstrap")
    calculate(., stat = "diff in props", order = c("yes", "no"))

  # BRANCH OFF
    ~~get_ci(.) -> ci

  } -> boot_dist

  # CONTINUE ON
  hypothesize(null = "independence")
  generate(reps = 1000, type = "permute")
  calculate(., stat = "diff in props", order = c("yes", "no"))
} -> null_dist

{% endhighlight %}

The syntax is odd to see but easy to type--I actually very much enjoy the nakedpipe experience, as it facilitates this kind of 'branched' thinking.[^1]

[^1]: And I never accidentally hit Ctrl+N instead of Ctrl+M...

In sum, I am not sure either of these features, 'looping' with hacksaw and 'branching' with nakedpipe, rises to the level of 'best practices', but I appreciate how they are better syntactical reflections of both my own thought process and coding preferences. Worth trying IMHO!


text:
package org.ovirt.engine.core.vdsbroker.gluster;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.ovirt.engine.core.common.businessentities.gluster.GlusterGeoRepSessionConfiguration;
import org.ovirt.engine.core.vdsbroker.irsbroker.StatusReturnForXmlRpc;

public class GlusterVolumeGeoRepConfigListXmlRpc extends StatusReturnForXmlRpc {

    private static final String GEO_REP_CONFIG = "geoRepConfig";
    private static final String SESSION_CONFIG = "sessionConfig";
    private static final String INFO = "info";

    private List<GlusterGeoRepSessionConfiguration> geoRepConfigList = new ArrayList<>();

    public GlusterVolumeGeoRepConfigListXmlRpc(Map<String, Object> innerMap) {
        super(innerMap);
        if (innerMap.containsKey(INFO)) {
            innerMap = (Map<String, Object>) innerMap.get(INFO);
        }
        if (innerMap.containsKey(SESSION_CONFIG)) {
            prepareConfigMap((Map<String, Object>) ((Map<String, Object>) innerMap.get(SESSION_CONFIG)).get(GEO_REP_CONFIG));
        }
    }

    private void prepareConfigMap(Map<String, Object> geoRepConfigs) {
        for (Entry<String, Object> currentGeoRepConfig : geoRepConfigs.entrySet()) {
            GlusterGeoRepSessionConfiguration config = new GlusterGeoRepSessionConfiguration();
            config.setKey(currentGeoRepConfig.getKey());
            config.setValue((String) currentGeoRepConfig.getValue());
            geoRepConfigList.add(config);
        }
    }

    public List<GlusterGeoRepSessionConfiguration> getSessionConfig() {
        return geoRepConfigList;
    }

    public void setSessionConfig(List<GlusterGeoRepSessionConfiguration> sessionConfig) {
        this.geoRepConfigList = sessionConfig;
    }
}


text:
package org.eclipse.jetty.websocket.jsr356.decoders;

import static org.hamcrest.Matchers.is;

import javax.websocket.DecodeException;

import org.junit.Assert;
import org.junit.Test;

public class IntegerDecoderTest
{
    @Test
    public void testDecode() throws DecodeException
    {
        IntegerDecoder decoder = new IntegerDecoder();
        Integer val = decoder.decode("123");
        Assert.assertThat("Decoded value",val,is(123));
    }
}