<commit_before>//===-- MipsRegisterInfo.cpp - MIPS Register Information -== --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the MIPS implementation of the TargetRegisterInfo class.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "mips-reg-info"

#include "MipsRegisterInfo.h"
#include "Mips.h"
#include "MipsAnalyzeImmediate.h"
#include "MipsSubtarget.h"
#include "MipsMachineFunction.h"
#include "llvm/Constants.h"
#include "llvm/Type.h"
#include "llvm/Function.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/Target/TargetFrameLowering.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Analysis/DebugInfo.h"

#define GET_REGINFO_TARGET_DESC
#include "MipsGenRegisterInfo.inc"

using namespace llvm;

MipsRegisterInfo::MipsRegisterInfo(const MipsSubtarget &ST,
                                   const TargetInstrInfo &tii)
  : MipsGenRegisterInfo(Mips::RA), Subtarget(ST), TII(tii) {}

unsigned MipsRegisterInfo::getPICCallReg() { return Mips::T9; }

//===----------------------------------------------------------------------===//
// Callee Saved Registers methods
//===----------------------------------------------------------------------===//

/// Mips Callee Saved Registers
const uint16_t* MipsRegisterInfo::
getCalleeSavedRegs(const MachineFunction *MF) const
{
  if (Subtarget.isSingleFloat())
    return CSR_SingleFloatOnly_SaveList;
  else if (!Subtarget.hasMips64())
    return CSR_O32_SaveList;
  else if (Subtarget.isABI_N32())
    return CSR_N32_SaveList;

  assert(Subtarget.isABI_N64());
  return CSR_N64_SaveList;
}

const uint32_t*
MipsRegisterInfo::getCallPreservedMask(CallingConv::ID) const
{
  if (Subtarget.isSingleFloat())
    return CSR_SingleFloatOnly_RegMask;
  else if (!Subtarget.hasMips64())
    return CSR_O32_RegMask;
  else if (Subtarget.isABI_N32())
    return CSR_N32_RegMask;

  assert(Subtarget.isABI_N64());
  return CSR_N64_RegMask;
}

BitVector MipsRegisterInfo::
getReservedRegs(const MachineFunction &MF) const {
  static const uint16_t ReservedCPURegs[] = {
    Mips::ZERO, Mips::AT, Mips::K0, Mips::K1,
    Mips::SP, Mips::RA
  };

  static const uint16_t ReservedCPU64Regs[] = {
    Mips::ZERO_64, Mips::AT_64, Mips::K0_64, Mips::K1_64,
    Mips::SP_64, Mips::RA_64
  };

  BitVector Reserved(getNumRegs());
  typedef TargetRegisterClass::const_iterator RegIter;

  for (unsigned I = 0; I < array_lengthof(ReservedCPURegs); ++I)
    Reserved.set(ReservedCPURegs[I]);

  if (Subtarget.hasMips64()) {
    for (unsigned I = 0; I < array_lengthof(ReservedCPU64Regs); ++I)
      Reserved.set(ReservedCPU64Regs[I]);

    // Reserve all registers in AFGR64.
    for (RegIter Reg = Mips::AFGR64RegClass.begin(),
         EReg = Mips::AFGR64RegClass.end(); Reg != EReg; ++Reg)
      Reserved.set(*Reg);
  } else {
    // Reserve all registers in CPU64Regs & FGR64.
    for (RegIter Reg = Mips::CPU64RegsRegClass.begin(),
         EReg = Mips::CPU64RegsRegClass.end(); Reg != EReg; ++Reg)
      Reserved.set(*Reg);

    for (RegIter Reg = Mips::FGR64RegClass.begin(),
         EReg = Mips::FGR64RegClass.end(); Reg != EReg; ++Reg)
      Reserved.set(*Reg);
  }

  // If GP is dedicated as a global base register, reserve it.
  if (MF.getInfo<MipsFunctionInfo>()->globalBaseRegFixed()) {
    Reserved.set(Mips::GP);
    Reserved.set(Mips::GP_64);
  }

  // Reserve FP if this function should have a dedicated frame pointer register.
  if (MF.getTarget().getFrameLowering()->hasFP(MF)) {
    Reserved.set(Mips::FP);
    Reserved.set(Mips::FP_64);
  }

  // Reserve hardware registers.
  Reserved.set(Mips::HWR29);
  Reserved.set(Mips::HWR29_64);

  return Reserved;
}

bool
MipsRegisterInfo::requiresRegisterScavenging(const MachineFunction &MF) const {
  return true;
}

bool
MipsRegisterInfo::trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
  return true;
}

// This function eliminate ADJCALLSTACKDOWN,
// ADJCALLSTACKUP pseudo instructions
void MipsRegisterInfo::
eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
                              MachineBasicBlock::iterator I) const {
  // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
  MBB.erase(I);
}

// FrameIndex represent objects inside a abstract stack.
// We must replace FrameIndex with an stack/frame pointer
// direct reference.
void MipsRegisterInfo::
eliminateFrameIndex(MachineBasicBlock::iterator II, int SPAdj,
                    RegScavenger *RS) const {
  MachineInstr &MI = *II;
  MachineFunction &MF = *MI.getParent()->getParent();
  MachineFrameInfo *MFI = MF.getFrameInfo();
  MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();

  unsigned i = 0;
  while (!MI.getOperand(i).isFI()) {
    ++i;
    assert(i < MI.getNumOperands() &&
           "Instr doesn't have FrameIndex operand!");
  }

  DEBUG(errs() << "\nFunction : " << MF.getFunction()->getName() << "\n";
        errs() << "<--------->\n" << MI);

  int FrameIndex = MI.getOperand(i).getIndex();
  uint64_t stackSize = MF.getFrameInfo()->getStackSize();
  int64_t spOffset = MF.getFrameInfo()->getObjectOffset(FrameIndex);

  DEBUG(errs() << "FrameIndex : " << FrameIndex << "\n"
               << "spOffset   : " << spOffset << "\n"
               << "stackSize  : " << stackSize << "\n");

  const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
  int MinCSFI = 0;
  int MaxCSFI = -1;

  if (CSI.size()) {
    MinCSFI = CSI[0].getFrameIdx();
    MaxCSFI = CSI[CSI.size() - 1].getFrameIdx();
  }

  // The following stack frame objects are always referenced relative to $sp:
  //  1. Outgoing arguments.
  //  2. Pointer to dynamically allocated stack space.
  //  3. Locations for callee-saved registers.
  // Everything else is referenced relative to whatever register
  // getFrameRegister() returns.
  unsigned FrameReg;

  if (MipsFI->isOutArgFI(FrameIndex) || MipsFI->isDynAllocFI(FrameIndex) ||
      (FrameIndex >= MinCSFI && FrameIndex <= MaxCSFI))
    FrameReg = Subtarget.isABI_N64() ? Mips::SP_64 : Mips::SP;
  else
    FrameReg = getFrameRegister(MF);

  // Calculate final offset.
  // - There is no need to change the offset if the frame object is one of the
  //   following: an outgoing argument, pointer to a dynamically allocated
  //   stack space or a $gp restore location,
  // - If the frame object is any of the following, its offset must be adjusted
  //   by adding the size of the stack:
  //   incoming argument, callee-saved register location or local variable.
  int64_t Offset;

  if (MipsFI->isOutArgFI(FrameIndex) || MipsFI->isGPFI(FrameIndex) ||
      MipsFI->isDynAllocFI(FrameIndex))
    Offset = spOffset;
  else
    Offset = spOffset + (int64_t)stackSize;

  Offset    += MI.getOperand(i+1).getImm();

  DEBUG(errs() << "Offset     : " << Offset << "\n" << "<--------->\n");

  // If MI is not a debug value, make sure Offset fits in the 16-bit immediate
  // field.
  if (!MI.isDebugValue() && !isInt<16>(Offset)) {
    MachineBasicBlock &MBB = *MI.getParent();
    DebugLoc DL = II->getDebugLoc();
    MipsAnalyzeImmediate AnalyzeImm;
    unsigned Size = Subtarget.isABI_N64() ? 64 : 32;
    unsigned LUi = Subtarget.isABI_N64() ? Mips::LUi64 : Mips::LUi;
    unsigned ADDu = Subtarget.isABI_N64() ? Mips::DADDu : Mips::ADDu;
    unsigned ZEROReg = Subtarget.isABI_N64() ? Mips::ZERO_64 : Mips::ZERO;
    unsigned ATReg = Subtarget.isABI_N64() ? Mips::AT_64 : Mips::AT;
    const MipsAnalyzeImmediate::InstSeq &Seq =
      AnalyzeImm.Analyze(Offset, Size, true /* LastInstrIsADDiu */);
    MipsAnalyzeImmediate::InstSeq::const_iterator Inst = Seq.begin();

    MipsFI->setEmitNOAT();

    // The first instruction can be a LUi, which is different from other
    // instructions (ADDiu, ORI and SLL) in that it does not have a register
    // operand.
    if (Inst->Opc == LUi)
      BuildMI(MBB, II, DL, TII.get(LUi), ATReg)
        .addImm(SignExtend64<16>(Inst->ImmOpnd));
    else
      BuildMI(MBB, II, DL, TII.get(Inst->Opc), ATReg).addReg(ZEROReg)
        .addImm(SignExtend64<16>(Inst->ImmOpnd));

    // Build the remaining instructions in Seq except for the last one.
    for (++Inst; Inst != Seq.end() - 1; ++Inst)
      BuildMI(MBB, II, DL, TII.get(Inst->Opc), ATReg).addReg(ATReg)
        .addImm(SignExtend64<16>(Inst->ImmOpnd));

    BuildMI(MBB, II, DL, TII.get(ADDu), ATReg).addReg(FrameReg).addReg(ATReg);

    FrameReg = ATReg;
    Offset = SignExtend64<16>(Inst->ImmOpnd);
  }

  MI.getOperand(i).ChangeToRegister(FrameReg, false);
  MI.getOperand(i+1).ChangeToImmediate(Offset);
}

unsigned MipsRegisterInfo::
getFrameRegister(const MachineFunction &MF) const {
  const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
  bool IsN64 = Subtarget.isABI_N64();

  return TFI->hasFP(MF) ? (IsN64 ? Mips::FP_64 : Mips::FP) :
                          (IsN64 ? Mips::SP_64 : Mips::SP);
}

unsigned MipsRegisterInfo::
getEHExceptionRegister() const {
  llvm_unreachable("What is the exception register");
}

unsigned MipsRegisterInfo::
getEHHandlerRegister() const {
  llvm_unreachable("What is the exception handler register");
}
<commit_msg>Stop reserving register $gp. Do not call isGPFI to check whether a frame object is the $gp save slot.<commit_after>//===-- MipsRegisterInfo.cpp - MIPS Register Information -== --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the MIPS implementation of the TargetRegisterInfo class.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "mips-reg-info"

#include "MipsRegisterInfo.h"
#include "Mips.h"
#include "MipsAnalyzeImmediate.h"
#include "MipsSubtarget.h"
#include "MipsMachineFunction.h"
#include "llvm/Constants.h"
#include "llvm/Type.h"
#include "llvm/Function.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/Target/TargetFrameLowering.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Analysis/DebugInfo.h"

#define GET_REGINFO_TARGET_DESC
#include "MipsGenRegisterInfo.inc"

using namespace llvm;

MipsRegisterInfo::MipsRegisterInfo(const MipsSubtarget &ST,
                                   const TargetInstrInfo &tii)
  : MipsGenRegisterInfo(Mips::RA), Subtarget(ST), TII(tii) {}

unsigned MipsRegisterInfo::getPICCallReg() { return Mips::T9; }

//===----------------------------------------------------------------------===//
// Callee Saved Registers methods
//===----------------------------------------------------------------------===//

/// Mips Callee Saved Registers
const uint16_t* MipsRegisterInfo::
getCalleeSavedRegs(const MachineFunction *MF) const
{
  if (Subtarget.isSingleFloat())
    return CSR_SingleFloatOnly_SaveList;
  else if (!Subtarget.hasMips64())
    return CSR_O32_SaveList;
  else if (Subtarget.isABI_N32())
    return CSR_N32_SaveList;

  assert(Subtarget.isABI_N64());
  return CSR_N64_SaveList;
}

const uint32_t*
MipsRegisterInfo::getCallPreservedMask(CallingConv::ID) const
{
  if (Subtarget.isSingleFloat())
    return CSR_SingleFloatOnly_RegMask;
  else if (!Subtarget.hasMips64())
    return CSR_O32_RegMask;
  else if (Subtarget.isABI_N32())
    return CSR_N32_RegMask;

  assert(Subtarget.isABI_N64());
  return CSR_N64_RegMask;
}

