<commit_before>/* Implementation of an accelerator datapath that uses a private scratchpad for
 * local memory.
 */

#include <string>

#include "ScratchpadDatapath.h"

ScratchpadDatapath::ScratchpadDatapath(std::string bench,
                                       std::string trace_file,
                                       std::string config_file)
    : BaseDatapath(bench, trace_file, config_file) {
  std::cerr << "-------------------------------" << std::endl;
  std::cerr << "      Setting ScratchPad       " << std::endl;
  std::cerr << "-------------------------------" << std::endl;
  scratchpad = new Scratchpad(1, cycleTime);
  scratchpadCanService = true;
}

ScratchpadDatapath::~ScratchpadDatapath() { delete scratchpad; }

void ScratchpadDatapath::globalOptimizationPass() {
  // Node removals must come first.
  removePhiNodes();
  /*memoryAmibguation() should execute after removeInductionDependence() because
   * it needs induction_nodes.*/
  removeInductionDependence();
  memoryAmbiguation();
  // Base address must be initialized next.
  initBaseAddress();
  completePartition();
  scratchpadPartition();
  loopFlatten();
  loopUnrolling();
  removeSharedLoads();
  storeBuffer();
  removeRepeatedStores();
  treeHeightReduction();
  // Must do loop pipelining last; after all the data/control dependences are
  // fixed
  loopPipelining();
}

/* First, compute all base addresses, then check each node to make sure that
 * each entry is valid.
 */
void ScratchpadDatapath::initBaseAddress() {
  BaseDatapath::initBaseAddress();
  std::unordered_map<std::string, unsigned> comp_part_config;
  readCompletePartitionConfig(comp_part_config);
  std::unordered_map<std::string, partitionEntry> part_config;
  readPartitionConfig(part_config);

  for (auto it = nodeToLabel.begin(); it != nodeToLabel.end(); ++it) {
    unsigned node_id = it->first;
    std::string part_name = nodeToLabel[node_id];
    if (part_config.find(part_name) == part_config.end() &&
        comp_part_config.find(part_name) == comp_part_config.end()) {
      std::cerr << "Unknown partition : " << part_name << "@inst: " << node_id
                << std::endl;
      exit(-1);
    }
  }
}

/*
 * Modify scratchpad
 */
void ScratchpadDatapath::completePartition() {
  std::unordered_map<std::string, unsigned> comp_part_config;
  if (!readCompletePartitionConfig(comp_part_config))
    return;

  std::cerr << "-------------------------------" << std::endl;
  std::cerr << "        Mem to Reg Conv        " << std::endl;
  std::cerr << "-------------------------------" << std::endl;

  for (auto it = comp_part_config.begin(); it != comp_part_config.end(); ++it) {
    std::string base_addr = it->first;
    unsigned size = it->second;

    registers.createRegister(base_addr, size, cycleTime);
  }
}

/*
 * Modify: baseAddress
 */
void ScratchpadDatapath::scratchpadPartition() {
  // read the partition config file to get the address range
  // <base addr, <type, part_factor> >
  std::unordered_map<std::string, partitionEntry> part_config;
  if (!readPartitionConfig(part_config))
    return;

  std::cerr << "-------------------------------" << std::endl;
  std::cerr << "      ScratchPad Partition     " << std::endl;
  std::cerr << "-------------------------------" << std::endl;
  std::string bn(benchName);

  std::unordered_map<unsigned, MemAccess> address;
  initAddress(address);
  // set scratchpad
  for (auto it = part_config.begin(); it != part_config.end(); ++it) {
    std::string base_addr = it->first;
    unsigned size = it->second.array_size;  // num of bytes
    unsigned p_factor = it->second.part_factor;
    unsigned wordsize = it->second.wordsize;  // in bytes
    unsigned per_size = ceil(((float)size) / p_factor);

    for (unsigned i = 0; i < p_factor; i++) {
      ostringstream oss;
      oss << base_addr << "-" << i;
      scratchpad->setScratchpad(oss.str(), per_size, wordsize);
    }
  }

  for (unsigned node_id = 0; node_id < numTotalNodes; node_id++) {
    if (!is_memory_op(microop.at(node_id)))
      continue;

    if (nodeToLabel.find(node_id) == nodeToLabel.end())
      continue;
    std::string base_label = nodeToLabel[node_id];
    long long int base_addr = arrayBaseAddress[base_label];

    auto part_it = part_config.find(base_label);
    if (part_it != part_config.end()) {
      std::string p_type = part_it->second.type;
      assert((!p_type.compare("block")) || (!p_type.compare("cyclic")));

      unsigned num_of_elements = part_it->second.array_size;
      unsigned p_factor = part_it->second.part_factor;
      long long int abs_addr = address[node_id].vaddr;
      unsigned data_size = address[node_id].size / 8;  // in bytes
      unsigned rel_addr = (abs_addr - base_addr) / data_size;
      if (!p_type.compare("block"))  // block partition
      {
        ostringstream oss;
        unsigned num_of_elements_in_2 = next_power_of_two(num_of_elements);
        oss << base_label << "-"
            << (int)(rel_addr / ceil(num_of_elements_in_2 / p_factor));
        nodeToLabel[node_id] = oss.str();
      } else  // cyclic partition
      {
        ostringstream oss;
        oss << base_label << "-" << (rel_addr) % p_factor;
        nodeToLabel[node_id] = oss.str();
      }
    }
  }
  writeBaseAddress();
}

void ScratchpadDatapath::setGraphForStepping() {
  BaseDatapath::setGraphForStepping();
  timeBeforeNodeExecution.assign(numTotalNodes, 0);
}
bool ScratchpadDatapath::step() {
  if (!BaseDatapath::step()) {
    scratchpad->step();
    scratchpadCanService = true;
    return false;
  } else {
    return true;
  }
}

void ScratchpadDatapath::stepExecutingQueue() {
  auto it = executingQueue.begin();
  int index = 0;
  while (it != executingQueue.end()) {
    unsigned node_id = *it;
    if (is_memory_op(microop.at(node_id))) {
      std::string node_part = nodeToLabel[node_id];
      if (registers.has(node_part)) {
        if (is_load_op(microop.at(node_id)))
          registers.getRegister(node_part)->increment_loads();
        else
          registers.getRegister(node_part)->increment_stores();
        markNodeCompleted(it, index);
      } else if (scratchpadCanService) {
        if (scratchpad->canServicePartition(node_part)) {
          if (is_load_op(microop.at(node_id)))
            scratchpad->increment_loads(node_part);
          else
            scratchpad->increment_stores(node_part);
          markNodeCompleted(it, index);
        } else {
          scratchpadCanService = scratchpad->canService();
          ++it;
          ++index;
        }
      } else {
        ++it;
        ++index;
      }
    } else {
      markNodeCompleted(it, index);
    }
  }
}
int ScratchpadDatapath::rescheduleNodesWhenNeeded(){
  std::vector<Vertex> topo_nodes;
  boost::topological_sort(graph_, std::back_inserter(topo_nodes));
  // bottom nodes first
  std::vector<float> alap_finish_time(numTotalNodes, num_cycles * cycleTime);
  for (auto vi = topo_nodes.begin(); vi != topo_nodes.end(); ++vi) {
    unsigned node_id = vertexToName[*vi];
    if (finalIsolated.at(node_id))
      continue;
    unsigned node_microop = microop.at(node_id);
    float alap_executing_time = alap_finish_time.at(node_id);
    if (!is_memory_op(node_microop) && !is_branch_op(node_microop)) {
      alap_executing_time -= node_latency(node_microop);
      if (alap_executing_time > (newLevel.at(node_id) + 1) * cycleTime) {
        newLevel.at(node_id) = floor(alap_executing_time / cycleTime);
      }
    } else {
      alap_executing_time = newLevel.at(node_id) * cycleTime;
    }

    in_edge_iter in_i, in_end;
    for (tie(in_i, in_end) = in_edges(*vi, graph_); in_i != in_end; ++in_i) {
      int parent_id = vertexToName[source(*in_i, graph_)];
      if (alap_finish_time.at(parent_id) > alap_executing_time)
        alap_finish_time.at(parent_id) = alap_executing_time;
    }
  }
  return num_cycles;
}
void ScratchpadDatapath::updateChildren(unsigned node_id) {
  if (nameToVertex.find(node_id) == nameToVertex.end())
    return;
  float latency_after_current_node = node_latency(microop.at(node_id));
  if (timeBeforeNodeExecution.at(node_id) > num_cycles * cycleTime) {
    latency_after_current_node += timeBeforeNodeExecution.at(node_id);
  }
  else {
    latency_after_current_node += num_cycles * cycleTime;
  }
  Vertex node = nameToVertex[node_id];
  out_edge_iter out_edge_it, out_edge_end;
  for (tie(out_edge_it, out_edge_end) = out_edges(node, graph_);
       out_edge_it != out_edge_end;
       ++out_edge_it) {
    unsigned child_id = vertexToName[target(*out_edge_it, graph_)];
    int edge_parid = edgeToParid[*out_edge_it];
    float child_earliest_time = timeBeforeNodeExecution.at(child_id);
    if (edge_parid != CONTROL_EDGE && child_earliest_time < latency_after_current_node)
      timeBeforeNodeExecution.at(child_id) = latency_after_current_node;
    if (numParents[child_id] > 0) {
      numParents[child_id]--;
      if (numParents[child_id] == 0) {
        unsigned child_microop = microop.at(child_id);
        if ((node_latency(child_microop) == 0 ||
             node_latency(microop.at(node_id)) == 0) &&
            edge_parid != CONTROL_EDGE)
          executingQueue.push_back(child_id);
        else if (is_memory_op(child_microop)) {
          if (is_store_op(child_microop))
            readyToExecuteQueue.push_front(child_id);
          else
            readyToExecuteQueue.push_back(child_id);
        }
        else {
          float after_child_time = timeBeforeNodeExecution.at(child_id)
            + node_latency(microop.at(node_id));
          if (after_child_time < (num_cycles + 1) * cycleTime &&
              edge_parid != CONTROL_EDGE )
            executingQueue.push_back(child_id);
          else
            readyToExecuteQueue.push_back(child_id);
        }
        numParents[child_id] = -1;
      }
    }
  }
}

