<commit_before>#include "./default_scene_creator.h"
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <string>
#include <vector>
#include "./importer.h"
#include "./nodes.h"
#include "./mesh_node.h"
#include "./label_node.h"
#include "./volume_node.h"
#include "./camera_node.h"
#include "./utils/persister.h"

BOOST_CLASS_EXPORT_GUID(LabelNode, "LabelNode")
BOOST_CLASS_EXPORT_GUID(MeshNode, "MeshNode")
BOOST_CLASS_EXPORT_GUID(VolumeNode, "VolumeNode")
BOOST_CLASS_EXPORT_GUID(CameraNode, "CameraNode")

DefaultSceneCreator::DefaultSceneCreator(std::shared_ptr<Nodes> nodes,
                                         std::shared_ptr<Labels> labels)
  : nodes(nodes), labels(labels)
{
}

void addLIDCIDRINodes(std::vector<std::shared_ptr<Node>> &sceneNodes)
{
  Eigen::Affine3f trans(
      Eigen::Scaling(2.0f) *
      Eigen::Translation3f(Eigen::Vector3f(0.15, 0.145f, 0.15)) *
      Eigen::AngleAxisf(M_PI, Eigen::Vector3f::UnitY()) *
      Eigen::AngleAxisf(0.5 * M_PI, Eigen::Vector3f::UnitX()));

  sceneNodes.push_back(std::make_shared<VolumeNode>(
      "assets/datasets/LIDC-IDRI-0469_lung2.mha",
      "assets/transferfunctions/LIDC-IDRI-0469.gra", trans.matrix(), false));
  sceneNodes.push_back(std::make_shared<VolumeNode>(
      "assets/datasets/LIDC-IDRI-0469_lesion1_mask_extracted_blurred.mha",
      "assets/transferfunctions/LIDC_IDRI_lesions_mask.gra", trans.matrix(), false));
  sceneNodes.push_back(std::make_shared<VolumeNode>(
      "assets/datasets/LIDC-IDRI-0469_lesion2_mask_extracted_blurred.mha",
      "assets/transferfunctions/LIDC_IDRI_lesions_mask.gra", trans.matrix(), false));
  sceneNodes.push_back(std::make_shared<VolumeNode>(
      "assets/datasets/LIDC-IDRI-0469_lesion3_mask_extracted_blurred.mha",
      "assets/transferfunctions/LIDC_IDRI_lesions_mask.gra", trans.matrix(), false));
  sceneNodes.push_back(std::make_shared<VolumeNode>(
      "assets/datasets/LIDC-IDRI-0469_lesion4_mask_extracted_blurred.mha",
      "assets/transferfunctions/LIDC_IDRI_lesions_mask.gra", trans.matrix(), false));
}

void DefaultSceneCreator::create()
{
  std::vector<std::shared_ptr<Node>> sceneNodes;
  // addMeshNodesTo(sceneNodes);
  // addLabelNodesTo(sceneNodes);
  Eigen::Affine3f trans(
      Eigen::AngleAxisf(-0.5 * M_PI, Eigen::Vector3f::UnitX()));
  sceneNodes.push_back(std::make_shared<VolumeNode>(
      "assets/datasets/delikt_messer_256.mha",
      "assets/transferfunctions/scapula4.gra",
      trans.matrix(), true));
  // addMultiVolumeNodesTo(sceneNodes);

  Persister::save(sceneNodes, "config/scene.xml");

  // nodes->addSceneNodesFrom("config/scene.xml");
  for (auto &node : sceneNodes)
    nodes->addNode(node);
}

void DefaultSceneCreator::addMeshNodesTo(
    std::vector<std::shared_ptr<Node>> &sceneNodes)
{
  const std::string filename = "assets/human-edited.dae";
  Importer importer;

  for (unsigned int meshIndex = 0; meshIndex < 2; ++meshIndex)
  {
    auto mesh = importer.import(filename, meshIndex);
    auto transformation = importer.getTransformationFor(filename, meshIndex);
    auto node = new MeshNode(filename, meshIndex, mesh, transformation);
    sceneNodes.push_back(std::unique_ptr<MeshNode>(node));
  }
}

void DefaultSceneCreator::addLabelNodesTo(
    std::vector<std::shared_ptr<Node>> &sceneNodes)
{
  auto label = Label(1, "Shoulder", Eigen::Vector3f(0.174f, 0.55f, 0.034f));
  sceneNodes.push_back(std::make_shared<LabelNode>(label));

  auto label2 = Label(2, "Ellbow", Eigen::Vector3f(0.34f, 0.322f, -0.007f));
  sceneNodes.push_back(std::make_shared<LabelNode>(label2));

  auto label3 = Label(3, "Wound", Eigen::Vector3f(0.262f, 0.422f, 0.058f),
                      Eigen::Vector2i(128, 128));
  sceneNodes.push_back(std::make_shared<LabelNode>(label3));

  auto label4 = Label(4, "Wound 2", Eigen::Vector3f(0.034f, 0.373f, 0.141f));
  sceneNodes.push_back(std::make_shared<LabelNode>(label4));
}

void DefaultSceneCreator::addMultiVolumeNodesTo(
    std::vector<std::shared_ptr<Node>> &sceneNodes)
{
  sceneNodes.push_back(std::make_shared<VolumeNode>(
      "assets/datasets/GRCH_Abdomen.mhd",
      "assets/transferfunctions/scapula4.gra", Eigen::Matrix4f::Identity()));
  sceneNodes.push_back(std::make_shared<VolumeNode>(
      "assets/datasets/GRCH_Schaedel_fein_H31.mhd",
      "assets/transferfunctions/scapula4.gra", Eigen::Matrix4f::Identity()));
}

<commit_msg>Minor: fix linting errors.<commit_after>#include "./default_scene_creator.h"
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <string>
#include <vector>
#include "./importer.h"
#include "./nodes.h"
#include "./mesh_node.h"
#include "./label_node.h"
#include "./volume_node.h"
#include "./camera_node.h"
#include "./utils/persister.h"

BOOST_CLASS_EXPORT_GUID(LabelNode, "LabelNode")
BOOST_CLASS_EXPORT_GUID(MeshNode, "MeshNode")
BOOST_CLASS_EXPORT_GUID(VolumeNode, "VolumeNode")
BOOST_CLASS_EXPORT_GUID(CameraNode, "CameraNode")

DefaultSceneCreator::DefaultSceneCreator(std::shared_ptr<Nodes> nodes,
                                         std::shared_ptr<Labels> labels)
  : nodes(nodes), labels(labels)
{
}

void addLIDCIDRINodes(std::vector<std::shared_ptr<Node>> &sceneNodes)
{
  Eigen::Affine3f trans(
      Eigen::Scaling(2.0f) *
      Eigen::Translation3f(Eigen::Vector3f(0.15, 0.145f, 0.15)) *
      Eigen::AngleAxisf(M_PI, Eigen::Vector3f::UnitY()) *
      Eigen::AngleAxisf(0.5 * M_PI, Eigen::Vector3f::UnitX()));

  sceneNodes.push_back(std::make_shared<VolumeNode>(
      "assets/datasets/LIDC-IDRI-0469_lung2.mha",
      "assets/transferfunctions/LIDC-IDRI-0469.gra", trans.matrix(), false));
  sceneNodes.push_back(std::make_shared<VolumeNode>(
      "assets/datasets/LIDC-IDRI-0469_lesion1_mask_extracted_blurred.mha",
      "assets/transferfunctions/LIDC_IDRI_lesions_mask.gra", trans.matrix(),
      false));
  sceneNodes.push_back(std::make_shared<VolumeNode>(
      "assets/datasets/LIDC-IDRI-0469_lesion2_mask_extracted_blurred.mha",
      "assets/transferfunctions/LIDC_IDRI_lesions_mask.gra", trans.matrix(),
      false));
  sceneNodes.push_back(std::make_shared<VolumeNode>(
      "assets/datasets/LIDC-IDRI-0469_lesion3_mask_extracted_blurred.mha",
      "assets/transferfunctions/LIDC_IDRI_lesions_mask.gra", trans.matrix(),
      false));
  sceneNodes.push_back(std::make_shared<VolumeNode>(
      "assets/datasets/LIDC-IDRI-0469_lesion4_mask_extracted_blurred.mha",
      "assets/transferfunctions/LIDC_IDRI_lesions_mask.gra", trans.matrix(),
      false));
}

void DefaultSceneCreator::create()
{
  std::vector<std::shared_ptr<Node>> sceneNodes;
  // addMeshNodesTo(sceneNodes);
  // addLabelNodesTo(sceneNodes);
  Eigen::Affine3f trans(
      Eigen::AngleAxisf(-0.5 * M_PI, Eigen::Vector3f::UnitX()));
  sceneNodes.push_back(std::make_shared<VolumeNode>(
      "assets/datasets/delikt_messer_256.mha",
      "assets/transferfunctions/scapula4.gra", trans.matrix(), true));
  // addMultiVolumeNodesTo(sceneNodes);

  Persister::save(sceneNodes, "config/scene.xml");

  // nodes->addSceneNodesFrom("config/scene.xml");
  for (auto &node : sceneNodes)
    nodes->addNode(node);
}