BitVector MipsRegisterInfo::
getReservedRegs(const MachineFunction &MF) const {
  static const uint16_t ReservedCPURegs[] = {
    Mips::ZERO, Mips::AT, Mips::K0, Mips::K1,
    Mips::SP, Mips::RA
  };

  static const uint16_t ReservedCPU64Regs[] = {
    Mips::ZERO_64, Mips::AT_64, Mips::K0_64, Mips::K1_64,
    Mips::SP_64, Mips::RA_64
  };

  BitVector Reserved(getNumRegs());
  typedef TargetRegisterClass::const_iterator RegIter;

  for (unsigned I = 0; I < array_lengthof(ReservedCPURegs); ++I)
    Reserved.set(ReservedCPURegs[I]);

  if (Subtarget.hasMips64()) {
    for (unsigned I = 0; I < array_lengthof(ReservedCPU64Regs); ++I)
      Reserved.set(ReservedCPU64Regs[I]);

    // Reserve all registers in AFGR64.
    for (RegIter Reg = Mips::AFGR64RegClass.begin(),
         EReg = Mips::AFGR64RegClass.end(); Reg != EReg; ++Reg)
      Reserved.set(*Reg);
  } else {
    // Reserve all registers in CPU64Regs & FGR64.
    for (RegIter Reg = Mips::CPU64RegsRegClass.begin(),
         EReg = Mips::CPU64RegsRegClass.end(); Reg != EReg; ++Reg)
      Reserved.set(*Reg);

    for (RegIter Reg = Mips::FGR64RegClass.begin(),
         EReg = Mips::FGR64RegClass.end(); Reg != EReg; ++Reg)
      Reserved.set(*Reg);
  }

  // Reserve FP if this function should have a dedicated frame pointer register.
  if (MF.getTarget().getFrameLowering()->hasFP(MF)) {
    Reserved.set(Mips::FP);
    Reserved.set(Mips::FP_64);
  }

  // Reserve hardware registers.
  Reserved.set(Mips::HWR29);
  Reserved.set(Mips::HWR29_64);

  return Reserved;
}

bool
MipsRegisterInfo::requiresRegisterScavenging(const MachineFunction &MF) const {
  return true;
}

bool
MipsRegisterInfo::trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
  return true;
}

// This function eliminate ADJCALLSTACKDOWN,
// ADJCALLSTACKUP pseudo instructions
void MipsRegisterInfo::
eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
                              MachineBasicBlock::iterator I) const {
  // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
  MBB.erase(I);
}

// FrameIndex represent objects inside a abstract stack.
// We must replace FrameIndex with an stack/frame pointer
// direct reference.
void MipsRegisterInfo::
eliminateFrameIndex(MachineBasicBlock::iterator II, int SPAdj,
                    RegScavenger *RS) const {
  MachineInstr &MI = *II;
  MachineFunction &MF = *MI.getParent()->getParent();
  MachineFrameInfo *MFI = MF.getFrameInfo();
  MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();

  unsigned i = 0;
  while (!MI.getOperand(i).isFI()) {
    ++i;
    assert(i < MI.getNumOperands() &&
           "Instr doesn't have FrameIndex operand!");
  }

  DEBUG(errs() << "\nFunction : " << MF.getFunction()->getName() << "\n";
        errs() << "<--------->\n" << MI);

  int FrameIndex = MI.getOperand(i).getIndex();
  uint64_t stackSize = MF.getFrameInfo()->getStackSize();
  int64_t spOffset = MF.getFrameInfo()->getObjectOffset(FrameIndex);

  DEBUG(errs() << "FrameIndex : " << FrameIndex << "\n"
               << "spOffset   : " << spOffset << "\n"
               << "stackSize  : " << stackSize << "\n");

  const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
  int MinCSFI = 0;
  int MaxCSFI = -1;

  if (CSI.size()) {
    MinCSFI = CSI[0].getFrameIdx();
    MaxCSFI = CSI[CSI.size() - 1].getFrameIdx();
  }

  // The following stack frame objects are always referenced relative to $sp:
  //  1. Outgoing arguments.
  //  2. Pointer to dynamically allocated stack space.
  //  3. Locations for callee-saved registers.
  // Everything else is referenced relative to whatever register
  // getFrameRegister() returns.
  unsigned FrameReg;

  if (MipsFI->isOutArgFI(FrameIndex) || MipsFI->isDynAllocFI(FrameIndex) ||
      (FrameIndex >= MinCSFI && FrameIndex <= MaxCSFI))
    FrameReg = Subtarget.isABI_N64() ? Mips::SP_64 : Mips::SP;
  else
    FrameReg = getFrameRegister(MF);

  // Calculate final offset.
  // - There is no need to change the offset if the frame object is one of the
  //   following: an outgoing argument, pointer to a dynamically allocated
  //   stack space or a $gp restore location,
  // - If the frame object is any of the following, its offset must be adjusted
  //   by adding the size of the stack:
  //   incoming argument, callee-saved register location or local variable.
  int64_t Offset;

  if (MipsFI->isOutArgFI(FrameIndex) || MipsFI->isDynAllocFI(FrameIndex))
    Offset = spOffset;
  else
    Offset = spOffset + (int64_t)stackSize;

  Offset    += MI.getOperand(i+1).getImm();

  DEBUG(errs() << "Offset     : " << Offset << "\n" << "<--------->\n");

  // If MI is not a debug value, make sure Offset fits in the 16-bit immediate
  // field.
  if (!MI.isDebugValue() && !isInt<16>(Offset)) {
    MachineBasicBlock &MBB = *MI.getParent();
    DebugLoc DL = II->getDebugLoc();
    MipsAnalyzeImmediate AnalyzeImm;
    unsigned Size = Subtarget.isABI_N64() ? 64 : 32;
    unsigned LUi = Subtarget.isABI_N64() ? Mips::LUi64 : Mips::LUi;
    unsigned ADDu = Subtarget.isABI_N64() ? Mips::DADDu : Mips::ADDu;
    unsigned ZEROReg = Subtarget.isABI_N64() ? Mips::ZERO_64 : Mips::ZERO;
    unsigned ATReg = Subtarget.isABI_N64() ? Mips::AT_64 : Mips::AT;
    const MipsAnalyzeImmediate::InstSeq &Seq =
      AnalyzeImm.Analyze(Offset, Size, true /* LastInstrIsADDiu */);
    MipsAnalyzeImmediate::InstSeq::const_iterator Inst = Seq.begin();

    MipsFI->setEmitNOAT();

    // The first instruction can be a LUi, which is different from other
    // instructions (ADDiu, ORI and SLL) in that it does not have a register
    // operand.
    if (Inst->Opc == LUi)
      BuildMI(MBB, II, DL, TII.get(LUi), ATReg)
        .addImm(SignExtend64<16>(Inst->ImmOpnd));
    else
      BuildMI(MBB, II, DL, TII.get(Inst->Opc), ATReg).addReg(ZEROReg)
        .addImm(SignExtend64<16>(Inst->ImmOpnd));

    // Build the remaining instructions in Seq except for the last one.
    for (++Inst; Inst != Seq.end() - 1; ++Inst)
      BuildMI(MBB, II, DL, TII.get(Inst->Opc), ATReg).addReg(ATReg)
        .addImm(SignExtend64<16>(Inst->ImmOpnd));

    BuildMI(MBB, II, DL, TII.get(ADDu), ATReg).addReg(FrameReg).addReg(ATReg);

    FrameReg = ATReg;
    Offset = SignExtend64<16>(Inst->ImmOpnd);
  }

  MI.getOperand(i).ChangeToRegister(FrameReg, false);
  MI.getOperand(i+1).ChangeToImmediate(Offset);
}

unsigned MipsRegisterInfo::
getFrameRegister(const MachineFunction &MF) const {
  const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
  bool IsN64 = Subtarget.isABI_N64();

  return TFI->hasFP(MF) ? (IsN64 ? Mips::FP_64 : Mips::FP) :
                          (IsN64 ? Mips::SP_64 : Mips::SP);
}

unsigned MipsRegisterInfo::
getEHExceptionRegister() const {
  llvm_unreachable("What is the exception register");
}

unsigned MipsRegisterInfo::
getEHHandlerRegister() const {
  llvm_unreachable("What is the exception handler register");
}
<|endoftext|>


<commit_before>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/atom_javascript_dialog_manager.h"

#include <string>
#include <utility>
#include <vector>

#include "atom/browser/api/atom_api_web_contents.h"
#include "atom/browser/native_window.h"
#include "atom/browser/ui/message_box.h"
#include "atom/browser/web_contents_preferences.h"
#include "atom/common/options_switches.h"
#include "base/bind.h"
#include "base/strings/utf_string_conversions.h"
#include "ui/gfx/image/image_skia.h"

using content::JavaScriptDialogType;