void ScratchpadDatapath::dumpStats() {
  BaseDatapath::dumpStats();
  BaseDatapath::writePerCycleActivity();
}

double ScratchpadDatapath::getTotalMemArea() {
  return scratchpad->getTotalArea();
}

unsigned ScratchpadDatapath::getTotalMemSize() {
  return scratchpad->getTotalSize();
}

void ScratchpadDatapath::getMemoryBlocks(std::vector<std::string>& names) {
  scratchpad->getMemoryBlocks(names);
}

void ScratchpadDatapath::getAverageMemPower(unsigned int cycles,
                                            float* avg_power,
                                            float* avg_dynamic,
                                            float* avg_leak) {
  scratchpad->getAveragePower(cycles, avg_power, avg_dynamic, avg_leak);
}
<commit_msg>Fixed a typo in updateChildren().<commit_after>/* Implementation of an accelerator datapath that uses a private scratchpad for
 * local memory.
 */

#include <string>

#include "ScratchpadDatapath.h"

ScratchpadDatapath::ScratchpadDatapath(std::string bench,
                                       std::string trace_file,
                                       std::string config_file)
    : BaseDatapath(bench, trace_file, config_file) {
  std::cerr << "-------------------------------" << std::endl;
  std::cerr << "      Setting ScratchPad       " << std::endl;
  std::cerr << "-------------------------------" << std::endl;
  scratchpad = new Scratchpad(1, cycleTime);
  scratchpadCanService = true;
}

ScratchpadDatapath::~ScratchpadDatapath() { delete scratchpad; }

void ScratchpadDatapath::globalOptimizationPass() {
  // Node removals must come first.
  removePhiNodes();
  /*memoryAmibguation() should execute after removeInductionDependence() because
   * it needs induction_nodes.*/
  removeInductionDependence();
  memoryAmbiguation();
  // Base address must be initialized next.
  initBaseAddress();
  completePartition();
  scratchpadPartition();
  loopFlatten();
  loopUnrolling();
  removeSharedLoads();
  storeBuffer();
  removeRepeatedStores();
  treeHeightReduction();
  // Must do loop pipelining last; after all the data/control dependences are
  // fixed
  loopPipelining();
}

/* First, compute all base addresses, then check each node to make sure that
 * each entry is valid.
 */
void ScratchpadDatapath::initBaseAddress() {
  BaseDatapath::initBaseAddress();
  std::unordered_map<std::string, unsigned> comp_part_config;
  readCompletePartitionConfig(comp_part_config);
  std::unordered_map<std::string, partitionEntry> part_config;
  readPartitionConfig(part_config);

  for (auto it = nodeToLabel.begin(); it != nodeToLabel.end(); ++it) {
    unsigned node_id = it->first;
    std::string part_name = nodeToLabel[node_id];
    if (part_config.find(part_name) == part_config.end() &&
        comp_part_config.find(part_name) == comp_part_config.end()) {
      std::cerr << "Unknown partition : " << part_name << "@inst: " << node_id
                << std::endl;
      exit(-1);
    }
  }
}

/*
 * Modify scratchpad
 */
void ScratchpadDatapath::completePartition() {
  std::unordered_map<std::string, unsigned> comp_part_config;
  if (!readCompletePartitionConfig(comp_part_config))
    return;

  std::cerr << "-------------------------------" << std::endl;
  std::cerr << "        Mem to Reg Conv        " << std::endl;
  std::cerr << "-------------------------------" << std::endl;

  for (auto it = comp_part_config.begin(); it != comp_part_config.end(); ++it) {
    std::string base_addr = it->first;
    unsigned size = it->second;

    registers.createRegister(base_addr, size, cycleTime);
  }
}

/*
 * Modify: baseAddress
 */
void ScratchpadDatapath::scratchpadPartition() {
  // read the partition config file to get the address range
  // <base addr, <type, part_factor> >
  std::unordered_map<std::string, partitionEntry> part_config;
  if (!readPartitionConfig(part_config))
    return;

  std::cerr << "-------------------------------" << std::endl;
  std::cerr << "      ScratchPad Partition     " << std::endl;
  std::cerr << "-------------------------------" << std::endl;
  std::string bn(benchName);

  std::unordered_map<unsigned, MemAccess> address;
  initAddress(address);
  // set scratchpad
  for (auto it = part_config.begin(); it != part_config.end(); ++it) {
    std::string base_addr = it->first;
    unsigned size = it->second.array_size;  // num of bytes
    unsigned p_factor = it->second.part_factor;
    unsigned wordsize = it->second.wordsize;  // in bytes
    unsigned per_size = ceil(((float)size) / p_factor);

    for (unsigned i = 0; i < p_factor; i++) {
      ostringstream oss;
      oss << base_addr << "-" << i;
      scratchpad->setScratchpad(oss.str(), per_size, wordsize);
    }
  }

  for (unsigned node_id = 0; node_id < numTotalNodes; node_id++) {
    if (!is_memory_op(microop.at(node_id)))
      continue;

    if (nodeToLabel.find(node_id) == nodeToLabel.end())
      continue;
    std::string base_label = nodeToLabel[node_id];
    long long int base_addr = arrayBaseAddress[base_label];

    auto part_it = part_config.find(base_label);
    if (part_it != part_config.end()) {
      std::string p_type = part_it->second.type;
      assert((!p_type.compare("block")) || (!p_type.compare("cyclic")));

      unsigned num_of_elements = part_it->second.array_size;
      unsigned p_factor = part_it->second.part_factor;
      long long int abs_addr = address[node_id].vaddr;
      unsigned data_size = address[node_id].size / 8;  // in bytes
      unsigned rel_addr = (abs_addr - base_addr) / data_size;
      if (!p_type.compare("block"))  // block partition
      {
        ostringstream oss;
        unsigned num_of_elements_in_2 = next_power_of_two(num_of_elements);
        oss << base_label << "-"
            << (int)(rel_addr / ceil(num_of_elements_in_2 / p_factor));
        nodeToLabel[node_id] = oss.str();
      } else  // cyclic partition
      {
        ostringstream oss;
        oss << base_label << "-" << (rel_addr) % p_factor;
        nodeToLabel[node_id] = oss.str();
      }
    }
  }
  writeBaseAddress();
}

void ScratchpadDatapath::setGraphForStepping() {
  BaseDatapath::setGraphForStepping();
  timeBeforeNodeExecution.assign(numTotalNodes, 0);
}
bool ScratchpadDatapath::step() {
  if (!BaseDatapath::step()) {
    scratchpad->step();
    scratchpadCanService = true;
    return false;
  } else {
    return true;
  }
}

void ScratchpadDatapath::stepExecutingQueue() {
  auto it = executingQueue.begin();
  int index = 0;
  while (it != executingQueue.end()) {
    unsigned node_id = *it;
    if (is_memory_op(microop.at(node_id))) {
      std::string node_part = nodeToLabel[node_id];
      if (registers.has(node_part)) {
        if (is_load_op(microop.at(node_id)))
          registers.getRegister(node_part)->increment_loads();
        else
          registers.getRegister(node_part)->increment_stores();
        markNodeCompleted(it, index);
      } else if (scratchpadCanService) {
        if (scratchpad->canServicePartition(node_part)) {
          if (is_load_op(microop.at(node_id)))
            scratchpad->increment_loads(node_part);
          else
            scratchpad->increment_stores(node_part);
          markNodeCompleted(it, index);
        } else {
          scratchpadCanService = scratchpad->canService();
          ++it;
          ++index;
        }
      } else {
        ++it;
        ++index;
      }
    } else {
      markNodeCompleted(it, index);
    }
  }
}
int ScratchpadDatapath::rescheduleNodesWhenNeeded(){
  std::vector<Vertex> topo_nodes;
  boost::topological_sort(graph_, std::back_inserter(topo_nodes));
  // bottom nodes first
  std::vector<float> alap_finish_time(numTotalNodes, num_cycles * cycleTime);
  for (auto vi = topo_nodes.begin(); vi != topo_nodes.end(); ++vi) {
    unsigned node_id = vertexToName[*vi];
    if (finalIsolated.at(node_id))
      continue;
    unsigned node_microop = microop.at(node_id);
    float alap_executing_time = alap_finish_time.at(node_id);
    if (!is_memory_op(node_microop) && !is_branch_op(node_microop)) {
      alap_executing_time -= node_latency(node_microop);
      if (alap_executing_time > (newLevel.at(node_id) + 1) * cycleTime) {
        newLevel.at(node_id) = floor(alap_executing_time / cycleTime);
      }
    } else {
      alap_executing_time = newLevel.at(node_id) * cycleTime;
    }

    in_edge_iter in_i, in_end;
    for (tie(in_i, in_end) = in_edges(*vi, graph_); in_i != in_end; ++in_i) {
      int parent_id = vertexToName[source(*in_i, graph_)];
      if (alap_finish_time.at(parent_id) > alap_executing_time)
        alap_finish_time.at(parent_id) = alap_executing_time;
    }
  }
  return num_cycles;
}
void ScratchpadDatapath::updateChildren(unsigned node_id) {
  if (nameToVertex.find(node_id) == nameToVertex.end())
    return;
  float latency_after_current_node = node_latency(microop.at(node_id));
  if (timeBeforeNodeExecution.at(node_id) > num_cycles * cycleTime) {
    latency_after_current_node += timeBeforeNodeExecution.at(node_id);
  }
  else {
    latency_after_current_node += num_cycles * cycleTime;
  }
  Vertex node = nameToVertex[node_id];
  out_edge_iter out_edge_it, out_edge_end;
  for (tie(out_edge_it, out_edge_end) = out_edges(node, graph_);
       out_edge_it != out_edge_end;
       ++out_edge_it) {
    unsigned child_id = vertexToName[target(*out_edge_it, graph_)];
    int edge_parid = edgeToParid[*out_edge_it];
    float child_earliest_time = timeBeforeNodeExecution.at(child_id);
    if (edge_parid != CONTROL_EDGE && child_earliest_time < latency_after_current_node)
      timeBeforeNodeExecution.at(child_id) = latency_after_current_node;
    if (numParents[child_id] > 0) {
      numParents[child_id]--;
      if (numParents[child_id] == 0) {
        unsigned child_microop = microop.at(child_id);
        if ((node_latency(child_microop) == 0 ||
             node_latency(microop.at(node_id)) == 0) &&
            edge_parid != CONTROL_EDGE)
          executingQueue.push_back(child_id);
        else if (is_memory_op(child_microop)) {
          if (is_store_op(child_microop))
            readyToExecuteQueue.push_front(child_id);
          else
            readyToExecuteQueue.push_back(child_id);
        }
        else {
          float after_child_time = timeBeforeNodeExecution.at(child_id)
            + node_latency(microop.at(child_id));
          if (after_child_time < (num_cycles + 1) * cycleTime &&
              edge_parid != CONTROL_EDGE )
            executingQueue.push_back(child_id);
          else
            readyToExecuteQueue.push_back(child_id);
        }
        numParents[child_id] = -1;
      }
    }
  }
}

