<commit_before>#include "stdsneezy.h"

int blackSun(TBeing *vict, cmdTypeT cmd, const char *arg, TObj *o, TObj *)
{
  affectedData aff;
  TBeing *ch;

  if(cmd != CMD_GENERIC_PULSE)
    return FALSE;

  if (!(ch = dynamic_cast<TBeing *>(o->equippedBy)))
    return FALSE;

  if(::number(0,0))
    return FALSE;

  aff.type = SPELL_PLASMA_MIRROR;
  aff.duration = UPDATES_PER_MUDHOUR/4;
  aff.modifier = 0;
  aff.location = APPLY_NONE;
  aff.bitvector = 0;
  aff.level = 40;

  colorAct(COLOR_SPELLS, "<k>Ancient visions of a dark land overcome you.<1>",
	   FALSE, ch, NULL, 0, TO_CHAR);
  colorAct(COLOR_SPELLS, "<k>A black sun grows unbearably <1><Y>hot<1><k> and <1><r>burns<1><k> your flesh.<1>",
	   FALSE, ch, NULL, 0, TO_CHAR);
  colorAct(COLOR_SPELLS, "<k>You snap back to reality gasping for breath, as a swirling shield of plasma surround you.<1>",
	   FALSE, ch, NULL, 0, TO_CHAR);

  colorAct(COLOR_SPELLS, "<k>$n looks momentarily startled as a swirling shield of plasma surrounds $m.<1>",
	   FALSE, ch, NULL, 0, TO_ROOM);

  ch->affectJoin(ch, &aff, AVG_DUR_NO, AVG_EFF_YES);

  return TRUE;
}
<commit_msg>woops, adjusted trigger rate to normal<commit_after>#include "stdsneezy.h"

int blackSun(TBeing *vict, cmdTypeT cmd, const char *arg, TObj *o, TObj *)
{
  affectedData aff;
  TBeing *ch;

  if(cmd != CMD_GENERIC_PULSE)
    return FALSE;

  if (!(ch = dynamic_cast<TBeing *>(o->equippedBy)))
    return FALSE;

  if(::number(0,99))
    return FALSE;

  aff.type = SPELL_PLASMA_MIRROR;
  aff.duration = UPDATES_PER_MUDHOUR/4;
  aff.modifier = 0;
  aff.location = APPLY_NONE;
  aff.bitvector = 0;
  aff.level = 40;

  colorAct(COLOR_SPELLS, "<k>Ancient visions of a dark land overcome you.<1>",
	   FALSE, ch, NULL, 0, TO_CHAR);
  colorAct(COLOR_SPELLS, "<k>A black sun grows unbearably <1><Y>hot<1><k> and <1><r>burns<1><k> your flesh.<1>",
	   FALSE, ch, NULL, 0, TO_CHAR);
  colorAct(COLOR_SPELLS, "<k>You snap back to reality gasping for breath, as a swirling shield of plasma surround you.<1>",
	   FALSE, ch, NULL, 0, TO_CHAR);

  colorAct(COLOR_SPELLS, "<k>$n looks momentarily startled as a swirling shield of plasma surrounds $m.<1>",
	   FALSE, ch, NULL, 0, TO_ROOM);

  ch->affectJoin(ch, &aff, AVG_DUR_NO, AVG_EFF_YES);

  return TRUE;
}
<|endoftext|>


<commit_before>// STL
#include <cassert>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
// StdAir
#include <stdair/STDAIR_Types.hpp>
#include <stdair/bom/BomList.hpp>
#include <stdair/bom/BomSource.hpp>
#include <stdair/factory/FacBomContent.hpp>
#include <stdair/service/Logger.hpp>
#include <stdair/STDAIR_Service.hpp>

// ///////// M A I N ////////////
int main (int argc, char* argv[]) {

  try {

    // Test create objects.

    // Output log File
    std::string lLogFilename ("stdair.log");

    // Set the log parameters
    std::ofstream logOutputFile;
    // open and clean the log outputfile
    logOutputFile.open (lLogFilename.c_str());
    logOutputFile.clear();

    const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
    stdair::STDAIR_Service stdairService (lLogParams);

    // DEBUG
    STDAIR_LOG_DEBUG ("Welcome to stdair");

    // Step 0.0: initialisation
    // Create the root of the Bom tree (i.e., a BomRoot object)
    stdair::BomRoot& lBomRoot =
      stdair::FacBomContent::instance().create<stdair::BomRoot>();

    // Step 0.1: Inventory level
    // Create an Inventory (BA)
    const stdair::AirlineCode_T lAirlineCode ("BA");
    stdair::InventoryKey_T lInventoryKey (lAirlineCode);

    stdair::Inventory& lInventory =
      stdair::FacBomContent::instance().create<stdair::Inventory>(lInventoryKey);
    stdair::FacBomContent::linkWithParent (lInventory, lBomRoot);

    // Display the inventory
    STDAIR_LOG_DEBUG ("Inventory: " << lInventory.toString());

    // Step 0.2: Flight-date level
    // Create a FlightDate (BA15/10-JUN-2010)
    const stdair::FlightNumber_T lFlightNumber = 15;
    const stdair::Date_T lDate (2010, 6, 10);
    stdair::FlightDateKey_T lFlightDateKey (lFlightNumber, lDate);

    stdair::FlightDate& lFlightDate = stdair::FacBomContent::
      instance().create<stdair::FlightDate> (lFlightDateKey);
    stdair::FacBomContent::linkWithParent (lFlightDate, lInventory);

    // Display the flight-date
    STDAIR_LOG_DEBUG ("FlightDate: " << lFlightDate.toString());

    // Step 0.3: Segment-date level
    // Create a first SegmentDate (LHR-SYD)
    const stdair::AirportCode_T lLHR ("LHR");
    const stdair::AirportCode_T lSYD ("SYD");
    stdair::SegmentDateKey_T lSegmentDateKey (lLHR, lSYD);

    stdair::SegmentDate& lLHRSYDSegment =
      stdair::FacBomContent::
      instance().create<stdair::SegmentDate> (lSegmentDateKey);
    stdair::FacBomContent::linkWithParent (lLHRSYDSegment, lFlightDate);

    // Display the segment-date
    STDAIR_LOG_DEBUG ("SegmentDate: " << lLHRSYDSegment.toString());

    // Create a second SegmentDate (LHR-BKK)
    const stdair::AirportCode_T lBKK ("BKK");
    lSegmentDateKey = stdair::SegmentDateKey_T (lLHR, lBKK);

    stdair::SegmentDate& lLHRBKKSegment =
      stdair::FacBomContent::
      instance().create<stdair::SegmentDate> (lSegmentDateKey);
    stdair::FacBomContent::linkWithParent (lLHRBKKSegment, lFlightDate);

    // Display the segment-date
    STDAIR_LOG_DEBUG ("SegmentDate: " << lLHRBKKSegment.toString());

    // Create a third SegmentDate (BKK-SYD)
    lSegmentDateKey = stdair::SegmentDateKey_T (lBKK, lSYD);

    stdair::SegmentDate& lBKKSYDSegment =
      stdair::FacBomContent::
      instance().create<stdair::SegmentDate> (lSegmentDateKey);
    stdair::FacBomContent::linkWithParent (lBKKSYDSegment, lFlightDate);

    // Display the segment-date
    STDAIR_LOG_DEBUG ("SegmentDate: " << lBKKSYDSegment.toString());

    // Step 0.4: Leg-date level
    // Create a first LegDate (LHR)
    stdair::LegDateKey_T lLegDateKey (lLHR);

    stdair::LegDate& lLHRLeg =
      stdair::FacBomContent::instance().create<stdair::LegDate> (lLegDateKey);
    stdair::FacBomContent::linkWithParent<stdair::LegDate>(lLHRLeg, lFlightDate);

    // Display the leg-date
    STDAIR_LOG_DEBUG ("LegDate: " << lLHRLeg.toString());

    // Create a second LegDate (BKK)
    lLegDateKey = stdair::LegDateKey_T (lBKK);

    stdair::LegDate& lBKKLeg =
      stdair::FacBomContent::instance().create<stdair::LegDate> (lLegDateKey);
    stdair::FacBomContent::linkWithParent (lBKKLeg, lFlightDate);

    // Display the leg-date
    STDAIR_LOG_DEBUG ("LegDate: " << lBKKLeg.toString());

    // Step 0.5: segment-cabin level
    // Create a SegmentCabin (Y) of the Segment LHR-BKK;
    const stdair::CabinCode_T lY ("Y");
    stdair::SegmentCabinKey_T lYSegmentCabinKey (lY);

    stdair::SegmentCabin& lLHRBKKSegmentYCabin =
      stdair::FacBomContent::
      instance().create<stdair::SegmentCabin> (lYSegmentCabinKey);
    stdair::FacBomContent::
      linkWithParent (lLHRBKKSegmentYCabin, lLHRBKKSegment);

    // Display the segment-cabin
    STDAIR_LOG_DEBUG ("SegmentCabin: " << lLHRBKKSegmentYCabin.toString());

    // Create a SegmentCabin (Y) of the Segment BKK-SYD;
    stdair::SegmentCabin& lBKKSYDSegmentYCabin =
      stdair::FacBomContent::
      instance().create<stdair::SegmentCabin> (lYSegmentCabinKey);
    stdair::FacBomContent::
      linkWithParent (lBKKSYDSegmentYCabin, lBKKSYDSegment);

    // Display the segment-cabin
    STDAIR_LOG_DEBUG ("SegmentCabin: " << lBKKSYDSegmentYCabin.toString());

    // Create a SegmentCabin (Y) of the Segment LHR-SYD;
    stdair::SegmentCabin& lLHRSYDSegmentYCabin =
      stdair::FacBomContent::
      instance().create<stdair::SegmentCabin> (lYSegmentCabinKey);
    stdair::FacBomContent::
      linkWithParent (lLHRSYDSegmentYCabin, lLHRSYDSegment);

    // Display the segment-cabin
    STDAIR_LOG_DEBUG ("SegmentCabin: " << lLHRSYDSegmentYCabin.toString());

    // Step 0.6: leg-cabin level
    // Create a LegCabin (Y) of the Leg LHR-BKK;
    stdair::LegCabinKey_T lYLegCabinKey (lY);

    stdair::LegCabin& lLHRLegYCabin =
      stdair::FacBomContent::instance().create<stdair::LegCabin> (lYLegCabinKey);
    stdair::FacBomContent::linkWithParent (lLHRLegYCabin, lLHRLeg);

    // Display the leg-cabin
    STDAIR_LOG_DEBUG ("LegCabin: " << lLHRLegYCabin.toString());

    // Create a LegCabin (Y) of the Leg BKK-SYD;
    stdair::LegCabin& lBKKLegYCabin =
      stdair::FacBomContent::instance().create<stdair::LegCabin> (lYLegCabinKey);
    stdair::FacBomContent::linkWithParent (lBKKLegYCabin, lBKKLeg);

    // Display the leg-cabin
    STDAIR_LOG_DEBUG ("LegCabin: " << lBKKLegYCabin.toString());

    // Step 0.7: booking class level
    // Create a BookingClass (Q) of the Segment LHR-BKK, cabin Y;
    const stdair::ClassCode_T lQ ("Q");
    stdair::BookingClassKey_T lQBookingClassKey (lQ);

    stdair::BookingClass& lLHRBKKSegmentYCabinQClass =
      stdair::FacBomContent::
      instance().create<stdair::BookingClass> (lQBookingClassKey);
    stdair::FacBomContent::
      linkWithParent (lLHRBKKSegmentYCabinQClass, lLHRBKKSegmentYCabin);

    // Display the booking class
    STDAIR_LOG_DEBUG ("BookingClass: "
		      << lLHRBKKSegmentYCabinQClass.toString());

    // Browse the BomRoot and display the created objects.
    STDAIR_LOG_DEBUG ("Browse the BomRoot");

    const stdair::InventoryList_T& lInventoryList = lBomRoot.getInventoryList();
    for (stdair::InventoryList_T::iterator itInv = lInventoryList.begin();
         itInv != lInventoryList.end(); ++itInv) {
      const stdair::Inventory& lCurrentInventory = *itInv;
      STDAIR_LOG_DEBUG ("Inventory: " << lCurrentInventory.toString());

      const stdair::FlightDateMap_T& lFlightDateMap =
        lCurrentInventory.getFlightDateMap ();
      for (stdair::FlightDateMap_T::iterator itFlightDate =
             lFlightDateMap.begin();
           itFlightDate != lFlightDateMap.end(); ++itFlightDate) {
        const stdair::FlightDate* lCurrentFlightDate = itFlightDate->second;
        STDAIR_LOG_DEBUG ("FlightDate: " << lCurrentFlightDate->describeKey());
      }
    }

    // Close the Log outputFile
    logOutputFile.close();

  } catch (const std::exception& stde) {
    std::cerr << "Standard exception: " << stde.what() << std::endl;
    return -1;

  } catch (...) {
    return -1;
  }

  return 0;
}
<commit_msg>[Dev] The sample batch now supports program options.<commit_after>// STL
#include <cassert>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
// Boost (Extended STL)
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/program_options.hpp>
#include <boost/tokenizer.hpp>
#include <boost/lexical_cast.hpp>
// StdAir
#include <stdair/STDAIR_Types.hpp>
#include <stdair/STDAIR_Service.hpp>
#include <stdair/bom/BomSource.hpp>
#include <stdair/bom/BomList.hpp>
#include <stdair/factory/FacBomContent.hpp>
#include <stdair/service/Logger.hpp>
#include <stdair/config/stdair-paths.hpp>