namespace atom {

namespace {

constexpr int kUserWantsNoMoreDialogs = -1;

}  // namespace

AtomJavaScriptDialogManager::AtomJavaScriptDialogManager(
    api::WebContents* api_web_contents)
    : api_web_contents_(api_web_contents) {}
AtomJavaScriptDialogManager::~AtomJavaScriptDialogManager() = default;

void AtomJavaScriptDialogManager::RunJavaScriptDialog(
    content::WebContents* web_contents,
    content::RenderFrameHost* rfh,
    JavaScriptDialogType dialog_type,
    const base::string16& message_text,
    const base::string16& default_prompt_text,
    DialogClosedCallback callback,
    bool* did_suppress_message) {
  auto origin_url = rfh->GetLastCommittedURL();
  const std::string& origin = origin_url.GetOrigin().spec();
  if (origin_counts_[origin] == kUserWantsNoMoreDialogs) {
    return std::move(callback).Run(false, base::string16());
  }

  if (dialog_type != JavaScriptDialogType::JAVASCRIPT_DIALOG_TYPE_ALERT &&
      dialog_type != JavaScriptDialogType::JAVASCRIPT_DIALOG_TYPE_CONFIRM) {
    std::move(callback).Run(false, base::string16());
    return;
  }

  std::vector<std::string> buttons = {"OK"};
  if (dialog_type == JavaScriptDialogType::JAVASCRIPT_DIALOG_TYPE_CONFIRM) {
    buttons.push_back("Cancel");
  }

  origin_counts_[origin]++;

  auto* web_preferences = WebContentsPreferences::From(web_contents);
  std::string checkbox;
  if (origin_counts_[origin] > 1 && web_preferences &&
      web_preferences->IsEnabled("safeDialogs") &&
      !web_preferences->GetPreference("safeDialogsMessage", &checkbox)) {
    checkbox = "Prevent this app from creating additional dialogs";
  }

  // Don't set parent for offscreen window.
  NativeWindow* window = nullptr;
  if (web_preferences && !web_preferences->IsEnabled(options::kOffscreen)) {
    auto* relay = NativeWindowRelay::FromWebContents(web_contents);
    if (relay)
      window = relay->GetNativeWindow();
  }

  atom::ShowMessageBox(
      window, atom::MessageBoxType::MESSAGE_BOX_TYPE_NONE, buttons, -1, 0,
      atom::MessageBoxOptions::MESSAGE_BOX_NONE, "",
      base::UTF16ToUTF8(message_text), "", checkbox, false, gfx::ImageSkia(),
      base::Bind(&AtomJavaScriptDialogManager::OnMessageBoxCallback,
                 base::Unretained(this), base::Passed(std::move(callback)),
                 origin));
}

void AtomJavaScriptDialogManager::RunBeforeUnloadDialog(
    content::WebContents* web_contents,
    content::RenderFrameHost* rfh,
    bool is_reload,
    DialogClosedCallback callback) {
  bool default_prevented = api_web_contents_->Emit("will-prevent-unload");
  std::move(callback).Run(default_prevented, base::string16());
  return;
}

void AtomJavaScriptDialogManager::CancelDialogs(
    content::WebContents* web_contents,
    bool reset_state) {}

void AtomJavaScriptDialogManager::OnMessageBoxCallback(
    DialogClosedCallback callback,
    const std::string& origin,
    int code,
    bool checkbox_checked) {
  if (checkbox_checked)
    origin_counts_[origin] = kUserWantsNoMoreDialogs;
  std::move(callback).Run(code == 0, base::string16());
}

}  // namespace atom
<commit_msg>fix: set default_id and cancel_id correctly on confirm dialogs (#17547)<commit_after>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/atom_javascript_dialog_manager.h"

#include <string>
#include <utility>
#include <vector>

#include "atom/browser/api/atom_api_web_contents.h"
#include "atom/browser/native_window.h"
#include "atom/browser/ui/message_box.h"
#include "atom/browser/web_contents_preferences.h"
#include "atom/common/options_switches.h"
#include "base/bind.h"
#include "base/strings/utf_string_conversions.h"
#include "ui/gfx/image/image_skia.h"

using content::JavaScriptDialogType;

namespace atom {

namespace {

constexpr int kUserWantsNoMoreDialogs = -1;

}  // namespace

AtomJavaScriptDialogManager::AtomJavaScriptDialogManager(
    api::WebContents* api_web_contents)
    : api_web_contents_(api_web_contents) {}
AtomJavaScriptDialogManager::~AtomJavaScriptDialogManager() = default;

void AtomJavaScriptDialogManager::RunJavaScriptDialog(
    content::WebContents* web_contents,
    content::RenderFrameHost* rfh,
    JavaScriptDialogType dialog_type,
    const base::string16& message_text,
    const base::string16& default_prompt_text,
    DialogClosedCallback callback,
    bool* did_suppress_message) {
  auto origin_url = rfh->GetLastCommittedURL();
  const std::string& origin = origin_url.GetOrigin().spec();
  if (origin_counts_[origin] == kUserWantsNoMoreDialogs) {
    return std::move(callback).Run(false, base::string16());
  }

  if (dialog_type != JavaScriptDialogType::JAVASCRIPT_DIALOG_TYPE_ALERT &&
      dialog_type != JavaScriptDialogType::JAVASCRIPT_DIALOG_TYPE_CONFIRM) {
    std::move(callback).Run(false, base::string16());
    return;
  }

  // No default button
  int default_id = -1;
  int cancel_id = 0;

  std::vector<std::string> buttons = {"OK"};
  if (dialog_type == JavaScriptDialogType::JAVASCRIPT_DIALOG_TYPE_CONFIRM) {
    buttons.push_back("Cancel");
    // First button is default, second button is cancel
    default_id = 0;
    cancel_id = 1;
  }

  origin_counts_[origin]++;

  auto* web_preferences = WebContentsPreferences::From(web_contents);
  std::string checkbox;
  if (origin_counts_[origin] > 1 && web_preferences &&
      web_preferences->IsEnabled("safeDialogs") &&
      !web_preferences->GetPreference("safeDialogsMessage", &checkbox)) {
    checkbox = "Prevent this app from creating additional dialogs";
  }

  // Don't set parent for offscreen window.
  NativeWindow* window = nullptr;
  if (web_preferences && !web_preferences->IsEnabled(options::kOffscreen)) {
    auto* relay = NativeWindowRelay::FromWebContents(web_contents);
    if (relay)
      window = relay->GetNativeWindow();
  }

  atom::ShowMessageBox(
      window, atom::MessageBoxType::MESSAGE_BOX_TYPE_NONE, buttons, default_id,
      cancel_id, atom::MessageBoxOptions::MESSAGE_BOX_NONE, "",
      base::UTF16ToUTF8(message_text), "", checkbox, false, gfx::ImageSkia(),
      base::Bind(&AtomJavaScriptDialogManager::OnMessageBoxCallback,
                 base::Unretained(this), base::Passed(std::move(callback)),
                 origin));
}

void AtomJavaScriptDialogManager::RunBeforeUnloadDialog(
    content::WebContents* web_contents,
    content::RenderFrameHost* rfh,
    bool is_reload,
    DialogClosedCallback callback) {
  bool default_prevented = api_web_contents_->Emit("will-prevent-unload");
  std::move(callback).Run(default_prevented, base::string16());
  return;
}

void AtomJavaScriptDialogManager::CancelDialogs(
    content::WebContents* web_contents,
    bool reset_state) {}

void AtomJavaScriptDialogManager::OnMessageBoxCallback(
    DialogClosedCallback callback,
    const std::string& origin,
    int code,
    bool checkbox_checked) {
  if (checkbox_checked)
    origin_counts_[origin] = kUserWantsNoMoreDialogs;
  std::move(callback).Run(code == 0, base::string16());
}

}  // namespace atom
<|endoftext|>


<commit_before><commit_msg>Update test_index_string.cpp<commit_after><|endoftext|>


<commit_before>8961cd9e-ad5b-11e7-8492-ac87a332f658<commit_msg>Too poor for Dropbox<commit_after>89d1a151-ad5b-11e7-9b54-ac87a332f658<|endoftext|>


<commit_before>// Copyright (c) 2018 PaddlePaddle 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.

#include "paddle/fluid/inference/api/api_anakin_engine.h"

#ifdef PADDLE_WITH_CUDA
#include <cuda.h>
#endif

#include <mkl_service.h>
#include <omp.h>
#include <map>
#include <string>
#include <utility>
#include <vector>

#include "framework/core/net/net.h"
#include "framework/operators/ops.h"
#include "saber/funcs/timer.h"

namespace paddle {

using paddle::contrib::AnakinConfig;

template <typename Target>
PaddleInferenceAnakinPredictor<Target>::PaddleInferenceAnakinPredictor(
    const contrib::AnakinConfig &config) {
  CHECK(Init(config));
}
template <>
PaddleInferenceAnakinPredictor<anakin::X86>::PaddleInferenceAnakinPredictor(
    const contrib::AnakinConfig &config) {
  omp_set_dynamic(0);
  omp_set_num_threads(1);
  mkl_set_num_threads(1);
  CHECK(Init(config));
}
template <typename Target>
bool PaddleInferenceAnakinPredictor<Target>::Init(
    const contrib::AnakinConfig &config) {
  if (!(graph_.load(config.model_file))) {
    VLOG(3) << "fail to load graph from " << config.model_file;
    return false;
  }
  auto inputs = graph_.get_ins();
  for (auto &input_str : inputs) {
    graph_.ResetBatchSize(input_str, config.max_batch_size);
    max_batch_size_ = config.max_batch_size;
  }
  // optimization for graph
  if (!(graph_.Optimize())) {
    return false;
  }
  // construct executer
  if (executor_p_ == nullptr) {
    executor_p_ = new anakin::Net<Target, anakin::saber::AK_FLOAT,
                                  anakin::Precision::FP32>(graph_, true);
  }
  return true;
}

template <typename Target>
bool PaddleInferenceAnakinPredictor<Target>::Run(
    const std::vector<PaddleTensor> &inputs,
    std::vector<PaddleTensor> *output_data, int batch_size) {
  for (const auto &input : inputs) {
    if (input.dtype != PaddleDType::FLOAT32) {
      VLOG(3) << "Only support float type inputs. " << input.name
              << "'s type is not float";
      return false;
    }
    auto d_tensor_in_p = executor_p_->get_in(input.name);
    auto net_shape = d_tensor_in_p->shape();
    if (net_shape.size() != input.shape.size()) {
      VLOG(3) << " input  " << input.name
              << "'s shape size should be equal to that of net";
      return false;
    }
    int sum = 1;
    for_each(input.shape.begin(), input.shape.end(), [&](int n) { sum *= n; });
    if (sum > net_shape.count()) {
      graph_.Reshape(input.name, input.shape);
      delete executor_p_;
      executor_p_ = new anakin::Net<Target, anakin::saber::AK_FLOAT,
                                    anakin::Precision::FP32>(graph_, true);
      d_tensor_in_p = executor_p_->get_in(input.name);
    }

    anakin::saber::Shape tmp_shape;
    for (auto s : input.shape) {
      tmp_shape.push_back(s);
    }
    d_tensor_in_p->reshape(tmp_shape);

    if (input.lod.size() > 0) {
      if (input.lod.size() > 1) {
        VLOG(3) << " input lod first dim should <=1, but you set "
                << input.lod.size();
        return false;
      }
      std::vector<int> offset(input.lod[0].begin(), input.lod[0].end());
      d_tensor_in_p->set_seq_offset(offset);
      VLOG(3) << "offset.size(): " << offset.size();
      for (int i = 0; i < offset.size(); i++) {
        VLOG(3) << offset[i];
      }
    }

    float *d_data_p = d_tensor_in_p->mutable_data();

#ifdef PADDLE_WITH_CUDA
    if (std::is_same<anakin::NV, Target>::value) {
      if (cudaMemcpy(d_data_p, static_cast<float *>(input.data.data()),
                     d_tensor_in_p->valid_size() * sizeof(float),
                     cudaMemcpyHostToDevice) != 0) {
        VLOG(3) << "copy data from CPU to GPU error";
        return false;
      }
    }
#endif
    if (std::is_same<anakin::X86, Target>::value) {
      memcpy(d_data_p, static_cast<float *>(input.data.data()),
             d_tensor_in_p->valid_size() * sizeof(float));
    }
  }
#ifdef PADDLE_WITH_CUDA
  cudaDeviceSynchronize();
  executor_p_->prediction();
  cudaDeviceSynchronize();
#endif

  if (output_data->empty()) {
    VLOG(3) << "At least one output should be set with tensors' names.";
    return false;
  }
  for (auto &output : *output_data) {
    auto *tensor = executor_p_->get_out(output.name);
    output.shape = tensor->valid_shape();
    if (output.data.length() < tensor->valid_size() * sizeof(float)) {
      output.data.Resize(tensor->valid_size() * sizeof(float));
    }

#if PADDLE_WITH_CUDA
    if (std::is_same<anakin::NV, Target>::value) {
      // Copy data from GPU -> CPU
      if (cudaMemcpy(output.data.data(), tensor->mutable_data(),
                     tensor->valid_size() * sizeof(float),
                     cudaMemcpyDeviceToHost) != 0) {
        VLOG(3) << "copy data from GPU to CPU error";
        return false;
      }
    }
#endif
    if (std::is_same<anakin::X86, Target>::value) {
      memcpy(output.data.data(), tensor->mutable_data(),
             tensor->valid_size() * sizeof(float));
    }
  }
  return true;
}

template <typename Target>
anakin::Net<Target, anakin::saber::AK_FLOAT, anakin::Precision::FP32>
    &PaddleInferenceAnakinPredictor<Target>::get_executer() {
  return *executor_p_;
}

// the cloned new Predictor of anakin share the same net weights from original
// Predictor
template <typename Target>
std::unique_ptr<PaddlePredictor>
PaddleInferenceAnakinPredictor<Target>::Clone() {
  VLOG(3) << "Anakin Predictor::clone";
  std::unique_ptr<PaddlePredictor> cls(
      new PaddleInferenceAnakinPredictor<Target>());
  // construct executer from other graph
  auto anakin_predictor_p =
      dynamic_cast<PaddleInferenceAnakinPredictor<Target> *>(cls.get());
  if (!anakin_predictor_p) {
    VLOG(3) << "fail to call Init";
    return nullptr;
  }
  anakin_predictor_p->get_executer().init(graph_);

  return std::move(cls);
}

#ifdef PADDLE_WITH_CUDA
template class PaddleInferenceAnakinPredictor<anakin::NV>;
#endif
template class PaddleInferenceAnakinPredictor<anakin::X86>;

// A factory to help create difference predictor.
template <>
std::unique_ptr<PaddlePredictor>
CreatePaddlePredictor<contrib::AnakinConfig, PaddleEngineKind::kAnakin>(
    const contrib::AnakinConfig &config) {
  VLOG(3) << "Anakin Predictor create.";
  if (config.target_type == contrib::AnakinConfig::NVGPU) {
#ifdef PADDLE_WITH_CUDA
    VLOG(3) << "Anakin Predictor create on [ NVIDIA GPU ].";
    std::unique_ptr<PaddlePredictor> x(
        new PaddleInferenceAnakinPredictor<anakin::NV>(config));
    return x;
#else
    LOG(ERROR) << "AnakinConfig::NVGPU could not used in ONLY-CPU environment";
    return nullptr;
#endif
  } else if (config.target_type == contrib::AnakinConfig::X86) {
    VLOG(3) << "Anakin Predictor create on [ Intel X86 ].";
    std::unique_ptr<PaddlePredictor> x(
        new PaddleInferenceAnakinPredictor<anakin::X86>(config));
    return x;
  } else {
    VLOG(3) << "Anakin Predictor create on unknown platform.";
    return nullptr;
  }
}

template <>
std::unique_ptr<PaddlePredictor> CreatePaddlePredictor<contrib::AnakinConfig>(
    const contrib::AnakinConfig &config) {
  return CreatePaddlePredictor(config);
};

#ifdef PADDLE_ANAKIN_ENABLE_OP_TIMER
template <typename Target>
using executor_t =
    anakin::Net<Target, anakin::saber::AK_FLOAT, anakin::Precision::FP32>;

template <typename Target>
void DisplayOpTimer(executor_t<Target> *net_executor, int epoch) {
  std::vector<float> op_time = net_executor->get_op_time();
  auto exec_funcs = net_executor->get_exec_funcs();
  auto op_param = net_executor->get_op_param();
  for (int i = 0; i < op_time.size(); i++) {
    LOG(INFO) << "name: " << exec_funcs[i].name
              << " op_type: " << exec_funcs[i].op_name
              << " op_param: " << op_param[i] << " time " << op_time[i] / epoch;
  }
  std::map<std::string, float> op_map;
  for (int i = 0; i < op_time.size(); i++) {
    auto it = op_map.find(op_param[i]);
    if (it != op_map.end())
      op_map[op_param[i]] += op_time[i];
    else
      op_map.insert(std::pair<std::string, float>(op_param[i], op_time[i]));
  }
  for (auto it = op_map.begin(); it != op_map.end(); ++it) {
    LOG(INFO) << it->first << "  " << (it->second) / epoch << " ms";
  }
}
#endif

template <typename Target>
PaddleInferenceAnakinPredictor<Target>::~PaddleInferenceAnakinPredictor() {
#ifdef PADDLE_ANAKIN_ENABLE_OP_TIMER
  DisplayOpTimer<Target>(executor_p_, max_batch_size_);
#endif
  delete executor_p_;
  executor_p_ = nullptr;
}

}  // namespace paddle
<commit_msg>update<commit_after>// Copyright (c) 2018 PaddlePaddle 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.

#include "paddle/fluid/inference/api/api_anakin_engine.h"

#ifdef PADDLE_WITH_CUDA
#include <cuda.h>
#endif

#include <mkl_service.h>
#include <omp.h>
#include <map>
#include <string>
#include <utility>
#include <vector>

#include "framework/core/net/net.h"
#include "framework/operators/ops.h"
#include "saber/funcs/timer.h"

namespace paddle {

using paddle::contrib::AnakinConfig;

template <typename Target>
PaddleInferenceAnakinPredictor<Target>::PaddleInferenceAnakinPredictor(
    const contrib::AnakinConfig &config) {
  CHECK(Init(config));
}
template <>
PaddleInferenceAnakinPredictor<anakin::X86>::PaddleInferenceAnakinPredictor(
    const contrib::AnakinConfig &config) {
  omp_set_dynamic(0);
  omp_set_num_threads(1);
  mkl_set_num_threads(1);
  CHECK(Init(config));
}
template <typename Target>
bool PaddleInferenceAnakinPredictor<Target>::Init(
    const contrib::AnakinConfig &config) {
  if (!(graph_.load(config.model_file))) {
    VLOG(3) << "fail to load graph from " << config.model_file;
    return false;
  }
  auto inputs = graph_.get_ins();
  for (auto &input_str : inputs) {
    graph_.ResetBatchSize(input_str, config.max_batch_size);
    max_batch_size_ = config.max_batch_size;
  }
  // optimization for graph
  if (!(graph_.Optimize())) {
    return false;
  }
  // construct executer
  if (executor_p_ == nullptr) {
    executor_p_ = new anakin::Net<Target, anakin::saber::AK_FLOAT,
                                  anakin::Precision::FP32>(graph_, true);
  }
  return true;
}

template <typename Target>
bool PaddleInferenceAnakinPredictor<Target>::Run(
    const std::vector<PaddleTensor> &inputs,
    std::vector<PaddleTensor> *output_data, int batch_size) {
  for (const auto &input : inputs) {
    if (input.dtype != PaddleDType::FLOAT32) {
      VLOG(3) << "Only support float type inputs. " << input.name
              << "'s type is not float";
      return false;
    }
    auto d_tensor_in_p = executor_p_->get_in(input.name);
    auto net_shape = d_tensor_in_p->shape();
    if (net_shape.size() != input.shape.size()) {
      VLOG(3) << " input  " << input.name
              << "'s shape size should be equal to that of net";
      return false;
    }
    int sum = 1;
    for_each(input.shape.begin(), input.shape.end(), [&](int n) { sum *= n; });
    if (sum > net_shape.count()) {
      graph_.Reshape(input.name, input.shape);
      delete executor_p_;
      executor_p_ = new anakin::Net<Target, anakin::saber::AK_FLOAT,
                                    anakin::Precision::FP32>(graph_, true);
      d_tensor_in_p = executor_p_->get_in(input.name);
    }

    anakin::saber::Shape tmp_shape;
    for (auto s : input.shape) {
      tmp_shape.push_back(s);
    }
    d_tensor_in_p->reshape(tmp_shape);

    if (input.lod.size() > 0) {
      if (input.lod.size() > 1) {
        VLOG(3) << " input lod first dim should <=1, but you set "
                << input.lod.size();
        return false;
      }
      std::vector<int> offset(input.lod[0].begin(), input.lod[0].end());
      d_tensor_in_p->set_seq_offset(offset);
      VLOG(3) << "offset.size(): " << offset.size();
      for (int i = 0; i < offset.size(); i++) {
        VLOG(3) << offset[i];
      }
    }

    float *d_data_p = d_tensor_in_p->mutable_data();

#ifdef PADDLE_WITH_CUDA
    if (std::is_same<anakin::NV, Target>::value) {
      if (cudaMemcpy(d_data_p, static_cast<float *>(input.data.data()),
                     d_tensor_in_p->valid_size() * sizeof(float),
                     cudaMemcpyHostToDevice) != 0) {
        VLOG(3) << "copy data from CPU to GPU error";
        return false;
      }
    }
#endif
    if (std::is_same<anakin::X86, Target>::value) {
      memcpy(d_data_p, static_cast<float *>(input.data.data()),
             d_tensor_in_p->valid_size() * sizeof(float));
    }
  }
#ifdef PADDLE_WITH_CUDA
  cudaDeviceSynchronize();
  executor_p_->prediction();
  cudaDeviceSynchronize();
#endif

  if (output_data->empty()) {
    VLOG(3) << "At least one output should be set with tensors' names.";
    return false;
  }
  for (auto &output : *output_data) {
    auto *tensor = executor_p_->get_out(output.name);
    output.shape = tensor->valid_shape();
    if (output.data.length() < tensor->valid_size() * sizeof(float)) {
      output.data.Resize(tensor->valid_size() * sizeof(float));
    }

#if PADDLE_WITH_CUDA
    if (std::is_same<anakin::NV, Target>::value) {
      // Copy data from GPU -> CPU
      if (cudaMemcpy(output.data.data(), tensor->mutable_data(),
                     tensor->valid_size() * sizeof(float),
                     cudaMemcpyDeviceToHost) != 0) {
        VLOG(3) << "copy data from GPU to CPU error";
        return false;
      }
    }
#endif
    if (std::is_same<anakin::X86, Target>::value) {
      memcpy(output.data.data(), tensor->mutable_data(),
             tensor->valid_size() * sizeof(float));
    }
  }
  return true;
}

template <typename Target>
anakin::Net<Target, anakin::saber::AK_FLOAT, anakin::Precision::FP32>
    &PaddleInferenceAnakinPredictor<Target>::get_executer() {
  return *executor_p_;
}

// the cloned new Predictor of anakin share the same net weights from original
// Predictor
template <typename Target>
std::unique_ptr<PaddlePredictor>
PaddleInferenceAnakinPredictor<Target>::Clone() {
  VLOG(3) << "Anakin Predictor::clone";
  std::unique_ptr<PaddlePredictor> cls(
      new PaddleInferenceAnakinPredictor<Target>());
  // construct executer from other graph
  auto anakin_predictor_p =
      dynamic_cast<PaddleInferenceAnakinPredictor<Target> *>(cls.get());
  if (!anakin_predictor_p) {
    VLOG(3) << "fail to call Init";
    return nullptr;
  }
  anakin_predictor_p->get_executer().init(graph_);

  return std::move(cls);
}

#ifdef PADDLE_WITH_CUDA
template class PaddleInferenceAnakinPredictor<anakin::NV>;
#endif
template class PaddleInferenceAnakinPredictor<anakin::X86>;

// A factory to help create difference predictor.
template <>
std::unique_ptr<PaddlePredictor>
CreatePaddlePredictor<contrib::AnakinConfig, PaddleEngineKind::kAnakin>(
    const contrib::AnakinConfig &config) {
  VLOG(3) << "Anakin Predictor create.";
  if (config.target_type == contrib::AnakinConfig::NVGPU) {
#ifdef PADDLE_WITH_CUDA
    VLOG(3) << "Anakin Predictor create on [ NVIDIA GPU ].";
    std::unique_ptr<PaddlePredictor> x(
        new PaddleInferenceAnakinPredictor<anakin::NV>(config));
    return x;
#else
    LOG(ERROR) << "AnakinConfig::NVGPU could not used in ONLY-CPU environment";
    return nullptr;
#endif
  } else if (config.target_type == contrib::AnakinConfig::X86) {
    VLOG(3) << "Anakin Predictor create on [ Intel X86 ].";
    std::unique_ptr<PaddlePredictor> x(
        new PaddleInferenceAnakinPredictor<anakin::X86>(config));
    return x;
  } else {
    VLOG(3) << "Anakin Predictor create on unknown platform.";
    return nullptr;
  }
}

#ifdef PADDLE_ANAKIN_ENABLE_OP_TIMER
template <typename Target>
using executor_t =
    anakin::Net<Target, anakin::saber::AK_FLOAT, anakin::Precision::FP32>;

template <typename Target>
void DisplayOpTimer(executor_t<Target> *net_executor, int epoch) {
  std::vector<float> op_time = net_executor->get_op_time();
  auto exec_funcs = net_executor->get_exec_funcs();
  auto op_param = net_executor->get_op_param();
  for (int i = 0; i < op_time.size(); i++) {
    LOG(INFO) << "name: " << exec_funcs[i].name
              << " op_type: " << exec_funcs[i].op_name
              << " op_param: " << op_param[i] << " time " << op_time[i] / epoch;
  }
  std::map<std::string, float> op_map;
  for (int i = 0; i < op_time.size(); i++) {
    auto it = op_map.find(op_param[i]);
    if (it != op_map.end())
      op_map[op_param[i]] += op_time[i];
    else
      op_map.insert(std::pair<std::string, float>(op_param[i], op_time[i]));
  }
  for (auto it = op_map.begin(); it != op_map.end(); ++it) {
    LOG(INFO) << it->first << "  " << (it->second) / epoch << " ms";
  }
}
#endif

template <typename Target>
PaddleInferenceAnakinPredictor<Target>::~PaddleInferenceAnakinPredictor() {
#ifdef PADDLE_ANAKIN_ENABLE_OP_TIMER
  DisplayOpTimer<Target>(executor_p_, max_batch_size_);
#endif
  delete executor_p_;
  executor_p_ = nullptr;
}

}  // namespace paddle
<|endoftext|>


<commit_before>a03e4b02-2747-11e6-a220-e0f84713e7b8<commit_msg>compiles now<commit_after>a0489919-2747-11e6-8b00-e0f84713e7b8<|endoftext|>


<commit_before><commit_msg>added width/height option<commit_after><|endoftext|>


<commit_before>a57e381e-2747-11e6-9258-e0f84713e7b8<commit_msg>Introduced random NullPointerException bug<commit_after>a58a668f-2747-11e6-b623-e0f84713e7b8<|endoftext|>


<commit_before>/*
 * main.cpp
 *
 *  Created on: Oct 9, 2016
 *      Author: Yimin Zhong
 */
#include <iostream>
#include "kernel.h"
#include "bicgstab.h"
#include "geometry.h"
int main() {
#ifdef RUN_OMP
    omp_set_num_threads(omp_get_max_threads());
#endif
    /*
     * allocating source, target locations and weights
     */
    vector<point> source, target;
    vector<double> weight;

    /*
     * select points inside tube and assign to source and target.
     *
     * 1. source points = target points for simplification.
     * 2. weight is calculated by using wcos.
     * 3. thickness of tube is 0.1
     * 4. radius of sphere is 1.0
     * 5. dx=dy=dz are set to be 1.0/40.0
     */
    double thickness = 0.1;
    double radius = 1.0;
    double dx = 1.0 / 40.0;

    spherical_tube(source, weight, thickness, radius, dx);
    target = source;

    /*
     * number of points(N), and number Cheyshev points (np) used for approximation.
     * tau is the parameter for K_{\tau}.
     */
    int N = (int) source.size();
    int np = 3;
    double tau = dx;

    /*
     * allocate rhs vector for solving following second kind integral equation
     *
     *  Ax = (0.5 I + K) x = c
     *
     * here c is set to be all ones. In theory, x should be all ones.
     */
    VectorXd c(N);
    c.setOnes();

    /*
     * setting up A operator as f in above context.
     *
     * where K is set to be approximated with FMM. For detail, see below.
     */
    auto f = [&](VectorXd& v) {
        kernel bbfmm;

        /*
         * Eval function is
         *
         * K(x, y) = - r.n/r^3/(4\pi)
         *
         *  where r = |x-y|. n = n_y.
         */
        bbfmm.eval = [&](point &a, point &b) {
            double d = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y) + (a.z - b.z)*(a.z - b.z);
            double r = sqrt(d);
            if (r < tau) return (1.0 / 8.0 / M_PI / tau) - (5.0 / 256.0 + 25.0 / 768.0) * tau / M_PI;
            else return -((a.x - b.x) * b.x + (a.y - b.y) * b.y + (a.z - b.z) * b.z) / d / r / (4 * M_PI);
            };

        VectorXd weighted_f(N);
        for (int i = 0; i < N; ++i) {
            weighted_f(i) = v(i) * weight[i];
        }

        bbfmm.initialize(np, source, target, weighted_f, N, N, 80, 10);

        VectorXd potentialMatrix;

        bbfmm.run(potentialMatrix);

        /*
         * plus 0.5 Identity.
         */
        potentialMatrix += v / 2.0;

        return potentialMatrix;
    };

    /*
     * allocation for solution x
     */
    VectorXd x(N);

    /*
     * using BICGSTAB to solve x.
     */
    bicgstab(f, c, x, 100, 1e-12);

    /*
     * check if norm(x - 1.0) is small enough.
     */
    VectorXd true_sol(N);
    true_sol.setOnes();
    std::cout << "BICGSTAB solution's relative error is " << std::scientific << (x - true_sol).norm() / true_sol.norm()
              << std::endl;

    /*
     *  Check solution against random target points.
     *
     *  \int K(x, y) dy = 0.  for inside
     *                  = 0.5 on edge
     *                  = 1.0 for outside
     *
     *
     */
    kernel check_bbfmm;
    check_bbfmm.eval = [&](point &a, point &b) {
        double d = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y) + (a.z - b.z) * (a.z - b.z);
        double r = sqrt(d);
        if (r < tau) return (1.0 / 8.0 / M_PI / tau) - (5.0 / 256.0 + 25.0 / 768.0) * tau / M_PI;
        else return -((a.x - b.x) * b.x + (a.y - b.y) * b.y + (a.z - b.z) * b.z) / d / r / (4 * M_PI);
    };

    /*
     * setting up check_target for testing.
     *
     * multiply a scalar(0.9) in order to prevent points out of box [-1, 1]^3.
     */
    vector<point> check_target;
    int M = 200;
    for (int i = 0; i < M; ++i) {
        check_target.push_back(point(
                1.8 * rand() / RAND_MAX - 0.9,
                1.8 * rand() / RAND_MAX - 0.9,
                1.8 * rand() / RAND_MAX - 0.9));
    }

    VectorXd wf(N);
    for (int i = 0; i < N; ++i) {
        wf(i) = x(i) * weight[i];
    }

    /*
     * calculate \int K(x, y) dy for all x \in check_target.
     */
    check_bbfmm.initialize(np, source, check_target, wf, N, M, 80, 10);
    VectorXd ret;
    check_bbfmm.run(ret);

    /*
     * direct summation for checking
     */
    VectorXd check_ret(check_target.size());
    check_ret.setZero();
    for (int j = 0; j < check_ret.rows(); ++j) {
        for (int i = 0; i < N; ++i) {
            check_ret(j) += check_bbfmm.eval(source[i], check_target[j]) * x(i) * weight[i];
        }
    }

    std::cout << "L∞ error of above test is " << std::scientific << (ret - check_ret).lpNorm<Infinity>() << std::endl;
}
<commit_msg>change regularization term<commit_after>/*
 * main.cpp
 *
 *  Created on: Oct 9, 2016
 *      Author: Yimin Zhong
 */