void ScratchpadDatapath::dumpStats() {
  BaseDatapath::dumpStats();
  BaseDatapath::writePerCycleActivity();
}

double ScratchpadDatapath::getTotalMemArea() {
  return scratchpad->getTotalArea();
}

unsigned ScratchpadDatapath::getTotalMemSize() {
  return scratchpad->getTotalSize();
}

void ScratchpadDatapath::getMemoryBlocks(std::vector<std::string>& names) {
  scratchpad->getMemoryBlocks(names);
}

void ScratchpadDatapath::getAverageMemPower(unsigned int cycles,
                                            float* avg_power,
                                            float* avg_dynamic,
                                            float* avg_leak) {
  scratchpad->getAveragePower(cycles, avg_power, avg_dynamic, avg_leak);
}
<|endoftext|>


<commit_before>/*
** Copyright 2009-2013 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/

#include <cstdlib>
#include <cstring>
#include <ctime>
#include <memory>
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/neb/callbacks.hh"
#include "com/centreon/broker/neb/events.hh"
#include "com/centreon/broker/neb/initial.hh"
#include "com/centreon/broker/neb/internal.hh"
#include "com/centreon/engine/broker.hh"
#include "com/centreon/engine/common.hh"
#include "com/centreon/engine/nebcallbacks.hh"
#include "com/centreon/engine/nebstructs.hh"
#include "com/centreon/engine/objects.hh"

// Internal Nagios host list.
extern "C" {
  extern host* host_list;
  extern hostdependency* hostdependency_list;
  extern hostgroup* hostgroup_list;
  extern service* service_list;
  extern servicedependency* servicedependency_list;
  extern servicegroup* servicegroup_list;
}

using namespace com::centreon::broker;

// NEB module list.
extern "C" {
  nebmodule* neb_module_list;
}

/**************************************
*                                     *
*          Static Functions           *
*                                     *
**************************************/

/**
 *  Send to the global publisher the list of custom variables.
 */
static void send_custom_variables_list() {
  // Start log message.
  logging::info(logging::medium)
    << "init: beginning custom variables dump";

  // Iterate through all hosts.
  for (host* h(host_list); h; h = h->next)
    // Send all custom variables.
    for (customvariablesmember* cv(h->custom_variables);
         cv;
         cv = cv->next) {
      // Fill callback struct.
      nebstruct_custom_variable_data nscvd;
      memset(&nscvd, 0, sizeof(nscvd));
      nscvd.type = NEBTYPE_HOSTCUSTOMVARIABLE_ADD;
      nscvd.timestamp.tv_sec = time(NULL);
      nscvd.var_name = cv->variable_name;
      nscvd.var_value = cv->variable_value;
      nscvd.object_ptr = h;

      // Callback.
      neb::callback_custom_variable(
             NEBCALLBACK_CUSTOM_VARIABLE_DATA,
             &nscvd);
    }

  // Iterate through all services.
  for (service* s(service_list); s; s = s->next)
    // Send all custom variables.
    for (customvariablesmember* cv(s->custom_variables);
         cv;
         cv = cv->next) {
      // Fill callback struct.
      nebstruct_custom_variable_data nscvd;
      memset(&nscvd, 0, sizeof(nscvd));
      nscvd.type = NEBTYPE_SERVICECUSTOMVARIABLE_ADD;
      nscvd.timestamp.tv_sec = time(NULL);
      nscvd.var_name = cv->variable_name;
      nscvd.var_value = cv->variable_value;
      nscvd.object_ptr = s;

      // Callback.
      neb::callback_custom_variable(
             NEBCALLBACK_CUSTOM_VARIABLE_DATA,
             &nscvd);
    }

  // End log message.
  logging::info(logging::medium)
    << "init: end of custom variables dump";

  return ;
}

/**
 *  Send to the global publisher the list of host dependencies within Nagios.
 */
static void send_host_dependencies_list() {
  // Start log message.
  logging::info(logging::medium)
    << "init: beginning host dependencies dump";

  // Loop through all dependencies.
  for (hostdependency* hd = hostdependency_list; hd; hd = hd->next) {
    misc::shared_ptr<neb::host_dependency> host_dependency(
      new neb::host_dependency);
    std::map<std::string, int>::const_iterator it;

    // Set host dependency parameters.
    if (hd->dependency_period)
      host_dependency->dependency_period = hd->dependency_period;
    if (hd->dependent_host_name) {
      it = neb::gl_hosts.find(hd->dependent_host_name);
      if (it != neb::gl_hosts.end())
        host_dependency->dependent_host_id = it->second;
    }
    host_dependency->inherits_parent = hd->inherits_parent;
    if (hd->host_name) {
      it = neb::gl_hosts.find(hd->host_name);
      if (it != neb::gl_hosts.end())
        host_dependency->host_id = it->second;
    }

    // Send host dependency event.
    logging::info(logging::low) << "init:  host "
      << host_dependency->dependent_host_id << " depends on host "
      << host_dependency->host_id;
    neb::gl_publisher.write(host_dependency.staticCast<io::data>());
  }

  // End log message.
  logging::info(logging::medium)
    << "init: end of host dependencies dump";

  return ;
}

/**
 *  Send to the global publisher the list of host groups within Engine.
 */
static void send_host_group_list() {
  // Start log message.
  logging::info(logging::medium)
    << "init: beginning host group dump";

  // Loop through all host groups.
  for (hostgroup* hg(hostgroup_list); hg; hg = hg->next) {
    // Fill callback struct.
    nebstruct_group_data nsgd;
    memset(&nsgd, 0, sizeof(nsgd));
    nsgd.type = NEBTYPE_HOSTGROUP_ADD;
    nsgd.object_ptr = hg;

    // Callback.
    neb::callback_group(NEBCALLBACK_GROUP_DATA, &nsgd);

    // Dump host group members.
    for (hostsmember* hgm(hg->members); hgm; hgm = hgm->next) {
      // Fill callback struct.
      nebstruct_group_member_data nsgmd;
      memset(&nsgmd, 0, sizeof(nsgmd));
      nsgmd.type = NEBTYPE_HOSTGROUPMEMBER_ADD;
      nsgmd.object_ptr = hgm->host_ptr;
      nsgmd.group_ptr = hg;

      // Callback.
      neb::callback_group_member(NEBCALLBACK_GROUP_MEMBER_DATA, &nsgmd);
    }
  }

  // End log message.
  logging::info(logging::medium)
    << "init: end of host group dump";

  return ;
}

/**
 *  Send to the global publisher the list of hosts within Nagios.
 */
static void send_host_list() {
  // Start log message.
  logging::info(logging::medium) << "init: beginning host dump";

  // Loop through all hosts.
  for (host* h(host_list); h; h = h->next) {
    // Fill callback struct.
    nebstruct_adaptive_host_data nsahd;
    memset(&nsahd, 0, sizeof(nsahd));
    nsahd.type = NEBTYPE_HOST_ADD;
    nsahd.command_type = CMD_NONE;
    nsahd.modified_attribute = MODATTR_ALL;
    nsahd.modified_attributes = MODATTR_ALL;
    nsahd.object_ptr = h;

    // Callback.
    neb::callback_host(NEBCALLBACK_ADAPTIVE_HOST_DATA, &nsahd);
  }

  // End log message.
  logging::info(logging::medium) << "init: end of host dump";

  return ;
}

/**
 *  Send to the global publisher the list of host parents within Nagios.
 */
static void send_host_parents_list() {
  // Start log message.
  logging::info(logging::medium) << "init: beginning host parents dump";

  // Loop through all hosts.
  int host_id;
  for (host* h = host_list; h; h = h->next) {
    std::map<std::string, int>::const_iterator it;

    // Search host_id.
    if (h->name) {
      it = neb::gl_hosts.find(h->name);
      if (it != neb::gl_hosts.end())
        host_id = it->second;
      else
        host_id = 0;
    }
    else
      host_id = 0;

    // Loop through all dependencies.
    for (hostsmember* parent = h->parent_hosts; parent; parent = parent->next) {
      misc::shared_ptr<neb::host_parent> hp(new neb::host_parent);
      std::map<std::string, int>::const_iterator it;

      hp->host_id = host_id;
      if (parent->host_name) {
        it = neb::gl_hosts.find(parent->host_name);
        if (it != neb::gl_hosts.end())
          hp->parent_id = it->second;
      }

      // Send host parent event.
      logging::info(logging::low) << "init:  host " << hp->parent_id
        << " is parent of host " << hp->host_id;
      neb::gl_publisher.write(hp.staticCast<io::data>());
    }
  }

  // End log message.
  logging::info(logging::medium) << "init: end of host parents dump";

  return ;
}