// //////// Type definitions ///////
typedef std::vector<std::string> WordList_T;

// //////// Constants //////
/** Default name and location for the log file. */
const std::string K_STDAIR_DEFAULT_LOG_FILENAME ("stdair.log");

/** Default name and location for the (CSV) input file. */
const std::string K_STDAIR_DEFAULT_INPUT_FILENAME ("../../test/samples/stdair01.csv");

/** Default for the input type. It can be either built-in or provided by an
    input file. That latter must then be given with the -i option. */
const bool K_STDAIR_DEFAULT_BUILT_IN_INPUT = false;

/** Early return status (so that it can be differentiated from an error). */
const int K_STDAIR_EARLY_RETURN_STATUS = 99;

// ///////// Parsing of Options & Configuration /////////
// A helper function to simplify the main part.
template<class T> std::ostream& operator<< (std::ostream& os,
                                            const std::vector<T>& v) {
  std::copy (v.begin(), v.end(), std::ostream_iterator<T> (std::cout, " "));
  return os;
}

/** Read and parse the command line options. */
int readConfiguration (int argc, char* argv[], bool& ioIsBuiltin,
                       stdair::Filename_T& ioInputFilename,
                       std::string& ioLogFilename) {
  // Default for the built-in input
  ioIsBuiltin = K_STDAIR_DEFAULT_BUILT_IN_INPUT;

  // Declare a group of options that will be allowed only on command line
  boost::program_options::options_description generic ("Generic options");
  generic.add_options()
    ("prefix", "print installation prefix")
    ("version,v", "print version string")
    ("help,h", "produce help message");

  // Declare a group of options that will be allowed both on command
  // line and in config file
  boost::program_options::options_description config ("Configuration");
  config.add_options()
    ("builtin,b",
     "The sample BOM tree can be either built-in or parsed from an input file. That latter must then be given with the -i/--input option")
    ("input,i",
     boost::program_options::value< std::string >(&ioInputFilename)->default_value(K_STDAIR_DEFAULT_INPUT_FILENAME),
     "(CVS) input file for the demand distributions")
    ("log,l",
     boost::program_options::value< std::string >(&ioLogFilename)->default_value(K_STDAIR_DEFAULT_LOG_FILENAME),
     "Filename for the logs")
    ;

  // Hidden options, will be allowed both on command line and
  // in config file, but will not be shown to the user.
  boost::program_options::options_description hidden ("Hidden options");
  hidden.add_options()
    ("copyright",
     boost::program_options::value< std::vector<std::string> >(),
     "Show the copyright (license)");

  boost::program_options::options_description cmdline_options;
  cmdline_options.add(generic).add(config).add(hidden);

  boost::program_options::options_description config_file_options;
  config_file_options.add(config).add(hidden);

  boost::program_options::options_description visible ("Allowed options");
  visible.add(generic).add(config);

  boost::program_options::positional_options_description p;
  p.add ("copyright", -1);

  boost::program_options::variables_map vm;
  boost::program_options::
    store (boost::program_options::command_line_parser (argc, argv).
           options (cmdline_options).positional(p).run(), vm);

  std::ifstream ifs ("stdair.cfg");
  boost::program_options::store (parse_config_file (ifs, config_file_options),
                                 vm);
  boost::program_options::notify (vm);

  if (vm.count ("help")) {
    std::cout << visible << std::endl;
    return K_STDAIR_EARLY_RETURN_STATUS;
  }

  if (vm.count ("version")) {
    std::cout << PACKAGE_NAME << ", version " << PACKAGE_VERSION << std::endl;
    return K_STDAIR_EARLY_RETURN_STATUS;
  }

  if (vm.count ("prefix")) {
    std::cout << "Installation prefix: " << PREFIXDIR << std::endl;
    return K_STDAIR_EARLY_RETURN_STATUS;
  }

  if (vm.count ("builtin")) {
    ioIsBuiltin = true;
  }
  const std::string isBuiltinStr = (ioIsBuiltin == true)?"yes":"no";
  std::cout << "The BOM should be built-in? " << isBuiltinStr << std::endl;

  if (ioIsBuiltin == false) {
    if (vm.count ("input")) {
      ioInputFilename = vm["input"].as< std::string >();
      std::cout << "Input filename is: " << ioInputFilename << std::endl;
    }
  }

  if (vm.count ("log")) {
    ioLogFilename = vm["log"].as< std::string >();
    std::cout << "Log filename is: " << ioLogFilename << std::endl;
  }

  return 0;
}

// //////////////////////////////////////////////////////////////////////
void buildSampleBom() {

  try {

    // DEBUG
    STDAIR_LOG_DEBUG ("StdAir will build the BOM tree from built-in specifications.");

    // Step 0.0: initialisation
    // Create the root of the Bom tree (i.e., a BomRoot object)
    stdair::BomRoot& lBomRoot =
      stdair::FacBomContent::instance().create<stdair::BomRoot>();

    // Step 0.1: Inventory level
    // Create an Inventory (BA)
    const stdair::AirlineCode_T lAirlineCode ("BA");
    stdair::InventoryKey_T lInventoryKey (lAirlineCode);

    stdair::Inventory& lInventory =
      stdair::FacBomContent::instance().create<stdair::Inventory>(lInventoryKey);
    stdair::FacBomContent::linkWithParent (lInventory, lBomRoot);

    // Display the inventory
    STDAIR_LOG_DEBUG ("Inventory: " << lInventory.toString());

    // Step 0.2: Flight-date level
    // Create a FlightDate (BA15/10-JUN-2010)
    const stdair::FlightNumber_T lFlightNumber = 15;
    const stdair::Date_T lDate (2010, 6, 10);
    stdair::FlightDateKey_T lFlightDateKey (lFlightNumber, lDate);

    stdair::FlightDate& lFlightDate = stdair::FacBomContent::
      instance().create<stdair::FlightDate> (lFlightDateKey);
    stdair::FacBomContent::linkWithParent (lFlightDate, lInventory);

    // Display the flight-date
    STDAIR_LOG_DEBUG ("FlightDate: " << lFlightDate.toString());

    // Step 0.3: Segment-date level
    // Create a first SegmentDate (LHR-SYD)
    const stdair::AirportCode_T lLHR ("LHR");
    const stdair::AirportCode_T lSYD ("SYD");
    stdair::SegmentDateKey_T lSegmentDateKey (lLHR, lSYD);

    stdair::SegmentDate& lLHRSYDSegment =
      stdair::FacBomContent::
      instance().create<stdair::SegmentDate> (lSegmentDateKey);
    stdair::FacBomContent::linkWithParent (lLHRSYDSegment, lFlightDate);

    // Display the segment-date
    STDAIR_LOG_DEBUG ("SegmentDate: " << lLHRSYDSegment.toString());

    // Create a second SegmentDate (LHR-BKK)
    const stdair::AirportCode_T lBKK ("BKK");
    lSegmentDateKey = stdair::SegmentDateKey_T (lLHR, lBKK);

    stdair::SegmentDate& lLHRBKKSegment =
      stdair::FacBomContent::
      instance().create<stdair::SegmentDate> (lSegmentDateKey);
    stdair::FacBomContent::linkWithParent (lLHRBKKSegment, lFlightDate);

    // Display the segment-date
    STDAIR_LOG_DEBUG ("SegmentDate: " << lLHRBKKSegment.toString());

    // Create a third SegmentDate (BKK-SYD)
    lSegmentDateKey = stdair::SegmentDateKey_T (lBKK, lSYD);

    stdair::SegmentDate& lBKKSYDSegment =
      stdair::FacBomContent::
      instance().create<stdair::SegmentDate> (lSegmentDateKey);
    stdair::FacBomContent::linkWithParent (lBKKSYDSegment, lFlightDate);

    // Display the segment-date
    STDAIR_LOG_DEBUG ("SegmentDate: " << lBKKSYDSegment.toString());

    // Step 0.4: Leg-date level
    // Create a first LegDate (LHR)
    stdair::LegDateKey_T lLegDateKey (lLHR);

    stdair::LegDate& lLHRLeg =
      stdair::FacBomContent::instance().create<stdair::LegDate> (lLegDateKey);
    stdair::FacBomContent::linkWithParent<stdair::LegDate>(lLHRLeg, lFlightDate);

    // Display the leg-date
    STDAIR_LOG_DEBUG ("LegDate: " << lLHRLeg.toString());

    // Create a second LegDate (BKK)
    lLegDateKey = stdair::LegDateKey_T (lBKK);

    stdair::LegDate& lBKKLeg =
      stdair::FacBomContent::instance().create<stdair::LegDate> (lLegDateKey);
    stdair::FacBomContent::linkWithParent (lBKKLeg, lFlightDate);

    // Display the leg-date
    STDAIR_LOG_DEBUG ("LegDate: " << lBKKLeg.toString());

    // Step 0.5: segment-cabin level
    // Create a SegmentCabin (Y) of the Segment LHR-BKK;
    const stdair::CabinCode_T lY ("Y");
    stdair::SegmentCabinKey_T lYSegmentCabinKey (lY);

    stdair::SegmentCabin& lLHRBKKSegmentYCabin =
      stdair::FacBomContent::
      instance().create<stdair::SegmentCabin> (lYSegmentCabinKey);
    stdair::FacBomContent::
      linkWithParent (lLHRBKKSegmentYCabin, lLHRBKKSegment);

    // Display the segment-cabin
    STDAIR_LOG_DEBUG ("SegmentCabin: " << lLHRBKKSegmentYCabin.toString());

    // Create a SegmentCabin (Y) of the Segment BKK-SYD;
    stdair::SegmentCabin& lBKKSYDSegmentYCabin =
      stdair::FacBomContent::
      instance().create<stdair::SegmentCabin> (lYSegmentCabinKey);
    stdair::FacBomContent::
      linkWithParent (lBKKSYDSegmentYCabin, lBKKSYDSegment);

    // Display the segment-cabin
    STDAIR_LOG_DEBUG ("SegmentCabin: " << lBKKSYDSegmentYCabin.toString());

    // Create a SegmentCabin (Y) of the Segment LHR-SYD;
    stdair::SegmentCabin& lLHRSYDSegmentYCabin =
      stdair::FacBomContent::
      instance().create<stdair::SegmentCabin> (lYSegmentCabinKey);
    stdair::FacBomContent::
      linkWithParent (lLHRSYDSegmentYCabin, lLHRSYDSegment);

    // Display the segment-cabin
    STDAIR_LOG_DEBUG ("SegmentCabin: " << lLHRSYDSegmentYCabin.toString());

    // Step 0.6: leg-cabin level
    // Create a LegCabin (Y) of the Leg LHR-BKK;
    stdair::LegCabinKey_T lYLegCabinKey (lY);

    stdair::LegCabin& lLHRLegYCabin =
      stdair::FacBomContent::instance().create<stdair::LegCabin> (lYLegCabinKey);
    stdair::FacBomContent::linkWithParent (lLHRLegYCabin, lLHRLeg);

    // Display the leg-cabin
    STDAIR_LOG_DEBUG ("LegCabin: " << lLHRLegYCabin.toString());

    // Create a LegCabin (Y) of the Leg BKK-SYD;
    stdair::LegCabin& lBKKLegYCabin =
      stdair::FacBomContent::instance().create<stdair::LegCabin> (lYLegCabinKey);
    stdair::FacBomContent::linkWithParent (lBKKLegYCabin, lBKKLeg);

    // Display the leg-cabin
    STDAIR_LOG_DEBUG ("LegCabin: " << lBKKLegYCabin.toString());

    // Step 0.7: booking class level
    // Create a BookingClass (Q) of the Segment LHR-BKK, cabin Y;
    const stdair::ClassCode_T lQ ("Q");
    stdair::BookingClassKey_T lQBookingClassKey (lQ);

    stdair::BookingClass& lLHRBKKSegmentYCabinQClass =
      stdair::FacBomContent::
      instance().create<stdair::BookingClass> (lQBookingClassKey);
    stdair::FacBomContent::
      linkWithParent (lLHRBKKSegmentYCabinQClass, lLHRBKKSegmentYCabin);

    // Display the booking class
    STDAIR_LOG_DEBUG ("BookingClass: "
		      << lLHRBKKSegmentYCabinQClass.toString());

    // Browse the BomRoot and display the created objects.
    STDAIR_LOG_DEBUG ("Browse the BomRoot");

    const stdair::InventoryList_T& lInventoryList = lBomRoot.getInventoryList();
    for (stdair::InventoryList_T::iterator itInv = lInventoryList.begin();
         itInv != lInventoryList.end(); ++itInv) {
      const stdair::Inventory& lCurrentInventory = *itInv;
      STDAIR_LOG_DEBUG ("Inventory: " << lCurrentInventory.toString());

      const stdair::FlightDateMap_T& lFlightDateMap =
        lCurrentInventory.getFlightDateMap ();
      for (stdair::FlightDateMap_T::iterator itFlightDate =
             lFlightDateMap.begin();
           itFlightDate != lFlightDateMap.end(); ++itFlightDate) {
        const stdair::FlightDate* lCurrentFlightDate = itFlightDate->second;
        STDAIR_LOG_DEBUG ("FlightDate: " << lCurrentFlightDate->describeKey());
      }
    }

  } catch (const std::exception& stde) {
    STDAIR_LOG_ERROR ("Standard exception: " << stde.what());
  }
}