void DefaultSceneCreator::addMeshNodesTo(
    std::vector<std::shared_ptr<Node>> &sceneNodes)
{
  const std::string filename = "assets/human-edited.dae";
  Importer importer;

  for (unsigned int meshIndex = 0; meshIndex < 2; ++meshIndex)
  {
    auto mesh = importer.import(filename, meshIndex);
    auto transformation = importer.getTransformationFor(filename, meshIndex);
    auto node = new MeshNode(filename, meshIndex, mesh, transformation);
    sceneNodes.push_back(std::unique_ptr<MeshNode>(node));
  }
}

void DefaultSceneCreator::addLabelNodesTo(
    std::vector<std::shared_ptr<Node>> &sceneNodes)
{
  auto label = Label(1, "Shoulder", Eigen::Vector3f(0.174f, 0.55f, 0.034f));
  sceneNodes.push_back(std::make_shared<LabelNode>(label));

  auto label2 = Label(2, "Ellbow", Eigen::Vector3f(0.34f, 0.322f, -0.007f));
  sceneNodes.push_back(std::make_shared<LabelNode>(label2));

  auto label3 = Label(3, "Wound", Eigen::Vector3f(0.262f, 0.422f, 0.058f),
                      Eigen::Vector2i(128, 128));
  sceneNodes.push_back(std::make_shared<LabelNode>(label3));

  auto label4 = Label(4, "Wound 2", Eigen::Vector3f(0.034f, 0.373f, 0.141f));
  sceneNodes.push_back(std::make_shared<LabelNode>(label4));
}

void DefaultSceneCreator::addMultiVolumeNodesTo(
    std::vector<std::shared_ptr<Node>> &sceneNodes)
{
  sceneNodes.push_back(std::make_shared<VolumeNode>(
      "assets/datasets/GRCH_Abdomen.mhd",
      "assets/transferfunctions/scapula4.gra", Eigen::Matrix4f::Identity()));
  sceneNodes.push_back(std::make_shared<VolumeNode>(
      "assets/datasets/GRCH_Schaedel_fein_H31.mhd",
      "assets/transferfunctions/scapula4.gra", Eigen::Matrix4f::Identity()));
}

<|endoftext|>