/**
 *  Send to the global publisher the list of modules loaded by Engine.
 */
static void send_module_list() {
  // Start log message.
  logging::info(logging::medium)
    << "init: beginning modules dump";

  // Browse module list.
  for (nebmodule* nm(neb_module_list); nm; nm = nm->next)
    if (nm->filename) {
      // Fill callback struct.
      nebstruct_module_data nsmd;
      memset(&nsmd, 0, sizeof(nsmd));
      nsmd.module = nm->filename;
      nsmd.args = nm->args;
      nsmd.type = NEBTYPE_MODULE_ADD;

      // Callback.
      neb::callback_module(NEBTYPE_MODULE_ADD, &nsmd);
    }

  // End log message.
  logging::info(logging::medium) << "init: end of modules dump";

  return ;
}

/**
 *  Send to the global publisher the list of service dependencies within
 *  Nagios.
 */
static void send_service_dependencies_list() {
  // Start log message.
  logging::info(logging::medium)
    << "init: beginning service dependencies dump";

  // Loop through all dependencies.
  for (servicedependency* sd = servicedependency_list; sd; sd = sd->next) {
    std::map<std::pair<std::string, std::string>, std::pair<int, int> >::const_iterator it;
    misc::shared_ptr<neb::service_dependency>
      service_dependency(new neb::service_dependency);

    // Search IDs.
    if (sd->dependent_host_name && sd->dependent_service_description) {
      it = neb::gl_services.find(std::make_pair<std::string, std::string>(
             sd->dependent_host_name, sd->dependent_service_description));
      if (it != neb::gl_services.end()) {
        service_dependency->dependent_host_id = it->second.first;
        service_dependency->dependent_service_id = it->second.second;
      }
    }
    if (sd->dependency_period)
      service_dependency->dependency_period = sd->dependency_period;
    service_dependency->inherits_parent = sd->inherits_parent;
    if (sd->host_name && sd->service_description) {
      it = neb::gl_services.find(std::make_pair<std::string, std::string>(
             sd->host_name, sd->service_description));
      if (it != neb::gl_services.end()) {
        service_dependency->host_id = it->second.first;
        service_dependency->service_id = it->second.second;
      }
    }

    // Send service dependency event.
    logging::info(logging::low) << "init:  service ("
      << service_dependency->dependent_host_id << ", "
      << service_dependency->dependent_service_id
      << ") depends on service (" << service_dependency->host_id
      << ", " << service_dependency->service_id << ")";
    neb::gl_publisher.write(service_dependency.staticCast<io::data>());
  }

  // End log message.
  logging::info(logging::medium)
    << "init: end of service dependencies dump";

  return ;
}

/**
 *  Send to the global publisher the list of service groups within Engine.
 */
static void send_service_group_list() {
  // Start log message.
  logging::info(logging::medium)
    << "init: beginning service group dump";

  // Loop through all service groups.
  for (servicegroup* sg(servicegroup_list); sg; sg = sg->next) {
    // Fill callback struct.
    nebstruct_group_data nsgd;
    memset(&nsgd, 0, sizeof(nsgd));
    nsgd.type = NEBTYPE_SERVICEGROUP_ADD;
    nsgd.object_ptr = sg;

    // Callback.
    neb::callback_group(NEBCALLBACK_GROUP_DATA, &nsgd);

    // Dump service group members.
    for (servicesmember* sgm(sg->members); sgm; sgm = sgm->next) {
      // Fill callback struct.
      nebstruct_group_member_data nsgmd;
      memset(&nsgmd, 0, sizeof(nsgmd));
      nsgmd.type = NEBTYPE_SERVICEGROUPMEMBER_ADD;
      nsgmd.object_ptr = sgm->service_ptr;
      nsgmd.group_ptr = sg;

      // Callback.
      neb::callback_group_member(NEBCALLBACK_GROUP_MEMBER_DATA, &nsgmd);
    }
  }

  // End log message.
  logging::info(logging::medium) << "init: end of service groups dump";

  return ;
}

/**
 *  Send to the global publisher the list of services within Nagios.
 */
static void send_service_list() {
  // Start log message.
  logging::info(logging::medium) << "init: beginning service dump";

  // Loop through all services.
  for (service* s = service_list; s; s = s->next) {
    // Fill callback struct.
    nebstruct_adaptive_service_data nsasd;
    memset(&nsasd, 0, sizeof(nsasd));
    nsasd.type = NEBTYPE_SERVICE_ADD;
    nsasd.command_type = CMD_NONE;
    nsasd.modified_attribute = MODATTR_ALL;
    nsasd.modified_attributes = MODATTR_ALL;
    nsasd.object_ptr = s;

    // Callback.
    neb::callback_service(NEBCALLBACK_ADAPTIVE_SERVICE_DATA, &nsasd);
  }

  // End log message.
  logging::info(logging::medium) << "init: end of services dump";

  return ;
}

/**************************************
*                                     *
*          Global Functions           *
*                                     *
**************************************/

/**
 *  Send initial configuration to the global publisher.
 */
void neb::send_initial_configuration() {
  send_host_list();
  send_service_list();
  send_custom_variables_list();
  send_host_parents_list();
  send_host_group_list();
  send_service_group_list();
  send_host_dependencies_list();
  send_service_dependencies_list();
  send_module_list();
  return ;
}
<commit_msg>NEB: create initial host parents using callback.<commit_after>/*
** Copyright 2009-2013 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/

#include <cstdlib>
#include <cstring>
#include <ctime>
#include <memory>
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/neb/callbacks.hh"
#include "com/centreon/broker/neb/events.hh"
#include "com/centreon/broker/neb/initial.hh"
#include "com/centreon/broker/neb/internal.hh"
#include "com/centreon/engine/broker.hh"
#include "com/centreon/engine/common.hh"
#include "com/centreon/engine/nebcallbacks.hh"
#include "com/centreon/engine/nebstructs.hh"
#include "com/centreon/engine/objects.hh"

// Internal Nagios host list.
extern "C" {
  extern host* host_list;
  extern hostdependency* hostdependency_list;
  extern hostgroup* hostgroup_list;
  extern service* service_list;
  extern servicedependency* servicedependency_list;
  extern servicegroup* servicegroup_list;
}

using namespace com::centreon::broker;

// NEB module list.
extern "C" {
  nebmodule* neb_module_list;
}

/**************************************
*                                     *
*          Static Functions           *
*                                     *
**************************************/

/**
 *  Send to the global publisher the list of custom variables.
 */
static void send_custom_variables_list() {
  // Start log message.
  logging::info(logging::medium)
    << "init: beginning custom variables dump";

  // Iterate through all hosts.
  for (host* h(host_list); h; h = h->next)
    // Send all custom variables.
    for (customvariablesmember* cv(h->custom_variables);
         cv;
         cv = cv->next) {
      // Fill callback struct.
      nebstruct_custom_variable_data nscvd;
      memset(&nscvd, 0, sizeof(nscvd));
      nscvd.type = NEBTYPE_HOSTCUSTOMVARIABLE_ADD;
      nscvd.timestamp.tv_sec = time(NULL);
      nscvd.var_name = cv->variable_name;
      nscvd.var_value = cv->variable_value;
      nscvd.object_ptr = h;

      // Callback.
      neb::callback_custom_variable(
             NEBCALLBACK_CUSTOM_VARIABLE_DATA,
             &nscvd);
    }

  // Iterate through all services.
  for (service* s(service_list); s; s = s->next)
    // Send all custom variables.
    for (customvariablesmember* cv(s->custom_variables);
         cv;
         cv = cv->next) {
      // Fill callback struct.
      nebstruct_custom_variable_data nscvd;
      memset(&nscvd, 0, sizeof(nscvd));
      nscvd.type = NEBTYPE_SERVICECUSTOMVARIABLE_ADD;
      nscvd.timestamp.tv_sec = time(NULL);
      nscvd.var_name = cv->variable_name;
      nscvd.var_value = cv->variable_value;
      nscvd.object_ptr = s;

      // Callback.
      neb::callback_custom_variable(
             NEBCALLBACK_CUSTOM_VARIABLE_DATA,
             &nscvd);
    }

  // End log message.
  logging::info(logging::medium)
    << "init: end of custom variables dump";

  return ;
}

/**
 *  Send to the global publisher the list of host dependencies within Nagios.
 */
static void send_host_dependencies_list() {
  // Start log message.
  logging::info(logging::medium)
    << "init: beginning host dependencies dump";

  // Loop through all dependencies.
  for (hostdependency* hd = hostdependency_list; hd; hd = hd->next) {
    misc::shared_ptr<neb::host_dependency> host_dependency(
      new neb::host_dependency);
    std::map<std::string, int>::const_iterator it;

    // Set host dependency parameters.
    if (hd->dependency_period)
      host_dependency->dependency_period = hd->dependency_period;
    if (hd->dependent_host_name) {
      it = neb::gl_hosts.find(hd->dependent_host_name);
      if (it != neb::gl_hosts.end())
        host_dependency->dependent_host_id = it->second;
    }
    host_dependency->inherits_parent = hd->inherits_parent;
    if (hd->host_name) {
      it = neb::gl_hosts.find(hd->host_name);
      if (it != neb::gl_hosts.end())
        host_dependency->host_id = it->second;
    }

    // Send host dependency event.
    logging::info(logging::low) << "init:  host "
      << host_dependency->dependent_host_id << " depends on host "
      << host_dependency->host_id;
    neb::gl_publisher.write(host_dependency.staticCast<io::data>());
  }

  // End log message.
  logging::info(logging::medium)
    << "init: end of host dependencies dump";

  return ;
}