// ///////// M A I N ////////////
int main (int argc, char* argv[]) {

  try {

    // Built-in
    bool isBuiltin;

    // Input file name
    stdair::Filename_T lInputFilename;

    // Output log File
    std::string lLogFilename;

    // Call the command-line option parser
    const int lOptionParserStatus =
      readConfiguration (argc, argv, isBuiltin, lInputFilename, lLogFilename);

    if (lOptionParserStatus == K_STDAIR_EARLY_RETURN_STATUS) {
      return 0;
    }

    // Set the log parameters
    std::ofstream logOutputFile;
    // Open and clean the log outputfile
    logOutputFile.open (lLogFilename.c_str());
    logOutputFile.clear();

    const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
    stdair::STDAIR_Service stdairService (lLogParams);

    // DEBUG
    STDAIR_LOG_DEBUG ("Welcome to stdair");

    // Check wether or not a (CSV) input file should be read
    if (isBuiltin == true) {
      // Build a sample BOM tree
      buildSampleBom();

    } else {
      // Read the input file
      //stdairService.readFromInputFile (lInputFilename);

      // DEBUG
      STDAIR_LOG_DEBUG ("StdAir will parse " << lInputFilename
                        << " and build the corresponding BOM tree.");
    }

    // Close the Log outputFile
    logOutputFile.close();

  } catch (const std::exception& stde) {
    std::cerr << "Standard exception: " << stde.what() << std::endl;
    return -1;

  } catch (...) {
    return -1;
  }

  return 0;
}
<|endoftext|>


<commit_before>#ifndef K3_UNIQPOLYBUF
#define K3_UNIQPOLYBUF

#include <unordered_set>

#if HAS_LIBDYNAMIC

#include <boost/serialization/array.hpp>
#include <boost/serialization/string.hpp>
#include <boost/functional/hash.hpp>

#include <yaml-cpp/yaml.h>
#include <rapidjson/document.h>
#include <csvpp/csv.h>
#include "serialization/Json.hpp"

#include "Common.hpp"
#include "collections/STLDataspace.hpp"
#include "collections/Collection.hpp"
#include "collections/FlatPolyBuffer.hpp"

namespace K3 {
namespace Libdynamic {

//////////////////////////////////////////
//
// Buffer functors.

struct UPBValueProxy {
  UPBValueProxy(size_t o) : asOffset(true), offset(o) {}
  UPBValueProxy(const void* p) : asOffset(false), elem(p) {}

  bool asOffset;
  union {
    void* elem;
    size_t offset;
  };
};

template<typename Tag>
using UPBKey = std::pair<Tag, UPBValueProxy>;

template<class T, typename Tag>
struct UPBEqual : std::binary_function<UPBKey<Tag>, UPBKey<Tag>, bool>
{
  using Buf = LibdynamicVector::buffer;
  Buf* buffer;

  UPBEqual(Buf* b) : buffer(b) {}

  bool operator()(const UPBKey<Tag>& left, const UPBKey<Tag>& right) const {
    void* lp = left.asOffset? buffer_data(buf) + left.second.offset : left.second.elem;
    void* rp = right.asOffset? buffer_data(buf) + right.second.offset : right.second.elem;
    return T::equalelem(left.first, left.second, right.first, right.second);
  }
};

template<typename T, typename Tag>
struct UPBHash : std::unary_function<UPBKey<Tag>, std::size_t>
{
  using Buf = LibdynamicVector::buffer;
  Buf* buffer;

  UPBHash(Buf* b) : buffer(b) {}

  std::size_t operator()(const UPBKey<Tag>& k) const {
    std::hash<Tag> hash;
    size_t h1 = hash(k.first);
    void* p = k.asOffset? buffer_data(buf) + k.second.offset : k.second.elem;
    boost::hash_combine(h1, T::hashelem(k.first, p));
    return h1;
  }
};

//////////////////////////////////////////
//
// UniquePolyBuffer

template<class Ignore, class Derived>
class UniquePolyBuffer : public FlatPolyBuffer<Ignore, Derived> {
public:
  using Super = FlatPolyBuffer<Ignore, Derived>;
  using Tag = typename Super::Tag;

  using FContainer = typename Super::FContainer;
  using VContainer = typename Super::VContainer;
  using TContainer = typename Super::TContainer;

  UniquePolyBuffer() : Super(), comparator(fixed()), hasher(fixed()), keys(10, comparator, hasher)  {}

  UniquePolyBuffer(const UniquePolyBuffer& other) : Super(other) {
    comparator = other.comparator;
    hasher = other.hasher;
    keys = other.keys;
  }

  UniquePolyBuffer(UniquePolyBuffer&& other) : Super(std::move(other)) {
    comparator = std::move(other.comparator);
    hasher = std::move(other.hasher);
    keys.swap(other.keys);
  }

  UniquePolyBuffer& operator=(const UniquePolyBuffer& other) {
    Super::operator=(other);
    comparator = other.comparator;
    hasher = other.hasher;
    keys = other.keys;
    return *this;
  }

  UniquePolyBuffer& operator=(UniquePolyBuffer&& other) {
    keys = std::move(other.keys);
    comparator = std::move(other.comparator);
    hasher = std::move(other.hasher);
    Super::operator=(std::move(other));
    return *this;
  }

  ~UniquePolyBuffer() {}

  void rebuildKeys() {
    size_t foffset = 0, sz = Super::size(unit_t{});
    for (size_t i = 0; i < sz; ++i) {
      Tag tg = Super::tag_at(i);
      keys.insert(std::make_pair(tg, std::move(UPBValueProxy { foffset })));
      foffset += this->elemsize(tg);
    }
  }

  //////////////////////////////////
  //
  // Tag-specific accessors.

  template<typename T>
  unit_t append(Tag tg, const T& t) {
    UPBValueProxy probe { reinterpret_cast<void*>(const_cast<T*>(&t)) };
    if ( keys.find(std::make_pair(tg, probe)) == keys.end() ) {
      FContainer* ncf = const_cast<FContainer*>(Super::fixedc());
      size_t offset = buffer_size(ncf);
      Super::append(tg, t);
      keys.insert(std::make_pair(tg, std::move(UPBValueProxy proxy { offset })));
    }
    return unit_t{};
  }

  // Clears a container, deleting any backing buffer.
  unit_t clear(unit_t) {
    keys.clear();
    return Super::clear(unit_t{});
  }

  unit_t load(const base_string& str) {
    return load(base_string(str));
  }

  // Restores a flat poly buffer from a string.
  unit_t load(base_string&& str) {
    Super::load(std::forward<base_string>(str));
    rebuildKeys();
    return unit_t{};
  }

  template <class archive>
  void save(archive& a, const unsigned int) const {
    a << boost::serialization::base_object<const Super>(*this);
  }

  template <class archive>
  void load(archive& a, const unsigned int) {
    a >> boost::serialization::base_object<Super>(*this);
    rebuildKeys();
  }

  template <class archive>
  void serialize(archive& a) const {
    Super::serialize(a);
  }

  template <class archive>
  void serialize(archive& a) {
    Super::serialize(a);
    rebuildKeys();
  }

  BOOST_SERIALIZATION_SPLIT_MEMBER()

private:
  UPBEqual<Derived, Tag> comparator;
  UPBHash<Derived, Tag> hasher;
  std::unordered_set<UPBKey<Tag>, UPBHash<Derived, Tag>, UPBEqual<Derived, Tag>> keys;
};

}; // end namespace Libdynamic

template<class Ignored, class Derived>
using UniquePolyBuffer = Libdynamic::UniquePolyBuffer<Ignored, Derived>;

}; // end namespace K3

namespace YAML {
template <class E, class Derived>
struct convert<K3::UniquePolyBuffer<E, Derived>> {
  using Tag = typename K3::UniquePolyBuffer<E, Derived>::Tag;
  static Node encode(const K3::UniquePolyBuffer<E, Derived>& c) {
    Node node;
    bool flag = true;
    c.iterate([&c, &node, &flag](Tag tg, size_t idx, size_t offset){
      if (flag) { flag = false; }
      node.push_back(c.yamlencode(tg, idx, offset));
    });
    if (flag) {
      node = YAML::Load("[]");
    }
    return node;
  }

  static bool decode(const Node& node, K3::UniquePolyBuffer<E, Derived>& c) {
    for (auto i : node) {
      c.yamldecode(i);
    }
    return true;
  }
};
}  // namespace YAML

namespace JSON {
using namespace rapidjson;
template <class E, class Derived>
struct convert<K3::UniquePolyBuffer<E, Derived>> {
  using Tag = typename K3::UniquePolyBuffer<E, Derived>::Tag;
  template <class Allocator>
  static Value encode(const K3::UniquePolyBuffer<E, Derived>& c, Allocator& al) {
    Value v;
    v.SetObject();
    v.AddMember("type", Value("UniquePolyBuffer"), al);
    Value inner;
    inner.SetArray();
    c.iterate([&c, &inner, &al](Tag tg, size_t idx, size_t offset){
      inner.PushBack(c.jsonencode(tg, idx, offset, al), al);
    });
    v.AddMember("value", inner.Move(), al);
    return v;
  }
};
}  // namespace JSON

#endif // HAS_LIBDYNAMIC

#endif
<commit_msg>Cleaning up UPB for hasher and comparator revisions<commit_after>#ifndef K3_UNIQPOLYBUF
#define K3_UNIQPOLYBUF

#include <unordered_set>

#if HAS_LIBDYNAMIC

#include <boost/serialization/array.hpp>
#include <boost/serialization/string.hpp>
#include <boost/functional/hash.hpp>

#include <yaml-cpp/yaml.h>
#include <rapidjson/document.h>
#include <csvpp/csv.h>
#include "serialization/Json.hpp"

#include "Common.hpp"
#include "collections/STLDataspace.hpp"
#include "collections/Collection.hpp"
#include "collections/FlatPolyBuffer.hpp"

namespace K3 {
namespace Libdynamic {

//////////////////////////////////////////
//
// Buffer functors.

struct UPBValueProxy {
  UPBValueProxy(size_t o) : asOffset(true), offset(o) {}
  UPBValueProxy(void* p) : asOffset(false), elem(p) {}

  bool asOffset;
  union {
    void* elem;
    size_t offset;
  };
};

template<typename Tag>
using UPBKey = std::pair<Tag, UPBValueProxy>;

template<class T, typename Tag>
struct UPBEqual : std::binary_function<UPBKey<Tag>, UPBKey<Tag>, bool>
{
  using Buf = LibdynamicVector::buffer;
  Buf* buffer;

  UPBEqual(Buf* b) : buffer(b) {}

  bool operator()(const UPBKey<Tag>& left, const UPBKey<Tag>& right) const {
    void* lp = left.asOffset? buffer_data(buffer) + left.second.offset : left.second.elem;
    void* rp = right.asOffset? buffer_data(buffer) + right.second.offset : right.second.elem;
    return T::equalelem(left.first, left.second, right.first, right.second);
  }
};

template<typename T, typename Tag>
struct UPBHash : std::unary_function<UPBKey<Tag>, std::size_t>
{
  using Buf = LibdynamicVector::buffer;
  Buf* buffer;

  UPBHash(Buf* b) : buffer(b) {}