#include <iostream>
#include "kernel.h"
#include "bicgstab.h"
#include "geometry.h"
int main() {
#ifdef RUN_OMP
    omp_set_num_threads(omp_get_max_threads());
#endif
    /*
     * allocating source, target locations and weights
     */
    vector<point> source, target;
    vector<double> weight;

    /*
     * select points inside tube and assign to source and target.
     *
     * 1. source points = target points for simplification.
     * 2. weight is calculated by using wcos.
     * 3. thickness of tube is 0.1
     * 4. radius of sphere is 1.0
     * 5. dx=dy=dz are set to be 1.0/40.0
     */
    double thickness = 0.1;
    double radius = 1.0;
    double dx = 1.0 / 40.0;

    spherical_tube(source, weight, thickness, radius, dx);
    target = source;

    /*
     * number of points(N), and number Cheyshev points (np) used for approximation.
     * tau is the parameter for K_{\tau}.
     */
    int N = (int) source.size();
    int np = 3;
    double tau = dx;

    /*
     * allocate rhs vector for solving following second kind integral equation
     *
     *  Ax = (0.5 I + K) x = c
     *
     * here c is set to be all ones. In theory, x should be all ones.
     */
    VectorXd c(N);
    c.setOnes();

    /*
     * setting up A operator as f in above context.
     *
     * where K is set to be approximated with FMM. For detail, see below.
     */
    auto f = [&](VectorXd& v) {
        kernel bbfmm;

        /*
         * Eval function is
         *
         * K(x, y) = - r.n/r^3/(4\pi)
         *
         *  where r = |x-y|. n = n_y.
         */
        bbfmm.eval = [&](point &a, point &b) {
            double d = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y) + (a.z - b.z)*(a.z - b.z);
            double r = sqrt(d);
            if (r < tau) return (1.0 / 4.0 / M_PI / tau) - (5.0 / 256.0 + 25.0 / 768.0) * tau / M_PI;
            else return -((a.x - b.x) * b.x + (a.y - b.y) * b.y + (a.z - b.z) * b.z) / d / r / (4 * M_PI);
            };

        VectorXd weighted_f(N);
        for (int i = 0; i < N; ++i) {
            weighted_f(i) = v(i) * weight[i];
        }

        bbfmm.initialize(np, source, target, weighted_f, N, N, 80, 10);

        VectorXd potentialMatrix;

        bbfmm.run(potentialMatrix);

        /*
         * plus 0.5 Identity.
         */
        potentialMatrix += v / 2.0;

        return potentialMatrix;
    };

    /*
     * allocation for solution x
     */
    VectorXd x(N);

    /*
     * using BICGSTAB to solve x.
     */
    bicgstab(f, c, x, 100, 1e-12);

    /*
     * check if norm(x - 1.0) is small enough.
     */
    VectorXd true_sol(N);
    true_sol.setOnes();
    std::cout << "BICGSTAB solution's relative error is " << std::scientific << (x - true_sol).norm() / true_sol.norm()
              << std::endl;

    /*
     *  Check solution against random target points.
     *
     *  \int K(x, y) dy = 0.  for inside
     *                  = 0.5 on edge
     *                  = 1.0 for outside
     *
     *
     */
    kernel check_bbfmm;
    check_bbfmm.eval = [&](point &a, point &b) {
        double d = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y) + (a.z - b.z) * (a.z - b.z);
        double r = sqrt(d);
        if (r < tau) return (1.0 / 4.0 / M_PI / tau) - (5.0 / 256.0 + 25.0 / 768.0) * tau / M_PI;
        else return -((a.x - b.x) * b.x + (a.y - b.y) * b.y + (a.z - b.z) * b.z) / d / r / (4 * M_PI);
    };

    /*
     * setting up check_target for testing.
     *
     * multiply a scalar(0.9) in order to prevent points out of box [-1, 1]^3.
     */
    vector<point> check_target;
    int M = 200;
    for (int i = 0; i < M; ++i) {
        check_target.push_back(point(
                1.8 * rand() / RAND_MAX - 0.9,
                1.8 * rand() / RAND_MAX - 0.9,
                1.8 * rand() / RAND_MAX - 0.9));
    }

    VectorXd wf(N);
    for (int i = 0; i < N; ++i) {
        wf(i) = x(i) * weight[i];
    }

    /*
     * calculate \int K(x, y) dy for all x \in check_target.
     */
    check_bbfmm.initialize(np, source, check_target, wf, N, M, 80, 10);
    VectorXd ret;
    check_bbfmm.run(ret);

    /*
     * direct summation for checking
     */
    VectorXd check_ret(check_target.size());
    check_ret.setZero();
    for (int j = 0; j < check_ret.rows(); ++j) {
        for (int i = 0; i < N; ++i) {
            check_ret(j) += check_bbfmm.eval(source[i], check_target[j]) * x(i) * weight[i];
        }
    }

    std::cout << "L∞ error of above test is " << std::scientific << (ret - check_ret).lpNorm<Infinity>() << std::endl;
}
<|endoftext|>