<commit_before>/*
 * <one line to give the library's name and an idea of what it does.>
 * Copyright 2013  David Edmundson <d.edmundson@lboro.ac.uk>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License or (at your option) version 3 or any later version
 * accepted by the membership of KDE e.V. (or its successor approved
 * by the membership of KDE e.V.), which shall act as a proxy
 * defined in Section 14 of version 3 of the license.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "defaultcontactmonitor_p.h"

DefaultContactMonitor::DefaultContactMonitor(const QString &contactId, const AllContactsMonitorPtr& allContactsWatcher):
    ContactMonitor(contactId),
    m_allContactsMonitor(allContactsWatcher)
{
    connect(allContactsWatcher.data(), SIGNAL(contactAdded(QString,KABC::Addressee)), SLOT(onContactAdded(QString,KABC::Addressee)));
    connect(allContactsWatcher.data(), SIGNAL(contactRemoved(QString)), SLOT(onContactRemoved(QString)));
    connect(allContactsWatcher.data(), SIGNAL(contactChanged(QString,KABC::Addressee)), SLOT(onContactChanged(QString,KABC::Addressee)));

    const KABC::Addressee contact = m_allContactsMonitor->contacts()[contactId];
    if (!contact.isEmpty()) {
        setContact(contact);
    }
}

void DefaultContactMonitor::onContactAdded(const QString& id, const KABC::Addressee& contact)
{
    if (id == contactId()) {
        setContact(contact);
    }
}

void DefaultContactMonitor::onContactChanged(const QString& id, const KABC::Addressee& contact)
{
    if (id == contactId()) {
        setContact(contact);
    }
}

void DefaultContactMonitor::onContactRemoved(const QString& id)
{
    if (id == contactId()) {
        setContact(KABC::Addressee());
    }
}

#include "defaultcontactmonitor_p.moc"
<commit_msg>Optimise DefaultContactMonitor loading<commit_after>/*
 * <one line to give the library's name and an idea of what it does.>
 * Copyright 2013  David Edmundson <d.edmundson@lboro.ac.uk>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License or (at your option) version 3 or any later version
 * accepted by the membership of KDE e.V. (or its successor approved
 * by the membership of KDE e.V.), which shall act as a proxy
 * defined in Section 14 of version 3 of the license.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "defaultcontactmonitor_p.h"

DefaultContactMonitor::DefaultContactMonitor(const QString &contactId, const AllContactsMonitorPtr& allContactsWatcher):
    ContactMonitor(contactId),
    m_allContactsMonitor(allContactsWatcher)
{
    connect(allContactsWatcher.data(), SIGNAL(contactAdded(QString,KABC::Addressee)), SLOT(onContactAdded(QString,KABC::Addressee)));
    connect(allContactsWatcher.data(), SIGNAL(contactRemoved(QString)), SLOT(onContactRemoved(QString)));
    connect(allContactsWatcher.data(), SIGNAL(contactChanged(QString,KABC::Addressee)), SLOT(onContactChanged(QString,KABC::Addressee)));

    KABC::Addressee::Map::const_iterator it = m_allContactsMonitor->contacts().constFind(contactId);
    if (it != m_allContactsMonitor->contacts().constEnd()) {
        setContact(*it);
    }
}

void DefaultContactMonitor::onContactAdded(const QString& id, const KABC::Addressee& contact)
{
    if (id == contactId()) {
        setContact(contact);
    }
}

void DefaultContactMonitor::onContactChanged(const QString& id, const KABC::Addressee& contact)
{
    if (id == contactId()) {
        setContact(contact);
    }
}

void DefaultContactMonitor::onContactRemoved(const QString& id)
{
    if (id == contactId()) {
        setContact(KABC::Addressee());
    }
}

#include "defaultcontactmonitor_p.moc"
<|endoftext|>


<commit_before>//===- ExtractFunction.cpp - Extract a function from Program --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements several methods that are used to extract functions,
// loops, or portions of a module from the rest of the module.
//
//===----------------------------------------------------------------------===//

#include "BugDriver.h"
#include "llvm/Constant.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Pass.h"
#include "llvm/Type.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Target/TargetData.h"
#include "Support/CommandLine.h"
#include "Support/Debug.h"
#include "Support/FileUtilities.h"
using namespace llvm;

namespace llvm {
  bool DisableSimplifyCFG = false;
} // End llvm namespace

namespace {
  cl::opt<bool>
  NoDCE ("disable-dce",
         cl::desc("Do not use the -dce pass to reduce testcases"));
  cl::opt<bool, true>
  NoSCFG("disable-simplifycfg", cl::location(DisableSimplifyCFG),
         cl::desc("Do not use the -simplifycfg pass to reduce testcases"));
}

/// deleteInstructionFromProgram - This method clones the current Program and
/// deletes the specified instruction from the cloned module.  It then runs a
/// series of cleanup passes (ADCE and SimplifyCFG) to eliminate any code which
/// depends on the value.  The modified module is then returned.
///
Module *BugDriver::deleteInstructionFromProgram(const Instruction *I,
                                                unsigned Simplification) const {
  Module *Result = CloneModule(Program);

  const BasicBlock *PBB = I->getParent();
  const Function *PF = PBB->getParent();

  Module::iterator RFI = Result->begin(); // Get iterator to corresponding fn
  std::advance(RFI, std::distance(PF->getParent()->begin(),
                                  Module::const_iterator(PF)));

  Function::iterator RBI = RFI->begin();  // Get iterator to corresponding BB
  std::advance(RBI, std::distance(PF->begin(), Function::const_iterator(PBB)));

  BasicBlock::iterator RI = RBI->begin(); // Get iterator to corresponding inst
  std::advance(RI, std::distance(PBB->begin(), BasicBlock::const_iterator(I)));
  Instruction *TheInst = RI;              // Got the corresponding instruction!

  // If this instruction produces a value, replace any users with null values
  if (TheInst->getType() != Type::VoidTy)
    TheInst->replaceAllUsesWith(Constant::getNullValue(TheInst->getType()));

  // Remove the instruction from the program.
  TheInst->getParent()->getInstList().erase(TheInst);

  // Spiff up the output a little bit.
  PassManager Passes;
  // Make sure that the appropriate target data is always used...
  Passes.add(new TargetData("bugpoint", Result));

  /// FIXME: If this used runPasses() like the methods below, we could get rid
  /// of the -disable-* options!
  if (Simplification > 1 && !NoDCE)
    Passes.add(createDeadCodeEliminationPass());
  if (Simplification && !DisableSimplifyCFG)
    Passes.add(createCFGSimplificationPass());      // Delete dead control flow

  Passes.add(createVerifierPass());
  Passes.run(*Result);
  return Result;
}

static const PassInfo *getPI(Pass *P) {
  const PassInfo *PI = P->getPassInfo();
  delete P;
  return PI;
}

/// performFinalCleanups - This method clones the current Program and performs
/// a series of cleanups intended to get rid of extra cruft on the module
/// before handing it to the user...
///
Module *BugDriver::performFinalCleanups(Module *M, bool MayModifySemantics) {
  // Make all functions external, so GlobalDCE doesn't delete them...
  for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
    I->setLinkage(GlobalValue::ExternalLinkage);

  std::vector<const PassInfo*> CleanupPasses;
  CleanupPasses.push_back(getPI(createFunctionResolvingPass()));
  CleanupPasses.push_back(getPI(createGlobalDCEPass()));
  CleanupPasses.push_back(getPI(createDeadTypeEliminationPass()));

  if (MayModifySemantics)
    CleanupPasses.push_back(getPI(createDeadArgHackingPass()));
  else
    CleanupPasses.push_back(getPI(createDeadArgEliminationPass()));

  Module *New = runPassesOn(M, CleanupPasses);
  if (New == 0) {
    std::cerr << "Final cleanups failed.  Sorry. :(  Please report a bug!\n";
  }
  delete M;
  return New;
}

/// ExtractLoop - Given a module, extract up to one loop from it into a new
/// function.  This returns null if there are no extractable loops in the
/// program or if the loop extractor crashes.
Module *BugDriver::ExtractLoop(Module *M) {
  std::vector<const PassInfo*> LoopExtractPasses;
  LoopExtractPasses.push_back(getPI(createSingleLoopExtractorPass()));

  Module *NewM = runPassesOn(M, LoopExtractPasses);
  if (NewM == 0) {
    Module *Old = swapProgramIn(M);
    std::cout << "*** Loop extraction failed: ";
    EmitProgressBytecode("loopextraction", true);
    std::cout << "*** Sorry. :(  Please report a bug!\n";
    swapProgramIn(Old);
    return 0;
  }

  // Check to see if we created any new functions.  If not, no loops were
  // extracted and we should return null.
  if (M->size() != NewM->size()) {
    delete NewM;
    return 0;
  }

  return NewM;
}

// DeleteFunctionBody - "Remove" the function by deleting all of its basic
// blocks, making it external.
//
void llvm::DeleteFunctionBody(Function *F) {
  // delete the body of the function...
  F->deleteBody();
  assert(F->isExternal() && "This didn't make the function external!");
}

/// SplitFunctionsOutOfModule - Given a module and a list of functions in the
/// module, split the functions OUT of the specified module, and place them in
/// the new module.
///
/// FIXME: this could be made DRAMATICALLY more efficient for large programs if
/// we just MOVED functions from one module to the other, instead of cloning the
/// whole module, then proceeding to delete an entire module's worth of stuff.
///
Module *llvm::SplitFunctionsOutOfModule(Module *M,
                                        const std::vector<Function*> &F) {
  // Make sure functions & globals are all external so that linkage
  // between the two modules will work.
  for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
    I->setLinkage(GlobalValue::ExternalLinkage);
  for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
    I->setLinkage(GlobalValue::ExternalLinkage);

  Module *New = CloneModule(M);

  // Make sure global initializers exist only in the safe module (CBE->.so)
  for (Module::giterator I = New->gbegin(), E = New->gend(); I != E; ++I)
    I->setInitializer(0);  // Delete the initializer to make it external

  // Remove the Test functions from the Safe module
  for (unsigned i = 0, e = F.size(); i != e; ++i) {
    Function *TNOF = M->getFunction(F[i]->getName(), F[i]->getFunctionType());
    DEBUG(std::cerr << "Removing function " << F[i]->getName() << "\n");
    assert(TNOF && "Function doesn't exist in module!");
    DeleteFunctionBody(TNOF);       // Function is now external in this module!
  }

  // Remove the Safe functions from the Test module
  for (Module::iterator I = New->begin(), E = New->end(); I != E; ++I) {
    bool funcFound = false;
    for (std::vector<Function*>::const_iterator FI = F.begin(), Fe = F.end();
         FI != Fe; ++FI)
      if (I->getName() == (*FI)->getName()) funcFound = true;

    if (!funcFound)
      DeleteFunctionBody(I);
  }
  return New;
}
<commit_msg>Fix an inverted condition that causes us to think that loop extraction accomplished something when it really did not.  This does not fix the bigger problem tho.<commit_after>//===- ExtractFunction.cpp - Extract a function from Program --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements several methods that are used to extract functions,
// loops, or portions of a module from the rest of the module.
//
//===----------------------------------------------------------------------===//

#include "BugDriver.h"
#include "llvm/Constant.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Pass.h"
#include "llvm/Type.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Target/TargetData.h"
#include "Support/CommandLine.h"
#include "Support/Debug.h"
#include "Support/FileUtilities.h"
using namespace llvm;

namespace llvm {
  bool DisableSimplifyCFG = false;
} // End llvm namespace

namespace {
  cl::opt<bool>
  NoDCE ("disable-dce",
         cl::desc("Do not use the -dce pass to reduce testcases"));
  cl::opt<bool, true>
  NoSCFG("disable-simplifycfg", cl::location(DisableSimplifyCFG),
         cl::desc("Do not use the -simplifycfg pass to reduce testcases"));
}

/// deleteInstructionFromProgram - This method clones the current Program and
/// deletes the specified instruction from the cloned module.  It then runs a
/// series of cleanup passes (ADCE and SimplifyCFG) to eliminate any code which
/// depends on the value.  The modified module is then returned.
///
Module *BugDriver::deleteInstructionFromProgram(const Instruction *I,
                                                unsigned Simplification) const {
  Module *Result = CloneModule(Program);

  const BasicBlock *PBB = I->getParent();
  const Function *PF = PBB->getParent();

  Module::iterator RFI = Result->begin(); // Get iterator to corresponding fn
  std::advance(RFI, std::distance(PF->getParent()->begin(),
                                  Module::const_iterator(PF)));

  Function::iterator RBI = RFI->begin();  // Get iterator to corresponding BB
  std::advance(RBI, std::distance(PF->begin(), Function::const_iterator(PBB)));

  BasicBlock::iterator RI = RBI->begin(); // Get iterator to corresponding inst
  std::advance(RI, std::distance(PBB->begin(), BasicBlock::const_iterator(I)));
  Instruction *TheInst = RI;              // Got the corresponding instruction!

  // If this instruction produces a value, replace any users with null values
  if (TheInst->getType() != Type::VoidTy)
    TheInst->replaceAllUsesWith(Constant::getNullValue(TheInst->getType()));

  // Remove the instruction from the program.
  TheInst->getParent()->getInstList().erase(TheInst);

  // Spiff up the output a little bit.
  PassManager Passes;
  // Make sure that the appropriate target data is always used...
  Passes.add(new TargetData("bugpoint", Result));

  /// FIXME: If this used runPasses() like the methods below, we could get rid
  /// of the -disable-* options!
  if (Simplification > 1 && !NoDCE)
    Passes.add(createDeadCodeEliminationPass());
  if (Simplification && !DisableSimplifyCFG)
    Passes.add(createCFGSimplificationPass());      // Delete dead control flow

  Passes.add(createVerifierPass());
  Passes.run(*Result);
  return Result;
}

static const PassInfo *getPI(Pass *P) {
  const PassInfo *PI = P->getPassInfo();
  delete P;
  return PI;
}

/// performFinalCleanups - This method clones the current Program and performs
/// a series of cleanups intended to get rid of extra cruft on the module
/// before handing it to the user...
///
Module *BugDriver::performFinalCleanups(Module *M, bool MayModifySemantics) {
  // Make all functions external, so GlobalDCE doesn't delete them...
  for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
    I->setLinkage(GlobalValue::ExternalLinkage);

  std::vector<const PassInfo*> CleanupPasses;
  CleanupPasses.push_back(getPI(createFunctionResolvingPass()));
  CleanupPasses.push_back(getPI(createGlobalDCEPass()));
  CleanupPasses.push_back(getPI(createDeadTypeEliminationPass()));

  if (MayModifySemantics)
    CleanupPasses.push_back(getPI(createDeadArgHackingPass()));
  else
    CleanupPasses.push_back(getPI(createDeadArgEliminationPass()));

  Module *New = runPassesOn(M, CleanupPasses);
  if (New == 0) {
    std::cerr << "Final cleanups failed.  Sorry. :(  Please report a bug!\n";
  }
  delete M;
  return New;
}

/// ExtractLoop - Given a module, extract up to one loop from it into a new
/// function.  This returns null if there are no extractable loops in the
/// program or if the loop extractor crashes.
Module *BugDriver::ExtractLoop(Module *M) {
  std::vector<const PassInfo*> LoopExtractPasses;
  LoopExtractPasses.push_back(getPI(createSingleLoopExtractorPass()));

  Module *NewM = runPassesOn(M, LoopExtractPasses);
  if (NewM == 0) {
    Module *Old = swapProgramIn(M);
    std::cout << "*** Loop extraction failed: ";
    EmitProgressBytecode("loopextraction", true);
    std::cout << "*** Sorry. :(  Please report a bug!\n";
    swapProgramIn(Old);
    return 0;
  }

  // Check to see if we created any new functions.  If not, no loops were
  // extracted and we should return null.
  if (M->size() == NewM->size()) {
    delete NewM;
    return 0;
  }

  return NewM;
}

// DeleteFunctionBody - "Remove" the function by deleting all of its basic
// blocks, making it external.
//
void llvm::DeleteFunctionBody(Function *F) {
  // delete the body of the function...
  F->deleteBody();
  assert(F->isExternal() && "This didn't make the function external!");
}

/// SplitFunctionsOutOfModule - Given a module and a list of functions in the
/// module, split the functions OUT of the specified module, and place them in
/// the new module.
///
/// FIXME: this could be made DRAMATICALLY more efficient for large programs if
/// we just MOVED functions from one module to the other, instead of cloning the
/// whole module, then proceeding to delete an entire module's worth of stuff.
///
Module *llvm::SplitFunctionsOutOfModule(Module *M,
                                        const std::vector<Function*> &F) {
  // Make sure functions & globals are all external so that linkage
  // between the two modules will work.
  for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
    I->setLinkage(GlobalValue::ExternalLinkage);
  for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
    I->setLinkage(GlobalValue::ExternalLinkage);

  Module *New = CloneModule(M);

  // Make sure global initializers exist only in the safe module (CBE->.so)
  for (Module::giterator I = New->gbegin(), E = New->gend(); I != E; ++I)
    I->setInitializer(0);  // Delete the initializer to make it external

  // Remove the Test functions from the Safe module
  for (unsigned i = 0, e = F.size(); i != e; ++i) {
    Function *TNOF = M->getFunction(F[i]->getName(), F[i]->getFunctionType());
    DEBUG(std::cerr << "Removing function " << F[i]->getName() << "\n");
    assert(TNOF && "Function doesn't exist in module!");
    DeleteFunctionBody(TNOF);       // Function is now external in this module!
  }

  // Remove the Safe functions from the Test module
  for (Module::iterator I = New->begin(), E = New->end(); I != E; ++I) {
    bool funcFound = false;
    for (std::vector<Function*>::const_iterator FI = F.begin(), Fe = F.end();
         FI != Fe; ++FI)
      if (I->getName() == (*FI)->getName()) funcFound = true;

    if (!funcFound)
      DeleteFunctionBody(I);
  }
  return New;
}
<|endoftext|>


<commit_before>/*
 * Chemharp, an efficient IO library for chemistry file formats
 * Copyright (C) 2015 Guillaume Fraux
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/
*/