  std::size_t operator()(const UPBKey<Tag>& k) const {
    std::hash<Tag> hash;
    size_t h1 = hash(k.first);
    void* p = k.asOffset? buffer_data(buffer) + k.second.offset : k.second.elem;
    boost::hash_combine(h1, T::hashelem(k.first, p));
    return h1;
  }
};

//////////////////////////////////////////
//
// UniquePolyBuffer

template<class Ignore, class Derived>
class UniquePolyBuffer : public FlatPolyBuffer<Ignore, Derived> {
public:
  using Super = FlatPolyBuffer<Ignore, Derived>;
  using Tag = typename Super::Tag;

  using FContainer = typename Super::FContainer;
  using VContainer = typename Super::VContainer;
  using TContainer = typename Super::TContainer;

  UniquePolyBuffer() : Super(), comparator(fixed()), hasher(fixed()), keys(10, comparator, hasher)  {}

  UniquePolyBuffer(const UniquePolyBuffer& other)
    : Super(other), comparator(other.comparator), hasher(other.hasher), keys(other.keys)
  {}

  UniquePolyBuffer(UniquePolyBuffer&& other)
    : Super(std::move(other)),
      comparator(std::move(other.comparator)), hasher(std::move(other.hasher)), keys(std::move(other.keys))
  {}

  UniquePolyBuffer& operator=(const UniquePolyBuffer& other) {
    Super::operator=(other);
    comparator = other.comparator;
    hasher = other.hasher;
    keys = other.keys;
    return *this;
  }

  UniquePolyBuffer& operator=(UniquePolyBuffer&& other) {
    keys = std::move(other.keys);
    comparator = std::move(other.comparator);
    hasher = std::move(other.hasher);
    Super::operator=(std::move(other));
    return *this;
  }

  ~UniquePolyBuffer() {}

  void rebuildKeys() {
    size_t foffset = 0, sz = Super::size(unit_t{});
    for (size_t i = 0; i < sz; ++i) {
      Tag tg = Super::tag_at(i);
      keys.insert(std::make_pair(tg, std::move(UPBValueProxy { foffset })));
      foffset += this->elemsize(tg);
    }
  }

  //////////////////////////////////
  //
  // Tag-specific accessors.

  template<typename T>
  unit_t append(Tag tg, const T& t) {
    UPBValueProxy probe { reinterpret_cast<void*>(const_cast<T*>(&t)) };
    if ( keys.find(std::make_pair(tg, probe)) == keys.end() ) {
      FContainer* ncf = const_cast<FContainer*>(Super::fixedc());
      size_t offset = buffer_size(ncf);
      Super::append(tg, t);
      keys.insert(std::make_pair(tg, std::move(UPBValueProxy { offset })));
    }
    return unit_t{};
  }

  // Clears a container, deleting any backing buffer.
  unit_t clear(unit_t) {
    keys.clear();
    return Super::clear(unit_t{});
  }

  unit_t load(const base_string& str) {
    return load(base_string(str));
  }

  // Restores a flat poly buffer from a string.
  unit_t load(base_string&& str) {
    Super::load(std::forward<base_string>(str));
    rebuildKeys();
    return unit_t{};
  }

  template <class archive>
  void save(archive& a, const unsigned int) const {
    a << boost::serialization::base_object<const Super>(*this);
  }

  template <class archive>
  void load(archive& a, const unsigned int) {
    a >> boost::serialization::base_object<Super>(*this);
    rebuildKeys();
  }

  template <class archive>
  void serialize(archive& a) const {
    Super::serialize(a);
  }

  template <class archive>
  void serialize(archive& a) {
    Super::serialize(a);
    rebuildKeys();
  }

  BOOST_SERIALIZATION_SPLIT_MEMBER()

private:
  UPBEqual<Derived, Tag> comparator;
  UPBHash<Derived, Tag> hasher;
  std::unordered_set<UPBKey<Tag>, UPBHash<Derived, Tag>, UPBEqual<Derived, Tag>> keys;
};

}; // end namespace Libdynamic

template<class Ignored, class Derived>
using UniquePolyBuffer = Libdynamic::UniquePolyBuffer<Ignored, Derived>;

}; // end namespace K3

namespace YAML {
template <class E, class Derived>
struct convert<K3::UniquePolyBuffer<E, Derived>> {
  using Tag = typename K3::UniquePolyBuffer<E, Derived>::Tag;
  static Node encode(const K3::UniquePolyBuffer<E, Derived>& c) {
    Node node;
    bool flag = true;
    c.iterate([&c, &node, &flag](Tag tg, size_t idx, size_t offset){
      if (flag) { flag = false; }
      node.push_back(c.yamlencode(tg, idx, offset));
    });
    if (flag) {
      node = YAML::Load("[]");
    }
    return node;
  }

  static bool decode(const Node& node, K3::UniquePolyBuffer<E, Derived>& c) {
    for (auto i : node) {
      c.yamldecode(i);
    }
    return true;
  }
};
}  // namespace YAML

namespace JSON {
using namespace rapidjson;
template <class E, class Derived>
struct convert<K3::UniquePolyBuffer<E, Derived>> {
  using Tag = typename K3::UniquePolyBuffer<E, Derived>::Tag;
  template <class Allocator>
  static Value encode(const K3::UniquePolyBuffer<E, Derived>& c, Allocator& al) {
    Value v;
    v.SetObject();
    v.AddMember("type", Value("UniquePolyBuffer"), al);
    Value inner;
    inner.SetArray();
    c.iterate([&c, &inner, &al](Tag tg, size_t idx, size_t offset){
      inner.PushBack(c.jsonencode(tg, idx, offset, al), al);
    });
    v.AddMember("value", inner.Move(), al);
    return v;
  }
};
}  // namespace JSON

#endif // HAS_LIBDYNAMIC

#endif
<|endoftext|>


<commit_before>#include <sched.h>
#include <linux/unistd.h>
#include <sys/types.h>
#include <sys/syscall.h>
#include <unistd.h>

#include "core_manager.h"
#include "core.h"
#include "network.h"
#include "ocache.h"
#include "config.h"
#include "packetize.h"
#include "message_types.h"

#include "log.h"
#define LOG_DEFAULT_RANK -1
#define LOG_DEFAULT_MODULE CORE_MANAGER

using namespace std;

CoreManager::CoreManager()
      :
      tid_to_core_map(3*g_config->getNumLocalCores()),
      tid_to_core_index_map(3*g_config->getNumLocalCores()),
      simthread_tid_to_core_map(3*g_config->getNumLocalCores())
{
   LOG_PRINT("Starting CoreManager Constructor.");

   m_maps_lock = Lock::create();

   tid_map = new UInt32 [g_config->getNumLocalCores()];
   core_to_simthread_tid_map = new UInt32 [g_config->getNumLocalCores()];

   // Need to subtract 1 for the MCP
   for (UInt32 i = 0; i < g_config->getNumLocalCores(); i++)
   {
      tid_map[i] = UINT_MAX;
      core_to_simthread_tid_map[i] = UINT_MAX;
      m_cores.push_back(new Core(g_config->getCoreListForProcess(g_config->getCurrentProcessNum())[i]));
   }

   LOG_PRINT("Finished CoreManager Constructor.");
}

CoreManager::~CoreManager()
{
   for (std::vector<Core *>::iterator i = m_cores.begin(); i != m_cores.end(); i++)
      delete *i;

   delete [] core_to_simthread_tid_map;
   delete [] tid_map;

   delete m_maps_lock;
}

void CoreManager::initializeCommId(UInt32 comm_id)
{
   UInt32 tid = getCurrentTID();
   pair<bool, UINT64> e = tid_to_core_map.find(tid);

   LOG_ASSERT_ERROR(e.first, "*ERROR* initializeCommId: Called without binding thread to a core.");
   UInt32 core_id = e.second;

   UnstructuredBuffer send_buff;
   send_buff << MCP_MESSAGE_BROADCAST_COMM_MAP_UPDATE;
   send_buff << comm_id;
   send_buff << core_id;

   LOG_PRINT("CoreMap: CoreManager Initializing comm_id: %d to core_id: %d", comm_id, core_id);

   // Broadcast this update to other cores
   getCoreFromID(core_id)->getNetwork()->netSend((SInt32)g_config->getMCPCoreNum(), MCP_SYSTEM_TYPE,
         (const void *)send_buff.getBuffer(), (UInt32)send_buff.size());

   // This should be used once miniMCPs are implemented.
   // Transport::Node *globalNode = Transport::getSingleton()->getGlobalNode();
   // globalNode->send(g_config->getMcpCoreId(),
   //                  send_buff.getBuffer(),
   //                  send_buff.size());
}

void CoreManager::initializeThread()
{
   ScopedLock scoped_maps_lock(*m_maps_lock);
   UInt32 tid = getCurrentTID();
   pair<bool, UInt64> e = tid_to_core_map.find(tid);

   LOG_ASSERT_ERROR(e.first == false, "*ERROR* Thread: %d already mapped to core: %d", tid, e.second);

   for (UInt32 i = 0; i < g_config->getNumLocalCores(); i++)
   {
      if (tid_map[i] == UINT_MAX)
      {
         UInt32 core_id = g_config->getCoreListForProcess(g_config->getCurrentProcessNum())[i];
         tid_map[i] = tid;
         tid_to_core_index_map.insert(tid, i);
         tid_to_core_map.insert(tid, core_id);
         LOG_PRINT("%d mapped to: %d core_id: %d", i, tid_map[i], core_id);
         return;
      }
      else
      {
         // LOG_PRINT("%d/%d already mapped to: %d", i, g_config->getNumLocalCores(), tid_map[i]);
      }
   }

   LOG_PRINT("*ERROR* initializeThread - No free cores out of %d total.", g_config->getNumLocalCores());
   LOG_NOTIFY_ERROR();
}

void CoreManager::initializeThread(UInt32 core_id)
{
   ScopedLock scoped_maps_lock(*m_maps_lock);
   UInt32 tid = getCurrentTID();
   pair<bool, UInt64> e = tid_to_core_map.find(tid);

   LOG_ASSERT_ERROR(e.first == false, "Tried to initialize core %d twice.", core_id);

   for (unsigned int i = 0; i < g_config->getNumLocalCores(); i++)
   {
      UInt32 local_core_id = g_config->getCoreListForProcess(g_config->getCurrentProcessNum())[i];
      if(local_core_id == core_id)
      {
         if (tid_map[i] == UINT_MAX)
         {
            tid_map[i] = tid;
            tid_to_core_index_map.insert(tid, i);
            tid_to_core_map.insert(tid, core_id);
            LOG_PRINT("%d mapped to: %d core_id: %d", i, tid_map[i], core_id);
            return;
         }
         else
         {
            LOG_PRINT("*ERROR* initializeThread -- %d/%d already mapped to thread %d", i, g_config->getNumLocalCores(), tid_map[i]);
            LOG_NOTIFY_ERROR();
         }
      }
   }

   LOG_PRINT("*ERROR* initializeThread - Requested core %d does not live on process %d.", core_id, g_config->getCurrentProcessNum());
   LOG_NOTIFY_ERROR();
}

UInt32 CoreManager::getCurrentCoreID()
{
   UInt32 id;
   UInt32 tid = getCurrentTID();

   pair<bool, UINT64> e = tid_to_core_map.find(tid);
   id = (e.first == false) ? -1 : e.second;

   ASSERT(!e.first || id < g_config->getTotalCores(), "Illegal core_id value returned by getCurrentCoreID!\n");

   return id;
}

Core *CoreManager::getCurrentCore()
{
   Core *core;
   UInt32 tid = getCurrentTID();

   pair<bool, UINT64> e = tid_to_core_index_map.find(tid);
   core = (e.first == false) ? NULL : m_cores[e.second];

   LOG_ASSERT_ERROR(!e.first || e.second < g_config->getTotalCores(), "Illegal core_id value returned by getCurrentCore!\n");
   return core;
}

Core *CoreManager::getCoreFromID(UInt32 id)
{
   Core *core = NULL;
   // Look up the index from the core list
   // FIXME: make this more cached
   const Config::CoreList & cores(g_config->getCoreListForProcess(g_config->getCurrentProcessNum()));
   UInt32 idx = 0;
   for (Config::CLCI i = cores.begin(); i != cores.end(); i++)
   {
      if (*i == id)
      {
         core = m_cores[idx];
         break;
      }

      idx++;
   }

   LOG_ASSERT_ERROR(!core || idx < g_config->getNumLocalCores(), "Illegal index in getCoreFromID!\n");

   return core;
}

Core *CoreManager::getCoreFromIndex(UInt32 index)
{
   LOG_ASSERT_ERROR(index < g_config->getNumLocalCores(), "getCoreFromIndex -- invalid index %d", index);

   return m_cores[index];
}