<commit_before><commit_msg>fix unit tests<commit_after><|endoftext|>


<commit_before>/******************************************************************************

******************************************************************************/

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <errno.h>
#include <wiringPiSPI.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>

using namespace std;

bool debug_flag = false;

// SPI Speed as per the datasheet of the accelerometer : 1,2 MHz
#define SPI_SPEED 1200000

// Minimum square value for triggering an output
#define MIN_TRIGGER 0.4 // in G

// Coefficient for 10bit ADC --> G
#define G_COEF_ADXL (3300/1024)/330
#define G_COEF_MMA (3300/1024)/800

// Offsets are calculated here for faaaaastness (heuristics)
#define X_OFFSET_ADXL -512 + 5
#define Y_OFFSET_ADXL -512 + 5
#define Z_OFFSET_ADXL -512 - 102// Account for gravity (ADXL 1G = 330mV/g)  // 330mV/(3,3V/1023)

#define X_OFFSET_MMA -512
#define Y_OFFSET_MMA -512
#define Z_OFFSET_MMA -512 - 248// Account for gravity (ADXL 1G = 800mV/g)  // 800mV/(3,3V/1023)

// Time
#define ONE_OVER_CPS (1000000/CLOCKS_PER_SEC)

// Sampling rate for the ADC
unsigned int sampling_rate_in_us = 1000000; // 1 second
// Type of accelerometer
char * type;

// We declare globals for faster reads
unsigned int channel_select;
unsigned char buffer[2];

// channel = 0, 1, 2
unsigned int readADC(int channel) {

   if (channel == 0) {
      buffer[0] = 0x60;
      buffer[1] = 0x00;
      channel_select = 0;
   } else if (channel == 1) {
      buffer[0] = 0x70;
      buffer[1] = 0x00;
      channel_select = 0;
   } else {
      buffer[0] = 0x60;
      buffer[1] = 0x00;
      channel_select = 1;
   }

   // We write two bits
   /*
      Note that the SPI protocol "returns" the same number of bits as sent,
      and in this case the 10-bit ADC data is encoded in the last two bits
      of the first byte and the eight bits of the second byte. I chose to
      retrieve the data in MSB-first order, so the result is the sum of
      (the bottom two bits of the first byte shifted up by eight bits) + the second byte.
   */
   wiringPiSPIDataRW(channel_select, buffer, 2);

   // Used just for testing :
   // unsigned int msb = buffer[1] + ((buffer[0] & 0x03) << 8);
   // unsigned int lsb = buffer[0] + ((buffer[1] & 0x03) << 8);

   return buffer[1] + ((buffer[0] & 0x03) << 8);
}

int main(int argc, char *argv[])
{
   // File descriptors for SPI
   int fd_mpc3002_1, fd_mpc3002_2;

   // Data values
   int x, y, z;
   double xg, yg, zg;

   // Running an average on the whole sim
   long x_avg, y_avg, z_avg, count_avg;
   x_avg = 0; y_avg = 0; z_avg = 0; count_avg = 0;

   // For clocking and precision
   clock_t tic, toc;
   unsigned int elapsed_time_in_us;

   if (argc == 1) {
      printf("Caribe Wave Sensor Pusher — pushes sensor data to stdout for next stage.\n");
      printf("Usage :\n");
      printf("  ./main [sampling rate] [debug]\n");
      printf("\n");
      printf("Arguments :\n");
      printf("  - type: type of accelerometer : ADXL, LIS or MMA (string).\n");
      printf("  - sampling rate: in milliseconds, between 0 and 1000.\n");
      printf("  - debug: 1 or 0.\n");
      printf("\n");
      exit(0);
   } else if (argc == 2) {
      type = argv[1];
   } else if (argc == 3) {
      type = argv[1];
      sampling_rate_in_us = max(0, min(1000, atoi(argv[2]))) * 1000;
   } else if (argc == 4) {
      type = argv[1];
      sampling_rate_in_us = max(0, min(1000, atoi(argv[2]))) * 1000;
      debug_flag = argv[3][0] == '1' ? true : false;
      if (debug_flag) printf("Debug flag is TRUE.\n");
   } else {
      if (debug_flag) printf("Too many arguments supplied. Default sampling rate used.\n");
   }

   if (debug_flag) printf("Starting up.\n");
   if (debug_flag) printf("Sampling rate will be %d µs.\n", sampling_rate_in_us);
   if (debug_flag) printf("Accel. type is : %s.\n", type);
   if (debug_flag) printf("Initializing sensor pusher ...\n");

   // Configure the interface.
   fd_mpc3002_1 = wiringPiSPISetup(0, SPI_SPEED);
   fd_mpc3002_2 = wiringPiSPISetup(1, SPI_SPEED);

   if (debug_flag) printf("SPI setup : OK.\n");

   if (debug_flag) printf("Initing first MPC3002  : %d.\n", fd_mpc3002_1);
   if (debug_flag) printf("Initing second MPC3002 : %d.\n", fd_mpc3002_2);

   if (debug_flag) printf("\n");

   do {

      tic = clock();

      x = 0; y = 0; z = 0;
      for (int i = 0; i < 10; ++i)
      {
         if (strcmp(type,"ADXL")==0) {
            x += readADC(0) + X_OFFSET_ADXL;
            y += readADC(1) + Y_OFFSET_ADXL;
            z += readADC(2) + Z_OFFSET_ADXL;
         } else if (strcmp(type,"MMA")==0) {
            x += readADC(0) + X_OFFSET_MMA;
            y += readADC(1) + Y_OFFSET_MMA;
            z += readADC(2) + Z_OFFSET_MMA;
         }
      }

      // Average on 1ms approx.
      x = x/10;
      y = y/10;
      z = z/10;

      if (strcmp(type,"ADXL")==0) {
         xg = (double) x*G_COEF_ADXL;
         yg = (double) y*G_COEF_ADXL;
         zg = (double) z*G_COEF_ADXL;
      } else if (strcmp(type,"MMA")==0) {
         xg = (double) x*G_COEF_MMA;
         yg = (double) y*G_COEF_MMA;
         zg = (double) z*G_COEF_MMA;
      }

      // 1G on at least one axis triggers the output
      if ( xg*xg + yg*yg + zg*zg > MIN_TRIGGER || debug_flag) {
         // Format : X_10bit X_G Y_10bit Y_G Z_1Obit Z_G
         printf("%d %f %d %f %d %f\n", x, xg, y, yg, z, zg);

         if (debug_flag) {
            x_avg += x; y_avg += y; z_avg += z;
            count_avg++;
            printf("  [Average since launch %ld %ld %ld]\n", x_avg/count_avg, y_avg/count_avg, z_avg/count_avg);
         }
      }

      toc = clock();
      elapsed_time_in_us = (toc - tic) * ONE_OVER_CPS; // in microsecs
      if (debug_flag) printf("  [Sampling took %d us]\n", elapsed_time_in_us);

      usleep(sampling_rate_in_us - max(0, static_cast<int>(min(elapsed_time_in_us, sampling_rate_in_us))));

   } while(true);

   if (debug_flag) printf("Exiting");

}
<commit_msg>More tweaking<commit_after>/******************************************************************************

******************************************************************************/

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <errno.h>
#include <wiringPiSPI.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>