#ifndef HARP_UNIT_CELL_HPP
#define HARP_UNIT_CELL_HPP

#include <array>

namespace harp {

//! 3 x 3 matrix type
typedef std::array<std::array<double, 3>, 3> Matrix3D;

/*!
 * @class UnitCell UnitCell.hpp UnitCell.cpp
 * @brief An UnitCell represent the box containing the atoms, and its periodicity
 *
 * A unit cell is fully represented by three lenghts (a, b, c); and three angles
 * (alpha, beta, gamma). The angles are stored in degrees, and the lenghts in
 * Angstroms.
 *
 * A cell also has a matricial representation, by projecting the three base
 * vector into an orthonormal base. We choose to represent such matrix as an
 * upper triangular matrix:
 *
 * 				| a_x   b_x   c_x |
 * 				|  0    b_y   c_y |
 * 				|  0     0    c_z |
 */
class UnitCell {
public:
    enum CellType {
        //! Orthorombic cell, with the three angles equals to 90°
        ORTHOROMBIC,
        //! Triclinic cell, with any values for the angles.
        TRICLINIC,
        //! Infinit cell, to use when there is no cell
        INFINITE
    };

    //! Construct an INFINITE unit cell
    UnitCell();
    //! Construct a cubic unit cell of side size \c a
    UnitCell(double a);
    //! Construct an ORTHOROMBIC unit cell of side size \c a, \c b, \c c
    UnitCell(double a, double b, double c);
    //! Construct a TRICLINIC unit cell of side size \c a, \c b, \c c, and cell
    //! angles \c alpha, \c beta, \c gamma
    UnitCell(double a, double b, double c, double alpha, double beta, double gamma);
    //! Construct a cell of type \c type, with all lenghts set to 0 and all angles
    //! set to 90°
    UnitCell(CellType type);
    //! Construct a cell of type \c type, with all lenghts set to \c a and all angles
    //! set to 90°
    UnitCell(CellType type, double a);
    //! Construct a cell of type \c type, with lenghts set to \c a ,\c b, \c d,
    //! and all angles set to 90°
    UnitCell(CellType type, double a, double b, double c);

    //! Get a matricial representation of the cell.
    Matrix3D matricial() const;
    //! Populate C-style matricial representation of the cell. The array should
    //! have a 3 x 3 size.
    void raw_matricial(double[3][3]) const;

    //! Get the cell type
    const CellType& type() const {return _type;}
    //! Set the cell type to t
    void type(CellType t);

    //! Get the first lenght (a) of the cell
    double a() const {return _a;}
    //! Set the first lenght (a) of the cell
    void a(double val);
    //! Get the second lenght (b) of the cell
    double b() const {return _b;}
    //! Set the second lenght (b) of the cell
    void b(double val);
    //! Get the third lenght (c) of the cell
    double c() const {return _c;}
    //! Set the third lenght (c) of the cell
    void c(double val);

    //! Get the first angle (alpha) of the cell
    double alpha() const {return _alpha;}
    //! Set the first lenght (alpha) of the cell if possible
    void alpha(double val);
    //! Get the second lenght (beta) of the cell
    double beta() const {return _beta;}
    //! Set the second lenght (beta) of the cell if possible
    void beta(double val);
    //! Get the third lenght (gamma) of the cell
    double gamma() const {return _gamma;}
    //! Set the third lenght (gamma) of the cell if possible
    void gamma(double val);

    //! Get the cell periodicity for the x axis
    bool periodic_x() const {return pbc_x;}
    //! Get the cell periodicity for the y axis
    bool periodic_y() const {return pbc_y;}
    //! Get the cell periodicity for the z axis
    bool periodic_z() const {return pbc_z;}
    //! True if the cell is periodic in the three dimmensions
    bool full_periodic() const {return pbc_x && pbc_y && pbc_z;}

    //! Set the cell periodicity for the x axis
    void periodic_x(bool p) {pbc_x = p;}
    //! Set the cell periodicity for the y axis
    void periodic_y(bool p) {pbc_y = p;}
    //! Set the cell periodicity for the z axis
    void periodic_z(bool p) {pbc_z = p;}
    //! Set the cell periodicity in three dimmensions
    void full_periodic(bool p) {pbc_x = p; pbc_y = p; pbc_z = p;}

private:
    //! Cell lenghts
    double _a, _b, _c;
    //! Cell angles
    double _alpha, _beta, _gamma;
    //! Cell type
    CellType _type;
    //! Cell periodicity
    bool pbc_x, pbc_y, pbc_z;
};

} // namespace harp

#endif
<commit_msg>Add move and copy constructors for UnitCell<commit_after>/*
 * Chemharp, an efficient IO library for chemistry file formats
 * Copyright (C) 2015 Guillaume Fraux
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/
*/

#ifndef HARP_UNIT_CELL_HPP
#define HARP_UNIT_CELL_HPP

#include <array>

namespace harp {

//! 3 x 3 matrix type
typedef std::array<std::array<double, 3>, 3> Matrix3D;

/*!
 * @class UnitCell UnitCell.hpp UnitCell.cpp
 * @brief An UnitCell represent the box containing the atoms, and its periodicity
 *
 * A unit cell is fully represented by three lenghts (a, b, c); and three angles
 * (alpha, beta, gamma). The angles are stored in degrees, and the lenghts in
 * Angstroms.
 *
 * A cell also has a matricial representation, by projecting the three base
 * vector into an orthonormal base. We choose to represent such matrix as an
 * upper triangular matrix:
 *
 * 				| a_x   b_x   c_x |
 * 				|  0    b_y   c_y |
 * 				|  0     0    c_z |
 */
class UnitCell {
public:
    enum CellType {
        //! Orthorombic cell, with the three angles equals to 90°
        ORTHOROMBIC,
        //! Triclinic cell, with any values for the angles.
        TRICLINIC,
        //! Infinit cell, to use when there is no cell
        INFINITE
    };

    //! Copy constructor
    UnitCell(const UnitCell& other) = default;
    UnitCell& operator=(const UnitCell& other) = default;
    //! Move constructor
    UnitCell(UnitCell&& other) = default;
    UnitCell& operator=(UnitCell&& other) = default;

    //! Construct an INFINITE unit cell
    UnitCell();
    //! Construct a cubic unit cell of side size \c a
    UnitCell(double a);
    //! Construct an ORTHOROMBIC unit cell of side size \c a, \c b, \c c
    UnitCell(double a, double b, double c);
    //! Construct a TRICLINIC unit cell of side size \c a, \c b, \c c, and cell
    //! angles \c alpha, \c beta, \c gamma
    UnitCell(double a, double b, double c, double alpha, double beta, double gamma);
    //! Construct a cell of type \c type, with all lenghts set to 0 and all angles
    //! set to 90°
    UnitCell(CellType type);
    //! Construct a cell of type \c type, with all lenghts set to \c a and all angles
    //! set to 90°
    UnitCell(CellType type, double a);
    //! Construct a cell of type \c type, with lenghts set to \c a ,\c b, \c d,
    //! and all angles set to 90°
    UnitCell(CellType type, double a, double b, double c);

    //! Get a matricial representation of the cell.
    Matrix3D matricial() const;
    //! Populate C-style matricial representation of the cell. The array should
    //! have a 3 x 3 size.
    void raw_matricial(double[3][3]) const;

    //! Get the cell type
    const CellType& type() const {return _type;}
    //! Set the cell type to t
    void type(CellType t);

    //! Get the first lenght (a) of the cell
    double a() const {return _a;}
    //! Set the first lenght (a) of the cell
    void a(double val);
    //! Get the second lenght (b) of the cell
    double b() const {return _b;}
    //! Set the second lenght (b) of the cell
    void b(double val);
    //! Get the third lenght (c) of the cell
    double c() const {return _c;}
    //! Set the third lenght (c) of the cell
    void c(double val);