void CoreManager::outputSummary()
{
   LOG_PRINT("Starting CoreManager::fini");

   ofstream out(g_config->getOutputFileName());

   for (UInt32 i = 0; i < g_config->getNumLocalCores(); i++)
   {
      LOG_PRINT("Output summary core %i", i);

      out << "*** Core[" << i << "] summary ***" << endl;
      if (g_config->getEnablePerformanceModeling())
      {
         m_cores[i]->getPerfModel()->outputSummary(out);
         m_cores[i]->getNetwork()->outputSummary(out);
      }

      if (g_config->getEnableDCacheModeling() || g_config->getEnableICacheModeling())
         m_cores[i]->getOCache()->outputSummary(out);

      delete m_cores[i];
      m_cores[i] = NULL;

      out << endl;
   }

   out.close();

   LOG_PRINT("Finish core_manager::fini");
}

int CoreManager::registerSimMemThread()
{
   UInt32 tid = getCurrentTID();

   ScopedLock sl(*m_maps_lock);
   pair<bool, UINT64> e = simthread_tid_to_core_map.find(tid);

   // If this thread isn't registered
   if (e.first == false)
   {
      // Search for an unused core to map this simthread thread to
      // one less to account for the MCP
      for (UInt32 i = 0; i < g_config->getNumLocalCores(); i++)
      {
         // Unused slots are set to UINT_MAX
         // FIXME: Use a different constant than UINT_MAX
         if (core_to_simthread_tid_map[i] == UINT_MAX)
         {
            core_to_simthread_tid_map[i] = tid;
            simthread_tid_to_core_map.insert(tid, i);
            return g_config->getCoreListForProcess(g_config->getCurrentProcessNum())[i];
         }
      }

      LOG_PRINT("*ERROR* registerSimMemThread - No free cores for thread: %d", tid);
      for (UInt32 j = 0; j < g_config->getNumLocalCores(); j++)
         LOG_PRINT("core_to_simthread_tid_map[%d] = %d\n", j, core_to_simthread_tid_map[j]);

      LOG_NOTIFY_ERROR();
   }
   else
   {
      LOG_PRINT("*WARNING* registerSimMemThread - Initialized thread twice");
      LOG_NOTIFY_WARNING();
      // FIXME: I think this is OK
      return simthread_tid_to_core_map.find(tid).second;
   }

   return -1;
}

UInt32 CoreManager::getCurrentTID()
{
   return  syscall(__NR_gettid);
}

<commit_msg>[core_manager] Don't delete cores during outputSummary.<commit_after>#include <sched.h>
#include <linux/unistd.h>
#include <sys/types.h>
#include <sys/syscall.h>
#include <unistd.h>

#include "core_manager.h"
#include "core.h"
#include "network.h"
#include "ocache.h"
#include "config.h"
#include "packetize.h"
#include "message_types.h"

#include "log.h"
#define LOG_DEFAULT_RANK -1
#define LOG_DEFAULT_MODULE CORE_MANAGER

using namespace std;

CoreManager::CoreManager()
      :
      tid_to_core_map(3*g_config->getNumLocalCores()),
      tid_to_core_index_map(3*g_config->getNumLocalCores()),
      simthread_tid_to_core_map(3*g_config->getNumLocalCores())
{
   LOG_PRINT("Starting CoreManager Constructor.");

   m_maps_lock = Lock::create();

   tid_map = new UInt32 [g_config->getNumLocalCores()];
   core_to_simthread_tid_map = new UInt32 [g_config->getNumLocalCores()];

   // Need to subtract 1 for the MCP
   for (UInt32 i = 0; i < g_config->getNumLocalCores(); i++)
   {
      tid_map[i] = UINT_MAX;
      core_to_simthread_tid_map[i] = UINT_MAX;
      m_cores.push_back(new Core(g_config->getCoreListForProcess(g_config->getCurrentProcessNum())[i]));
   }

   LOG_PRINT("Finished CoreManager Constructor.");
}

CoreManager::~CoreManager()
{
   for (std::vector<Core *>::iterator i = m_cores.begin(); i != m_cores.end(); i++)
      delete *i;

   delete [] core_to_simthread_tid_map;
   delete [] tid_map;

   delete m_maps_lock;
}

void CoreManager::initializeCommId(UInt32 comm_id)
{
   UInt32 tid = getCurrentTID();
   pair<bool, UINT64> e = tid_to_core_map.find(tid);

   LOG_ASSERT_ERROR(e.first, "*ERROR* initializeCommId: Called without binding thread to a core.");
   UInt32 core_id = e.second;

   UnstructuredBuffer send_buff;
   send_buff << MCP_MESSAGE_BROADCAST_COMM_MAP_UPDATE;
   send_buff << comm_id;
   send_buff << core_id;

   LOG_PRINT("CoreMap: CoreManager Initializing comm_id: %d to core_id: %d", comm_id, core_id);

   // Broadcast this update to other cores
   getCoreFromID(core_id)->getNetwork()->netSend((SInt32)g_config->getMCPCoreNum(), MCP_SYSTEM_TYPE,
         (const void *)send_buff.getBuffer(), (UInt32)send_buff.size());

   // This should be used once miniMCPs are implemented.
   // Transport::Node *globalNode = Transport::getSingleton()->getGlobalNode();
   // globalNode->send(g_config->getMcpCoreId(),
   //                  send_buff.getBuffer(),
   //                  send_buff.size());
}

void CoreManager::initializeThread()
{
   ScopedLock scoped_maps_lock(*m_maps_lock);
   UInt32 tid = getCurrentTID();
   pair<bool, UInt64> e = tid_to_core_map.find(tid);

   LOG_ASSERT_ERROR(e.first == false, "*ERROR* Thread: %d already mapped to core: %d", tid, e.second);

   for (UInt32 i = 0; i < g_config->getNumLocalCores(); i++)
   {
      if (tid_map[i] == UINT_MAX)
      {
         UInt32 core_id = g_config->getCoreListForProcess(g_config->getCurrentProcessNum())[i];
         tid_map[i] = tid;
         tid_to_core_index_map.insert(tid, i);
         tid_to_core_map.insert(tid, core_id);
         LOG_PRINT("%d mapped to: %d core_id: %d", i, tid_map[i], core_id);
         return;
      }
      else
      {
         // LOG_PRINT("%d/%d already mapped to: %d", i, g_config->getNumLocalCores(), tid_map[i]);
      }
   }

   LOG_PRINT("*ERROR* initializeThread - No free cores out of %d total.", g_config->getNumLocalCores());
   LOG_NOTIFY_ERROR();
}

void CoreManager::initializeThread(UInt32 core_id)
{
   ScopedLock scoped_maps_lock(*m_maps_lock);
   UInt32 tid = getCurrentTID();
   pair<bool, UInt64> e = tid_to_core_map.find(tid);

   LOG_ASSERT_ERROR(e.first == false, "Tried to initialize core %d twice.", core_id);

   for (unsigned int i = 0; i < g_config->getNumLocalCores(); i++)
   {
      UInt32 local_core_id = g_config->getCoreListForProcess(g_config->getCurrentProcessNum())[i];
      if(local_core_id == core_id)
      {
         if (tid_map[i] == UINT_MAX)
         {
            tid_map[i] = tid;
            tid_to_core_index_map.insert(tid, i);
            tid_to_core_map.insert(tid, core_id);
            LOG_PRINT("%d mapped to: %d core_id: %d", i, tid_map[i], core_id);
            return;
         }
         else
         {
            LOG_PRINT("*ERROR* initializeThread -- %d/%d already mapped to thread %d", i, g_config->getNumLocalCores(), tid_map[i]);
            LOG_NOTIFY_ERROR();
         }
      }
   }

   LOG_PRINT("*ERROR* initializeThread - Requested core %d does not live on process %d.", core_id, g_config->getCurrentProcessNum());
   LOG_NOTIFY_ERROR();
}

UInt32 CoreManager::getCurrentCoreID()
{
   UInt32 id;
   UInt32 tid = getCurrentTID();

   pair<bool, UINT64> e = tid_to_core_map.find(tid);
   id = (e.first == false) ? -1 : e.second;

   ASSERT(!e.first || id < g_config->getTotalCores(), "Illegal core_id value returned by getCurrentCoreID!\n");

   return id;
}

Core *CoreManager::getCurrentCore()
{
   Core *core;
   UInt32 tid = getCurrentTID();

   pair<bool, UINT64> e = tid_to_core_index_map.find(tid);
   core = (e.first == false) ? NULL : m_cores[e.second];

   LOG_ASSERT_ERROR(!e.first || e.second < g_config->getTotalCores(), "Illegal core_id value returned by getCurrentCore!\n");
   return core;
}

Core *CoreManager::getCoreFromID(UInt32 id)
{
   Core *core = NULL;
   // Look up the index from the core list
   // FIXME: make this more cached
   const Config::CoreList & cores(g_config->getCoreListForProcess(g_config->getCurrentProcessNum()));
   UInt32 idx = 0;
   for (Config::CLCI i = cores.begin(); i != cores.end(); i++)
   {
      if (*i == id)
      {
         core = m_cores[idx];
         break;
      }

      idx++;
   }

   LOG_ASSERT_ERROR(!core || idx < g_config->getNumLocalCores(), "Illegal index in getCoreFromID!\n");

   return core;
}

Core *CoreManager::getCoreFromIndex(UInt32 index)
{
   LOG_ASSERT_ERROR(index < g_config->getNumLocalCores(), "getCoreFromIndex -- invalid index %d", index);

   return m_cores[index];
}

void CoreManager::outputSummary()
{
   LOG_PRINT("Starting CoreManager::fini");

   ofstream out(g_config->getOutputFileName());

   for (UInt32 i = 0; i < g_config->getNumLocalCores(); i++)
   {
      LOG_PRINT("Output summary core %i", i);

      out << "*** Core[" << i << "] summary ***" << endl;
      if (g_config->getEnablePerformanceModeling())
      {
         m_cores[i]->getPerfModel()->outputSummary(out);
         m_cores[i]->getNetwork()->outputSummary(out);
      }

      if (g_config->getEnableDCacheModeling() || g_config->getEnableICacheModeling())
         m_cores[i]->getOCache()->outputSummary(out);

      out << endl;
   }

   out.close();

   LOG_PRINT("Finish core_manager::fini");
}

int CoreManager::registerSimMemThread()
{
   UInt32 tid = getCurrentTID();

   ScopedLock sl(*m_maps_lock);
   pair<bool, UINT64> e = simthread_tid_to_core_map.find(tid);

   // If this thread isn't registered
   if (e.first == false)
   {
      // Search for an unused core to map this simthread thread to
      // one less to account for the MCP
      for (UInt32 i = 0; i < g_config->getNumLocalCores(); i++)
      {
         // Unused slots are set to UINT_MAX
         // FIXME: Use a different constant than UINT_MAX
         if (core_to_simthread_tid_map[i] == UINT_MAX)
         {
            core_to_simthread_tid_map[i] = tid;
            simthread_tid_to_core_map.insert(tid, i);
            return g_config->getCoreListForProcess(g_config->getCurrentProcessNum())[i];
         }
      }

      LOG_PRINT("*ERROR* registerSimMemThread - No free cores for thread: %d", tid);
      for (UInt32 j = 0; j < g_config->getNumLocalCores(); j++)
         LOG_PRINT("core_to_simthread_tid_map[%d] = %d\n", j, core_to_simthread_tid_map[j]);

      LOG_NOTIFY_ERROR();
   }
   else
   {
      LOG_PRINT("*WARNING* registerSimMemThread - Initialized thread twice");
      LOG_NOTIFY_WARNING();
      // FIXME: I think this is OK
      return simthread_tid_to_core_map.find(tid).second;
   }

   return -1;
}

UInt32 CoreManager::getCurrentTID()
{
   return  syscall(__NR_gettid);
}

<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkAttributeData.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/
#include "vtkAttributeData.h"
#include "vtkBitArray.h"
#include "vtkCharArray.h"
#include "vtkUnsignedCharArray.h"
#include "vtkShortArray.h"
#include "vtkUnsignedShortArray.h"
#include "vtkIntArray.h"
#include "vtkUnsignedIntArray.h"
#include "vtkLongArray.h"
#include "vtkUnsignedLongArray.h"
#include "vtkFloatArray.h"
#include "vtkDoubleArray.h"

// Construct object with an initial data array of type dataType (by default
// dataType is VTK_FLOAT.
vtkAttributeData::vtkAttributeData(int dataType)
{
  this->Data = vtkFloatArray::New();
  this->Data->Register(this);
  this->Data->Delete();
  this->SetDataType(dataType);
}

vtkAttributeData::vtkAttributeData()
{
  this->Data = vtkFloatArray::New();
  this->Data->Register(this);
  this->Data->Delete();
}

vtkAttributeData::~vtkAttributeData()
{
  this->Data->UnRegister(this);
}