using namespace std;

bool debug_flag = false;

// SPI Speed as per the datasheet of the accelerometer : 1,2 MHz
#define SPI_SPEED 1200000

// Minimum square value for triggering an output
#define MIN_TRIGGER 0.4 // in G

// Coefficient for 10bit ADC --> G
#define G_COEF_ADXL (3300/1024)/330
#define G_COEF_MMA (3300/1024)/800

// Offsets are calculated here for faaaaastness (heuristics)
#define X_OFFSET_ADXL -512 + 5
#define Y_OFFSET_ADXL -512 + 5
#define Z_OFFSET_ADXL -512 - 102 - 16// Account for gravity (ADXL 1G = 330mV/g)  // 330mV/(3,3V/1023)

#define X_OFFSET_MMA -512
#define Y_OFFSET_MMA -512
#define Z_OFFSET_MMA -512 - 248// Account for gravity (ADXL 1G = 800mV/g)  // 800mV/(3,3V/1023)

// Time
#define ONE_OVER_CPS (1000000/CLOCKS_PER_SEC)

// Sampling rate for the ADC
unsigned int sampling_rate_in_us = 1000000; // 1 second
// Type of accelerometer
char * type;

// We declare globals for faster reads
unsigned int channel_select;
unsigned char buffer[2];

// channel = 0, 1, 2
unsigned int readADC(int channel) {

   if (channel == 0) {
      buffer[0] = 0x60;
      buffer[1] = 0x00;
      channel_select = 0;
   } else if (channel == 1) {
      buffer[0] = 0x70;
      buffer[1] = 0x00;
      channel_select = 0;
   } else {
      buffer[0] = 0x60;
      buffer[1] = 0x00;
      channel_select = 1;
   }

   // We write two bits
   /*
      Note that the SPI protocol "returns" the same number of bits as sent,
      and in this case the 10-bit ADC data is encoded in the last two bits
      of the first byte and the eight bits of the second byte. I chose to
      retrieve the data in MSB-first order, so the result is the sum of
      (the bottom two bits of the first byte shifted up by eight bits) + the second byte.
   */
   wiringPiSPIDataRW(channel_select, buffer, 2);

   // Used just for testing :
   // unsigned int msb = buffer[1] + ((buffer[0] & 0x03) << 8);
   // unsigned int lsb = buffer[0] + ((buffer[1] & 0x03) << 8);

   return buffer[1] + ((buffer[0] & 0x03) << 8);
}

int main(int argc, char *argv[])
{
   // File descriptors for SPI
   int fd_mpc3002_1, fd_mpc3002_2;

   // Data values
   int x, y, z;
   double xg, yg, zg;

   // Running an average on the whole sim
   long x_avg, y_avg, z_avg, count_avg;
   x_avg = 0; y_avg = 0; z_avg = 0; count_avg = 0;

   // For clocking and precision
   clock_t tic, toc;
   unsigned int elapsed_time_in_us;

   if (argc == 1) {
      printf("Caribe Wave Sensor Pusher — pushes sensor data to stdout for next stage.\n");
      printf("Usage :\n");
      printf("  ./main [sampling rate] [debug]\n");
      printf("\n");
      printf("Arguments :\n");
      printf("  - type: type of accelerometer : ADXL, LIS or MMA (string).\n");
      printf("  - sampling rate: in milliseconds, between 0 and 1000.\n");
      printf("  - debug: 1 or 0.\n");
      printf("\n");
      exit(0);
   } else if (argc == 2) {
      type = argv[1];
   } else if (argc == 3) {
      type = argv[1];
      sampling_rate_in_us = max(0, min(1000, atoi(argv[2]))) * 1000;
   } else if (argc == 4) {
      type = argv[1];
      sampling_rate_in_us = max(0, min(1000, atoi(argv[2]))) * 1000;
      debug_flag = argv[3][0] == '1' ? true : false;
      if (debug_flag) printf("Debug flag is TRUE.\n");
   } else {
      if (debug_flag) printf("Too many arguments supplied. Default sampling rate used.\n");
   }

   if (debug_flag) printf("Starting up.\n");
   if (debug_flag) printf("Sampling rate will be %d µs.\n", sampling_rate_in_us);
   if (debug_flag) printf("Accel. type is : %s.\n", type);
   if (debug_flag) printf("Initializing sensor pusher ...\n");

   // Configure the interface.
   fd_mpc3002_1 = wiringPiSPISetup(0, SPI_SPEED);
   fd_mpc3002_2 = wiringPiSPISetup(1, SPI_SPEED);

   if (debug_flag) printf("SPI setup : OK.\n");

   if (debug_flag) printf("Initing first MPC3002  : %d.\n", fd_mpc3002_1);
   if (debug_flag) printf("Initing second MPC3002 : %d.\n", fd_mpc3002_2);

   if (debug_flag) printf("\n");

   do {

      tic = clock();

      x = 0; y = 0; z = 0;
      for (int i = 0; i < 10; ++i)
      {
         if (strcmp(type,"ADXL")==0) {
            x += readADC(0) + X_OFFSET_ADXL;
            y += readADC(1) + Y_OFFSET_ADXL;
            z += readADC(2) + Z_OFFSET_ADXL;
         } else if (strcmp(type,"MMA")==0) {
            x += readADC(0) + X_OFFSET_MMA;
            y += readADC(1) + Y_OFFSET_MMA;
            z += readADC(2) + Z_OFFSET_MMA;
         }
      }

      // Average on 1ms approx.
      x = x/10;
      y = y/10;
      z = z/10;

      if (strcmp(type,"ADXL")==0) {
         xg = (double) x*G_COEF_ADXL;
         yg = (double) y*G_COEF_ADXL;
         zg = (double) z*G_COEF_ADXL;
      } else if (strcmp(type,"MMA")==0) {
         xg = (double) x*G_COEF_MMA;
         yg = (double) y*G_COEF_MMA;
         zg = (double) z*G_COEF_MMA;
      }

      // 1G on at least one axis triggers the output
      if ( xg*xg + yg*yg + zg*zg > MIN_TRIGGER || debug_flag) {
         // Format : X_10bit X_G Y_10bit Y_G Z_1Obit Z_G
         printf("%d %f %d %f %d %f\n", x, xg, y, yg, z, zg);

         if (debug_flag) {
            x_avg += x; y_avg += y; z_avg += z;
            count_avg++;
            printf("  [Average since launch %ld %ld %ld]\n", x_avg/count_avg, y_avg/count_avg, z_avg/count_avg);
         }
      }

      toc = clock();
      elapsed_time_in_us = (toc - tic) * ONE_OVER_CPS; // in microsecs
      if (debug_flag) printf("  [Sampling took %d us]\n", elapsed_time_in_us);

      usleep(sampling_rate_in_us - max(0, static_cast<int>(min(elapsed_time_in_us, sampling_rate_in_us))));

   } while(true);

   if (debug_flag) printf("Exiting");

}
<|endoftext|>


<commit_before>#include <iostream>
#include <opencv2/opencv.hpp>
#include "ImgReader.h"
#include "HSVConverter.h"
#include "HistogramCalculator.h"
#include "ImageSimilaritySorter.h"
#include "L1Distance.h"
#include "utils.h"

using namespace std;
using namespace cv;

int main(int argc, char **argv) {
    string dir = "data";
    vector<string> imgnames = ImgReader().get_filenames_from_dir(dir);
    vector<Mat> imgs = ImgReader().read_imgs_from_filenames(imgnames);
    cout << "read images: " << endl << imgnames << endl;

    vector<Mat> hsv_imgs = HSVConverter().convert_all(imgs);
    cout << "converted images to hsv space" << endl;

    vector<float> maxs = {0, 0, 0};
    for(Mat hsv_img : hsv_imgs) {
        for(int i = 0; i < hsv_img.rows; i++) {
            for(int j = 0; j < hsv_img.cols; j++) {
                maxs[0] = max(maxs[0], hsv_img.at<Vec3f>(i, j)[0]);
                maxs[1] = max(maxs[1], hsv_img.at<Vec3f>(i, j)[1]);
                maxs[2] = max(maxs[2], hsv_img.at<Vec3f>(i, j)[2]);
            }
        }
    }
    cout << "maximum hsv elements " << maxs << endl;

    Vec3i nbins(16, 3, 3);
    HistogramCalculator hist_calc(nbins, HSVConverter::hsv_range);
    vector<Mat> hsv_hists;
    for(Mat hsv_img : hsv_imgs) {
        hsv_hists.push_back(hist_calc.calc(hsv_img));
    }
    cout << "calculated histograms" << endl;

    vector<Mat> norm_hsv_hists;
    for(Mat &hist : hsv_hists){
        norm_hsv_hists.push_back(hist_calc.normalize(hist));
    }
    cout << "calculated normalized histograms" << endl;

    for(int img = 0; img < hsv_hists.size(); img++) {
        Mat &hist = hsv_hists[img];
        Mat &norm_hist = norm_hsv_hists[img];
        cout << "histogram of " << img << ":" << endl;
        for(int i = 0; i < nbins[0]; i++) {
            for(int j = 0; j < nbins[1]; j++) {
                for(int k = 0; k < nbins[2]; k++) {
                    Vec3i bin(i, j, k);
                    cout << "bin " << bin << ": abs " << hist.at<float>(i,j,k) << " norm " << norm_hist.at<float>(i,j,k);
                    cout << " (repr " << hist_calc.calc_repr(bin) << ")" << endl;
                }
            }
        }
        int bin_sum_abs = sum(hist)[0];
        float bin_sum_norm = sum(norm_hist)[0];
        cout << "bin sum abs " << bin_sum_abs << " expected " << hsv_imgs[img].total() << endl;
        cout << "bin sum norm " << bin_sum_norm << " expected 1" << endl;
    }

    int query_id = 1;
    vector<int> ids_sorted = ImageSimilaritySorter().sort_by_distance(query_id, norm_hsv_hists, L1Distance());
    cout << "images similar to " << query_id << ": " << ids_sorted << endl;

    for(int i = 0; i < imgs.size(); i++) {
        imshow(imgnames[i], imgs[i]);
    }
    waitKey();
    return 0;
}
<commit_msg>added funny image concatenation<commit_after>#include <iostream>
#include <opencv2/opencv.hpp>
#include "ImgReader.h"
#include "HSVConverter.h"
#include "HistogramCalculator.h"
#include "ImageSimilaritySorter.h"
#include "L1Distance.h"
#include "utils.h"

using namespace std;
using namespace cv;