    //! Get the first angle (alpha) of the cell
    double alpha() const {return _alpha;}
    //! Set the first lenght (alpha) of the cell if possible
    void alpha(double val);
    //! Get the second lenght (beta) of the cell
    double beta() const {return _beta;}
    //! Set the second lenght (beta) of the cell if possible
    void beta(double val);
    //! Get the third lenght (gamma) of the cell
    double gamma() const {return _gamma;}
    //! Set the third lenght (gamma) of the cell if possible
    void gamma(double val);

    //! Get the cell periodicity for the x axis
    bool periodic_x() const {return pbc_x;}
    //! Get the cell periodicity for the y axis
    bool periodic_y() const {return pbc_y;}
    //! Get the cell periodicity for the z axis
    bool periodic_z() const {return pbc_z;}
    //! True if the cell is periodic in the three dimmensions
    bool full_periodic() const {return pbc_x && pbc_y && pbc_z;}

    //! Set the cell periodicity for the x axis
    void periodic_x(bool p) {pbc_x = p;}
    //! Set the cell periodicity for the y axis
    void periodic_y(bool p) {pbc_y = p;}
    //! Set the cell periodicity for the z axis
    void periodic_z(bool p) {pbc_z = p;}
    //! Set the cell periodicity in three dimmensions
    void full_periodic(bool p) {pbc_x = p; pbc_y = p; pbc_z = p;}

private:
    //! Cell lenghts
    double _a, _b, _c;
    //! Cell angles
    double _alpha, _beta, _gamma;
    //! Cell type
    CellType _type;
    //! Cell periodicity
    bool pbc_x, pbc_y, pbc_z;
};

} // namespace harp

#endif
<|endoftext|>


<commit_before>// Copyright © 2012, 2014 Lénaïc Bagnères, hnc@singularity.fr

// This file is part of hnc.

// hnc is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// hnc is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.

// You should have received a copy of the GNU Affero General Public License
// along with hnc. If not, see <http://www.gnu.org/licenses/>

#ifndef HNC_MATH_HPP
#define HNC_MATH_HPP

#include "math/cartesian_product.hpp"

#include "math/geometric_mean.hpp"

#include "math/linear_equation.hpp"

#include "math/mean.hpp"
#include "math/median.hpp"

#include "math/nth_root.hpp"

#include "math/pi.hpp"

#include "math/relational_operator.hpp"

#include "math/variance.hpp"
#include "math/variance.hpp"

namespace hnc
{
	/**
	 * @brief Provides some mathematical functions
	 *
	 * @code
	   #include <hnc/math.hpp>
	   @endcode
	 */
	namespace math
	{
		// For Doxygen only
	}
}

#endif
<commit_msg>Fix hnc/math.hpp includes<commit_after>// Copyright © 2012, 2014 Lénaïc Bagnères, hnc@singularity.fr

// This file is part of hnc.

// hnc is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// hnc is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.

// You should have received a copy of the GNU Affero General Public License
// along with hnc. If not, see <http://www.gnu.org/licenses/>

#ifndef HNC_MATH_HPP
#define HNC_MATH_HPP

#include "math/cartesian_product.hpp"
#include "math/combination.hpp"

#include "math/geometric_mean.hpp"

#include "math/linear_equation.hpp"

#include "math/mean.hpp"
#include "math/median.hpp"

#include "math/nth_root.hpp"

#include "math/pi.hpp"

#include "math/relational_operator.hpp"

#include "math/standard_deviation.hpp"
#include "math/variance.hpp"

namespace hnc
{
	/**
	 * @brief Provides some mathematical functions
	 *
	 * @code
	   #include <hnc/math.hpp>
	   @endcode
	 */
	namespace math
	{
		// For Doxygen only
	}
}

#endif
<|endoftext|>


<commit_before>/* Reference documentation for libpqxx.
 *
 * Documentation is generated from header files.  This header is here only to
 * provide parts of that documentation.  There is no need to include it from
 * client code.
 *
 * Copyright 2001-2017, Jeroen T. Vermeulen.
 *
 * See COPYING for copyright license.  If you did not receive a file called
 * COPYING with this source code, please notify the distributor of this mistake,
 * or contact the author.
 */
#ifndef PQXX_H_DOC
#define PQXX_H_DOC

/** @mainpage
 * @author Jeroen T. Vermeulen
 *
 * Welcome to libpqxx, the C++ API to the PostgreSQL database management system.
 *
 * Compiling this package requires PostgreSQL to be installed -- including the
 * C headers for client development.  The library builds on top of PostgreSQL's
 * standard C API, libpq.  The libpq headers are not needed to compile client
 * programs, however.
 *
 * For a quick introduction to installing and using libpqxx, see the README.md
 * file; a more extensive tutorial is available in doc/html/Tutorial/index.html.
 *
 * The latest information can be found at http://pqxx.org/
 *
 * Some links that should help you find your bearings:
 * \li \ref gettingstarted
 * \li \ref threading
 * \li \ref connection
 * \li \ref transaction
 * \li \ref performance
 * \li \ref transactor
 *
 * @see http://pqxx.org/
 */

/** @page gettingstarted Getting started
 * The most basic three types in libpqxx are the connection (which inherits its
 * API from pqxx::connection_base and its setup behaviour from
 * pqxx::connectionpolicy), the transaction (derived from
 * pqxx::transaction_base), and the result (pqxx::result).
 *
 * They fit together as follows:
 * \li You connect to the database by creating a
 * connection object (see \ref connection).  The connection type you'll usually
 * want is pqxx::connection.
 * \li You create a transaction object (see \ref transaction) operating on that
 * connection.  You'll usually want the pqxx::work variety.  If you don't want
 * transactional behaviour, use pqxx::nontransaction.  Once you're done you call
 * the transaction's @c commit function to make its work final.  If you don't
 * call this, the work will be rolled back when the transaction object is
 * destroyed.
 * \li Until then, use the transaction's @c exec function to execute queries,
 * which you pass in as simple strings.
 * \li The function returns a pqxx::result object, which acts as a standard
 * container of rows.  Each row in itself acts as a container of fields.  You
 * can use array indexing and/or iterators to access either.
 * \li The field's data is stored as a text string.  You can read it as such
 * using its @c c_str() function, or convert it to other types using its @c as()
 * and @c to() member functions.  These are templated on the destination type:
 * @c myfield.as<int>(); or @c myfield.to(myint);
 * \li After you've closed the transaction, the connection is free to run a next
 * transaction.
 *
 * Here's a very basic example.  It connects to the default database (you'll
 * need to have one set up), queries it for a very simple result, converts it to
 * an @c int, and prints it out.  It also contains some basic error handling.
 *
 * @code
 * #include <iostream>
 * #include <pqxx/pqxx>
 *
 * int main()
 * {
 *   try
 *   {
 *     // Connect to the database.  In practice we may have to pass some
 *     // arguments to say where the database server is, and so on.
 *     pqxx::connection c;
 *
 *     // Start a transaction.  In libpqxx, you always work in one.
 *     pqxx::work w(c);
 *
 *     // work::exec1() executes a query returning a single row of data.
 *     // We'll just ask the database to return the number 1 to us.
 *     pqxx::row r = w.exec1("SELECT 1");
 *
 *     // Commit your transaction.  If an exception occurred before this
 *     // point, execution will have left the block, and the transaction will
 *     // have been destroyed along the way.  In that case, the failed
 *     // transaction would implicitly abort instead of getting to this point.
 *     w.commit();
 *
 *     // Look at the first and only field in the row, parse it as an integer,
 *     // and print it.
 *     std::cout << r[0].as<int>() << std::endl;
 *   }
 *   catch (const std::exception &e)
 *   {
 *     std::cerr << e.what() << std::endl;
 *     return 1;
 *   }
 * }
 * @endcode
 *
 * This prints the number 1.  Notice that you can keep the result object
 * around after the transaction (or even the connection) has been closed.
 *
 * Here's a slightly more complicated example.  It takes an argument from the
 * command line and retrieves a string with that value.  The interesting part is
 * that it uses the escaping-and-quoting function @c quote() to embed this
 * string value in SQL safely.  It also reads the result field's value as a
 * plain C-style string using its @c c_str() function.
 *
 * @code
 * #include <iostream>
 * #include <stdexcept>
 * #include <pqxx/pqxx>
 *
 * int main(int argc, char *argv[])
 * {
 *   try
 *   {
 *     if (!argv[1]) throw std::runtime_error("Give me a string!");
 *
 *     pqxx::connection c;
 *     pqxx::work w(c);
 *
 *     // work::exec() returns a full result set, which can consist of any
 *     // number of rows.
 *     pqxx::result r = w.exec("SELECT " + w.quote(argv[1]));
 *
 *     // End our transaction here.  We can still use the result afterwards.
 *     w.commit();
 *
 *     // Print the first field of the first row.  Read it as a C string,
 *     // just like std::string::c_str() does.
 *     std::cout << r[0][0].c_str() << std::endl;
 *   }
 *   catch (const std::exception &e)
 *   {
 *     std::cerr << e.what() << std::endl;
 *     return 1;
 *   }
 * }
 * @endcode
 *
 * You can find more about converting field values to native types, or
 * converting values to strings for use with libpqxx, under
 * \ref stringconversion.  More about getting to the rows and fields of a
 * result is under \ref accessingresults.
 *
 * If you want to handle exceptions thrown by libpqxx in more detail, for
 * example to print the SQL contents of a query that failed, see \ref exception.
 */