int vtkAttributeData::Allocate(const int sz, const int ext)
{
  int numComp=this->Data->GetNumberOfComponents();
  return this->Data->Allocate(sz*numComp,ext*numComp);
}

void vtkAttributeData::Initialize()
{
  this->Data->Initialize();
}

int vtkAttributeData::GetDataType()
{
  return this->Data->GetDataType();
}

// Specify the underlying data type of the object.
void vtkAttributeData::SetDataType(int dataType)
{
  if ( dataType == this->Data->GetDataType() )
    {
    return;
    }

  this->Modified();

  switch (dataType)
    {
    case VTK_BIT:
      this->Data->Delete();
      this->Data = vtkBitArray::New();
      break;

    case VTK_CHAR:
      this->Data->Delete();
      this->Data = vtkCharArray::New();
      break;

    case VTK_UNSIGNED_CHAR:
      this->Data->Delete();
      this->Data = vtkUnsignedCharArray::New();
      break;

    case VTK_SHORT:
      this->Data->Delete();
      this->Data = vtkShortArray::New();
      break;

    case VTK_UNSIGNED_SHORT:
      this->Data->Delete();
      this->Data = vtkUnsignedShortArray::New();
      break;

    case VTK_INT:
      this->Data->Delete();
      this->Data = vtkIntArray::New();
      break;

    case VTK_UNSIGNED_INT:
      this->Data->Delete();
      this->Data = vtkUnsignedIntArray::New();
      break;

    case VTK_LONG:
      this->Data->Delete();
      this->Data = vtkLongArray::New();
      break;

    case VTK_UNSIGNED_LONG:
      this->Data->Delete();
      this->Data = vtkUnsignedLongArray::New();
      break;

    case VTK_FLOAT:
      this->Data->Delete();
      this->Data = vtkFloatArray::New();
      break;

    case VTK_DOUBLE:
      this->Data->Delete();
      this->Data = vtkDoubleArray::New();
      break;

    default:
      vtkErrorMacro(<<"Unsupported data type! Setting to VTK_FLOAT");
      this->SetDataType(VTK_FLOAT);
    }
}

// Set the data for this object. The tuple dimension must be consistent with
// the object.
void vtkAttributeData::SetData(vtkDataArray *data)
{
  if ( data != this->Data && data != NULL )
    {
    if (data->GetNumberOfComponents() != this->Data->GetNumberOfComponents() )
      {
      vtkErrorMacro(<<"Number of components is different...can't set data");
      return;
      }
    this->Data->UnRegister(this);
    this->Data = data;
    this->Data->Register(this);
    this->Modified();
    }
}

// Deep copy of data. Checks consistency to make sure this operation
// makes sense.
void vtkAttributeData::DeepCopy(vtkAttributeData *da)
{
  if ( da->Data != this->Data && da->Data != NULL )
    {
    if (da->Data->GetNumberOfComponents() != this->Data->GetNumberOfComponents() )
      {
      vtkErrorMacro(<<"Number of components is different...can't copy");
      return;
      }
    this->Data->DeepCopy(da->Data);
    this->Modified();
    }
}

// Shallow copy of data (i.e. via reference counting). Checks
// consistency to make sure this operation makes sense.
void vtkAttributeData::ShallowCopy(vtkAttributeData *da)
{
  this->SetData(da->GetData());
}

unsigned long vtkAttributeData::GetActualMemorySize()
{
  return this->Data->GetActualMemorySize();
}

void vtkAttributeData::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkObject::PrintSelf(os,indent);

  os << indent << "Data: " << this->Data << "\n";
}

<commit_msg>Better error checking during copy.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkAttributeData.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/
#include "vtkAttributeData.h"
#include "vtkBitArray.h"
#include "vtkCharArray.h"
#include "vtkUnsignedCharArray.h"
#include "vtkShortArray.h"
#include "vtkUnsignedShortArray.h"
#include "vtkIntArray.h"
#include "vtkUnsignedIntArray.h"
#include "vtkLongArray.h"
#include "vtkUnsignedLongArray.h"
#include "vtkFloatArray.h"
#include "vtkDoubleArray.h"

// Construct object with an initial data array of type dataType (by default
// dataType is VTK_FLOAT.
vtkAttributeData::vtkAttributeData(int dataType)
{
  this->Data = vtkFloatArray::New();
  this->Data->Register(this);
  this->Data->Delete();
  this->SetDataType(dataType);
}

vtkAttributeData::vtkAttributeData()
{
  this->Data = vtkFloatArray::New();
  this->Data->Register(this);
  this->Data->Delete();
}

vtkAttributeData::~vtkAttributeData()
{
  this->Data->UnRegister(this);
}

int vtkAttributeData::Allocate(const int sz, const int ext)
{
  int numComp=this->Data->GetNumberOfComponents();
  return this->Data->Allocate(sz*numComp,ext*numComp);
}

void vtkAttributeData::Initialize()
{
  this->Data->Initialize();
}

int vtkAttributeData::GetDataType()
{
  return this->Data->GetDataType();
}

// Specify the underlying data type of the object.
void vtkAttributeData::SetDataType(int dataType)
{
  if ( dataType == this->Data->GetDataType() )
    {
    return;
    }

  this->Modified();

  switch (dataType)
    {
    case VTK_BIT:
      this->Data->Delete();
      this->Data = vtkBitArray::New();
      break;

    case VTK_CHAR:
      this->Data->Delete();
      this->Data = vtkCharArray::New();
      break;

    case VTK_UNSIGNED_CHAR:
      this->Data->Delete();
      this->Data = vtkUnsignedCharArray::New();
      break;

    case VTK_SHORT:
      this->Data->Delete();
      this->Data = vtkShortArray::New();
      break;

    case VTK_UNSIGNED_SHORT:
      this->Data->Delete();
      this->Data = vtkUnsignedShortArray::New();
      break;

    case VTK_INT:
      this->Data->Delete();
      this->Data = vtkIntArray::New();
      break;

    case VTK_UNSIGNED_INT:
      this->Data->Delete();
      this->Data = vtkUnsignedIntArray::New();
      break;

    case VTK_LONG:
      this->Data->Delete();
      this->Data = vtkLongArray::New();
      break;

    case VTK_UNSIGNED_LONG:
      this->Data->Delete();
      this->Data = vtkUnsignedLongArray::New();
      break;

    case VTK_FLOAT:
      this->Data->Delete();
      this->Data = vtkFloatArray::New();
      break;

    case VTK_DOUBLE:
      this->Data->Delete();
      this->Data = vtkDoubleArray::New();
      break;

    default:
      vtkErrorMacro(<<"Unsupported data type! Setting to VTK_FLOAT");
      this->SetDataType(VTK_FLOAT);
    }
}

// Set the data for this object. The tuple dimension must be consistent with
// the object.
void vtkAttributeData::SetData(vtkDataArray *data)
{
  if ( data != this->Data && data != NULL )
    {
    if (data->GetNumberOfComponents() != this->Data->GetNumberOfComponents() )
      {
      vtkErrorMacro(<<"Number of components is different...can't set data");
      return;
      }
    this->Data->UnRegister(this);
    this->Data = data;
    this->Data->Register(this);
    this->Modified();
    }
}

// Deep copy of data. Checks consistency to make sure this operation
// makes sense.
void vtkAttributeData::DeepCopy(vtkAttributeData *da)
{
  if (da == NULL)
    {
    return;
    }
  if ( da->Data != this->Data && da->Data != NULL )
    {
    if (da->Data->GetNumberOfComponents() != this->Data->GetNumberOfComponents() )
      {
      vtkErrorMacro(<<"Number of components is different...can't copy");
      return;
      }
    this->Data->DeepCopy(da->Data);
    this->Modified();
    }
}

// Shallow copy of data (i.e. via reference counting). Checks
// consistency to make sure this operation makes sense.
void vtkAttributeData::ShallowCopy(vtkAttributeData *da)
{
  this->SetData(da->GetData());
}

unsigned long vtkAttributeData::GetActualMemorySize()
{
  return this->Data->GetActualMemorySize();
}

void vtkAttributeData::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkObject::PrintSelf(os,indent);

  os << indent << "Data: " << this->Data << "\n";
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: MABConnection.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: fs $ $Date: 2001-06-25 09:51:16 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_MAB_CONNECTION_HXX_
#define _CONNECTIVITY_MAB_CONNECTION_HXX_

#ifndef _CONNECTIVITY_FILE_OCONNECTION_HXX_
#include "file/FConnection.hxx"
#endif

namespace com { namespace sun { namespace star { namespace sheet {
    class XSpreadsheetDocument;
} } } }

namespace connectivity
{
    namespace mozaddressbook
    {
        class OMozabDriver;
        class OMozabConnection : public file::OConnection
        {

            sal_Int32       m_nAnonABCount;
            rtl::OUString   m_sMozillaURI;
            sal_Bool        m_UsesFactory ;
            sal_Bool        m_IsLDAP ;

        public:
            OMozabConnection(OMozabDriver* _pDriver);
            virtual ~OMozabConnection();

            virtual void construct(const ::rtl::OUString& _rUrl,
                const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rInfo )
                throw( ::com::sun::star::sdbc::SQLException);

            // XServiceInfo
            DECLARE_SERVICE_INFO();

            // OComponentHelper
            virtual void SAL_CALL disposing(void);

            // XConnection
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > createCatalog();
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

            // no interface methods
            rtl::OUString getMozURI() const
                { return m_sMozillaURI; }

            sal_Bool usesFactory(void) const { return m_UsesFactory ; }
            sal_Bool isLDAP(void) const { return m_IsLDAP ; }

            sal_Int32 getNextAnonymousAB()
                { return (++m_nAnonABCount); }
        };
    }
}

#endif // _CONNECTIVITY_MAB_CONNECTION_HXX_

<commit_msg>added int for max result records<commit_after>/*************************************************************************
 *
 *  $RCSfile: MABConnection.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: fs $ $Date: 2001-06-27 14:56:47 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_MAB_CONNECTION_HXX_
#define _CONNECTIVITY_MAB_CONNECTION_HXX_

#ifndef _CONNECTIVITY_FILE_OCONNECTION_HXX_
#include "file/FConnection.hxx"
#endif

namespace com { namespace sun { namespace star { namespace sheet {
    class XSpreadsheetDocument;
} } } }

namespace connectivity
{
    namespace mozaddressbook
    {
        class OMozabDriver;
        class OMozabConnection : public file::OConnection
        {

            rtl::OUString   m_sMozillaURI;
            sal_Int32       m_nAnonABCount;
            sal_Int32       m_nMaxResultRecords;
            sal_Bool        m_UsesFactory ;
            sal_Bool        m_IsLDAP ;

        public:
            OMozabConnection(OMozabDriver* _pDriver);
            virtual ~OMozabConnection();

            virtual void construct(const ::rtl::OUString& _rUrl,
                const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rInfo )
                throw( ::com::sun::star::sdbc::SQLException);

            // XServiceInfo
            DECLARE_SERVICE_INFO();

            // OComponentHelper
            virtual void SAL_CALL disposing(void);

            // XConnection
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > createCatalog();
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

            // no interface methods
            rtl::OUString getMozURI() const
                { return m_sMozillaURI; }

            sal_Bool usesFactory(void) const { return m_UsesFactory ; }
            sal_Bool isLDAP(void) const { return m_IsLDAP ; }

            sal_Int32   getNextAnonymousAB()    { return (++m_nAnonABCount); }
            sal_Int32   getMaxResultRecords()   { return m_nMaxResultRecords; }
        };
    }
}

#endif // _CONNECTIVITY_MAB_CONNECTION_HXX_

<|endoftext|>


<commit_before>/*
 * Stack.cpp
 *
 *  Created on: 24 Oct 2015
 *      Author: hieu
 */
#include <algorithm>
#include <boost/foreach.hpp>
#include "Stack.h"
#include "../Hypothesis.h"
#include "../Manager.h"
#include "../../Scores.h"
#include "../../System.h"

using namespace std;