int main(int argc, char **argv) {
    string dir = "data";
    vector<string> imgnames = ImgReader().get_filenames_from_dir(dir);
    vector<Mat> imgs = ImgReader().read_imgs_from_filenames(imgnames);
    cout << "read images: " << endl << imgnames << endl;

    vector<Mat> hsv_imgs = HSVConverter().convert_all(imgs);
    cout << "converted images to hsv space" << endl;

    vector<float> maxs = {0, 0, 0};
    for(Mat hsv_img : hsv_imgs) {
        for(int i = 0; i < hsv_img.rows; i++) {
            for(int j = 0; j < hsv_img.cols; j++) {
                maxs[0] = max(maxs[0], hsv_img.at<Vec3f>(i, j)[0]);
                maxs[1] = max(maxs[1], hsv_img.at<Vec3f>(i, j)[1]);
                maxs[2] = max(maxs[2], hsv_img.at<Vec3f>(i, j)[2]);
            }
        }
    }
    cout << "maximum hsv elements " << maxs << endl;

    Vec3i nbins(16, 3, 3);
    HistogramCalculator hist_calc(nbins, HSVConverter::hsv_range);
    vector<Mat> hsv_hists;
    for(Mat hsv_img : hsv_imgs) {
        hsv_hists.push_back(hist_calc.calc(hsv_img));
    }
    cout << "calculated histograms" << endl;

    vector<Mat> norm_hsv_hists;
    for(Mat &hist : hsv_hists){
        norm_hsv_hists.push_back(hist_calc.normalize(hist));
    }
    cout << "calculated normalized histograms" << endl;

    for(int img = 0; img < hsv_hists.size(); img++) {
        Mat &hist = hsv_hists[img];
        Mat &norm_hist = norm_hsv_hists[img];
        cout << "histogram of " << img << ":" << endl;
        for(int i = 0; i < nbins[0]; i++) {
            for(int j = 0; j < nbins[1]; j++) {
                for(int k = 0; k < nbins[2]; k++) {
                    Vec3i bin(i, j, k);
                    cout << "bin " << bin << ": abs " << hist.at<float>(i,j,k) << " norm " << norm_hist.at<float>(i,j,k);
                    cout << " (repr " << hist_calc.calc_repr(bin) << ")" << endl;
                }
            }
        }
        int bin_sum_abs = sum(hist)[0];
        float bin_sum_norm = sum(norm_hist)[0];
        cout << "bin sum abs " << bin_sum_abs << " expected " << hsv_imgs[img].total() << endl;
        cout << "bin sum norm " << bin_sum_norm << " expected 1" << endl;
    }

    int query_id = 1;
    vector<int> ids_sorted = ImageSimilaritySorter().sort_by_distance(query_id, norm_hsv_hists, L1Distance());
    cout << "images similar to " << query_id << ": " << ids_sorted << endl;

    vector<Mat> thumbnails;
    for(int i : ids_sorted){
        Mat res;
        cv::resize(imgs[i], res, Size(200, 200));
        thumbnails.push_back(res);
    }
    Mat conc_thumbnails;
    hconcat(thumbnails, conc_thumbnails);

    imshow("most similar images", conc_thumbnails);
    //for(int i = 0; i < imgs.size(); i++) {
    //    imshow(imgnames[i], imgs[i]);
    //}

    waitKey();
    return 0;
}
<|endoftext|>


<commit_before>#include <cstdlib>
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <vector>
#include <deque>
#include <map>
#include <unordered_map>
#include <memory>

#include <cstdio>
#include <readline/readline.h>
#include "Parsers.hpp"

using namespace std;

using Parsers::Parser;
using Parsers::satisfy;
using Parsers::anyChar;
using Parsers::spaces;

const Parser alpha(satisfy([](char c){
  if(isgraph(c) && c != '(' && c != ')' && c != '\\'){
    return true;
  }
  return false;
}));

const Parser identifier(+alpha);
const Parser lambda('\\');
const Parser leftBracket('(');
const Parser rightBracket(')');
const Parser panic(anyChar[ ([](const string& str){ cerr << "[Lex] Unexpected input: " << str << endl;}) ]);

class Token{
  public:
    enum Type{Undefined, Identifier, Lambda, LeftBracket, RightBracket, EndOfFile} type;
    std::string name;

    Token() : type(Undefined), name() {}
    Token(const string& str) : type(Undefined), name(str) {}
    Token(Type t) : type(t), name() {}
    Token(Type t, const string& str) : type(t), name(str) {}
};

Parser tokenParser(Token& token){
  auto f = [&token](Token::Type t){
    return [&token, t](const string& str){ token = Token(t, str);};
  };
  return (identifier[f(Token::Identifier)]
      | lambda[f(Token::Lambda)]
      | leftBracket[f(Token::LeftBracket)]
      | rightBracket[f(Token::RightBracket)]
      | panic[f(Token::Undefined)]
      );
}

class Scanner{
    deque<Token> tokens;
  public:
    Scanner(const string& buffer){
      auto first = buffer.begin(), last = buffer.end();
      Token token;
      while(first != last){
        tie(ignore, first) = spaces.runParser(first, last);
        if(first == last) break;
        tie(ignore, first) = tokenParser(token).runParser(first, last);
        tokens.push_back(token);
      }
    }

    Token getToken(){
      if(tokens.empty()) return Token(Token::EndOfFile, "EOF");
      Token token = tokens.front();
      tokens.pop_front();
      return token;
    }

    Token peekToken(){
      if(tokens.empty()) return Token(Token::EndOfFile, "EOF");
      return tokens.front();
    }

    void ungetToken(const Token& token){
      if(token.type == Token::EndOfFile) return ;
      tokens.push_front(token);
    }

    bool eof(){
      return tokens.empty();
    }
};

class Expression{
  public:
    enum Type{Nothing, Var, Lambda, Ap} type;
    string name;
    shared_ptr<Expression> body, arg;

    Expression() : type(Nothing), name(), body(), arg() {}
    Expression(Type t) : type(t), name(), body(), arg() {}
    Expression(const Expression& expr) : type(expr.type), name(expr.name), body(expr.body), arg(expr.arg) {}

    bool isVar() const { return type == Var;}
    bool isLam() const { return type == Lambda;}
    bool isAp() const { return type == Ap;}
    void print() const ;
    void prettyPrint() const ;
};

shared_ptr<Expression> parseExpression(Scanner&);
shared_ptr<Expression> parseExpressionTail(Scanner&);

shared_ptr<Expression> parseExpression(Scanner &scanner){
  shared_ptr<Expression> expr(parseExpressionTail(scanner));
  while(true){
    switch(scanner.peekToken().type){
      case Token::RightBracket:
      case Token::EndOfFile:
        return expr;

      default: break;
    }
    shared_ptr<Expression> expr1(new Expression(Expression::Ap));
    expr1->body = expr;
    expr1->arg  = parseExpressionTail(scanner);
    expr = expr1;
  }
}

shared_ptr<Expression> parseExpressionTail(Scanner &scanner){
  Token token = scanner.getToken();
  shared_ptr<Expression> expr(nullptr);
  switch(token.type){
    case Token::Lambda:
      token = scanner.getToken();
      if(token.type != Token::Identifier){
        cerr << "[Parse] Expected an identifier: " << token.name << endl;
        exit(1);
      }
      expr.reset(new Expression(Expression::Lambda));
      expr->name = token.name;
      expr->body = parseExpression(scanner);
      return expr;

    case Token::Identifier:
      expr.reset(new Expression(Expression::Var));
      expr->name = token.name;
      return expr;

    case Token::LeftBracket:
      expr = parseExpression(scanner);
      token = scanner.getToken();
      if(token.type != Token::RightBracket){
        cerr << "[Parse] Expected a `)`: " << token.name << endl;
        exit(1);
      }
      return expr;

    case Token::RightBracket:
    case Token::EndOfFile:
    default:
      cerr << "[Parse] Unexpected token: " << token.name << endl;
      exit(1);
  }
}

/* Data structures
 *
 * data Expression = Var | Lambda | Ap
 *
 * type Primitive = Var -> Expression
 * data Object = Object Expression Context | Primitive Context
 * data Context = [(Var, Object)]
 * type Var = String
 *
 * weakNormalForm :: Object -> Object
 * normalForm :: Object -> Object
 *
 * weakNormalForm / normalForm morphs a object (beta reduction)
 *
 */

class Object;
class Context;

class Context{
    unordered_map<string, shared_ptr<Object>> _env;
  public:
    Context() : _env() {}
    Context(const Context& context) : _env(context._env) {}

    shared_ptr<Context> insert(const string&, const shared_ptr<Object>) const;
    shared_ptr<Context> erase(const string&) const;
    shared_ptr<Object> lookup(const string&) const;
    shared_ptr<Object> operator [] (const string&) const;
    bool exist(const string&) const;
};

shared_ptr<Context> Context::insert(const string& str, const shared_ptr<Object> obj) const {
  shared_ptr<Context> env(new Context(*this));
  env->_env[str] = obj;
  return env;
}

shared_ptr<Context> Context::erase(const string& str) const {
  shared_ptr<Context> env(new Context(*this));
  env->_env.erase(str);
  return env;
}

shared_ptr<Object> Context::lookup(const string& str) const {
  auto it = _env.find(str);
  if(it == _env.cend()){
    cerr << "[Context lookup] Unbounded variable: " << str << endl;
    exit(1);
  }
  return it->second;
}

shared_ptr<Object> Context::operator [] (const string& str) const {
  return lookup(str);
}

bool Context::exist(const string& str) const {
  if(_env.count(str) > 0) return true;
  return false;
}

class Object{
  public:
    shared_ptr<Expression> _expr;
    shared_ptr<Context> _env;

    Object(){}
    Object(shared_ptr<Expression> expr) : _expr(expr), _env(new Context) {}
    Object(shared_ptr<Expression> expr, shared_ptr<Context> env) : _expr(expr), _env(env){}

    Object weakNormalForm();
    Object normalForm();

    string& name(){ return _expr->name;}
    shared_ptr<Expression>& body(){ return _expr->body;}
    shared_ptr<Expression>& arg(){ return _expr->arg;}
};

Object Object::weakNormalForm(){
  if(_expr->isVar()){
    if(_env->exist( name() )){
      return (*this) = _env->lookup( name() )->weakNormalForm();
    }else{
      return (*this) = Object(_expr);
    }
  }else if(_expr->isLam()){
    return *this;
  }else if(_expr->isAp()){
    Object obj2(body(), _env);
    obj2 = obj2.weakNormalForm();
    if(obj2._expr->isLam()){
      return (*this) = Object(obj2.body(), obj2._env->insert(obj2.name(), shared_ptr<Object>(new Object(arg(), _env)))).weakNormalForm();
    }else{
      Object obj3(shared_ptr<Expression>(new Expression(Expression::Ap)), _env);
      obj3.body() = Object(body(), _env).weakNormalForm()._expr;
      obj3.arg()  = Object(arg(), _env).normalForm()._expr;
      return (*this) = obj3;
    }
  }else{
    cerr << "[Weak Normal Form] Unexpected Expression type: " << _expr->type << endl;
    exit(1);
  }
}

Object Object::normalForm(){
  if(_expr->isVar()){
    if(_env->exist( name() )){
      return (*this) = _env->lookup( name() )->normalForm();
    }else{
      return (*this) = Object(_expr);
    }
  }else if(_expr->isLam()){
    Object obj2(shared_ptr<Expression>(new Expression(*_expr)), _env);
    obj2.body() = Object(body(), _env->erase(name())).normalForm()._expr;
    return (*this) = obj2;
  }else if(_expr->isAp()){
    Object obj2(body(), _env);
    obj2 = obj2.weakNormalForm();
    if(obj2._expr->isLam()){
      return (*this) = Object(obj2.body(), obj2._env->insert(obj2.name(), shared_ptr<Object>(new Object(arg(), _env)))).normalForm();
    }else{
      Object obj3(shared_ptr<Expression>(new Expression(Expression::Ap)), _env);
      obj3.body() = Object(body(), _env).weakNormalForm()._expr;
      obj3.arg()  = Object(arg(), _env).normalForm()._expr;
      return (*this) = obj3;
    }
  }else{
    cerr << "[Weak Normal Form] Unexpected Expression type: " << _expr->type << endl;
    exit(1);
  }
}

int main(int argc, char *argv[])
{
  string rawInput;
  while(true){
    char *input = readline("Prelude> ");
    if(input == nullptr){
      cout << endl;
      break;
    }
    rawInput += input;
    rawInput += "\n";
    free(input);
  }

  Scanner scanner(rawInput);

  shared_ptr<Expression> expr = parseExpression(scanner);

  expr->print();
  cout << endl;
  cout << endl;

  Object(expr).normalForm()._expr->prettyPrint();
  cout << endl;

  cout << "\nLeaving main\n";
  return 0;
}

void Expression::print() const {
  switch(type){
    case Nothing:
      cerr << "[Expression] Unexpected expression type: Nothing" << endl;
      break;

    case Var:
      cout << "[\"var\",\"" << name << "\"]";
      break;

    case Lambda:
      cout << "[\"lam\",\"" << name << "\",";
      body->print();
      cout << "]";
      break;

    case Ap:
      cout << "[\"app\",";
      body->print();
      cout << ",";
      arg->print();
      cout << "]";
      break;

  }
}

void Expression::prettyPrint() const {
  if(isVar()){
    cout << name;
  }else if(isLam()){
    cout << "\\" << name << " ";
    body->prettyPrint();
  }else if(isAp()){
    if(body->isLam() || body->isAp()) cout << "(";
    body->prettyPrint();
    if(body->isLam() || body->isAp()) cout << ")";
    cout << " ";
    if(arg->isLam() || arg->isAp()) cout << "(";
    arg->prettyPrint();
    if(arg->isLam() || arg->isAp()) cout << ")";
  }else{
    cerr << "[Expression] Unexpected expression type: Nothing" << endl;
  }
}
<commit_msg>prelude: logic operation<commit_after>#include <cstdlib>
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <vector>
#include <deque>
#include <map>
#include <unordered_map>
#include <memory>

#include <cstdio>
#include <readline/readline.h>
#include "Parsers.hpp"

using namespace std;

using Parsers::Parser;
using Parsers::satisfy;
using Parsers::anyChar;
using Parsers::spaces;

const Parser alpha(satisfy([](char c){
  if(isgraph(c) && c != '(' && c != ')' && c != '\\'){
    return true;
  }
  return false;
}));

const Parser identifier(+alpha);
const Parser lambda('\\');
const Parser leftBracket('(');
const Parser rightBracket(')');
const Parser panic(anyChar[ ([](const string& str){ cerr << "[Lex] Unexpected input: " << str << endl;}) ]);