/**
 *  Send to the global publisher the list of host groups within Engine.
 */
static void send_host_group_list() {
  // Start log message.
  logging::info(logging::medium)
    << "init: beginning host group dump";

  // Loop through all host groups.
  for (hostgroup* hg(hostgroup_list); hg; hg = hg->next) {
    // Fill callback struct.
    nebstruct_group_data nsgd;
    memset(&nsgd, 0, sizeof(nsgd));
    nsgd.type = NEBTYPE_HOSTGROUP_ADD;
    nsgd.object_ptr = hg;

    // Callback.
    neb::callback_group(NEBCALLBACK_GROUP_DATA, &nsgd);

    // Dump host group members.
    for (hostsmember* hgm(hg->members); hgm; hgm = hgm->next) {
      // Fill callback struct.
      nebstruct_group_member_data nsgmd;
      memset(&nsgmd, 0, sizeof(nsgmd));
      nsgmd.type = NEBTYPE_HOSTGROUPMEMBER_ADD;
      nsgmd.object_ptr = hgm->host_ptr;
      nsgmd.group_ptr = hg;

      // Callback.
      neb::callback_group_member(NEBCALLBACK_GROUP_MEMBER_DATA, &nsgmd);
    }
  }

  // End log message.
  logging::info(logging::medium)
    << "init: end of host group dump";

  return ;
}

/**
 *  Send to the global publisher the list of hosts within Nagios.
 */
static void send_host_list() {
  // Start log message.
  logging::info(logging::medium) << "init: beginning host dump";

  // Loop through all hosts.
  for (host* h(host_list); h; h = h->next) {
    // Fill callback struct.
    nebstruct_adaptive_host_data nsahd;
    memset(&nsahd, 0, sizeof(nsahd));
    nsahd.type = NEBTYPE_HOST_ADD;
    nsahd.command_type = CMD_NONE;
    nsahd.modified_attribute = MODATTR_ALL;
    nsahd.modified_attributes = MODATTR_ALL;
    nsahd.object_ptr = h;

    // Callback.
    neb::callback_host(NEBCALLBACK_ADAPTIVE_HOST_DATA, &nsahd);
  }

  // End log message.
  logging::info(logging::medium) << "init: end of host dump";

  return ;
}

/**
 *  Send to the global publisher the list of host parents within Nagios.
 */
static void send_host_parents_list() {
  // Start log message.
  logging::info(logging::medium) << "init: beginning host parents dump";

  try {
    // Loop through all hosts.
    for (host* h(host_list); h; h = h->next)
      // Loop through all parents.
      for (hostsmember* parent(h->parent_hosts);
           parent;
           parent = parent->next) {
        // Fill callback struct.
        nebstruct_relation_data nsrd;
        memset(&nsrd, 0, sizeof(nsrd));
        nsrd.type = NEBTYPE_PARENT_ADD;
        nsrd.flags = NEBFLAG_NONE;
        nsrd.attr = NEBATTR_NONE;
        nsrd.timestamp.tv_sec = time(NULL);
        nsrd.hst = parent->host_ptr;
        nsrd.dep_hst = h;

        // Callback.
        neb::callback_relation(NEBTYPE_PARENT_ADD, &nsrd);
      }
  }
  catch (std::exception const& e) {
    logging::error(logging::high)
      << "init: error occurred while dumping host parents: "
      << e.what();
  }
  catch (...) {
    logging::error(logging::high)
      << "init: unknown error occurred while dumping host parents";
  }

  // End log message.
  logging::info(logging::medium) << "init: end of host parents dump";

  return ;
}

/**
 *  Send to the global publisher the list of modules loaded by Engine.
 */
static void send_module_list() {
  // Start log message.
  logging::info(logging::medium)
    << "init: beginning modules dump";

  // Browse module list.
  for (nebmodule* nm(neb_module_list); nm; nm = nm->next)
    if (nm->filename) {
      // Fill callback struct.
      nebstruct_module_data nsmd;
      memset(&nsmd, 0, sizeof(nsmd));
      nsmd.module = nm->filename;
      nsmd.args = nm->args;
      nsmd.type = NEBTYPE_MODULE_ADD;

      // Callback.
      neb::callback_module(NEBTYPE_MODULE_ADD, &nsmd);
    }

  // End log message.
  logging::info(logging::medium) << "init: end of modules dump";

  return ;
}

/**
 *  Send to the global publisher the list of service dependencies within
 *  Nagios.
 */
static void send_service_dependencies_list() {
  // Start log message.
  logging::info(logging::medium)
    << "init: beginning service dependencies dump";

  // Loop through all dependencies.
  for (servicedependency* sd = servicedependency_list; sd; sd = sd->next) {
    std::map<std::pair<std::string, std::string>, std::pair<int, int> >::const_iterator it;
    misc::shared_ptr<neb::service_dependency>
      service_dependency(new neb::service_dependency);

    // Search IDs.
    if (sd->dependent_host_name && sd->dependent_service_description) {
      it = neb::gl_services.find(std::make_pair<std::string, std::string>(
             sd->dependent_host_name, sd->dependent_service_description));
      if (it != neb::gl_services.end()) {
        service_dependency->dependent_host_id = it->second.first;
        service_dependency->dependent_service_id = it->second.second;
      }
    }
    if (sd->dependency_period)
      service_dependency->dependency_period = sd->dependency_period;
    service_dependency->inherits_parent = sd->inherits_parent;
    if (sd->host_name && sd->service_description) {
      it = neb::gl_services.find(std::make_pair<std::string, std::string>(
             sd->host_name, sd->service_description));
      if (it != neb::gl_services.end()) {
        service_dependency->host_id = it->second.first;
        service_dependency->service_id = it->second.second;
      }
    }

    // Send service dependency event.
    logging::info(logging::low) << "init:  service ("
      << service_dependency->dependent_host_id << ", "
      << service_dependency->dependent_service_id
      << ") depends on service (" << service_dependency->host_id
      << ", " << service_dependency->service_id << ")";
    neb::gl_publisher.write(service_dependency.staticCast<io::data>());
  }

  // End log message.
  logging::info(logging::medium)
    << "init: end of service dependencies dump";

  return ;
}

/**
 *  Send to the global publisher the list of service groups within Engine.
 */
static void send_service_group_list() {
  // Start log message.
  logging::info(logging::medium)
    << "init: beginning service group dump";

  // Loop through all service groups.
  for (servicegroup* sg(servicegroup_list); sg; sg = sg->next) {
    // Fill callback struct.
    nebstruct_group_data nsgd;
    memset(&nsgd, 0, sizeof(nsgd));
    nsgd.type = NEBTYPE_SERVICEGROUP_ADD;
    nsgd.object_ptr = sg;

    // Callback.
    neb::callback_group(NEBCALLBACK_GROUP_DATA, &nsgd);

    // Dump service group members.
    for (servicesmember* sgm(sg->members); sgm; sgm = sgm->next) {
      // Fill callback struct.
      nebstruct_group_member_data nsgmd;
      memset(&nsgmd, 0, sizeof(nsgmd));
      nsgmd.type = NEBTYPE_SERVICEGROUPMEMBER_ADD;
      nsgmd.object_ptr = sgm->service_ptr;
      nsgmd.group_ptr = sg;

      // Callback.
      neb::callback_group_member(NEBCALLBACK_GROUP_MEMBER_DATA, &nsgmd);
    }
  }

  // End log message.
  logging::info(logging::medium) << "init: end of service groups dump";

  return ;
}

/**
 *  Send to the global publisher the list of services within Nagios.
 */
static void send_service_list() {
  // Start log message.
  logging::info(logging::medium) << "init: beginning service dump";

  // Loop through all services.
  for (service* s = service_list; s; s = s->next) {
    // Fill callback struct.
    nebstruct_adaptive_service_data nsasd;
    memset(&nsasd, 0, sizeof(nsasd));
    nsasd.type = NEBTYPE_SERVICE_ADD;
    nsasd.command_type = CMD_NONE;
    nsasd.modified_attribute = MODATTR_ALL;
    nsasd.modified_attributes = MODATTR_ALL;
    nsasd.object_ptr = s;

    // Callback.
    neb::callback_service(NEBCALLBACK_ADAPTIVE_SERVICE_DATA, &nsasd);
  }

  // End log message.
  logging::info(logging::medium) << "init: end of services dump";

  return ;
}

/**************************************
*                                     *
*          Global Functions           *
*                                     *
**************************************/

/**
 *  Send initial configuration to the global publisher.
 */