namespace Moses2
{

namespace NSCubePruning
{
MiniStack::MiniStack(const Manager &mgr)
:m_coll(MemPoolAllocator<const Hypothesis*>(mgr.GetPool()))
,m_sortedHypos(NULL)
{}

StackAdd MiniStack::Add(const Hypothesis *hypo)
{
  std::pair<MiniStack::_HCType::iterator, bool> addRet = m_coll.insert(hypo);

  // CHECK RECOMBINATION
  if (addRet.second) {
	// equiv hypo doesn't exists
	return StackAdd(true, NULL);
  }
  else {
	  const Hypothesis *hypoExisting = *addRet.first;
	  if (hypo->GetScores().GetTotalScore() > hypoExisting->GetScores().GetTotalScore()) {
		  // incoming hypo is better than the one we have
		  const Hypothesis *const &hypoExisting1 = *addRet.first;
		  const Hypothesis *&hypoExisting2 = const_cast<const Hypothesis *&>(hypoExisting1);
		  hypoExisting2 = hypo;

		  return StackAdd(true, const_cast<Hypothesis*>(hypoExisting));
	  }
	  else {
		  // already storing the best hypo. discard incoming hypo
		  return StackAdd(false, const_cast<Hypothesis*>(hypo));
	  }
  }

  assert(false);
}

CubeEdge::Hypotheses &MiniStack::GetSortedAndPruneHypos(const Manager &mgr) const
{
  if (m_sortedHypos == NULL) {
    // create sortedHypos first
    MemPool &pool = mgr.GetPool();
	m_sortedHypos = new (pool.Allocate< Vector<const Hypothesis*> >()) Vector<const Hypothesis*>(pool, m_coll.size());

	  size_t ind = 0;
	  BOOST_FOREACH(const Hypothesis *hypo, m_coll) {
		  (*m_sortedHypos)[ind] = hypo;
		  ++ind;
	  }

    SortAndPruneHypos(mgr);
  }

  return *m_sortedHypos;
}

void MiniStack::SortAndPruneHypos(const Manager &mgr) const
{
  size_t stackSize = mgr.system.stackSize;
  Recycler<Hypothesis*> &recycler = mgr.GetHypoRecycle();

  /*
  cerr << "UNSORTED hypos:" << endl;
  for (size_t i = 0; i < hypos.size(); ++i) {
	  const Hypothesis *hypo = hypos[i];
	  cerr << *hypo << endl;
  }
  cerr << endl;
  */
  Vector<const Hypothesis*>::iterator iterMiddle;
  iterMiddle = (stackSize == 0 || m_sortedHypos->size() < stackSize)
			   ? m_sortedHypos->end()
			   : m_sortedHypos->begin() + stackSize;

  std::partial_sort(m_sortedHypos->begin(), iterMiddle, m_sortedHypos->end(),
		  HypothesisFutureScoreOrderer());

  // prune
  if (stackSize && m_sortedHypos->size() > stackSize) {
	  for (size_t i = stackSize; i < m_sortedHypos->size(); ++i) {
		  Hypothesis *hypo = const_cast<Hypothesis*>((*m_sortedHypos)[i]);
		  recycler.Add(hypo);
	  }
	  m_sortedHypos->resize(stackSize);
  }

  /*
  cerr << "sorted hypos:" << endl;
  for (size_t i = 0; i < hypos.size(); ++i) {
	  const Hypothesis *hypo = hypos[i];
	  cerr << hypo << " " << *hypo << endl;
  }
  cerr << endl;
  */

}

///////////////////////////////////////////////////////////////
Stack::Stack(const Manager &mgr)
:m_mgr(mgr)
,m_coll(MemPoolAllocator< std::pair<HypoCoverage, MiniStack*> >(mgr.GetPool()))
{
}

Stack::~Stack() {
	// TODO Auto-generated destructor stub
}

void Stack::Add(const Hypothesis *hypo, Recycler<Hypothesis*> &hypoRecycle)
{
  HypoCoverage key(&hypo->GetBitmap(), hypo->GetInputPath().range.GetEndPos());
  StackAdd added = GetMiniStack(key).Add(hypo);

  if (added.toBeDeleted) {
	hypoRecycle.Add(added.toBeDeleted);
  }
}

std::vector<const Hypothesis*> Stack::GetBestHypos(size_t num) const
{
  std::vector<const Hypothesis*> ret;
  BOOST_FOREACH(const Coll::value_type &val, m_coll) {
		const MiniStack::_HCType &hypos = val.second->GetColl();
		ret.insert(ret.end(), hypos.begin(), hypos.end());
  }

  std::vector<const Hypothesis*>::iterator iterMiddle;
  iterMiddle = (num == 0 || ret.size() < num)
			   ? ret.end()
			   : ret.begin()+num;

  std::partial_sort(ret.begin(), iterMiddle, ret.end(),
		  HypothesisFutureScoreOrderer());

  return ret;
}

size_t Stack::GetHypoSize() const
{
	size_t ret = 0;
	BOOST_FOREACH(const Coll::value_type &val, m_coll) {
		const MiniStack::_HCType &hypos = val.second->GetColl();
		ret += hypos.size();
	}
	return ret;
}

MiniStack &Stack::GetMiniStack(const HypoCoverage &key)
{
	MiniStack *ret;
	Coll::iterator iter = m_coll.find(key);
	if (iter == m_coll.end()) {
		ret = new (m_mgr.GetPool().Allocate<MiniStack>()) MiniStack(m_mgr);
		m_coll[key] = ret;
	}
	else {
		ret = iter->second;
	}
	return *ret;

	//return m_coll[key];
}

}

}

<commit_msg>prefetch losing hypo for reuse<commit_after>/*
 * Stack.cpp
 *
 *  Created on: 24 Oct 2015
 *      Author: hieu
 */
#include <algorithm>
#include <boost/foreach.hpp>
#include "Stack.h"
#include "../Hypothesis.h"
#include "../Manager.h"
#include "../../Scores.h"
#include "../../System.h"

using namespace std;

namespace Moses2
{

namespace NSCubePruning
{
MiniStack::MiniStack(const Manager &mgr)
:m_coll(MemPoolAllocator<const Hypothesis*>(mgr.GetPool()))
,m_sortedHypos(NULL)
{}

StackAdd MiniStack::Add(const Hypothesis *hypo)
{
  std::pair<_HCType::iterator, bool> addRet = m_coll.insert(hypo);

  // CHECK RECOMBINATION
  if (addRet.second) {
	// equiv hypo doesn't exists
	return StackAdd(true, NULL);
  }
  else {
	  const Hypothesis *hypoExisting = *addRet.first;
	  if (hypo->GetScores().GetTotalScore() > hypoExisting->GetScores().GetTotalScore()) {
		  // incoming hypo is better than the one we have
		  const Hypothesis *const &hypoExisting1 = *addRet.first;
		  const Hypothesis *&hypoExisting2 = const_cast<const Hypothesis *&>(hypoExisting1);
		  hypoExisting2 = hypo;

		  return StackAdd(true, const_cast<Hypothesis*>(hypoExisting));
	  }
	  else {
		  // already storing the best hypo. discard incoming hypo
		  return StackAdd(false, const_cast<Hypothesis*>(hypo));
	  }
  }

  assert(false);
}

CubeEdge::Hypotheses &MiniStack::GetSortedAndPruneHypos(const Manager &mgr) const
{
  if (m_sortedHypos == NULL) {
    // create sortedHypos first
    MemPool &pool = mgr.GetPool();
	m_sortedHypos = new (pool.Allocate< Vector<const Hypothesis*> >()) Vector<const Hypothesis*>(pool, m_coll.size());

	  size_t ind = 0;
	  BOOST_FOREACH(const Hypothesis *hypo, m_coll) {
		  (*m_sortedHypos)[ind] = hypo;
		  ++ind;
	  }

    SortAndPruneHypos(mgr);
  }

  return *m_sortedHypos;
}

void MiniStack::SortAndPruneHypos(const Manager &mgr) const
{
  size_t stackSize = mgr.system.stackSize;
  Recycler<Hypothesis*> &recycler = mgr.GetHypoRecycle();

  /*
  cerr << "UNSORTED hypos:" << endl;
  for (size_t i = 0; i < hypos.size(); ++i) {
	  const Hypothesis *hypo = hypos[i];
	  cerr << *hypo << endl;
  }
  cerr << endl;
  */
  Vector<const Hypothesis*>::iterator iterMiddle;
  iterMiddle = (stackSize == 0 || m_sortedHypos->size() < stackSize)
			   ? m_sortedHypos->end()
			   : m_sortedHypos->begin() + stackSize;

  std::partial_sort(m_sortedHypos->begin(), iterMiddle, m_sortedHypos->end(),
		  HypothesisFutureScoreOrderer());

  // prune
  if (stackSize && m_sortedHypos->size() > stackSize) {
	  for (size_t i = stackSize; i < m_sortedHypos->size(); ++i) {
		  Hypothesis *hypo = const_cast<Hypothesis*>((*m_sortedHypos)[i]);
		  recycler.Add(hypo);
	  }
	  m_sortedHypos->resize(stackSize);
  }

  /*
  cerr << "sorted hypos:" << endl;
  for (size_t i = 0; i < hypos.size(); ++i) {
	  const Hypothesis *hypo = hypos[i];
	  cerr << hypo << " " << *hypo << endl;
  }
  cerr << endl;
  */

}

///////////////////////////////////////////////////////////////
Stack::Stack(const Manager &mgr)
:m_mgr(mgr)
,m_coll(MemPoolAllocator< std::pair<HypoCoverage, MiniStack*> >(mgr.GetPool()))
{
}

Stack::~Stack() {
	// TODO Auto-generated destructor stub
}

void Stack::Add(const Hypothesis *hypo, Recycler<Hypothesis*> &hypoRecycle)
{
  HypoCoverage key(&hypo->GetBitmap(), hypo->GetInputPath().range.GetEndPos());
  StackAdd added = GetMiniStack(key).Add(hypo);

  __builtin_prefetch(added.toBeDeleted);

  if (added.toBeDeleted) {
	hypoRecycle.Add(added.toBeDeleted);
  }
}

std::vector<const Hypothesis*> Stack::GetBestHypos(size_t num) const
{
  std::vector<const Hypothesis*> ret;
  BOOST_FOREACH(const Coll::value_type &val, m_coll) {
		const MiniStack::_HCType &hypos = val.second->GetColl();
		ret.insert(ret.end(), hypos.begin(), hypos.end());
  }

  std::vector<const Hypothesis*>::iterator iterMiddle;
  iterMiddle = (num == 0 || ret.size() < num)
			   ? ret.end()
			   : ret.begin()+num;

  std::partial_sort(ret.begin(), iterMiddle, ret.end(),
		  HypothesisFutureScoreOrderer());

  return ret;
}

size_t Stack::GetHypoSize() const
{
	size_t ret = 0;
	BOOST_FOREACH(const Coll::value_type &val, m_coll) {
		const MiniStack::_HCType &hypos = val.second->GetColl();
		ret += hypos.size();
	}
	return ret;
}

MiniStack &Stack::GetMiniStack(const HypoCoverage &key)
{
	MiniStack *ret;
	Coll::iterator iter = m_coll.find(key);
	if (iter == m_coll.end()) {
		ret = new (m_mgr.GetPool().Allocate<MiniStack>()) MiniStack(m_mgr);
		m_coll[key] = ret;
	}
	else {
		ret = iter->second;
	}
	return *ret;

	//return m_coll[key];
}

}

}

<|endoftext|>


<commit_before>/**
 ** \file object/event-class.cc
 ** \brief Creation of the URBI object event.
 */

#include <boost/assign.hpp>

#include <object/code-class.hh>
#include <object/event-class.hh>
#include <object/float-class.hh>
#include <object/list-class.hh>
#include <object/object.hh>
#include <runner/runner.hh>

namespace object
{
  using namespace boost::assign;

  rObject event_class;

  Event::Event()
    : value_(new List)
    , active_(false)
  {
    proto_add(event_class);
  }

  Event::Event(const value_type& value)
    : value_(value)
    , active_(false)
  {
    proto_add(event_class);
  }

  Event::Event(rEvent model)
    : value_(model->value_)
    , active_(false)
  {
    proto_add(event_class);
  }

  rObject
  Event::active()
  {
    return active_get() ? true_class : false_class;
  }

  bool
  Event::active_get() const
  {
    return active_;
  }

  rList
  Event::alive()
  {
    return live_;
  }

  void
  Event::stop()
  {
    active_ = false;
    live_->remove_by_id(this);
  }

  rEvent
  Event::trigger(runner::Runner& r, objects_type payload)
  {
    rEvent instance = new Event(this);
    instance->value_ = new List(payload);
    instance->active_ = true;
    live_->push_back(instance);
    urbi_call(r, this, SYMBOL(emit), payload);
    return instance;
  }

  rList
  Event::values()
  {
    return value_;
  }

  const Event::value_type&
  Event::value_get() const
  {
    return value_;
  }

  void
  Event::initialize(CxxObject::Binder<Event>& bind)
  {
    bind(SYMBOL(active), &Event::active);
    bind(SYMBOL(alive), &Event::alive);
    bind(SYMBOL(stop), &Event::stop);
    bind(SYMBOL(trigger), &Event::trigger);
    bind(SYMBOL(values), &Event::values);
  }

  bool Event::event_added = CxxObject::add<Event>("Event", event_class);
  const std::string Event::type_name = "Event";
  std::string Event::type_name_get() const
  {
    return type_name;
  }

} // namespace object
<commit_msg>Build active event list in constructor.<commit_after>/**
 ** \file object/event-class.cc
 ** \brief Creation of the URBI object event.
 */