class Token{
  public:
    enum Type{Undefined, Identifier, Lambda, LeftBracket, RightBracket, EndOfFile} type;
    std::string name;

    Token() : type(Undefined), name() {}
    Token(const string& str) : type(Undefined), name(str) {}
    Token(Type t) : type(t), name() {}
    Token(Type t, const string& str) : type(t), name(str) {}
};

Parser tokenParser(Token& token){
  auto f = [&token](Token::Type t){
    return [&token, t](const string& str){ token = Token(t, str);};
  };
  return (identifier[f(Token::Identifier)]
      | lambda[f(Token::Lambda)]
      | leftBracket[f(Token::LeftBracket)]
      | rightBracket[f(Token::RightBracket)]
      | panic[f(Token::Undefined)]
      );
}

class Scanner{
    deque<Token> tokens;
  public:
    Scanner(const string& buffer){
      auto first = buffer.begin(), last = buffer.end();
      Token token;
      while(first != last){
        tie(ignore, first) = spaces.runParser(first, last);
        if(first == last) break;
        tie(ignore, first) = tokenParser(token).runParser(first, last);
        tokens.push_back(token);
      }
    }

    Token getToken(){
      if(tokens.empty()) return Token(Token::EndOfFile, "EOF");
      Token token = tokens.front();
      tokens.pop_front();
      return token;
    }

    Token peekToken(){
      if(tokens.empty()) return Token(Token::EndOfFile, "EOF");
      return tokens.front();
    }

    void ungetToken(const Token& token){
      if(token.type == Token::EndOfFile) return ;
      tokens.push_front(token);
    }

    bool eof(){
      return tokens.empty();
    }
};

class Expression{
  public:
    enum Type{Nothing, Var, Lambda, Ap} type;
    string name;
    shared_ptr<Expression> body, arg;

    Expression() : type(Nothing), name(), body(), arg() {}
    Expression(Type t) : type(t), name(), body(), arg() {}
    Expression(const Expression& expr) : type(expr.type), name(expr.name), body(expr.body), arg(expr.arg) {}

    bool isVar() const { return type == Var;}
    bool isLam() const { return type == Lambda;}
    bool isAp() const { return type == Ap;}
    void print() const ;
    void prettyPrint() const ;
};

shared_ptr<Expression> parseExpression(Scanner&);
shared_ptr<Expression> parseExpressionTail(Scanner&);

shared_ptr<Expression> parseExpression(Scanner &scanner){
  shared_ptr<Expression> expr(parseExpressionTail(scanner));
  while(true){
    switch(scanner.peekToken().type){
      case Token::RightBracket:
      case Token::EndOfFile:
        return expr;

      default: break;
    }
    shared_ptr<Expression> expr1(new Expression(Expression::Ap));
    expr1->body = expr;
    expr1->arg  = parseExpressionTail(scanner);
    expr = expr1;
  }
}

shared_ptr<Expression> parseExpressionTail(Scanner &scanner){
  Token token = scanner.getToken();
  shared_ptr<Expression> expr(nullptr);
  switch(token.type){
    case Token::Lambda:
      token = scanner.getToken();
      if(token.type != Token::Identifier){
        cerr << "[Parse] Expected an identifier: " << token.name << endl;
        exit(1);
      }
      expr.reset(new Expression(Expression::Lambda));
      expr->name = token.name;
      expr->body = parseExpression(scanner);
      return expr;

    case Token::Identifier:
      expr.reset(new Expression(Expression::Var));
      expr->name = token.name;
      return expr;

    case Token::LeftBracket:
      expr = parseExpression(scanner);
      token = scanner.getToken();
      if(token.type != Token::RightBracket){
        cerr << "[Parse] Expected a `)`: " << token.name << endl;
        exit(1);
      }
      return expr;

    case Token::RightBracket:
    case Token::EndOfFile:
    default:
      cerr << "[Parse] Unexpected token: " << token.name << endl;
      exit(1);
  }
}

/* Data structures
 *
 * data Expression = Var | Lambda | Ap
 *
 * type Primitive = Var -> Expression
 * data Object = Object Expression Context | Primitive Context
 * data Context = [(Var, Object)]
 *
 * weakNormalForm :: Object -> Object
 * normalForm :: Object -> Object
 *
 * weakNormalForm / normalForm morphs a object (beta reduction)
 *
 */

class Object;
class Context;

class Context{
    unordered_map<string, shared_ptr<Object>> _env;
  public:
    Context() : _env() {}
    Context(const Context& context) : _env(context._env) {}

    Context& add(const string&, const string&);
    shared_ptr<Context> insert(const string&, const shared_ptr<Object>) const;
    shared_ptr<Context> erase(const string&) const;
    shared_ptr<Object> lookup(const string&) const;
    shared_ptr<Object> operator [] (const string&) const;
    bool exist(const string&) const;
};

class Object{
  public:
    shared_ptr<Expression> _expr;
    shared_ptr<Context> _env;

    Object(){}
    Object(shared_ptr<Expression> expr) : _expr(expr), _env(new Context) {}
    Object(shared_ptr<Expression> expr, shared_ptr<Context> env) : _expr(expr), _env(env){}

    Object weakNormalForm();
    Object normalForm();

    string& name(){ return _expr->name;}
    shared_ptr<Expression>& body(){ return _expr->body;}
    shared_ptr<Expression>& arg(){ return _expr->arg;}
};

Context& Context::add(const string& name, const string& rule){
  Scanner scanner(rule);
  auto expr = parseExpression(scanner);
  shared_ptr<Context> env(new Context(*this));
  _env[name].reset(new Object(expr, env));
  return *this;
}

shared_ptr<Context> Context::insert(const string& str, const shared_ptr<Object> obj) const {
  shared_ptr<Context> env(new Context(*this));
  env->_env[str] = obj;
  return env;
}

shared_ptr<Context> Context::erase(const string& str) const {
  shared_ptr<Context> env(new Context(*this));
  env->_env.erase(str);
  return env;
}

shared_ptr<Object> Context::lookup(const string& str) const {
  auto it = _env.find(str);
  if(it == _env.cend()){
    cerr << "[Context lookup] Unbounded variable: " << str << endl;
    exit(1);
  }
  return it->second;
}

shared_ptr<Object> Context::operator [] (const string& str) const {
  return lookup(str);
}

bool Context::exist(const string& str) const {
  if(_env.count(str) > 0) return true;
  return false;
}

Object Object::weakNormalForm(){
  if(_expr->isVar()){
    if(_env->exist( name() )){
      return (*this) = _env->lookup( name() )->weakNormalForm();
    }else{
      return (*this) = Object(_expr);
    }
  }else if(_expr->isLam()){
    return *this;
  }else if(_expr->isAp()){
    Object obj2(body(), _env);
    obj2 = obj2.weakNormalForm();
    if(obj2._expr->isLam()){
      return (*this) = Object(obj2.body(), obj2._env->insert(obj2.name(), shared_ptr<Object>(new Object(arg(), _env)))).weakNormalForm();
    }else{
      Object obj3(shared_ptr<Expression>(new Expression(Expression::Ap)), _env);
      obj3.body() = Object(body(), _env).weakNormalForm()._expr;
      obj3.arg()  = Object(arg(), _env).normalForm()._expr;
      return (*this) = obj3;
    }
  }else{
    cerr << "[Weak Normal Form] Unexpected Expression type: " << _expr->type << endl;
    exit(1);
  }
}

Object Object::normalForm(){
  if(_expr->isVar()){
    if(_env->exist( name() )){
      return (*this) = _env->lookup( name() )->normalForm();
    }else{
      return (*this) = Object(_expr);
    }
  }else if(_expr->isLam()){
    Object obj2(shared_ptr<Expression>(new Expression(*_expr)), _env);
    obj2.body() = Object(body(), _env->erase(name())).normalForm()._expr;
    return (*this) = obj2;
  }else if(_expr->isAp()){
    Object obj2(body(), _env);
    obj2 = obj2.weakNormalForm();
    if(obj2._expr->isLam()){
      return (*this) = Object(obj2.body(), obj2._env->insert(obj2.name(), shared_ptr<Object>(new Object(arg(), _env)))).normalForm();
    }else{
      Object obj3(shared_ptr<Expression>(new Expression(Expression::Ap)), _env);
      obj3.body() = Object(body(), _env).weakNormalForm()._expr;
      obj3.arg()  = Object(arg(), _env).normalForm()._expr;
      return (*this) = obj3;
    }
  }else{
    cerr << "[Weak Normal Form] Unexpected Expression type: " << _expr->type << endl;
    exit(1);
  }
}

int main(int argc, char *argv[])
{
  string rawInput;
  while(true){
    char *input = readline("Prelude> ");
    if(input == nullptr){
      cout << endl;
      break;
    }
    rawInput += input;
    rawInput += "\n";
    free(input);
  }

  Scanner scanner(rawInput);

  shared_ptr<Expression> expr = parseExpression(scanner);

  expr->print();
  cout << endl;
  cout << endl;

  shared_ptr<Context> prelude(new Context);

  prelude->add("bool", "\\x x true false");
  prelude->add("true", "\\a \\b a");
  prelude->add("false", "\\a \\b b");
  prelude->add("if", "\\pred \\then \\else pred then else");
  prelude->add("not", "\\x x false true");
  prelude->add("and", "\\x \\y x y false");
  prelude->add("or", "\\x \\y x true y");
  prelude->add("Y", "\\f (\\x f (x x)) (\\x f (x x))");

  Object(expr, prelude).normalForm()._expr->prettyPrint();
  cout << endl;

  cout << "\nLeaving main\n";
  return 0;
}

void Expression::print() const {
  switch(type){
    case Nothing:
      cerr << "[Expression] Unexpected expression type: Nothing" << endl;
      break;

    case Var:
      cout << "[\"var\",\"" << name << "\"]";
      break;

    case Lambda:
      cout << "[\"lam\",\"" << name << "\",";
      body->print();
      cout << "]";
      break;

    case Ap:
      cout << "[\"app\",";
      body->print();
      cout << ",";
      arg->print();
      cout << "]";
      break;

  }
}

void Expression::prettyPrint() const {
  if(isVar()){
    cout << name;
  }else if(isLam()){
    cout << "\\" << name << " ";
    body->prettyPrint();
  }else if(isAp()){
    if(body->isLam() || body->isAp()) cout << "(";
    body->prettyPrint();
    if(body->isLam() || body->isAp()) cout << ")";
    cout << " ";
    if(arg->isLam() || arg->isAp()) cout << "(";
    arg->prettyPrint();
    if(arg->isLam() || arg->isAp()) cout << ")";
  }else{
    cerr << "[Expression] Unexpected expression type: Nothing" << endl;
  }
}
<|endoftext|>


<commit_before>#include <iostream>

#include "fixed_point.hpp"

int main() {
    auto g1 = [](double x) -> double {
        return (x * x + 2) / 3;
    };

    // will result in NaNs because the value under the square root
    // will become negative at some point.
    auto g2 = [](double x) -> double {
        return std::sqrt(3 * x - 2);
    };

    auto g3 = [](double x) -> double {
        return 3 - (2 / x);
    };

    auto g4 = [](double x) -> double {
        return (x * x  - 2) / (2 * x - 3);
    };

    std::vector<std::function<double(double)>> vec {g1, g2, g3, g4};
    std::vector<std::string> filenames {"g1.txt", "g2.txt", "g3.txt", "g4.txt"};
    std::vector<std::string> funcnames {"g1", "g2", "g3", "g4"};
    const double x0 = 0;
    const double abstol = 5e-7;

    for (auto i = 0; i < vec.size(); ++i) {
        fp::test_fixed_point(vec[i], x0, abstol, funcnames[i], filenames[i]);
    }
}<commit_msg>Correctly calculating some derivatives.<commit_after>#include <iostream>

#include "derivative.hpp"

int f(int, int, int)
{
    return 0;
}

double g(double*, char*, std::ostream&)
{
    return 0.0;
}

double f1(double x)
{
    return x * x;
}

double f2(double x)
{
    return 2 * x * x + 3 * x;
}

int main() {

    auto df1 = fp::derivative(f1, 1.);
    auto df2 = fp::derivative(f2, 1.0 / 2.0);

    std::cout << df1 << std::endl;
    std::cout << df2 << std::endl;
}<|endoftext|>


<commit_before>aaf0dd2b-4b02-11e5-ae33-28cfe9171a43<commit_msg>The previous fix has been fixed<commit_after>aafe6f6b-4b02-11e5-a811-28cfe9171a43<|endoftext|>


<commit_before>cf838a78-ad59-11e7-8ea0-ac87a332f658<commit_msg>I am finally done<commit_after>d03d1830-ad59-11e7-ab85-ac87a332f658<|endoftext|>


<commit_before>7393241e-4b02-11e5-9953-28cfe9171a43<commit_msg>Really doesn't crash if X, now<commit_after>739def21-4b02-11e5-a6df-28cfe9171a43<|endoftext|>