/** @page accessingresults Accessing results and result rows
 *
 * Let's say you have a result object.  For example, your program may have done:
 *
 * @code
 * pqxx::result r = w.exec("SELECT * FROM mytable");
 * @endcode
 *
 * Now how do you access the data inside @c r?
 *
 * The simplest way is array indexing.  A result acts as an array of rows,
 * and a row acts as an array of fields.
 *
 * @code
 * const int num_rows = r.size();
 * for (int rownum=0; rownum < num_rows; ++rownum)
 * {
 *   const pqxx::row row = r[rownum];
 *   const int num_cols = row.size();
 *   for (int colnum=0; colnum < num_cols; ++colnum)
 *   {
 *     const pqxx::field field = row[colnum];
 *     std::cout << field.c_str() << '\t';
 *   }
 *
 *   std::cout << std::endl;
 * }
 * @endcode
 *
 * But results and rows also define @c const_iterator types:
 *
 * @code
 * for (const auto &row: r)
 *  {
 *    for (const auto &field: row) std::cout << field.c_str() << '\t';
 *    std::cout << std::endl;
 *  }
 * @endcode
 *
 * They also have @c const_reverse_iterator types, which iterate backwards from
 * @c rbegin() to @c rend() exclusive.
 *
 * All these iterator types provide one extra bit of convenience that you won't
 * normally find in C++ iterators: referential transparency.  You don't need to
 * dereference them to get to the row or field they refer to.  That is, instead
 * of @c row->end() you can also choose to say @c row.end().  Similarly, you
 * may prefer @c field.c_str() over @c field->c_str().
 *
 * This becomes really helpful with the array-indexing operator.  With regular
 * C++ iterators you would need ugly expressions like @c (*row)[0] or
 * @c row->operator[](0).  With the iterator types defined by the result and
 * row classes you can simply say @c row[0].
 */

/** @page threading Thread safety
 *
 * This library does not contain any locking code to protect objects against
 * simultaneous modification in multi-threaded programs.  Therefore it is up
 * to you, the user of the library, to ensure that your threaded client
 * programs perform no conflicting operations concurrently.
 *
 * Most of the time this isn't hard.  Result sets are immutable, so you can
 * share them between threads without problem.  The main rule is:
 *
 * \li Treat a connection, together with any and all objects related to it, as
 * a "world" of its own.  You should generally make sure that the same "world"
 * is never accessed by another thread while you're doing anything non-const
 * in there.
 *
 * That means: don't issue a query on a transaction while you're also opening
 * a subtransaction, don't access a cursor while you may also be committing,
 * and so on.
 *
 * In particular, cursors are tricky.  It's easy to perform a non-const
 * operation without noticing.  So, if you're going to share cursors or
 * cursor-related objects between threads, lock very conservatively!
 *
 * Use @c pqxx::describe_thread_safety to find out at runtime what level of
 * thread safety is implemented in your build and version of libpqxx.  It
 * returns a pqxx::thread_safety_model describing what you can and cannot rely
 * on.  A command-line utility @c tools/pqxxthreadsafety prints out the same
 * information.
 */

#endif
<commit_msg>Minor doc update.<commit_after>/* Reference documentation for libpqxx.
 *
 * Documentation is generated from header files.  This header is here only to
 * provide parts of that documentation.  There is no need to include it from
 * client code.
 *
 * Copyright 2001-2017, Jeroen T. Vermeulen.
 *
 * See COPYING for copyright license.  If you did not receive a file called
 * COPYING with this source code, please notify the distributor of this mistake,
 * or contact the author.
 */
#ifndef PQXX_H_DOC
#define PQXX_H_DOC

/** @mainpage
 * @author Jeroen T. Vermeulen
 *
 * Welcome to libpqxx, the C++ API to the PostgreSQL database management system.
 *
 * Compiling this package requires PostgreSQL to be installed -- including the
 * C headers for client development.  The library builds on top of PostgreSQL's
 * standard C API, libpq.  The libpq headers are not needed to compile client
 * programs, however.
 *
 * For a quick introduction to installing and using libpqxx, see the README.md
 * file; a more extensive tutorial is available in doc/html/Tutorial/index.html.
 *
 * The latest information can be found at http://pqxx.org/
 *
 * Some links that should help you find your bearings:
 * \li \ref gettingstarted
 * \li \ref threading
 * \li \ref connection
 * \li \ref transaction
 * \li \ref performance
 * \li \ref transactor
 *
 * @see http://pqxx.org/
 */

/** @page gettingstarted Getting started
 * The most basic three types in libpqxx are the connection (which inherits its
 * API from pqxx::connection_base and its setup behaviour from
 * pqxx::connectionpolicy), the transaction (derived from
 * pqxx::transaction_base), and the result (pqxx::result).
 *
 * They fit together as follows:
 * \li You connect to the database by creating a
 * connection object (see \ref connection).  The connection type you'll usually
 * want is pqxx::connection.
 * \li You create a transaction object (see \ref transaction) operating on that
 * connection.  You'll usually want the pqxx::work variety.  If you don't want
 * transactional behaviour, use pqxx::nontransaction.  Once you're done you call
 * the transaction's @c commit function to make its work final.  If you don't
 * call this, the work will be rolled back when the transaction object is
 * destroyed.
 * \li Until then, use the transaction's @c exec() functions to execute
 * queries, which you pass in as simple strings.
 * \li Most of the @exec() functions return a pqxx::result object, which acts
 * as a standard container of rows.  Each row in itself acts as a container of
 * fields.  You can use array indexing and/or iterators to access either.
 * \li The field's data is stored as a text string.  You can read it as such
 * using its @c c_str() function, or convert it to other types using its @c as()
 * and @c to() member functions.  These are templated on the destination type:
 * @c myfield.as<int>(); or @c myfield.to(myint);
 * \li After you've closed the transaction, the connection is free to run a next
 * transaction.
 *
 * Here's a very basic example.  It connects to the default database (you'll
 * need to have one set up), queries it for a very simple result, converts it to
 * an @c int, and prints it out.  It also contains some basic error handling.
 *
 * @code
 * #include <iostream>
 * #include <pqxx/pqxx>
 *
 * int main()
 * {
 *   try
 *   {
 *     // Connect to the database.  In practice we may have to pass some
 *     // arguments to say where the database server is, and so on.
 *     pqxx::connection c;
 *
 *     // Start a transaction.  In libpqxx, you always work in one.
 *     pqxx::work w(c);
 *
 *     // work::exec1() executes a query returning a single row of data.
 *     // We'll just ask the database to return the number 1 to us.
 *     pqxx::row r = w.exec1("SELECT 1");
 *
 *     // Commit your transaction.  If an exception occurred before this
 *     // point, execution will have left the block, and the transaction will
 *     // have been destroyed along the way.  In that case, the failed
 *     // transaction would implicitly abort instead of getting to this point.
 *     w.commit();
 *
 *     // Look at the first and only field in the row, parse it as an integer,
 *     // and print it.
 *     std::cout << r[0].as<int>() << std::endl;
 *   }
 *   catch (const std::exception &e)
 *   {
 *     std::cerr << e.what() << std::endl;
 *     return 1;
 *   }
 * }
 * @endcode
 *
 * This prints the number 1.  Notice that you can keep the result object
 * around after the transaction (or even the connection) has been closed.
 *
 * Here's a slightly more complicated example.  It takes an argument from the
 * command line and retrieves a string with that value.  The interesting part is
 * that it uses the escaping-and-quoting function @c quote() to embed this
 * string value in SQL safely.  It also reads the result field's value as a
 * plain C-style string using its @c c_str() function.
 *
 * @code
 * #include <iostream>
 * #include <stdexcept>
 * #include <pqxx/pqxx>
 *
 * int main(int argc, char *argv[])
 * {
 *   try
 *   {
 *     if (!argv[1]) throw std::runtime_error("Give me a string!");
 *
 *     pqxx::connection c;
 *     pqxx::work w(c);
 *
 *     // work::exec() returns a full result set, which can consist of any
 *     // number of rows.
 *     pqxx::result r = w.exec("SELECT " + w.quote(argv[1]));
 *
 *     // End our transaction here.  We can still use the result afterwards.
 *     w.commit();
 *
 *     // Print the first field of the first row.  Read it as a C string,
 *     // just like std::string::c_str() does.
 *     std::cout << r[0][0].c_str() << std::endl;
 *   }
 *   catch (const std::exception &e)
 *   {
 *     std::cerr << e.what() << std::endl;
 *     return 1;
 *   }
 * }
 * @endcode
 *
 * You can find more about converting field values to native types, or
 * converting values to strings for use with libpqxx, under
 * \ref stringconversion.  More about getting to the rows and fields of a
 * result is under \ref accessingresults.
 *
 * If you want to handle exceptions thrown by libpqxx in more detail, for
 * example to print the SQL contents of a query that failed, see \ref exception.
 */