#include <boost/assign.hpp>

#include <object/code-class.hh>
#include <object/event-class.hh>
#include <object/float-class.hh>
#include <object/list-class.hh>
#include <object/object.hh>
#include <runner/runner.hh>

namespace object
{
  using namespace boost::assign;

  rObject event_class;

  Event::Event()
    : value_(new List)
    , active_(false)
    , live_(new List)
  {
    proto_add(event_class);
  }

  Event::Event(const value_type& value)
    : value_(value)
    , active_(false)
    , live_(new List)
  {
    proto_add(event_class);
  }

  Event::Event(rEvent model)
    : value_(model->value_)
    , active_(false)
    , live_(model->live_)
  {
    proto_add(event_class);
  }

  rObject
  Event::active()
  {
    return active_get() ? true_class : false_class;
  }

  bool
  Event::active_get() const
  {
    return active_;
  }

  rList
  Event::alive()
  {
    return live_;
  }

  void
  Event::stop()
  {
    active_ = false;
    live_->remove_by_id(this);
  }

  rEvent
  Event::trigger(runner::Runner& r, objects_type payload)
  {
    rEvent instance = new Event(this);
    instance->value_ = new List(payload);
    instance->active_ = true;
    live_->push_back(instance);
    urbi_call(r, this, SYMBOL(emit), payload);
    return instance;
  }

  rList
  Event::values()
  {
    return value_;
  }

  const Event::value_type&
  Event::value_get() const
  {
    return value_;
  }

  void
  Event::initialize(CxxObject::Binder<Event>& bind)
  {
    bind(SYMBOL(active), &Event::active);
    bind(SYMBOL(alive), &Event::alive);
    bind(SYMBOL(stop), &Event::stop);
    bind(SYMBOL(trigger), &Event::trigger);
    bind(SYMBOL(values), &Event::values);
  }

  bool Event::event_added = CxxObject::add<Event>("Event", event_class);
  const std::string Event::type_name = "Event";
  std::string Event::type_name_get() const
  {
    return type_name;
  }

} // namespace object
<|endoftext|>


<commit_before>#include <cctype>

#include <libport/lexical-cast.hh>

#include <object/format-info.hh>
#include <object/symbols.hh>

namespace object
{
  FormatInfo::FormatInfo()
    : alignment_(Align::RIGHT)
    , alt_(false)
    , case_(Case::UNDEFINED)
    , group_(0)
    , pad_(' ')
    , pattern_("%s")
    , precision_(6)
    , prefix_(0)
    , spec_('s')
    , width_(0)
  {
    proto_add(proto ? proto : Object::proto);
  }

  FormatInfo::FormatInfo(rFormatInfo model)
    : alignment_(model->alignment_)
    , alt_(model->alt_)
    , case_(model->case_)
    , group_(model->group_)
    , pad_(model->pad_)
    , pattern_(model->pattern_)
    , precision_(model->precision_)
    , prefix_(model->prefix_)
    , spec_(model->spec_)
    , width_(model->width_)
  {
    proto_add(model);
  }

  void
  FormatInfo::init(const std::string& pattern)
  {
    size_t cursor = 0;
    bool piped;

    if (pattern.empty())
      runner::raise_primitive_error("pattern is empty");
    if (pattern[0] != '%')
      runner::raise_primitive_error("format: Pattern \"" + pattern
                                    + "\" doesn't begin with %");
    if (pattern.size() == 1)
      runner::raise_primitive_error("format: Trailing `%'");
    if ((piped = pattern[1] == '|'))
    {
      size_t pos = pattern.find_first_of('|', 2);
      if (pos == pattern.npos)
        runner::raise_primitive_error("format begins with '|' but "
                                     "doesn't end with '|'");
      pattern_ = pattern.substr(0, pos + 1);
      cursor++;
    }

    // Parsing flags.
    std::string flags("-=+#0 '");
    std::string excludes("");
    char current;
    while ((pattern.size() > ++cursor)
           && flags.npos != flags.find(current = pattern[cursor]))
    {
// FIXME:
//    if (excludes.npos != excludes.find(current))
//      WARNING;
      switch (current)
      {
        case '-': alignment_ = Align::LEFT; excludes += "-="; break;
        case '=': alignment_ = Align::CENTER; excludes += "-="; break;
        case '+': prefix_ = '+'; excludes + " +"; break;
        case ' ': prefix_ = ' '; excludes + " +"; break;
        case '0': pad_ = '0'; break;
        case '#': alt_ = true; break;
        case '\'': group_ = ' '; break;
      };
    }

    // Parsing width.
    std::string substr_ =
      pattern.substr(cursor,
                     pattern.find_first_not_of("0123456789",
                                               cursor) - cursor);
    if (substr_.size())
    {
      width_ = lexical_cast<size_t>(substr_);
      cursor += substr_.size();
    }

    // Parsing precision.
    if (pattern.size() > cursor && pattern[cursor] == '.' && cursor++)
    {
      substr_ =
        pattern.substr(cursor, pattern.find_first_not_of("0123456789",
                                                         cursor) - cursor);
      if (substr_.size())
      {
        precision_ = lexical_cast<unsigned int>(substr_);
        cursor += substr_.size();
      }
      else
        runner::raise_primitive_error(std::string("format: Unexpected \"")
                                      + pattern[cursor]
                                      + "\", expected width ([1-9][0-9]*).");
    }

    // Parsing spec.
    if ((piped && cursor < pattern_.size() - 1)
        || (!piped && cursor < pattern.size()))
    {
      spec_ = tolower(current = pattern[cursor]);
      substr_ = "sdbxoefgEGDX";
      if (substr_.find(spec_) != substr_.npos)
      {
        if (spec_ != 's')
          case_ = (islower(pattern[cursor])) ? Case::LOWER : Case::UPPER;
      }
      else
        runner::raise_primitive_error
          (std::string("format: \"") + spec_
           + "\" is not a valid conversion type character");
    }

    int overflow;
    if (piped)
    {
      if ((overflow = pattern_.size() - 1 - ++cursor) > 0)
        runner::raise_primitive_error("format is between pipes and \""
                                      + pattern_.substr(cursor, overflow)
                                      + "\" are too many characters");
    }
    else
      pattern_ = pattern.substr(0, ++cursor);
  }

  std::string
  FormatInfo::as_string() const
  {
    return pattern_;
  }

  void
  FormatInfo::initialize(CxxObject::Binder<FormatInfo>& bind)
  {
    bind(SYMBOL(init), &FormatInfo::init);
    bind(SYMBOL(asString), &FormatInfo::as_string);
    bind(SYMBOL(width), &FormatInfo::width_get);
    bind(SYMBOL(precision), &FormatInfo::precision_get);
    bind(SYMBOL(alt), &FormatInfo::alt_get);
    bind(SYMBOL(prefix), &FormatInfo::prefix_get);
    bind(SYMBOL(alignment), &FormatInfo::alignment_get);
    bind(SYMBOL(uppercase), &FormatInfo::case_get);
    bind(SYMBOL(group), &FormatInfo::group_get);
    bind(SYMBOL(pad), &FormatInfo::pad_get);
    bind(SYMBOL(spec), &FormatInfo::spec_get);
    bind(SYMBOL(pattern), &FormatInfo::pattern_get);
  }

  rObject
  FormatInfo::proto_make()
  {
    return new FormatInfo();
  }

  URBI_CXX_OBJECT_REGISTER(FormatInfo);
} // namespace object
<commit_msg>format-info: style changes.<commit_after>#include <cctype>

#include <libport/lexical-cast.hh>

#include <object/format-info.hh>
#include <object/symbols.hh>

namespace object
{
  FormatInfo::FormatInfo()
    : alignment_(Align::RIGHT)
    , alt_(false)
    , case_(Case::UNDEFINED)
    , group_(0)
    , pad_(' ')
    , pattern_("%s")
    , precision_(6)
    , prefix_(0)
    , spec_('s')
    , width_(0)
  {
    proto_add(proto ? proto : Object::proto);
  }

  FormatInfo::FormatInfo(rFormatInfo model)
    : alignment_(model->alignment_)
    , alt_(model->alt_)
    , case_(model->case_)
    , group_(model->group_)
    , pad_(model->pad_)
    , pattern_(model->pattern_)
    , precision_(model->precision_)
    , prefix_(model->prefix_)
    , spec_(model->spec_)
    , width_(model->width_)
  {
    proto_add(model);
  }

  void
  FormatInfo::init(const std::string& pattern)
  {
    size_t cursor = 0;
    bool piped;

    if (pattern.empty())
      RAISE("format: pattern is empty");
    if (pattern[0] != '%')
      RAISE("format: pattern \"" + pattern + "\" doesn't begin with %");
    if (pattern.size() == 1)
      RAISE("format: trailing `%'");
    if ((piped = pattern[1] == '|'))
    {
      size_t pos = pattern.find_first_of('|', 2);
      if (pos == pattern.npos)
        RAISE("format: format begins with '|' but "
              "does not end with '|'");
      pattern_ = pattern.substr(0, pos + 1);
      cursor++;
    }

    // Parsing flags.
    std::string flags("-=+#0 '");
    std::string excludes("");
    char current;
    while ((pattern.size() > ++cursor)
           && flags.npos != flags.find(current = pattern[cursor]))
    {
// FIXME:
//    if (excludes.npos != excludes.find(current))
//      WARNING;
      switch (current)
      {
        case '-': alignment_ = Align::LEFT; excludes += "-="; break;
        case '=': alignment_ = Align::CENTER; excludes += "-="; break;
        case '+': prefix_ = '+'; excludes + " +"; break;
        case ' ': prefix_ = ' '; excludes + " +"; break;
        case '0': pad_ = '0'; break;
        case '#': alt_ = true; break;
        case '\'': group_ = ' '; break;
      };
    }

    // Parsing width.
    std::string substr_ =
      pattern.substr(cursor,
                     pattern.find_first_not_of("0123456789",
                                               cursor) - cursor);
    if (substr_.size())
    {
      width_ = lexical_cast<size_t>(substr_);
      cursor += substr_.size();
    }

    // Parsing precision.
    if (pattern.size() > cursor && pattern[cursor] == '.' && cursor++)
    {
      substr_ =
        pattern.substr(cursor, pattern.find_first_not_of("0123456789",
                                                         cursor) - cursor);
      if (substr_.size())
      {
        precision_ = lexical_cast<unsigned int>(substr_);
        cursor += substr_.size();
      }
      else
        runner::raise_primitive_error(std::string("format: Unexpected \"")
                                      + pattern[cursor]
                                      + "\", expected width ([1-9][0-9]*).");
    }

    // Parsing spec.
    if ((piped && cursor < pattern_.size() - 1)
        || (!piped && cursor < pattern.size()))
    {
      spec_ = tolower(current = pattern[cursor]);
      substr_ = "sdbxoefgEGDX";
      if (substr_.find(spec_) != substr_.npos)
      {
        if (spec_ != 's')
          case_ = (islower(pattern[cursor])) ? Case::LOWER : Case::UPPER;
      }
      else
        runner::raise_primitive_error
          (std::string("format: \"") + spec_
           + "\" is not a valid conversion type character");
    }

    int overflow;
    if (!piped)
      pattern_ = pattern.substr(0, ++cursor);
    else if (0 < (overflow = pattern_.size() - 1 - ++cursor))
      RAISE("format: format is between pipes and \""
            + pattern_.substr(cursor, overflow)
            + "\" are too many characters");
  }

  std::string
  FormatInfo::as_string() const
  {
    return pattern_;
  }

  void
  FormatInfo::initialize(CxxObject::Binder<FormatInfo>& bind)
  {
    bind(SYMBOL(init), &FormatInfo::init);
    bind(SYMBOL(asString), &FormatInfo::as_string);
    bind(SYMBOL(width), &FormatInfo::width_get);
    bind(SYMBOL(precision), &FormatInfo::precision_get);
    bind(SYMBOL(alt), &FormatInfo::alt_get);
    bind(SYMBOL(prefix), &FormatInfo::prefix_get);
    bind(SYMBOL(alignment), &FormatInfo::alignment_get);
    bind(SYMBOL(uppercase), &FormatInfo::case_get);
    bind(SYMBOL(group), &FormatInfo::group_get);
    bind(SYMBOL(pad), &FormatInfo::pad_get);
    bind(SYMBOL(spec), &FormatInfo::spec_get);
    bind(SYMBOL(pattern), &FormatInfo::pattern_get);
  }

  rObject
  FormatInfo::proto_make()
  {
    return new FormatInfo();
  }

  URBI_CXX_OBJECT_REGISTER(FormatInfo);
} // namespace object
<|endoftext|>