void neb::send_initial_configuration() {
  send_host_list();
  send_service_list();
  send_custom_variables_list();
  send_host_parents_list();
  send_host_group_list();
  send_service_group_list();
  send_host_dependencies_list();
  send_service_dependencies_list();
  send_module_list();
  return ;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <cmath>
#include <algorithm>

using namespace std;

#define MAX_PAIR_NUM 1000

int main() {
  cout << "test";
  cout << "test2";
  cout << "test3";
  cout << "test4";
}
<commit_msg>revisit p1009<commit_after>#include <iostream>
#include <cmath>
#include <algorithm>

using namespace std;

#define MAX_PAIR_NUM 1000

int pixel_pair[MAX_PAIR_NUM][2];
int img_width;

int main() {
  while (cin >> img_width && img_width > 0) {
    int num, pixel;
    int pair_cnt  = 0;
    int pixel_cnt = 0;

    while (cin >> pixel >> num && num != 0 && pixel != 0) {
      pixel_pair[pair_cnt][0] = pixel;
      pixel_pair[pair_cnt][1] = num;

      pair_cnt++;

      pixel_cnt += num;
    }

    for (int i = 0; i < pair_cnt; i++)
      cout << pixel_pair[i][0] << " " << pixel_pair[i][1] << endl;

    cout << pixel_cnt << endl;
  }
}
<|endoftext|>


<commit_before>/*

Copyright (c) 2006, Arvid Norberg
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 the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

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 COPYRIGHT OWNER 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.

*/

#ifndef TORRENT_EXTENSIONS_HPP_INCLUDED
#define TORRENT_EXTENSIONS_HPP_INCLUDED

#ifndef TORRENT_DISABLE_EXTENSIONS

#ifdef _MSC_VER
#pragma warning(push, 1)
#endif

#include <boost/weak_ptr.hpp>

#ifdef _MSC_VER
#pragma warning(pop)
#endif

#include <vector>
#include "libtorrent/config.hpp"
#include "libtorrent/buffer.hpp"

namespace libtorrent
{
	namespace aux { struct session_impl; }

	struct peer_plugin;
	class bt_peer_connection;
	struct peer_request;
	class peer_connection;
	class entry;
	struct lazy_entry;
	struct disk_buffer_holder;
	struct bitfield;
	class alert;

	struct TORRENT_EXPORT plugin
	{
		virtual ~plugin() {}

		virtual boost::shared_ptr<torrent_plugin> new_torrent(torrent* t, void* user)
		{ return boost::shared_ptr<torrent_plugin>(); }

		// called when plugin is added to a session
		virtual void added(boost::weak_ptr<aux::session_impl> s) {}

		// called when an alert is posted
		// alerts that are filtered are not
		// posted
		virtual void on_alert(alert const* a) {}

		// called once per second
		virtual void on_tick() {}

		// called when saving settings state
		virtual void save_state(entry& ent) const {}

		// called when loading settings state
		virtual void load_state(lazy_entry const& ent) {}
	};

	struct TORRENT_EXPORT torrent_plugin
	{
		virtual ~torrent_plugin() {}
		// throwing an exception closes the connection
		// returning a 0 pointer is valid and will not add
		// the peer_plugin to the peer_connection
		virtual boost::shared_ptr<peer_plugin> new_connection(peer_connection*)
		{ return boost::shared_ptr<peer_plugin>(); }

		virtual void on_piece_pass(int index) {}
		virtual void on_piece_failed(int index) {}

		// called aproximately once every second
		virtual void tick() {}

		// if true is returned, it means the handler handled the event,
		// and no other plugins will have their handlers called, and the
		// default behavior will be skipped
		virtual bool on_pause() { return false; }
		virtual bool on_resume() { return false; }

		// this is called when the initial checking of
		// files is completed.
		virtual void on_files_checked() {}

		// called when the torrent changes state
		// the state is one of torrent_status::state_t
		// enum members
		virtual void on_state(int s) {}
	};

	struct TORRENT_EXPORT peer_plugin
	{
		virtual ~peer_plugin() {}

		virtual char const* type() const { return ""; }

		// can add entries to the extension handshake
		// this is not called for web seeds
		virtual void add_handshake(entry&) {}

		// throwing an exception from any of the handlers (except add_handshake)
		// closes the connection

		// this is called when the initial BT handshake is received. Returning false
		// means that the other end doesn't support this extension and will remove
		// it from the list of plugins.
		// this is not called for web seeds
		virtual bool on_handshake(char const* reserved_bits) { return true; }

		// called when the extension handshake from the other end is received
		// if this returns false, it means that this extension isn't
		// supported by this peer. It will result in this peer_plugin
		// being removed from the peer_connection and destructed.
		// this is not called for web seeds
		virtual bool on_extension_handshake(lazy_entry const& h) { return true; }

		// returning true from any of the message handlers
		// indicates that the plugin has handeled the message.
		// it will break the plugin chain traversing and not let
		// anyone else handle the message, including the default
		// handler.

		virtual bool on_choke()
		{ return false; }

		virtual bool on_unchoke()
		{ return false; }

		virtual bool on_interested()
		{ return false; }

		virtual bool on_not_interested()
		{ return false; }

		virtual bool on_have(int index)
		{ return false; }

		virtual bool on_bitfield(bitfield const& bitfield)
		{ return false; }

		virtual bool on_have_all()
		{ return false; }

		virtual bool on_have_none()
		{ return false; }

		virtual bool on_allowed_fast(int index)
		{ return false; }

		virtual bool on_request(peer_request const& req)
		{ return false; }

		virtual bool on_piece(peer_request const& piece, disk_buffer_holder& data)
		{ return false; }

		virtual bool on_cancel(peer_request const& req)
		{ return false; }

		virtual bool on_reject(peer_request const& req)
		{ return false; }

		virtual bool on_suggest(int index)
		{ return false; }

		// called when an extended message is received. If returning true,
		// the message is not processed by any other plugin and if false
		// is returned the next plugin in the chain will receive it to
		// be able to handle it
		// this is not called for web seeds
		virtual bool on_extended(int length
			, int msg, buffer::const_interval body)
		{ return false; }

		// this is not called for web seeds
		virtual bool on_unknown_message(int length, int msg
			, buffer::const_interval body)
		{ return false; }

		// called when a piece that this peer participated in either
		// fails or passes the hash_check
		virtual void on_piece_pass(int index) {}
		virtual void on_piece_failed(int index) {}

		// called aproximately once every second
		virtual void tick() {}

		// called each time a request message is to be sent. If true
		// is returned, the original request message won't be sent and
		// no other plugin will have this function called.
		virtual bool write_request(peer_request const& r) { return false; }
	};

}

#endif

#endif // TORRENT_EXTENSIONS_HPP_INCLUDED

<commit_msg>fix build<commit_after>/*

Copyright (c) 2006, Arvid Norberg
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 the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

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 COPYRIGHT OWNER 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.

*/

#ifndef TORRENT_EXTENSIONS_HPP_INCLUDED
#define TORRENT_EXTENSIONS_HPP_INCLUDED

#ifndef TORRENT_DISABLE_EXTENSIONS

#ifdef _MSC_VER
#pragma warning(push, 1)
#endif

#include <boost/weak_ptr.hpp>

#ifdef _MSC_VER
#pragma warning(pop)
#endif

#include <vector>
#include "libtorrent/config.hpp"
#include "libtorrent/buffer.hpp"

namespace libtorrent
{
	namespace aux { struct session_impl; }

	struct peer_plugin;
	class bt_peer_connection;
	struct peer_request;
	class peer_connection;
	class entry;
	struct lazy_entry;
	struct disk_buffer_holder;
	struct bitfield;
	class alert;
	struct torrent_plugin;

	struct TORRENT_EXPORT plugin
	{
		virtual ~plugin() {}

		virtual boost::shared_ptr<torrent_plugin> new_torrent(torrent* t, void* user)
		{ return boost::shared_ptr<torrent_plugin>(); }

		// called when plugin is added to a session
		virtual void added(boost::weak_ptr<aux::session_impl> s) {}

		// called when an alert is posted
		// alerts that are filtered are not
		// posted
		virtual void on_alert(alert const* a) {}

		// called once per second
		virtual void on_tick() {}

		// called when saving settings state
		virtual void save_state(entry& ent) const {}

		// called when loading settings state
		virtual void load_state(lazy_entry const& ent) {}
	};

	struct TORRENT_EXPORT torrent_plugin
	{
		virtual ~torrent_plugin() {}
		// throwing an exception closes the connection
		// returning a 0 pointer is valid and will not add
		// the peer_plugin to the peer_connection
		virtual boost::shared_ptr<peer_plugin> new_connection(peer_connection*)
		{ return boost::shared_ptr<peer_plugin>(); }

		virtual void on_piece_pass(int index) {}
		virtual void on_piece_failed(int index) {}

		// called aproximately once every second
		virtual void tick() {}

		// if true is returned, it means the handler handled the event,
		// and no other plugins will have their handlers called, and the
		// default behavior will be skipped
		virtual bool on_pause() { return false; }
		virtual bool on_resume() { return false; }

		// this is called when the initial checking of
		// files is completed.
		virtual void on_files_checked() {}

		// called when the torrent changes state
		// the state is one of torrent_status::state_t
		// enum members
		virtual void on_state(int s) {}
	};

	struct TORRENT_EXPORT peer_plugin
	{
		virtual ~peer_plugin() {}

		virtual char const* type() const { return ""; }

		// can add entries to the extension handshake
		// this is not called for web seeds
		virtual void add_handshake(entry&) {}

		// throwing an exception from any of the handlers (except add_handshake)
		// closes the connection

		// this is called when the initial BT handshake is received. Returning false
		// means that the other end doesn't support this extension and will remove
		// it from the list of plugins.
		// this is not called for web seeds
		virtual bool on_handshake(char const* reserved_bits) { return true; }

		// called when the extension handshake from the other end is received
		// if this returns false, it means that this extension isn't
		// supported by this peer. It will result in this peer_plugin
		// being removed from the peer_connection and destructed.
		// this is not called for web seeds
		virtual bool on_extension_handshake(lazy_entry const& h) { return true; }

		// returning true from any of the message handlers
		// indicates that the plugin has handeled the message.
		// it will break the plugin chain traversing and not let
		// anyone else handle the message, including the default
		// handler.

		virtual bool on_choke()
		{ return false; }

		virtual bool on_unchoke()
		{ return false; }

		virtual bool on_interested()
		{ return false; }

		virtual bool on_not_interested()
		{ return false; }

		virtual bool on_have(int index)
		{ return false; }

		virtual bool on_bitfield(bitfield const& bitfield)
		{ return false; }

		virtual bool on_have_all()
		{ return false; }

		virtual bool on_have_none()
		{ return false; }

		virtual bool on_allowed_fast(int index)
		{ return false; }

		virtual bool on_request(peer_request const& req)
		{ return false; }

		virtual bool on_piece(peer_request const& piece, disk_buffer_holder& data)
		{ return false; }

		virtual bool on_cancel(peer_request const& req)
		{ return false; }

		virtual bool on_reject(peer_request const& req)
		{ return false; }

		virtual bool on_suggest(int index)
		{ return false; }

		// called when an extended message is received. If returning true,
		// the message is not processed by any other plugin and if false
		// is returned the next plugin in the chain will receive it to
		// be able to handle it
		// this is not called for web seeds
		virtual bool on_extended(int length
			, int msg, buffer::const_interval body)
		{ return false; }

		// this is not called for web seeds
		virtual bool on_unknown_message(int length, int msg
			, buffer::const_interval body)
		{ return false; }

		// called when a piece that this peer participated in either
		// fails or passes the hash_check
		virtual void on_piece_pass(int index) {}
		virtual void on_piece_failed(int index) {}

		// called aproximately once every second
		virtual void tick() {}

		// called each time a request message is to be sent. If true
		// is returned, the original request message won't be sent and
		// no other plugin will have this function called.
		virtual bool write_request(peer_request const& r) { return false; }
	};

}

#endif

#endif // TORRENT_EXTENSIONS_HPP_INCLUDED

<|endoftext|>


<commit_before>//- Standard Library -
#include <iostream>
#include <fstream>
#include <map>
#include <vector>
#include <algorithm>

//- Beach Judge -
#include <BeachJudge/Base.h>
#include <BeachJudge/Page.h>

using namespace std;

const char *includePrefix = "../www/";

namespace beachjudge
{
	map<string, Page *> g_pageMap;
	map<string, void (*)(stringstream &, Socket *, Session *, std::string)> g_templateMap;

	void Page::RegisterTemplate(string entry, void (*func)(stringstream &, Socket *, Session *, string))
	{
		g_templateMap[entry] = func;
	}
	void Page::RegisterDefaultTemplates()
	{
	}
	Page *Page::Create(string file)
	{
		if(!fileExists(file.c_str()))
			return 0;

		if(g_pageMap.count(file))
			return g_pageMap[file];

		string html, lineIn;
		ifstream inFile(file.c_str());
		while(getline(inFile, lineIn))
		{
			html = html.append(lineIn);
			html = html.append("\r\n");
		}

		Page *page = new Page();
		page->m_fileSource = file;
		page->m_html = html;
		g_pageMap[file] = page;
		return page;
	}
	void Page::Cleanup()
	{
		while(g_pageMap.size())
			delete g_pageMap.begin()->second;
	}

	Page::Page()
	{
	}
	Page::~Page()
	{
		g_pageMap.erase(m_fileSource);
	}
	void Page::AddToStream(stringstream &stream, Socket *client, Session *session, map<string, string> *masterLocalVars)
	{
		stringstream pageStream(m_html);
		string chunk, varChunk, arg, val;
		vector<string> ifStack;
		map<string, string> localVars;

		while(getline(pageStream, chunk, '$'))
		{
			bool valid = true;
			if(ifStack.size())
			{
				if(session)
				{
					for(vector<string>::iterator it = ifStack.begin(); it != ifStack.end(); it++)
						if(session->GetVariable(*it) == 0)
						{
							valid = false;
							break;
						}
				}
				else if(ifStack.front().compare("loggedOut"))
					valid = false;
			}

			if(valid)
				stream << chunk;

			if(pageStream.eof())
				break;

			varChunk = "";
			while(true)
			{
				char peek = pageStream.peek();
				if((peek >= 'A' && peek <= 'Z') || (peek >= 'a' && peek <= 'z'))
				{
					varChunk.push_back(peek);
					pageStream.get();
				}
				else if(peek == ':')
				{
					arg = "";
					pageStream.get();
					while(true)
					{
						char argPeek = pageStream.peek();
						if((argPeek >= 'A' && argPeek <= 'Z') || (argPeek >= 'a' && argPeek <= 'z') || argPeek == '.' || argPeek == '/')
						{
							arg.push_back(argPeek);
							pageStream.get();
						}
						else if(argPeek == '=')
						{
							val = "";
							pageStream.get();
							while(true)
							{
								char valPeek = pageStream.peek();
								if((valPeek >= 'A' && valPeek <= 'Z') || (valPeek >= 'a' && valPeek <= 'z') || (valPeek >= '0' && valPeek <= '9') || valPeek == '.' || valPeek == '/' || valPeek == ' ')
								{
									val.push_back(valPeek);
									pageStream.get();
								}
								else
									break;
							}
						}
						else
							break;
					}
				}
				else
					break;
			}

			if(!varChunk.compare("if"))
				ifStack.push_back(arg);
			else if(!varChunk.compare("endif"))
				ifStack.erase(find(ifStack.begin(), ifStack.end(), arg));
			else if(!varChunk.compare("set"))
			{
				if(arg.size() && val.size())
				{
					if(masterLocalVars)
						masterLocalVars->operator[](arg) = val;
					else
						localVars[arg] = val;
				}
				else
					stream << "$" << varChunk << ":" << arg << "=" << val;
			}
			else if(!varChunk.compare("get"))
			{
				bool fail = false;
				if(masterLocalVars)
				{
					if(masterLocalVars->count(arg))
						stream << masterLocalVars->operator[](arg);
					else
						fail = true;
				}
				else if(localVars.count(arg))
					stream << localVars[arg];
				else
					fail = true;

				if(fail)
					stream << "$" << varChunk << ":" << arg;
			}
			else if(!varChunk.compare("include"))
			{
				string file(includePrefix);
				file.append(arg);
				if(fileExists(file.c_str()))
				{
					Page *page = Page::Create(file);
					page->AddToStream(stream, client, session, &localVars);
				}
			}
			else if(valid)
			{
				if(g_templateMap.count(varChunk))
					g_templateMap[varChunk](stream, client, session, arg);
				else
					stream << "$" << varChunk;
			}
		}

		delete this;
	}
}
<commit_msg>Addressed Page generation bug with includes<commit_after>//- Standard Library -
#include <iostream>
#include <fstream>
#include <map>
#include <vector>
#include <algorithm>

//- Beach Judge -
#include <BeachJudge/Base.h>
#include <BeachJudge/Page.h>

using namespace std;

const char *includePrefix = "../www/";

namespace beachjudge
{
	map<string, Page *> g_pageMap;
	map<string, void (*)(stringstream &, Socket *, Session *, std::string)> g_templateMap;

	void Page::RegisterTemplate(string entry, void (*func)(stringstream &, Socket *, Session *, string))
	{
		g_templateMap[entry] = func;
	}
	void Page::RegisterDefaultTemplates()
	{
	}
	Page *Page::Create(string file)
	{
		if(!fileExists(file.c_str()))
			return 0;

		if(g_pageMap.count(file))
			return g_pageMap[file];

		string html, lineIn;
		ifstream inFile(file.c_str());
		while(getline(inFile, lineIn))
		{
			html = html.append(lineIn);
			html = html.append("\r\n");
		}

		Page *page = new Page();
		page->m_fileSource = file;
		page->m_html = html;
		g_pageMap[file] = page;
		return page;
	}
	void Page::Cleanup()
	{
		while(g_pageMap.size())
			delete g_pageMap.begin()->second;
	}

	Page::Page()
	{
	}
	Page::~Page()
	{
		g_pageMap.erase(m_fileSource);
	}
	void Page::AddToStream(stringstream &stream, Socket *client, Session *session, map<string, string> *masterLocalVars)
	{
		stringstream pageStream(m_html);
		string chunk, varChunk, arg, val;
		vector<string> ifStack;
		map<string, string> localVars;

		while(getline(pageStream, chunk, '$'))
		{
			bool valid = true;
			if(ifStack.size())
			{
				if(session)
				{
					for(vector<string>::iterator it = ifStack.begin(); it != ifStack.end(); it++)
						if(session->GetVariable(*it) == 0)
						{
							valid = false;
							break;
						}
				}
				else if(ifStack.front().compare("loggedOut"))
					valid = false;
			}

			if(valid)
				stream << chunk;

			if(pageStream.eof())
				break;

			varChunk = "";
			while(true)
			{
				char peek = pageStream.peek();
				if((peek >= 'A' && peek <= 'Z') || (peek >= 'a' && peek <= 'z'))
				{
					varChunk.push_back(peek);
					pageStream.get();
				}
				else if(peek == ':')
				{
					arg = "";
					pageStream.get();
					while(true)
					{
						char argPeek = pageStream.peek();
						if((argPeek >= 'A' && argPeek <= 'Z') || (argPeek >= 'a' && argPeek <= 'z') || argPeek == '.' || argPeek == '/')
						{
							arg.push_back(argPeek);
							pageStream.get();
						}
						else if(argPeek == '=')
						{
							val = "";
							pageStream.get();
							while(true)
							{
								char valPeek = pageStream.peek();
								if((valPeek >= 'A' && valPeek <= 'Z') || (valPeek >= 'a' && valPeek <= 'z') || (valPeek >= '0' && valPeek <= '9') || valPeek == '.' || valPeek == '/' || valPeek == ' ')
								{
									val.push_back(valPeek);
									pageStream.get();
								}
								else
									break;
							}
						}
						else
							break;
					}
				}
				else
					break;
			}

			if(!varChunk.compare("if"))
				ifStack.push_back(arg);
			else if(!varChunk.compare("endif"))
				ifStack.erase(find(ifStack.begin(), ifStack.end(), arg));
			else if(valid)
			{
				if(!varChunk.compare("set"))
				{
					if(arg.size() && val.size())
					{
						if(masterLocalVars)
							masterLocalVars->operator[](arg) = val;
						else
							localVars[arg] = val;
					}
					else
						stream << "$" << varChunk << ":" << arg << "=" << val;
				}
				else if(!varChunk.compare("get"))
				{
					bool fail = false;
					if(masterLocalVars)
					{
						if(masterLocalVars->count(arg))
							stream << masterLocalVars->operator[](arg);
						else
							fail = true;
					}
					else if(localVars.count(arg))
						stream << localVars[arg];
					else
						fail = true;

					if(fail)
						stream << "$" << varChunk << ":" << arg;
				}
				else if(!varChunk.compare("include"))
				{
					string file(includePrefix);
					file.append(arg);
					if(fileExists(file.c_str()))
					{
						Page *page = Page::Create(file);
						page->AddToStream(stream, client, session, &localVars);
					}
				}
				else if(g_templateMap.count(varChunk))
					g_templateMap[varChunk](stream, client, session, arg);
				else
					stream << "$" << varChunk;
			}
		}

		delete this;
	}
}
<|endoftext|>


<commit_before>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */

/*
 *  Main authors:
 *     Guido Tack <guido.tack@monash.edu>
 */

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include <iostream>
#include <fstream>

#include <minizinc/model.hh>
#include <minizinc/parser.hh>
#include <minizinc/prettyprinter.hh>
#include <minizinc/typecheck.hh>
#include <minizinc/exception.hh>

#include <minizinc/flatten.hh>
#include <minizinc/optimize.hh>
#include <minizinc/builtins.hh>

using namespace MiniZinc;
using namespace std;

int main(int argc, char** argv) {
  int i=1;
  string filename;
  vector<string> datafiles;
  vector<string> includePaths;
  bool flag_ignoreStdlib = false;
  bool flag_typecheck = true;
  bool flag_eval = true;
  bool flag_output = true;
  bool flag_verbose = false;
  bool flag_newfzn = false;
  bool flag_optimize = true;
  if (argc < 2)
    goto error;

  GC::init();

  for (;;) {
    if (string(argv[i])==string("-h") || string(argv[i])==string("--help"))
        goto error;
    if (string(argv[i])==string("-I")) {
      i++;
      if (i==argc) {
        goto error;
      }
      includePaths.push_back(argv[i]+string("/"));
    } else if (string(argv[i])==string("--ignore-stdlib")) {
      flag_ignoreStdlib = true;
    } else if (string(argv[i])==string("--no-output")) {
      flag_output = false;
    } else if (string(argv[i])==string("--no-typecheck")) {
      flag_typecheck = false; flag_eval=false;
    } else if (string(argv[i])==string("--no-eval")) {
      flag_eval = false;
    } else if (string(argv[i])==string("--verbose")) {
      flag_verbose = true;
    } else if (string(argv[i])==string("--newfzn")) {
      flag_newfzn = true;
    } else if (string(argv[i])==string("--no-optimize")) {
      flag_optimize = false;
    } else {
      break;
    }
    i++;
  }

  if (i==argc) {
    goto error;
  }
  filename = argv[i++];

  while (i<argc)
    datafiles.push_back(argv[i++]);

  {
    if (flag_verbose)
      std::cerr << "Parsing '" << filename << "' ..." << std::endl;
    if (Model* m = parse(filename, datafiles, includePaths, flag_ignoreStdlib,
                         std::cerr)) {
      try {
        if (flag_typecheck) {
          if (flag_verbose)
            std::cerr << "Typechecking..." << std::endl;
          MiniZinc::typecheck(m);
          MiniZinc::registerBuiltins(m);

          if (flag_verbose)
            std::cerr << "Flattening..." << std::endl;
          Model* flat = flatten(m);

          if (flag_optimize) {
            if (flag_verbose)
              std::cerr << "Optimizing..." << std::endl;
            optimize(flat);
          }

          if (flag_output) {
            if (!flag_newfzn) {
              if (flag_verbose)
                std::cerr << "Converting to old FlatZinc..." << std::endl;
              oldflatzinc(flat);
            }

            if (flag_verbose)
              std::cerr << "Printing FlatZinc..." << std::endl;
            Printer p;
            p.print(flat,std::cout);
          }
          delete flat;
        } else if (flag_output) { // !flag_typecheck
          Printer p;
          p.print(m,std::cout);
        }
      } catch (LocationException& e) {
        std::cerr << e.what() << ": " << e.msg() << std::endl;
        std::cerr << e.loc() << std::endl;
        exit(EXIT_FAILURE);
      } catch (Exception& e) {
        std::cerr << e.what() << ": " << e.msg() << std::endl;
        exit(EXIT_FAILURE);
      }
      delete m;
    }
  }

  if (flag_verbose)
    std::cerr << "Done." << std::endl;
  return 0;

error:
  std::cerr << "Usage: "<< argv[0]
            << " [<options>] [-I <include path>] <model>.mzn [<data>.dzn ...]" << std::endl
            << std::endl
            << "Options:" << std::endl
            << "\t--help  -h\tPrint this help message" << std::endl
            << "\t--ignore-stdlib\tIgnore the standard libraries stdlib.mzn and builtins.mzn" << std::endl
            << "\t--newfzn\tOutput in the new FlatZinc format" << std::endl
            << "\t--verbose\tPrint progress statements" << std::endl
            << "\t--no-typecheck\tDo not typecheck (implies --no-eval)" << std::endl
            << "\t--no-eval\tDo not evaluate" << std::endl
            << "\t--no-optimize\tDo not optimize the FlatZinc (may speed up large instances)" << std::endl
            << "\t--no-output\tDo not print the output" << std::endl;

  exit(EXIT_FAILURE);
}
<commit_msg>Use the simple pretty printer for outputting flatzinc<commit_after>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */

/*
 *  Main authors:
 *     Guido Tack <guido.tack@monash.edu>
 */

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include <iostream>
#include <fstream>

#include <minizinc/model.hh>
#include <minizinc/parser.hh>
#include <minizinc/prettyprinter.hh>
#include <minizinc/typecheck.hh>
#include <minizinc/exception.hh>

#include <minizinc/flatten.hh>
#include <minizinc/optimize.hh>
#include <minizinc/builtins.hh>

using namespace MiniZinc;
using namespace std;

int main(int argc, char** argv) {
  int i=1;
  string filename;
  vector<string> datafiles;
  vector<string> includePaths;
  bool flag_ignoreStdlib = false;
  bool flag_typecheck = true;
  bool flag_eval = true;
  bool flag_output = true;
  bool flag_verbose = false;
  bool flag_newfzn = false;
  bool flag_optimize = true;
  if (argc < 2)
    goto error;

  GC::init();

  for (;;) {
    if (string(argv[i])==string("-h") || string(argv[i])==string("--help"))
        goto error;
    if (string(argv[i])==string("-I")) {
      i++;
      if (i==argc) {
        goto error;
      }
      includePaths.push_back(argv[i]+string("/"));
    } else if (string(argv[i])==string("--ignore-stdlib")) {
      flag_ignoreStdlib = true;
    } else if (string(argv[i])==string("--no-output")) {
      flag_output = false;
    } else if (string(argv[i])==string("--no-typecheck")) {
      flag_typecheck = false; flag_eval=false;
    } else if (string(argv[i])==string("--no-eval")) {
      flag_eval = false;
    } else if (string(argv[i])==string("--verbose")) {
      flag_verbose = true;
    } else if (string(argv[i])==string("--newfzn")) {
      flag_newfzn = true;
    } else if (string(argv[i])==string("--no-optimize")) {
      flag_optimize = false;
    } else {
      break;
    }
    i++;
  }

  if (i==argc) {
    goto error;
  }
  filename = argv[i++];

  while (i<argc)
    datafiles.push_back(argv[i++]);

  {
    if (flag_verbose)
      std::cerr << "Parsing '" << filename << "' ..." << std::endl;
    if (Model* m = parse(filename, datafiles, includePaths, flag_ignoreStdlib,
                         std::cerr)) {
      try {
        if (flag_typecheck) {
          if (flag_verbose)
            std::cerr << "Typechecking..." << std::endl;
          MiniZinc::typecheck(m);
          MiniZinc::registerBuiltins(m);

          if (flag_verbose)
            std::cerr << "Flattening..." << std::endl;
          Model* flat = flatten(m);

          if (flag_optimize) {
            if (flag_verbose)
              std::cerr << "Optimizing..." << std::endl;
            optimize(flat);
          }

          if (flag_output) {
            if (!flag_newfzn) {
              if (flag_verbose)
                std::cerr << "Converting to old FlatZinc..." << std::endl;
              oldflatzinc(flat);
            }

            if (flag_verbose)
              std::cerr << "Printing FlatZinc..." << std::endl;
            Printer p;
            p.print(flat,std::cout,0);
          }
          delete flat;
        } else if (flag_output) { // !flag_typecheck
          Printer p;
          p.print(m,std::cout);
        }
      } catch (LocationException& e) {
        std::cerr << e.what() << ": " << e.msg() << std::endl;
        std::cerr << e.loc() << std::endl;
        exit(EXIT_FAILURE);
      } catch (Exception& e) {
        std::cerr << e.what() << ": " << e.msg() << std::endl;
        exit(EXIT_FAILURE);
      }
      delete m;
    }
  }

  if (flag_verbose)
    std::cerr << "Done." << std::endl;
  return 0;

error:
  std::cerr << "Usage: "<< argv[0]
            << " [<options>] [-I <include path>] <model>.mzn [<data>.dzn ...]" << std::endl
            << std::endl
            << "Options:" << std::endl
            << "\t--help  -h\tPrint this help message" << std::endl
            << "\t--ignore-stdlib\tIgnore the standard libraries stdlib.mzn and builtins.mzn" << std::endl
            << "\t--newfzn\tOutput in the new FlatZinc format" << std::endl
            << "\t--verbose\tPrint progress statements" << std::endl
            << "\t--no-typecheck\tDo not typecheck (implies --no-eval)" << std::endl
            << "\t--no-eval\tDo not evaluate" << std::endl
            << "\t--no-optimize\tDo not optimize the FlatZinc (may speed up large instances)" << std::endl
            << "\t--no-output\tDo not print the output" << std::endl;

  exit(EXIT_FAILURE);
}
<|endoftext|>