/** @page accessingresults Accessing results and result rows
 *
 * Let's say you have a result object.  For example, your program may have done:
 *
 * @code
 * pqxx::result r = w.exec("SELECT * FROM mytable");
 * @endcode
 *
 * Now how do you access the data inside @c r?
 *
 * The simplest way is array indexing.  A result acts as an array of rows,
 * and a row acts as an array of fields.
 *
 * @code
 * const int num_rows = r.size();
 * for (int rownum=0; rownum < num_rows; ++rownum)
 * {
 *   const pqxx::row row = r[rownum];
 *   const int num_cols = row.size();
 *   for (int colnum=0; colnum < num_cols; ++colnum)
 *   {
 *     const pqxx::field field = row[colnum];
 *     std::cout << field.c_str() << '\t';
 *   }
 *
 *   std::cout << std::endl;
 * }
 * @endcode
 *
 * But results and rows also define @c const_iterator types:
 *
 * @code
 * for (const auto &row: r)
 *  {
 *    for (const auto &field: row) std::cout << field.c_str() << '\t';
 *    std::cout << std::endl;
 *  }
 * @endcode
 *
 * They also have @c const_reverse_iterator types, which iterate backwards from
 * @c rbegin() to @c rend() exclusive.
 *
 * All these iterator types provide one extra bit of convenience that you won't
 * normally find in C++ iterators: referential transparency.  You don't need to
 * dereference them to get to the row or field they refer to.  That is, instead
 * of @c row->end() you can also choose to say @c row.end().  Similarly, you
 * may prefer @c field.c_str() over @c field->c_str().
 *
 * This becomes really helpful with the array-indexing operator.  With regular
 * C++ iterators you would need ugly expressions like @c (*row)[0] or
 * @c row->operator[](0).  With the iterator types defined by the result and
 * row classes you can simply say @c row[0].
 */

/** @page threading Thread safety
 *
 * This library does not contain any locking code to protect objects against
 * simultaneous modification in multi-threaded programs.  Therefore it is up
 * to you, the user of the library, to ensure that your threaded client
 * programs perform no conflicting operations concurrently.
 *
 * Most of the time this isn't hard.  Result sets are immutable, so you can
 * share them between threads without problem.  The main rule is:
 *
 * \li Treat a connection, together with any and all objects related to it, as
 * a "world" of its own.  You should generally make sure that the same "world"
 * is never accessed by another thread while you're doing anything non-const
 * in there.
 *
 * That means: don't issue a query on a transaction while you're also opening
 * a subtransaction, don't access a cursor while you may also be committing,
 * and so on.
 *
 * In particular, cursors are tricky.  It's easy to perform a non-const
 * operation without noticing.  So, if you're going to share cursors or
 * cursor-related objects between threads, lock very conservatively!
 *
 * Use @c pqxx::describe_thread_safety to find out at runtime what level of
 * thread safety is implemented in your build and version of libpqxx.  It
 * returns a pqxx::thread_safety_model describing what you can and cannot rely
 * on.  A command-line utility @c tools/pqxxthreadsafety prints out the same
 * information.
 */

#endif
<|endoftext|>


<commit_before>/*
 * This file is part of the Phatbooks project and is distributed under the
 * terms of the license contained in the file LICENSE.txt distributed
 * with this package.
 *
 * Author: Matthew Harvey <matthew@matthewharvey.net>
 *
 * Copyright (c) 2012-2013, Matthew Harvey.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#ifndef GUARD_repeater_impl_hpp_7204316857831701
#define GUARD_repeater_impl_hpp_7204316857831701

#include "date.hpp"
#include "interval_type.hpp"
#include "ordinary_journal.hpp"
#include "phatbooks_database_connection.hpp"
#include "proto_journal.hpp"
#include <boost/date_time/gregorian/gregorian.hpp>
#include <sqloxx/handle.hpp>
#include <sqloxx/id.hpp>
#include <sqloxx/persistent_object.hpp>
#include <memory>
#include <list>
#include <string>
#include <vector>

namespace phatbooks
{

// begin forward declarations

class DraftJournal;
class Frequency;

// end forward declarations

/**
 * Instances of this class serve as "alarms" that "fire" at regular intervals.
 * On firing, a \c Repeater triggers an automatic journal posting, and
 * updates itself to await the next firing.
 *
 * Important properties of a Repeater are: (a) the Journal that it causes
 * the posting of, when the repeater fires; and (b) the time between each
 * firing. The time between firings is represented by a number of units, and
 * a type of unit. So, a journal that fires every 3 weeks has \e weeks as its
 * interval type (\e represented by the IntervalType enum), and 3 as the
 * number of units (\e interval_units). At any point in time, a Repeater
 * also has (c) its \e next_date, the date at which it will next fire.
 *
 * Repeaters are associated with DraftJournals. When a Repeater fires, it
 * causes an OrdinaryJournal to be "cloned from" the DraftJournal, and then
 * posted.
 *
 * Client code should not deal with Repeater instances directly, but
 * only ever via sqloxx::Handle<Repeater>.
 */
class Repeater:
	public sqloxx::PersistentObject<Repeater, PhatbooksDatabaseConnection>
{
public:

	typedef sqloxx::PersistentObject
	<	Repeater,
		PhatbooksDatabaseConnection
	>	PersistentObject;

	/**
	 * Sets up tables in the database required for the persistence
	 * of Repeater objects.
	 */
	typedef sqloxx::IdentityMap<Repeater> IdentityMap;

	static void setup_tables(PhatbooksDatabaseConnection& dbc);

	/**
	 * Construct a fresh Repeater with no Id, not yet persisted to the
	 * database.
	 *
	 * Cannot be called except by IdentityMap. This is enforced by by
	 * Signature parameter.
	 */
	Repeater
	(	IdentityMap& p_identity_map,
		IdentityMap::Signature const& p_signature
	);

	/**
	 * Get a Repeater by Id from the database.
	 *
	 * Cannot be called except by IdentityMap. This is enforced by the
	 * Signature parameter.
	 */
	Repeater
	(	IdentityMap& p_identity_map,
		sqloxx::Id p_id,
		IdentityMap::Signature const& p_signature
	);

	// copy constructor is private

	Repeater(Repeater&&) = delete;
	Repeater& operator=(Repeater const&) = delete;
	Repeater& operator=(Repeater&&) = delete;

	~Repeater();

	/**
	 * @throws InvalidFrequencyException in the event that the "next date"
	 * has already been set for this Repeater and \e p_frequency is
	 * incompatible with that "next date".
	 *
	 * @see \e is_valid_date_for_interval_type
	 */
	void set_frequency(Frequency const& p_frequency);

	/**
	 * @throws InvalidRepeaterDateException in the event that the Frequency
	 * has already been set for this Repeater and \e p_next_date
	 * incompatible with that frequency.
	 *
	 * @throws InvalidRepeaterDateException in the event that \e p_next_date
	 * is earlier than the database_connection().entity_creation_date().
	 *
	 * @see \e is_valid_date_for_interval_type
	 */
	void set_next_date(boost::gregorian::date const& p_next_date);

	/**
	 * Associate the Repeater with a particular DraftJournal, by
	 * passing the id of the DraftJournal to \e p_journal_id.
	 * This function should \e not normally be called. The usual way
	 * to associate a Repeater with a DraftJournal is via
	 * \e DraftJournal::push_repeater(...). The DraftJournal class
	 * takes care of assigning the correct journal id to Repeaters,
	 * without client code needing to do this directly.
	 */
	void set_journal_id(sqloxx::Id p_journal_id);

	Frequency frequency();

	/**
	 * Calling next_date() (which is equivalent to calling next_date(0)), will
	 * return the date when the Repeater is next due to fire. Calling
	 * next_date(1) will return the date when the Repeater is next due to
	 * fire after \e that. Etc.
	 *
	 * @throws UnsafeArithmeticException in the extremely unlikely event of
	 * arithmetic overflow during execution.
	 */
	boost::gregorian::date next_date
	(	std::vector<boost::gregorian::date>::size_type n = 0
	);

	/**
	 * Post an OrdinaryJournal - based on this Repeater's DraftJournal -
	 * with the date of the OrdinaryJournal being next_date(0). Then
	 * update \e next_date internally to (what was) next_date(1).
	 *
	 * If the DraftJournal is database_connection().budget_instrument(),
	 * and is devoid of Entries, then an OrdinaryJournal is not
	 * actually posted; however the next_date is still updated. In this
	 * case, an OrdinaryJournal will still be returned, but it will have id,
	 * no Entries and no other attributes.
	 * This behaviour is to avoid mystifying the user with
	 * empty journal posting notifications in case they have not
	 * yet set up any BudgetItems.
	 *
	 * @todo HIGH PRIORITY Document exception safety.
	 */
	sqloxx::Handle<OrdinaryJournal> fire_next();

	sqloxx::Handle<DraftJournal> draft_journal();

	void swap(Repeater& rhs);

	static std::string exclusive_table_name();
	static std::string primary_key_name();

	/**
	 * Copy attributes of rhs to *this, but do \e not copy:\n
	 * 	\e id,\n
	 * 	\e database_connection, or\n
	 * 	\e journal_id.
	 */
	void mimic(Repeater& rhs);

private:

	Repeater(Repeater const& rhs);
	void do_load() override;
	void do_save_existing() override;
	void do_save_new() override;
	void do_ghostify() override;
	void process_saving_statement(sqloxx::SQLStatement& statement);

	struct RepeaterData;

	std::unique_ptr<RepeaterData> m_data;
};

// Free functions

/**
 * Bring Repeaters up to date (thereby posting auto posted journals),
 * returning a list containing the resulting
 * OrdinaryJournals, sorted by the order in which they have been
 * posted, from earliest to latest.
 */
std::list<sqloxx::Handle<OrdinaryJournal> >
update_repeaters
(	PhatbooksDatabaseConnection& dbc,
	boost::gregorian::date d = today()
);

}  // namespace phatbooks

#endif  // GUARD_repeater_impl_hpp_7204316857831701
<commit_msg>Documented the fact that Repeater::fire_next() provides the strong exception safety guarantee.<commit_after>/*
 * This file is part of the Phatbooks project and is distributed under the
 * terms of the license contained in the file LICENSE.txt distributed
 * with this package.
 *
 * Author: Matthew Harvey <matthew@matthewharvey.net>
 *
 * Copyright (c) 2012-2013, Matthew Harvey.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#ifndef GUARD_repeater_impl_hpp_7204316857831701
#define GUARD_repeater_impl_hpp_7204316857831701

#include "date.hpp"
#include "interval_type.hpp"
#include "ordinary_journal.hpp"
#include "phatbooks_database_connection.hpp"
#include "proto_journal.hpp"
#include <boost/date_time/gregorian/gregorian.hpp>
#include <sqloxx/handle.hpp>
#include <sqloxx/id.hpp>
#include <sqloxx/persistent_object.hpp>
#include <memory>
#include <list>
#include <string>
#include <vector>

namespace phatbooks
{

// begin forward declarations

class DraftJournal;
class Frequency;

// end forward declarations

/**
 * Instances of this class serve as "alarms" that "fire" at regular intervals.
 * On firing, a \c Repeater triggers an automatic journal posting, and
 * updates itself to await the next firing.
 *
 * Important properties of a Repeater are: (a) the Journal that it causes
 * the posting of, when the repeater fires; and (b) the time between each
 * firing. The time between firings is represented by a number of units, and
 * a type of unit. So, a journal that fires every 3 weeks has \e weeks as its
 * interval type (\e represented by the IntervalType enum), and 3 as the
 * number of units (\e interval_units). At any point in time, a Repeater
 * also has (c) its \e next_date, the date at which it will next fire.
 *
 * Repeaters are associated with DraftJournals. When a Repeater fires, it
 * causes an OrdinaryJournal to be "cloned from" the DraftJournal, and then
 * posted.
 *
 * Client code should not deal with Repeater instances directly, but
 * only ever via sqloxx::Handle<Repeater>.
 */
class Repeater:
	public sqloxx::PersistentObject<Repeater, PhatbooksDatabaseConnection>
{
public:

	typedef sqloxx::PersistentObject
	<	Repeater,
		PhatbooksDatabaseConnection
	>	PersistentObject;

	/**
	 * Sets up tables in the database required for the persistence
	 * of Repeater objects.
	 */
	typedef sqloxx::IdentityMap<Repeater> IdentityMap;

	static void setup_tables(PhatbooksDatabaseConnection& dbc);

	/**
	 * Construct a fresh Repeater with no Id, not yet persisted to the
	 * database.
	 *
	 * Cannot be called except by IdentityMap. This is enforced by by
	 * Signature parameter.
	 */
	Repeater
	(	IdentityMap& p_identity_map,
		IdentityMap::Signature const& p_signature
	);

	/**
	 * Get a Repeater by Id from the database.
	 *
	 * Cannot be called except by IdentityMap. This is enforced by the
	 * Signature parameter.
	 */
	Repeater
	(	IdentityMap& p_identity_map,
		sqloxx::Id p_id,
		IdentityMap::Signature const& p_signature
	);

	// copy constructor is private

	Repeater(Repeater&&) = delete;
	Repeater& operator=(Repeater const&) = delete;
	Repeater& operator=(Repeater&&) = delete;

	~Repeater();

	/**
	 * @throws InvalidFrequencyException in the event that the "next date"
	 * has already been set for this Repeater and \e p_frequency is
	 * incompatible with that "next date".
	 *
	 * @see \e is_valid_date_for_interval_type
	 */
	void set_frequency(Frequency const& p_frequency);

	/**
	 * @throws InvalidRepeaterDateException in the event that the Frequency
	 * has already been set for this Repeater and \e p_next_date
	 * incompatible with that frequency.
	 *
	 * @throws InvalidRepeaterDateException in the event that \e p_next_date
	 * is earlier than the database_connection().entity_creation_date().
	 *
	 * @see \e is_valid_date_for_interval_type
	 */
	void set_next_date(boost::gregorian::date const& p_next_date);

	/**
	 * Associate the Repeater with a particular DraftJournal, by
	 * passing the id of the DraftJournal to \e p_journal_id.
	 * This function should \e not normally be called. The usual way
	 * to associate a Repeater with a DraftJournal is via
	 * \e DraftJournal::push_repeater(...). The DraftJournal class
	 * takes care of assigning the correct journal id to Repeaters,
	 * without client code needing to do this directly.
	 */
	void set_journal_id(sqloxx::Id p_journal_id);

	Frequency frequency();

	/**
	 * Calling next_date() (which is equivalent to calling next_date(0)), will
	 * return the date when the Repeater is next due to fire. Calling
	 * next_date(1) will return the date when the Repeater is next due to
	 * fire after \e that. Etc.
	 *
	 * @throws UnsafeArithmeticException in the extremely unlikely event of
	 * arithmetic overflow during execution.
	 */
	boost::gregorian::date next_date
	(	std::vector<boost::gregorian::date>::size_type n = 0
	);

	/**
	 * Post an OrdinaryJournal - based on this Repeater's DraftJournal -
	 * with the date of the OrdinaryJournal being next_date(0). Then
	 * update \e next_date internally to (what was) next_date(1).
	 *
	 * If the DraftJournal is database_connection().budget_instrument(),
	 * and is devoid of Entries, then an OrdinaryJournal is not
	 * actually posted; however the next_date is still updated. In this
	 * case, an OrdinaryJournal will still be returned, but it will have id,
	 * no Entries and no other attributes.
	 * This behaviour is to avoid mystifying the user with
	 * empty journal posting notifications in case they have not
	 * yet set up any BudgetItems.
	 *
	 * Exception safety: strong guarantee.
	 */
	sqloxx::Handle<OrdinaryJournal> fire_next();

	sqloxx::Handle<DraftJournal> draft_journal();

	void swap(Repeater& rhs);

	static std::string exclusive_table_name();
	static std::string primary_key_name();

	/**
	 * Copy attributes of rhs to *this, but do \e not copy:\n
	 * 	\e id,\n
	 * 	\e database_connection, or\n
	 * 	\e journal_id.
	 */
	void mimic(Repeater& rhs);

private:

	Repeater(Repeater const& rhs);
	void do_load() override;
	void do_save_existing() override;
	void do_save_new() override;
	void do_ghostify() override;
	void process_saving_statement(sqloxx::SQLStatement& statement);

	struct RepeaterData;

	std::unique_ptr<RepeaterData> m_data;
};

// Free functions

/**
 * Bring Repeaters up to date (thereby posting auto posted journals),
 * returning a list containing the resulting
 * OrdinaryJournals, sorted by the order in which they have been
 * posted, from earliest to latest.
 */
std::list<sqloxx::Handle<OrdinaryJournal> >
update_repeaters
(	PhatbooksDatabaseConnection& dbc,
	boost::gregorian::date d = today()
);

}  // namespace phatbooks

#endif  // GUARD_repeater_impl_hpp_7204316857831701
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkFilter.hh
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
// .NAME vtkFilter - abstract class for specifying filter behaviour
// .SECTION Description
// vtkFilter is an abstract class that specifies the interface for data
// filters. Each filter must have an UpdateFilter() and Execute() method
// that will cause the filter to execute if its input or the filter itself
// has been modified since the last execution time.

#ifndef __vtkFilter_h
#define __vtkFilter_h

#include "vtkSource.hh"
class vtkDataSet;

class vtkFilter : public vtkSource
{
public:
  vtkFilter();
  void PrintSelf(ostream& os, vtkIndent indent);
  char *GetClassName() {return "vtkFilter";};

  // Description:
  // All filters must provide a method to update the visualization
  // pipeline.
  virtual void Update();

protected:
  vtkDataSet *Input;
  char Updating;

  // Every filter must have execute method.
  virtual void Execute();
};

#endif

<commit_msg>ERR: Removed extraneous virtual declaration.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkFilter.hh
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
// .NAME vtkFilter - abstract class for specifying filter behaviour
// .SECTION Description
// vtkFilter is an abstract class that specifies the interface for data
// filters. Each filter must have an UpdateFilter() and Execute() method
// that will cause the filter to execute if its input or the filter itself
// has been modified since the last execution time.

#ifndef __vtkFilter_h
#define __vtkFilter_h

#include "vtkSource.hh"
class vtkDataSet;

class vtkFilter : public vtkSource
{
public:
  vtkFilter();
  void PrintSelf(ostream& os, vtkIndent indent);
  char *GetClassName() {return "vtkFilter";};

  // Description:
  // All filters must provide a method to update the visualization
  // pipeline. (Method interface inherited from vtkSource).
  void Update();

protected:
  vtkDataSet *Input;
  char Updating;

  // Every filter must have execute method.
  void Execute();
};

#endif

<|endoftext|>


<commit_before><commit_msg>Connection: Fix savepoint string concatenation<commit_after><|endoftext|>