<commit_before>#include <chrono>
#include <iomanip>
#include <iostream>
#include <thread>
#include <tox/tox.h>
#include <sodium.h>

using namespace std;
using namespace std::chrono;
using namespace std::this_thread;

// Forward Declarations

void handle_friend_request(Tox*, const uint8_t*, const uint8_t*, size_t, void*);
void handle_friend_message(Tox*, uint32_t, TOX_MESSAGE_TYPE, const uint8_t*,
		           size_t, void*);

struct DHTNode
{
    string ip;
    uint16_t port;
    const char hexKey[TOX_PUBLIC_KEY_SIZE*2 + 1];
    unsigned char binKey[TOX_PUBLIC_KEY_SIZE];
};

bool g_exit = false;

int main(int argc, const char* argv[])
{

    // Create tox instance

    TOX_ERR_NEW error;
    Tox* tox = tox_new(NULL, &error);
    if (error != TOX_ERR_NEW_OK)
    {
        cout << "Failed to initialize tox." << endl;
	return -1;
    }

    // Callbacks

    tox_callback_friend_request(tox, handle_friend_request);
    tox_callback_friend_message(tox, handle_friend_message);

    // Add Bootstrap nodes

    DHTNode nodes[] =
    {
        { "biribiri.org", 33445, "F404ABAA1C99A9D37D61AB54898F56793E1DEF8BD46B1038B9D822E8460FAB67", {0} }
    };

    for (size_t i = 0; i < sizeof(nodes)/sizeof(DHTNode); ++i)
    {
        sodium_hex2bin(nodes[i].binKey, sizeof(nodes[i].binKey),
                       nodes[i].hexKey, sizeof(nodes[i].hexKey)-1, NULL, NULL, NULL);
        tox_bootstrap(tox, nodes[i].ip.c_str(), nodes[i].port, nodes[i].binKey, NULL);
    }

    // Print address

    uint8_t selfAddress[TOX_ADDRESS_SIZE];
    tox_self_get_address(tox, selfAddress);

    for (size_t i = 0; i < TOX_ADDRESS_SIZE; ++i)
    {
        cout << hex << setfill('0') << setw(2) << (int) selfAddress[i];
    }
    cout << dec << endl;

    // Main loop

    while (!g_exit)
    {
        sleep_for(milliseconds(tox_iteration_interval(tox)));
	tox_iterate(tox, NULL);
    }

    return 0;
}

void handle_friend_request(Tox* tox, const uint8_t* publicKey, const uint8_t* message,
                                  size_t length, void* userData)
{
    // Add friend

    cout << "Adding friend!" << endl;

    TOX_ERR_FRIEND_ADD error;
    tox_friend_add_norequest(tox, publicKey, &error);
    if (error != TOX_ERR_FRIEND_ADD_OK)
    {
        cout << "Failed to add friend :(" << endl;
    }
}

void handle_friend_message(Tox* tox, uint32_t friendNum,
                                  TOX_MESSAGE_TYPE type,
		                  const uint8_t* message,
				  size_t length, void* userData)
{
    // Check for quit message
    if (length == 4 && string(message, message + length) == "quit")
    {
        g_exit = true;
	return;
    }

    // Echo message

    cout << "Echoing!" << endl;

    TOX_ERR_FRIEND_SEND_MESSAGE error;
    tox_friend_send_message(tox, friendNum, type, message, length, &error);
    if (error != TOX_ERR_FRIEND_SEND_MESSAGE_OK)
    {
        cout << "Unable to parrot message X(" << endl;
    }
}
<commit_msg>Fix some formatting issues.<commit_after>#include <chrono>
#include <iomanip>
#include <iostream>
#include <thread>
#include <tox/tox.h>
#include <sodium.h>

using namespace std;
using namespace std::chrono;
using namespace std::this_thread;

// Forward Declarations

void handle_friend_request(Tox*, const uint8_t*, const uint8_t*, size_t, void*);
void handle_friend_message(Tox*, uint32_t, TOX_MESSAGE_TYPE, const uint8_t*,
                           size_t, void*);

struct DHTNode
{
    string ip;
    uint16_t port;
    const char hexKey[TOX_PUBLIC_KEY_SIZE*2 + 1];
    unsigned char binKey[TOX_PUBLIC_KEY_SIZE];
};

bool g_exit = false;

int main(int argc, const char* argv[])
{

    // Create tox instance

    TOX_ERR_NEW error;
    Tox* tox = tox_new(NULL, &error);
    if (error != TOX_ERR_NEW_OK)
    {
        cout << "Failed to initialize tox." << endl;
        return -1;
    }

    // Callbacks

    tox_callback_friend_request(tox, handle_friend_request);
    tox_callback_friend_message(tox, handle_friend_message);

    // Add Bootstrap nodes

    DHTNode nodes[] =
    {
        {
            "biribiri.org",
            33445,
            "F404ABAA1C99A9D37D61AB54898F56793E1DEF8BD46B1038B9D822E8460FAB67",
            {0}
        }
    };

    for (size_t i = 0; i < sizeof(nodes)/sizeof(DHTNode); ++i)
    {
        sodium_hex2bin(nodes[i].binKey, sizeof(nodes[i].binKey),
                       nodes[i].hexKey, sizeof(nodes[i].hexKey)-1, NULL, NULL,
                       NULL);
        tox_bootstrap(tox, nodes[i].ip.c_str(), nodes[i].port, nodes[i].binKey,
                      NULL);
    }

    // Print address

    uint8_t selfAddress[TOX_ADDRESS_SIZE];
    tox_self_get_address(tox, selfAddress);

    for (size_t i = 0; i < TOX_ADDRESS_SIZE; ++i)
    {
        cout << hex << setfill('0') << setw(2) << (int) selfAddress[i];
    }
    cout << dec << endl;

    // Main loop

    while (!g_exit)
    {
        sleep_for(milliseconds(tox_iteration_interval(tox)));
        tox_iterate(tox, NULL);
    }

    return 0;
}

void handle_friend_request(Tox* tox, const uint8_t* publicKey,
                           const uint8_t* message, size_t length,
                           void* userData)
{
    // Add friend

    cout << "Adding friend!" << endl;

    TOX_ERR_FRIEND_ADD error;
    tox_friend_add_norequest(tox, publicKey, &error);
    if (error != TOX_ERR_FRIEND_ADD_OK)
    {
        cout << "Failed to add friend :(" << endl;
    }
}

void handle_friend_message(Tox* tox, uint32_t friendNum, TOX_MESSAGE_TYPE type,
                           const uint8_t* message, size_t length,
                           void* userData)
{
    // Check for quit message
    if (length == 4 && string(message, message + length) == "quit")
    {
        g_exit = true;
        return;
    }

    // Echo message

    cout << "Echoing!" << endl;

    TOX_ERR_FRIEND_SEND_MESSAGE error;
    tox_friend_send_message(tox, friendNum, type, message, length, &error);
    if (error != TOX_ERR_FRIEND_SEND_MESSAGE_OK)
    {
        cout << "Unable to parrot message X(" << endl;
    }
}
<|endoftext|>


<commit_before>//
// base.hpp
// ~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

#ifndef EIGENJS_BASIC_HPP
#define EIGENJS_BASIC_HPP

#include <v8.h>
#include <node.h>
#include <nan.h>

#include <boost/mpl/and.hpp>
#include <boost/mpl/or.hpp>

#include <eigen3/Eigen/Dense>

#include <complex>
#include <memory>
#include <type_traits>

#include "Complex_fwd.hpp"
#include "Matrix_fwd.hpp"
#include "CMatrix_fwd.hpp"
#include "Vector_fwd.hpp"
#include "CVector_fwd.hpp"
#include "RowVector_fwd.hpp"
#include "CRowVector_fwd.hpp"
#include "Block_fwd.hpp"

#include "detail/is_eigen_block.hpp"
#include "detail/is_eigen_matrix.hpp"

namespace EigenJS {

namespace detail {
  template <typename ScalarType>
  struct std_complex_dummy_ptr {
    typedef ScalarType scalar_type;
    typedef std::complex<scalar_type> value_type;

    NAN_INLINE value_type& operator*() { return value_; }
    NAN_INLINE const value_type& operator*() const { return value_; }
    NAN_INLINE value_type* operator->() { return &value_; }
    NAN_INLINE const value_type* operator->() const { return &value_; }

   private:
    value_type value_;
  };

  template <typename T>
  struct unwrap_block {
    typedef T type;
  };

  template<typename XprType, int BlockRows, int BlockCols, bool InnerPanel>
  struct unwrap_block<
    Eigen::Block<XprType, BlockRows, BlockCols, InnerPanel>
  > {
    typedef XprType type;
  };

}  // namespace detail

template <
  template <typename, typename, const char*> class Derived
, typename ScalarType
, typename ValueType
, const char* ClassName
>
struct base : node::ObjectWrap {
  typedef Derived<ScalarType, ValueType, ClassName> derived_type;

  typedef ScalarType scalar_type;
  typedef typename detail::unwrap_block<ValueType>::type value_type;

  typedef typename std::conditional<
      std::is_same<
        value_type
      , typename detail::std_complex_dummy_ptr<scalar_type>::value_type
      >::value
    , detail::std_complex_dummy_ptr<scalar_type>
    , std::shared_ptr<value_type>
    >::type pointer_type;

  static NAN_INLINE bool is_scalar(const v8::Handle<v8::Value>& arg) {
    return arg->IsNumber() ? true : false;
  }

  static NAN_INLINE bool is_complex(const v8::Handle<v8::Value>& arg) {
    return Complex<scalar_type>::base_type::has_instance(arg);
  }

  static NAN_INLINE bool
  is_complex_or_saclar(const v8::Handle<v8::Value>& arg) {
    return
      Complex<scalar_type>::base_type::has_instance(arg) || arg->IsNumber()
      ? true : false;
  }

  static NAN_INLINE bool is_matrix(const v8::Handle<v8::Value>& arg) {
    return Matrix<scalar_type, value_type>::base_type::has_instance(arg);
  }

  static NAN_INLINE bool is_cmatrix(const v8::Handle<v8::Value>& arg) {
    return CMatrix<scalar_type, value_type>::base_type::has_instance(arg);
  }

  static NAN_INLINE bool is_vector(const v8::Handle<v8::Value>& arg) {
    return Vector<scalar_type, value_type>::base_type::has_instance(arg);
  }

  static NAN_INLINE bool is_cvector(const v8::Handle<v8::Value>& arg) {
    return CVector<scalar_type, value_type>::base_type::has_instance(arg);
  }

  static NAN_INLINE bool is_rowvector(const v8::Handle<v8::Value>& arg) {
    return RowVector<scalar_type, value_type>::base_type::has_instance(arg);
  }

  static NAN_INLINE bool is_crowvector(const v8::Handle<v8::Value>& arg) {
    return CRowVector<scalar_type, value_type>::base_type::has_instance(arg);
  }

  static NAN_INLINE bool has_instance(const v8::Handle<v8::Value>& value) {
    NanScope();
    v8::Local<v8::FunctionTemplate> tpl = NanNew(function_template);
    return tpl->HasInstance(value);
  }

  template <typename T>
  static NAN_INLINE v8::Local<v8::Object>
  new_instance(const T& args, int argc, v8::Handle<v8::Value> argv[]) {
    v8::Local<v8::Function> ctor = NanNew(constructor);
    v8::Local<v8::Object> instance = ctor->NewInstance(argc, argv);
    return instance;
  }

  template <typename T, int Rows, int Cols>
  static NAN_INLINE bool is_out_of_range(
      const Eigen::Matrix<T, Rows, Cols>& eigen_matrix
    , const typename Eigen::Matrix<T, Rows, Cols>::Index& row
    , const typename Eigen::Matrix<T, Rows, Cols>::Index& col) {
    return row < 0 || row >= eigen_matrix.rows() ||
           col < 0 || col >= eigen_matrix.cols()
      ? NanThrowError("Row or column numbers are out of range"), true
      : false;
  }

  template <typename T, typename U>
  static NAN_INLINE
  typename std::enable_if<
    boost::mpl::and_<
      detail::is_eigen_matrix<typename T::value_type>
    , detail::is_eigen_matrix<typename U::value_type>
    >::value
  , bool
  >::type
  is_nonconformate_arguments(
      const T* const& op1
    , const U* const& op2) {
    return (*op1)->rows() != (*op2)->rows() ||
           (*op1)->cols() != (*op2)->cols()
      ? NanThrowError("Nonconformant arguments"), true
      : false;
  }

  template <typename T, typename U>
  static NAN_INLINE
  typename std::enable_if<
    boost::mpl::and_<
      detail::is_eigen_matrix<typename T::value_type>
    , detail::is_eigen_matrix<typename U::value_type>
    >::value
  , bool
  >::type
  is_invalid_matrix_product(
      const T* const& op1
    , const U* const& op2) {
    return (*op1)->cols() != (*op2)->rows()
      ? NanThrowError("Invalid matrix product"), true
      : false;
  }

 public:
  NAN_INLINE value_type& operator*() { return *value_ptr_; }
  NAN_INLINE const value_type& operator*() const { return *value_ptr_; }
  NAN_INLINE value_type* operator->() { return value_ptr_.get(); }
  NAN_INLINE const value_type* operator->() const { return value_ptr_.get(); }

  NAN_INLINE operator const pointer_type&() const {
    return value_ptr_;
  }

 protected:
  base() : value_ptr_(new value_type()) {}

  explicit base(const Complex<scalar_type>&) : value_ptr_() {}

  base(const pointer_type& value_ptr)
    : value_ptr_(value_ptr)
  {}

  ~base() {}

  static v8::Persistent<v8::FunctionTemplate> function_template;
  static v8::Persistent<v8::Function> constructor;

 private:
  friend derived_type;
  pointer_type value_ptr_;
};

template<
  template <typename, typename, const char*> class Derived
, typename ScalarType
, typename ValueType
, const char* ClassName
>
v8::Persistent<v8::FunctionTemplate>
    base<Derived, ScalarType, ValueType, ClassName>::function_template;

template<
  template <typename, typename, const char*> class Derived
, typename ScalarType
, typename ValueType
, const char* ClassName
>
v8::Persistent<v8::Function>
    base<Derived, ScalarType, ValueType, ClassName>::constructor;

}  // namespace EigenJS

#endif  // EIGENJS_BASIC_HPP
<commit_msg>src: added a constructor for Block<commit_after>//
// base.hpp
// ~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

#ifndef EIGENJS_BASIC_HPP
#define EIGENJS_BASIC_HPP

#include <v8.h>
#include <node.h>
#include <nan.h>

#include <boost/mpl/and.hpp>
#include <boost/mpl/or.hpp>

#include <eigen3/Eigen/Dense>

#include <complex>
#include <memory>
#include <type_traits>

#include "Complex_fwd.hpp"
#include "Matrix_fwd.hpp"
#include "CMatrix_fwd.hpp"
#include "Vector_fwd.hpp"
#include "CVector_fwd.hpp"
#include "RowVector_fwd.hpp"
#include "CRowVector_fwd.hpp"
#include "Block_fwd.hpp"

#include "detail/is_eigen_matrix.hpp"

namespace EigenJS {

namespace detail {
  template <typename ScalarType>
  struct std_complex_dummy_ptr {
    typedef ScalarType scalar_type;
    typedef std::complex<scalar_type> value_type;

    NAN_INLINE value_type& operator*() { return value_; }
    NAN_INLINE const value_type& operator*() const { return value_; }
    NAN_INLINE value_type* operator->() { return &value_; }
    NAN_INLINE const value_type* operator->() const { return &value_; }

   private:
    value_type value_;
  };

  template <typename T>
  struct unwrap_block {
    typedef T type;
  };

  template<typename XprType, int BlockRows, int BlockCols, bool InnerPanel>
  struct unwrap_block<
    Eigen::Block<XprType, BlockRows, BlockCols, InnerPanel>
  > {
    typedef XprType type;
  };

}  // namespace detail

template <
  template <typename, typename, const char*> class Derived
, typename ScalarType
, typename ValueType
, const char* ClassName
>
struct base : node::ObjectWrap {
  typedef Derived<ScalarType, ValueType, ClassName> derived_type;

  typedef ScalarType scalar_type;
  typedef typename detail::unwrap_block<ValueType>::type value_type;

  typedef typename std::conditional<
      std::is_same<
        value_type
      , typename detail::std_complex_dummy_ptr<scalar_type>::value_type
      >::value
    , detail::std_complex_dummy_ptr<scalar_type>
    , std::shared_ptr<value_type>
    >::type pointer_type;

  static NAN_INLINE bool is_scalar(const v8::Handle<v8::Value>& arg) {
    return arg->IsNumber() ? true : false;
  }

  static NAN_INLINE bool is_complex(const v8::Handle<v8::Value>& arg) {
    return Complex<scalar_type>::base_type::has_instance(arg);
  }

  static NAN_INLINE bool
  is_complex_or_saclar(const v8::Handle<v8::Value>& arg) {
    return
      Complex<scalar_type>::base_type::has_instance(arg) || arg->IsNumber()
      ? true : false;
  }

  static NAN_INLINE bool is_matrix(const v8::Handle<v8::Value>& arg) {
    return Matrix<scalar_type, value_type>::base_type::has_instance(arg);
  }

  static NAN_INLINE bool is_cmatrix(const v8::Handle<v8::Value>& arg) {
    return CMatrix<scalar_type, value_type>::base_type::has_instance(arg);
  }

  static NAN_INLINE bool is_vector(const v8::Handle<v8::Value>& arg) {
    return Vector<scalar_type, value_type>::base_type::has_instance(arg);
  }

  static NAN_INLINE bool is_cvector(const v8::Handle<v8::Value>& arg) {
    return CVector<scalar_type, value_type>::base_type::has_instance(arg);
  }

  static NAN_INLINE bool is_rowvector(const v8::Handle<v8::Value>& arg) {
    return RowVector<scalar_type, value_type>::base_type::has_instance(arg);
  }

  static NAN_INLINE bool is_crowvector(const v8::Handle<v8::Value>& arg) {
    return CRowVector<scalar_type, value_type>::base_type::has_instance(arg);
  }

  static NAN_INLINE bool has_instance(const v8::Handle<v8::Value>& value) {
    NanScope();
    v8::Local<v8::FunctionTemplate> tpl = NanNew(function_template);
    return tpl->HasInstance(value);
  }

  template <typename T>
  static NAN_INLINE v8::Local<v8::Object>
  new_instance(const T& args, int argc, v8::Handle<v8::Value> argv[]) {
    v8::Local<v8::Function> ctor = NanNew(constructor);
    v8::Local<v8::Object> instance = ctor->NewInstance(argc, argv);
    return instance;
  }

  template <typename T, int Rows, int Cols>
  static NAN_INLINE bool is_out_of_range(
      const Eigen::Matrix<T, Rows, Cols>& eigen_matrix
    , const typename Eigen::Matrix<T, Rows, Cols>::Index& row
    , const typename Eigen::Matrix<T, Rows, Cols>::Index& col) {
    return row < 0 || row >= eigen_matrix.rows() ||
           col < 0 || col >= eigen_matrix.cols()
      ? NanThrowError("Row or column numbers are out of range"), true
      : false;
  }

  template <typename T, typename U>
  static NAN_INLINE
  typename std::enable_if<
    boost::mpl::and_<
      detail::is_eigen_matrix<typename T::value_type>
    , detail::is_eigen_matrix<typename U::value_type>
    >::value
  , bool
  >::type
  is_nonconformate_arguments(
      const T* const& op1
    , const U* const& op2) {
    return (*op1)->rows() != (*op2)->rows() ||
           (*op1)->cols() != (*op2)->cols()
      ? NanThrowError("Nonconformant arguments"), true
      : false;
  }

  template <typename T, typename U>
  static NAN_INLINE
  typename std::enable_if<
    boost::mpl::and_<
      detail::is_eigen_matrix<typename T::value_type>
    , detail::is_eigen_matrix<typename U::value_type>
    >::value
  , bool
  >::type
  is_invalid_matrix_product(
      const T* const& op1
    , const U* const& op2) {
    return (*op1)->cols() != (*op2)->rows()
      ? NanThrowError("Invalid matrix product"), true
      : false;
  }

 public:
  NAN_INLINE value_type& operator*() { return *value_ptr_; }
  NAN_INLINE const value_type& operator*() const { return *value_ptr_; }
  NAN_INLINE value_type* operator->() { return value_ptr_.get(); }
  NAN_INLINE const value_type* operator->() const { return value_ptr_.get(); }

  NAN_INLINE operator const pointer_type&() const {
    return value_ptr_;
  }

 protected:
  base() : value_ptr_(new value_type()) {}

  explicit base(const Complex<scalar_type>&) : value_ptr_() {}

  explicit base(const pointer_type& value_ptr)
    : value_ptr_(value_ptr)
  {}

  ~base() {}

  static v8::Persistent<v8::FunctionTemplate> function_template;
  static v8::Persistent<v8::Function> constructor;

 private:
  friend derived_type;
  pointer_type value_ptr_;
};

template<
  template <typename, typename, const char*> class Derived
, typename ScalarType
, typename ValueType
, const char* ClassName
>
v8::Persistent<v8::FunctionTemplate>
    base<Derived, ScalarType, ValueType, ClassName>::function_template;

template<
  template <typename, typename, const char*> class Derived
, typename ScalarType
, typename ValueType
, const char* ClassName
>
v8::Persistent<v8::Function>
    base<Derived, ScalarType, ValueType, ClassName>::constructor;

}  // namespace EigenJS

#endif  // EIGENJS_BASIC_HPP
<|endoftext|>


<commit_before>#include "coreroutines.h"
#include "CompleteGraphScorer.h"
#include "FastScorer.h"
#include "PValueModuleScorer.h"
#include <tclap/CmdLine.h>
#include <cstring>

typedef std::map<std::string, TGroups> TDiseases;

bool parseMultipleDiseaseFile(const std::string& filename, TDiseases& diseaseEntries) {
  std::ifstream instream(filename);
  std::string line;
  TDiseases entries;
  while (!instream.eof()) {
    std::getline(instream, line);
    std::stringstream stream(line);
    std::string entry;
    std::string name;
    stream >> name;
    std::vector<std::string> genes;
    TGroups groups;
    while (!stream.eof()) {
      stream >> entry;
      //entry.erase(entry.find_last_not_of(" \n\r\t")+1);
      char* dup = strdup(entry.c_str());
      char* pch = strtok(dup, ",");
      std::vector<std::string> group;
      while (pch != 0) {
	group.push_back(pch);
	pch = strtok(0, ",");
      }
      groups.push_back(group);
    }
    if (groups.size() > 0) {
      diseaseEntries[name] = groups;
    }
  }
  return true;
}

bool readDegreeGroups(const std::string& filename, TIndexMap& geneToIndexMap, std::map<int, int>& nodeDegreeGroup) {
  std::ifstream dinfile(filename);
  TGroups groups;

  if (false == readGroups(dinfile, groups)) {
    printf("Could not read degree group file.");
    return false;
  }
  int i = 0;
  for (auto const& g : groups) {
    for (auto const& node : g) {
      nodeDegreeGroup[geneToIndexMap[node]] = i;
    }
    i++;
  }

  dinfile.close();

  return true;
}

int main(int argc, char** argv) {
  try {

    // Command-line parsing
    TCLAP::CmdLine cmd("Command description message", ' ', "0.9");
    TCLAP::ValueArg<std::string> netFilename("n", "network", "Network file", true, "", "string");
    cmd.add(netFilename);
    TCLAP::ValueArg<std::string> groupsFilename("g", "groups", "Groups file", true, "", "string");
    cmd.add(groupsFilename);
    TCLAP::ValueArg<int> pvalIterations("p", "pval", "Pvalue iterations", false, -1, "int");
    cmd.add(pvalIterations);
    TCLAP::ValueArg<std::string> outFilename("o", "outfile", "Output summary file", false, "", "string");
    cmd.add(outFilename);
    TCLAP::ValueArg<int> cGroupSize("s", "size", "Complete graph group size", false, 3, "int");
    cmd.add(cGroupSize);

    TCLAP::ValueArg<std::string> method("m", "method", "Scoring method, complete or fast", false, "fast", "string");
    cmd.add(method);

    TCLAP::ValueArg<std::string> degree("d", "degree_groups", "Degree groups for node permutations", false, "", "string");
    cmd.add(degree);

    TCLAP::SwitchArg multiple("l", "multiple", "Do multiple runs", false);
    cmd.add(multiple);

    // Read in command-line options.
    cmd.parse(argc, argv);

    //// Read in groups from file
    // std::map<int, int> nodeDegreeGroups;
    // std::string gfilename = groupsFilename.getValue();
    // std::ifstream ginfile(gfilename);
    // TGroups groups;
    // readGroups(ginfile, groups);

    // // Flatten out groups
    // std::vector<std::string> entries;
    // flattenGroups<std::string>(groups, entries);
    // const int numEntriesInGroups = entries.size();

    int cgraphSize = cGroupSize.getValue();
    if (cgraphSize != 3 && cgraphSize != 4) {
      printf("Inappropriate complete graph size, %d. Only accept 3 or 4.", cgraphSize);
      exit(-1);
    }

    // Do we calculate a p-value?
    int pIterations = pvalIterations.getValue();

    // Get network filename
    std::string nfilename = netFilename.getValue();
    std::ifstream ninfile(nfilename);
    std::string line;

    // // Grab degree groups
    // std::map<int, int> nodeDegreeGroups;
    // std::string dFileName = degree.getValue();
    // if (dFileName == "") {
    //   for (auto const& i : fullMap) {
    // 	nodeDegreeGroups[i.second] = 0;
    //   }
    // } else {
    //   if (false == readDegreeGroups(dFileName, fullMap, nodeDegreeGroups)) {
    // 	printf("Problem reading node degree groups.");
    // 	return(-1);
    //   }
    // }

    // Grab network names
    std::getline(ninfile, line);
    TIndexMap fullMap, map;
    int numNodes = parseNamesLine(line, fullMap);

    float* mat(0);
    IModuleScorer* moduleScorer(0);
    int matrixWidth(0);

    // Make module scorer
    if (cgraphSize == 4) {
      moduleScorer = new CompleteGraphScorer4();
    }
    else {
      if (method.getValue() == "complete") {
	moduleScorer = new CompleteGraphScorer();
      } else {
	moduleScorer = new FastScorer();
      }
    }

    if (!multiple.getValue()) {

      // Read in groups from file
      std::string gfilename = groupsFilename.getValue();
      std::ifstream ginfile(gfilename);
      TGroups groups;
      readGroups(ginfile, groups);

      // Flatten out groups
      std::vector<std::string> entries;
      flattenGroups<std::string>(groups, entries);
      const int numEntriesInGroups = entries.size();

      // Grab degree groups
      std::map<int, int> nodeDegreeGroups;
      std::string dFileName = degree.getValue();
      if (dFileName == "") {
	for (auto const& i : fullMap) {
	  nodeDegreeGroups[i.second] = 0;
	}
      } else {
	if (false == readDegreeGroups(dFileName, fullMap, nodeDegreeGroups)) {
	  printf("Problem reading node degree groups.");
	  return(-1);
	}
      }

      if (pIterations == -1) {
	// Just score the nodes. No p-value calculation.
	//moduleScorer = new CompleteGraphScorer4();
	matrixWidth = numEntriesInGroups;

	// Allocate memory for subnework
	mat = (float*)malloc(sizeof(float) * matrixWidth * matrixWidth);
	if (mat == 0) {
	  printf("Could not allocate matrix buffer of %d bytes.\n",
		 (int)(numEntriesInGroups * numEntriesInGroups * sizeof(float)));
	  exit(-1);
	}

	std::cout << "Pulling out necessary subnetwork from file." << std::endl;
	// Pull in values from full matrix
	readEntriesFromNetwork(ninfile, fullMap, entries, map, mat, matrixWidth);
      }
      else {
	// We need to calculate empirical p-values.
	// PValueModulesScorer will take ownership of the complete graph scorer.
	moduleScorer = new PValueModuleScorer(pIterations, moduleScorer, nodeDegreeGroups);
	if (moduleScorer == 0) {
	  std::cerr << "ModuleScorer is nil. Something went wrong." << std::endl;
	  exit(-1);
	}

	matrixWidth = numNodes;
	map = fullMap;
	std::cout << "Reading entire network into memory. This may take a while." << std::endl;

	// Allocate a big block of memory. This could easily fail.
	mat = (float*)malloc(sizeof(float) * matrixWidth * matrixWidth);
	if (mat == 0) {
	  std::cerr << "Could not allocate matrix buffer of ";
	  std::cerr << (int)(matrixWidth * matrixWidth * sizeof(float)) << " bytes." << std::endl;
	  exit(-1);
	}

	// Read the network from the stream
	readEntireNetwork(ninfile, numNodes, mat);
	std::cout << "Completed reading network of " << sizeof(float) * matrixWidth * matrixWidth / (1024*1024*1024.0) << "GB." << std::endl;

      }

      TIndicesGroups igroups;
      mapGroupsToIndices<std::string>(groups, map, igroups);

      // Score genes based on strong modules
      std::cout << "Scoring genes." << std::endl;
      TScoreMap scores;
      TIndices inds;
      for (auto const& g : igroups) {
	for (auto i : g) {
	  inds.push_back(i);
	}
      }

      moduleScorer->ScoreModule(mat, matrixWidth, igroups, inds, scores);

      TReverseIndexMap rmap2;
      for (auto const &p : map) {
	rmap2[p.second] = p.first;
      }
      moduleScorer->BriefSummary(scores, rmap2, std::cout);

      // Write summary to file.
      std::string outFile = outFilename.getValue();
      if (outFile != "") {
	std::cout << std::endl << "Writing summary to output file " << outFile << std::endl;
	std::ofstream outStream(outFile, std::ofstream::out);
	moduleScorer->LongSummary(scores, rmap2, igroups, outStream);
      }
    }
    else {
      // Deal with multiple thingies.
      std::string gfilename = groupsFilename.getValue();
      TDiseases diseases;
      if (parseMultipleDiseaseFile(gfilename, diseases)) {
	// Allocate a big block of memory. This could easily fail.
	matrixWidth = numNodes;
	map = fullMap;
	std::cout << "Reading entire network into memory. This may take a while." << std::endl;
	mat = (float*)malloc(sizeof(float) * matrixWidth * matrixWidth);
	if (mat == 0) {
	  std::cerr << "Could not allocate matrix buffer of ";
	  std::cerr << (int)(matrixWidth * matrixWidth * sizeof(float)) << " bytes." << std::endl;
	  exit(-1);
	}
	// Read the network from the stream
	readEntireNetwork(ninfile, numNodes, mat);
	std::cout << "Completed reading network of " << sizeof(float) * matrixWidth * matrixWidth / (1024*1024*1024.0) << "GB." << std::endl;

	std::map<int, int> nodeDegreeGroups;
	if (pIterations > 0) {
	  // We need to calculate empirical p-values.
	  // PValueModulesScorer will take ownership of the complete graph scorer.
	  std::string dFileName = degree.getValue();
	  if (dFileName == "") {
	    for (auto const& i : fullMap) {
	      nodeDegreeGroups[i.second] = 0;
	    }
	  } else {
	    if (false == readDegreeGroups(dFileName, fullMap, nodeDegreeGroups)) {
	      printf("Problem reading node degree groups.");
	      return(-1);
	    }
	  }
	  moduleScorer = new PValueModuleScorer(pIterations, moduleScorer, nodeDegreeGroups);
	  if (moduleScorer == 0) {
	    std::cerr << "ModuleScorer is nil. Something went wrong." << std::endl;
	    exit(-1);
	  }
	}

	std::string outFile = outFilename.getValue();
	std::ofstream* outStream = 0;
	if (outFile != "") {
	  outStream = new std::ofstream(outFile, std::ofstream::out);
	}
	for (const auto &disease : diseases) {
	  TIndicesGroups igroups;
	  mapGroupsToIndices<std::string>(disease.second, map, igroups);
	  TIndices inds;
	  for (auto const& g : igroups) {
	    for (auto i : g) {
	      inds.push_back(i);
	    }
	  }
	  TScoreMap scores;
      	  moduleScorer->ScoreModule(mat, matrixWidth, igroups, inds, scores);

	  TReverseIndexMap rmap2;
	  for (auto const &p : map) {
	    rmap2[p.second] = p.first;
	  }
	  printf("%s\n", disease.first.c_str());
	  moduleScorer->BriefSummary(scores, rmap2, std::cout);
	  printf("\n\n");
	  if (outFile != "") {
	    *outStream << "-----------------" << std::endl;
	    *outStream << disease.first << std::endl;
	    moduleScorer->LongSummary(scores, rmap2, igroups, *outStream);
	  }
	}
	if (outStream) delete outStream;
      }
      else {
	printf("Problem reading entries from file.\n");
      }
    }

    // Delete heap stuffs.
    free(mat);
    delete moduleScorer;

  } catch (TCLAP::ArgException &e) {
    std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
  }

}
<commit_msg>small change.<commit_after>#include "coreroutines.h"
#include "CompleteGraphScorer.h"
#include "FastScorer.h"
#include "PValueModuleScorer.h"
#include <tclap/CmdLine.h>
#include <cstring>

typedef std::map<std::string, TGroups> TDiseases;

bool parseMultipleDiseaseFile(const std::string& filename, TDiseases& diseaseEntries) {
  std::ifstream instream(filename);
  std::string line;
  while (!instream.eof()) {
    TGroups groups;
    std::getline(instream, line);
    std::vector<std::string> split;
    std::stringstream stream(line);
    std::string entry;
    while (std::getline(stream, entry, '\t')) {
      split.push_back(entry);
    }

    for (int i = 1; i < split.size(); ++i) {
      std::stringstream ss(split[i]);
      std::vector<std::string> items;
      while (std::getline(ss, entry, ',')) {
	items.push_back(entry);
      }
      groups.push_back(items);
    }
    if (groups.size() > 0) diseaseEntries[split[0]] = groups;
  }
  return true;
}

// bool parseMultipleDiseaseFile(const std::string& filename, TDiseases& diseaseEntries) {
//   std::ifstream instream(filename);
//   std::string line;
//   TDiseases entries;
//   while (!instream.eof()) {
//     std::getline(instream, line);
//     std::stringstream stream(line);
//     std::string entry;
//     std::string name;
//     stream >> name;
//     std::vector<std::string> genes;
//     TGroups groups;
//     //while (!stream.eof()) {
//     //std::stringstream ss(
//     while (std::getline(stream, entry) {
//       stream >> entry;
//       //entry.erase(entry.find_last_not_of(" \n\r\t")+1);
//       char* dup = strdup(entry.c_str());
//       char* pch = strtok(dup, ",");
//       std::vector<std::string> group;
//       while (pch != 0) {
// 	group.push_back(pch);
// 	pch = strtok(0, ",");
//       }
//       groups.push_back(group);
//     }
//     if (groups.size() > 0) {
//       diseaseEntries[name] = groups;
//     }
//   }
//   return true;
// }

bool readDegreeGroups(const std::string& filename, TIndexMap& geneToIndexMap, std::map<int, int>& nodeDegreeGroup) {
  std::ifstream dinfile(filename);
  TGroups groups;

  if (false == readGroups(dinfile, groups)) {
    printf("Could not read degree group file.");
    return false;
  }
  int i = 0;
  for (auto const& g : groups) {
    for (auto const& node : g) {
      nodeDegreeGroup[geneToIndexMap[node]] = i;
    }
    i++;
  }

  dinfile.close();

  return true;
}

int main(int argc, char** argv) {
  try {

    // Command-line parsing
    TCLAP::CmdLine cmd("Command description message", ' ', "0.9");
    TCLAP::ValueArg<std::string> netFilename("n", "network", "Network file", true, "", "string");
    cmd.add(netFilename);
    TCLAP::ValueArg<std::string> groupsFilename("g", "groups", "Groups file", true, "", "string");
    cmd.add(groupsFilename);
    TCLAP::ValueArg<int> pvalIterations("p", "pval", "Pvalue iterations", false, -1, "int");
    cmd.add(pvalIterations);
    TCLAP::ValueArg<std::string> outFilename("o", "outfile", "Output summary file", false, "", "string");
    cmd.add(outFilename);
    TCLAP::ValueArg<int> cGroupSize("s", "size", "Complete graph group size", false, 3, "int");
    cmd.add(cGroupSize);

    TCLAP::ValueArg<std::string> method("m", "method", "Scoring method, complete or fast", false, "fast", "string");
    cmd.add(method);

    TCLAP::ValueArg<std::string> degree("d", "degree_groups", "Degree groups for node permutations", false, "", "string");
    cmd.add(degree);

    TCLAP::SwitchArg multiple("l", "multiple", "Do multiple runs", false);
    cmd.add(multiple);

    // Read in command-line options.
    cmd.parse(argc, argv);

    //// Read in groups from file
    // std::map<int, int> nodeDegreeGroups;
    // std::string gfilename = groupsFilename.getValue();
    // std::ifstream ginfile(gfilename);
    // TGroups groups;
    // readGroups(ginfile, groups);

    // // Flatten out groups
    // std::vector<std::string> entries;
    // flattenGroups<std::string>(groups, entries);
    // const int numEntriesInGroups = entries.size();

    int cgraphSize = cGroupSize.getValue();
    if (cgraphSize != 3 && cgraphSize != 4) {
      printf("Inappropriate complete graph size, %d. Only accept 3 or 4.", cgraphSize);
      exit(-1);
    }

    // Do we calculate a p-value?
    int pIterations = pvalIterations.getValue();

    // Get network filename
    std::string nfilename = netFilename.getValue();
    std::ifstream ninfile(nfilename);
    std::string line;

    // // Grab degree groups
    // std::map<int, int> nodeDegreeGroups;
    // std::string dFileName = degree.getValue();
    // if (dFileName == "") {
    //   for (auto const& i : fullMap) {
    // 	nodeDegreeGroups[i.second] = 0;
    //   }
    // } else {
    //   if (false == readDegreeGroups(dFileName, fullMap, nodeDegreeGroups)) {
    // 	printf("Problem reading node degree groups.");
    // 	return(-1);
    //   }
    // }

    // Grab network names
    std::getline(ninfile, line);
    TIndexMap fullMap, map;
    int numNodes = parseNamesLine(line, fullMap);

    float* mat(0);
    IModuleScorer* moduleScorer(0);
    int matrixWidth(0);

    // Make module scorer
    if (cgraphSize == 4) {
      moduleScorer = new CompleteGraphScorer4();
    }
    else {
      if (method.getValue() == "complete") {
	moduleScorer = new CompleteGraphScorer();
      } else {
	moduleScorer = new FastScorer();
      }
    }

    if (!multiple.getValue()) {

      // Read in groups from file
      std::string gfilename = groupsFilename.getValue();
      std::ifstream ginfile(gfilename);
      TGroups groups;
      readGroups(ginfile, groups);

      // Flatten out groups
      std::vector<std::string> entries;
      flattenGroups<std::string>(groups, entries);
      const int numEntriesInGroups = entries.size();

      // Grab degree groups
      std::map<int, int> nodeDegreeGroups;
      std::string dFileName = degree.getValue();
      if (dFileName == "") {
	for (auto const& i : fullMap) {
	  nodeDegreeGroups[i.second] = 0;
	}
      } else {
	if (false == readDegreeGroups(dFileName, fullMap, nodeDegreeGroups)) {
	  printf("Problem reading node degree groups.");
	  return(-1);
	}
      }

      if (pIterations == -1) {
	// Just score the nodes. No p-value calculation.
	//moduleScorer = new CompleteGraphScorer4();
	matrixWidth = numEntriesInGroups;

	// Allocate memory for subnework
	mat = (float*)malloc(sizeof(float) * matrixWidth * matrixWidth);
	if (mat == 0) {
	  printf("Could not allocate matrix buffer of %d bytes.\n",
		 (int)(numEntriesInGroups * numEntriesInGroups * sizeof(float)));
	  exit(-1);
	}

	std::cout << "Pulling out necessary subnetwork from file." << std::endl;
	// Pull in values from full matrix
	readEntriesFromNetwork(ninfile, fullMap, entries, map, mat, matrixWidth);
      }
      else {
	// We need to calculate empirical p-values.
	// PValueModulesScorer will take ownership of the complete graph scorer.
	moduleScorer = new PValueModuleScorer(pIterations, moduleScorer, nodeDegreeGroups);
	if (moduleScorer == 0) {
	  std::cerr << "ModuleScorer is nil. Something went wrong." << std::endl;
	  exit(-1);
	}

	matrixWidth = numNodes;
	map = fullMap;
	std::cout << "Reading entire network into memory. This may take a while." << std::endl;

	// Allocate a big block of memory. This could easily fail.
	mat = (float*)malloc(sizeof(float) * matrixWidth * matrixWidth);
	if (mat == 0) {
	  std::cerr << "Could not allocate matrix buffer of ";
	  std::cerr << (int)(matrixWidth * matrixWidth * sizeof(float)) << " bytes." << std::endl;
	  exit(-1);
	}

	// Read the network from the stream
	readEntireNetwork(ninfile, numNodes, mat);
	std::cout << "Completed reading network of " << sizeof(float) * matrixWidth * matrixWidth / (1024*1024*1024.0) << "GB." << std::endl;

      }

      TIndicesGroups igroups;
      mapGroupsToIndices<std::string>(groups, map, igroups);

      // Score genes based on strong modules
      std::cout << "Scoring genes." << std::endl;
      TScoreMap scores;
      TIndices inds;
      for (auto const& g : igroups) {
	for (auto i : g) {
	  inds.push_back(i);
	}
      }

      moduleScorer->ScoreModule(mat, matrixWidth, igroups, inds, scores);

      TReverseIndexMap rmap2;
      for (auto const &p : map) {
	rmap2[p.second] = p.first;
      }
      moduleScorer->BriefSummary(scores, rmap2, std::cout);

      // Write summary to file.
      std::string outFile = outFilename.getValue();
      if (outFile != "") {
	std::cout << std::endl << "Writing summary to output file " << outFile << std::endl;
	std::ofstream outStream(outFile, std::ofstream::out);
	moduleScorer->LongSummary(scores, rmap2, igroups, outStream);
      }
    }
    else {
      // Deal with multiple thingies.
      std::string gfilename = groupsFilename.getValue();
      TDiseases diseases;
      if (parseMultipleDiseaseFile(gfilename, diseases)) {
	// Allocate a big block of memory. This could easily fail.
	matrixWidth = numNodes;
	map = fullMap;
	std::cout << "Reading entire network into memory. This may take a while." << std::endl;
	mat = (float*)malloc(sizeof(float) * matrixWidth * matrixWidth);
	if (mat == 0) {
	  std::cerr << "Could not allocate matrix buffer of ";
	  std::cerr << (int)(matrixWidth * matrixWidth * sizeof(float)) << " bytes." << std::endl;
	  exit(-1);
	}
	// Read the network from the stream
	readEntireNetwork(ninfile, numNodes, mat);
	std::cout << "Completed reading network of " << sizeof(float) * matrixWidth * matrixWidth / (1024*1024*1024.0) << "GB." << std::endl;

	std::map<int, int> nodeDegreeGroups;
	if (pIterations > 0) {
	  // We need to calculate empirical p-values.
	  // PValueModulesScorer will take ownership of the complete graph scorer.
	  std::string dFileName = degree.getValue();
	  if (dFileName == "") {
	    for (auto const& i : fullMap) {
	      nodeDegreeGroups[i.second] = 0;
	    }
	  } else {
	    if (false == readDegreeGroups(dFileName, fullMap, nodeDegreeGroups)) {
	      printf("Problem reading node degree groups.");
	      return(-1);
	    }
	  }
	  moduleScorer = new PValueModuleScorer(pIterations, moduleScorer, nodeDegreeGroups);
	  if (moduleScorer == 0) {
	    std::cerr << "ModuleScorer is nil. Something went wrong." << std::endl;
	    exit(-1);
	  }
	}

	std::string outFile = outFilename.getValue();
	std::ofstream* outStream = 0;
	if (outFile != "") {
	  outStream = new std::ofstream(outFile, std::ofstream::out);
	}
	for (const auto &disease : diseases) {
	  TIndicesGroups igroups;
	  mapGroupsToIndices<std::string>(disease.second, map, igroups);
	  TIndices inds;
	  for (auto const& g : igroups) {
	    for (auto i : g) {
	      inds.push_back(i);
	    }
	  }
	  TScoreMap scores;
      	  moduleScorer->ScoreModule(mat, matrixWidth, igroups, inds, scores);

	  TReverseIndexMap rmap2;
	  for (auto const &p : map) {
	    rmap2[p.second] = p.first;
	  }
	  printf("%s\n", disease.first.c_str());
	  moduleScorer->BriefSummary(scores, rmap2, std::cout);
	  printf("\n\n");
	  if (outFile != "") {
	    *outStream << "-------------------" << std::endl;
	    *outStream << disease.first << std::endl;
	    *outStream << "-------------------" << std::endl;
	    moduleScorer->LongSummary(scores, rmap2, igroups, *outStream);
	  }
	}
	if (outStream) delete outStream;
      }
      else {
	printf("Problem reading entries from file.\n");
      }
    }

    // Delete heap stuffs.
    free(mat);
    delete moduleScorer;

  } catch (TCLAP::ArgException &e) {
    std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
  }

}
<|endoftext|>


<commit_before>#include "slk.h"

namespace w3x
{
	static bool is_string(std::string_view& s)
	{
		bool r = false;
		if (!s.empty() && s.front() == '"') {
			s.remove_prefix(1);
			r = true;
		}
		if (!s.empty() && s.back() == '"') {
			s.remove_suffix(1);
			r = true;
		}
		return r;
	}

	int parse_slk(lua_State* L)
	{
		slk l(luaL_checkstring(L, 1));
		const char* file = luaL_optstring(L, 2, "...");
		if (!l.parse()) {
			return luaL_error(L, "\n%s:%d: %s", file, (int)lua_tointeger(L, -2), lua_tostring(L, -1));
		}
		for (size_t x = 0; x < l.maxx; ++x) {
			is_string(l.row[x]);
		}
		for (size_t y = 0; y < l.maxy; ++y) {
			is_string(l.col[y]);
		}
		lua_createtable(L, l.maxy, 0);
		for (size_t y = 1; y < l.maxy; ++y) {
			lua_pushlstring(L, l.col[y].data(), l.col[y].size());
			lua_createtable(L, l.maxx, 0);
			for (size_t x = 1; x < l.maxx; ++x) {
				lua_pushlstring(L, l.row[x].data(), l.row[x].size());
				auto& data = l.data[x][y];
				if (is_string(data)) {
					lua_pushlstring(L, data.data(), data.size());
				}
				else if (!data.empty()) {
					lua_pushlstring(L, data.data(), data.size());
					if (!lua_stringtonumber(L, lua_tostring(L, -1))) {
						lua_pushinteger(L, 0);
					}
					lua_remove(L, -2);
				}
				else {
					lua_pushnil(L);
				}
				lua_rawset(L, -3);
			}
			lua_rawset(L, -3);
		}
		return 1;
	}
}

extern "C" __declspec(dllexport)
int luaopen_w3xparser(lua_State* L)
{
	static luaL_Reg l[] = {
	    { "slk", w3x::parse_slk },
		{ NULL, NULL },
	};
	luaL_newlib(L, l);
	return 1;
}
<commit_msg>这个参数反了<commit_after>#include "slk.h"

namespace w3x
{
	static bool is_string(std::string_view& s)
	{
		bool r = false;
		if (!s.empty() && s.front() == '"') {
			s.remove_prefix(1);
			r = true;
		}
		if (!s.empty() && s.back() == '"') {
			s.remove_suffix(1);
			r = true;
		}
		return r;
	}

	int parse_slk(lua_State* L)
	{
		slk l(luaL_checkstring(L, 1));
		const char* file = luaL_optstring(L, 2, "...");
		if (!l.parse()) {
			return luaL_error(L, "\n%s:%d: %s", file, (int)lua_tointeger(L, -2), lua_tostring(L, -1));
		}
		for (size_t x = 0; x < l.maxx; ++x) {
			is_string(l.row[x]);
		}
		for (size_t y = 0; y < l.maxy; ++y) {
			is_string(l.col[y]);
		}
		lua_createtable(L, 0, l.maxy);
		for (size_t y = 1; y < l.maxy; ++y) {
			lua_pushlstring(L, l.col[y].data(), l.col[y].size());
			lua_createtable(L, 0, l.maxx);
			for (size_t x = 1; x < l.maxx; ++x) {
				lua_pushlstring(L, l.row[x].data(), l.row[x].size());
				auto& data = l.data[x][y];
				if (is_string(data)) {
					lua_pushlstring(L, data.data(), data.size());
				}
				else if (!data.empty()) {
					lua_pushlstring(L, data.data(), data.size());
					if (!lua_stringtonumber(L, lua_tostring(L, -1))) {
						lua_pushinteger(L, 0);
					}
					lua_remove(L, -2);
				}
				else {
					lua_pushnil(L);
				}
				lua_rawset(L, -3);
			}
			lua_rawset(L, -3);
		}
		return 1;
	}
}

extern "C" __declspec(dllexport)
int luaopen_w3xparser(lua_State* L)
{
	static luaL_Reg l[] = {
	    { "slk", w3x::parse_slk },
		{ NULL, NULL },
	};
	luaL_newlib(L, l);
	return 1;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

void prompt(){
	cout<<"$ ";
}

//clear the line from the first # to the end of the input
void comment(char line[],int linesize){
	char * hashtag;
	hashtag = strchr(line,'#');
	if(hashtag!=NULL){
		 memset(&line[hashtag-line],0,linesize);
	}
}
void execute(char *str[],int size){
//for(int i=0;i<sizeof(str);i++) cout<<str[i]<<endl;

char * newstr[256];
char * connector;
int i,j,aux;

	for(i=0;i<size;i++){
		//newstr[0] receives commands, first parameter after a connector
		newstr[0] = str[i];
		aux=1;
		//test command without flags carryng a ';'
		connector = strchr(newstr[0],';');
		if(connector!=NULL) newstr[0][connector-newstr[0]] = '\0';
		else
			for(j=i+1;j<size;j++){
				connector = strchr(str[j],';');
				if(connector!=NULL){
				//erase the last character if ';'
					str[j][connector-str[j]] = '\0';
				}

				//add flags to newstr
				newstr[aux] = str[j];
				aux++;
				i = j;

				if(connector!=NULL) break;
			}

	//	for(int k=0;k<aux;k++)cout<<"indice "<<k<<" "<<newstr[k]<<endl;

		int pid = fork();
		if(pid == -1){
			perror("There was an error with fork().");
			exit(1);
		}
		else if(pid == 0){
		  	 if(-1 == execvp(newstr[0], newstr)){
				perror("There was an error");
			}
    	 		 exit(1);
		}
		else if(pid>0){
			if(-1 == wait(0))
		   	perror("There was an error with wait()");

		}

		// clear the vector newstr in order to execute new commands
		for(int k=0;k<aux;k++)newstr[k]='\0';
	}
}

int main(){
   int INPUTSIZE=256,index;
   char input[256];
   char * str[256];
   char * pch;

   while(true){
	do{
	    //output login@machine$
	    prompt();
	    cin.getline(input,INPUTSIZE);
	}while(input[0]=='#');

	comment(input,INPUTSIZE);

	if(memcmp(input, "exit",4)==0) exit(0);

	index=0;
	pch= strtok (input," ");

	while(pch != NULL){
	    str[index]=pch;
	    pch = strtok(NULL, " ");
	    index++;
	}

	str[index] = NULL;
	//for(int i=0;i<sizeof(str);i++) cout<<str[i]<<endl;

	execute(str,index);

    }
 return 0;
}
<commit_msg>function prompt completed login@machine<commit_after>#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

//output login @ machine $
void prompt(){
	int pid = fork();
		if(pid == -1){
			perror("fork() presented error");
			exit(1);
			}
		else if(pid==0){
			char host[50];
			if ((gethostname(host, sizeof(host)-1))==-1) {
				host[0] = 'h';
				host[1] = 'o';
				host[2] = 's';
				host[3] = 't';
				host[4] = '\0';
				perror("Error trying to get hostname");
			}

			char login[50];

			if (getlogin_r(login, sizeof(login)-1)) {
				login[0] = 'l';
				login[1] = 'o';
				login[2] = 'g';
				login[3] = 'i';
				login[4] = 'n';
				login[5] = '\0';
				perror("Error trying to get user login");
			}

			cout << login << "@" << host << "$ ";
			exit(1);
			}else if(pid>0){
				if(-1 == wait(0))
			   	perror("wait() presented error");

			}
}

//clear the line from the first # to the end of the input
void comment(char line[],int linesize){
	char * hashtag;
	hashtag = strchr(line,'#');
	if(hashtag!=NULL){
		 memset(&line[hashtag-line],0,linesize);
	}
}
void execute(char *str[],int size){
//for(int i=0;i<size;i++) cout<<str[i]<<endl;

char * newstr[256];
char * connector;
int i,j,aux;

	for(i=0;i<size;i++){
		//newstr[0] receives commands, first parameter after a connector
		newstr[0] = str[i];
		aux=1;
		//test command without flags carryng a ';'
		connector = strchr(newstr[0],';');
		if(connector!=NULL) newstr[0][connector-newstr[0]] = '\0';
		else
			for(j=i+1;j<size;j++){
				connector = strchr(str[j],';');
				if(connector!=NULL){
				//erase the last character if ';'
					str[j][connector-str[j]] = '\0';
				}

				//add flags to newstr
				newstr[aux] = str[j];
				aux++;
				i = j;

				if(connector!=NULL) break;
			}
//	for(int g=0;g<aux+2;g++)cout<<"indice "<<g<<" "<<newstr[g]<<endl;

		int pid = fork();
		if(pid == -1){
			perror("There was an error with fork().");
			exit(1);
		}
		else if(pid == 0){
		  	 if(-1 == execvp(newstr[0], newstr)){
				perror("There was an error");
			}
    	 		 exit(1);
		}
		else if(pid>0){
			if(-1 == wait(0))
		   	perror("There was an error with wait()");

		}

		// clear the vector newstr in order to execute new commands
		for(int k=0;k<aux;k++)newstr[k]='\0';
	}
}

int main(){
   int INPUTSIZE=256,index;
   char input[256];
   char * str[256];
   char * pch;

   while(true){
	do{
	    prompt(); //output login @ machine $
	    cin.getline(input,256);
	}while(input[0]=='#');

	comment(input,INPUTSIZE);

	if(memcmp(input, "exit",4)==0) exit(0);

	index=0;
	pch= strtok (input," ");

	while(pch != NULL){
	    str[index]=pch;
	    pch = strtok(NULL, " ");
	    index++;
	}

	str[index] = NULL;
	//for(int i=0;i<sizeof(str);i++) cout<<str[i]<<endl;

	execute(str,index);

    }
 return 0;
}
<|endoftext|>


<commit_before>// A simple example that shows the usage of a TGSplitButton. The
// checkbutton is used to change the split state of the button.
//
// author, Roel Aaij 13/07/2007

#include <iostream>
#include <TApplication.h>
#include <TGClient.h>
#include <TGButton.h>
#include <TGFrame.h>
#include <TGLayout.h>
#include <TGWindow.h>
#include <TGLabel.h>
#include <TString.h>
#include <TGMenu.h>

// A little class to automatically handle the generation of unique
// widget ids.
enum EMenuIds {
   ID_1,
   ID_2,
   ID_3,
   ID_4,
   ID_5
};

class IDList {
private:
   Int_t nID ;               // Generates unique widget IDs.
public:
   IDList() : nID(0) {}
   ~IDList() {}
   Int_t GetUnID(void) { return ++nID ; }
} ;

class SplitButtonTest : public TGMainFrame {

private:
   TGSplitButton *fMButton;  // Split Button
   TGPopupMenu   *fPopMenu;  // TGpopupMenu that will be attached to
                             // the button.
   IDList         IDs ;      // Generator for unique widget IDs.

public:
   SplitButtonTest(const TGWindow *p, UInt_t w, UInt_t h) ;
   virtual ~SplitButtonTest() ;

   void DoExit() ;
   void DoSplit(Bool_t split) ;
   void HandleMenu(Int_t id) ;

   ClassDef(SplitButtonTest, 0)
};

SplitButtonTest::SplitButtonTest(const TGWindow *p, UInt_t w, UInt_t h)
   : TGMainFrame(p, w, h)
{
   SetCleanup(kDeepCleanup) ;

   Connect("CloseWindow()", "SplitButtonTest", this, "DoExit()") ;
   DontCallClose() ;

   TGVerticalFrame *fVL = new TGVerticalFrame(this, 100, 100) ;
   TGHorizontalFrame *fHL = new TGHorizontalFrame(fVL, 100, 40) ;

   // Create a popup menu.
   fPopMenu = new TGPopupMenu(gClient->GetRoot());
   fPopMenu->AddEntry("Button &1", ID_1);
   fPopMenu->AddEntry("Button &2", ID_2);
   fPopMenu->DisableEntry(ID_2);
   fPopMenu->AddEntry("Button &3", ID_3);
   fPopMenu->AddSeparator();

   // Create a split button, the menu is adopted.
   fMButton = new TGSplitButton(fHL, new TGHotString("Button &Options"),
                                fPopMenu, IDs.GetUnID());

   // It is possible to add entries later
   fPopMenu->AddEntry("En&try with really really long name", ID_4);
   fPopMenu->AddEntry("&Exit", ID_5);

   // Connect the special signal for the activation of items in a menu
   // that belongs to a split button to the slot.
   fMButton->Connect("ItemClicked(Int_t)", "SplitButtonTest", this,
                     "HandleMenu(Int_t)");

   TGCheckButton *fCButton = new TGCheckButton(fHL, new TGHotString("Split"),
                                               IDs.GetUnID());
   fCButton->SetState(kButtonDown);
   fCButton->Connect("Toggled(Bool_t)", "SplitButtonTest", this, "DoSplit(Bool_t)");

   // Add frames to their parent for layout.
   fHL->AddFrame(fCButton, new TGLayoutHints(kLHintsCenterX | kLHintsCenterY,
                                             0, 10, 0, 0)) ;
   fHL->AddFrame(fMButton, new TGLayoutHints(kLHintsCenterX | kLHintsCenterY));
   fVL->AddFrame(fHL, new TGLayoutHints(kLHintsCenterX | kLHintsCenterY)) ;
   AddFrame(fVL, new TGLayoutHints(kLHintsCenterX | kLHintsCenterY)) ;

   SetWindowName("SplitButton Test") ;
   MapSubwindows() ;
   Resize(GetDefaultSize()) ;
   MapWindow() ;

} ;

SplitButtonTest::~SplitButtonTest()
{
   // Destructor
   Cleanup() ;
}

void SplitButtonTest::DoExit()
{
   // Exit this application via the Exit button or Window Manager.
   // Use one of the both lines according to your needs.
   // Please note to re-run this macro in the same ROOT session,
   // you have to compile it to get signals/slots 'on place'.

   //DeleteWindow();            // to stay in the ROOT session
   gApplication->Terminate();   // to exit and close the ROOT session
}

void SplitButtonTest::DoSplit(Bool_t split)
{
   fMButton->SetSplit(split);
}

void SplitButtonTest::HandleMenu(Int_t id)
{
   // Activation of menu items in the popup menu are handled in a user
   // defined slot to which the ItemClicked(Int_t) signal is
   // connected.

   switch (id) {
   case ID_1:
      std::cout << "Button 1 was activated" << std::endl;
      break;
   case ID_2:
      std::cout << "Button 2 was activated" << std::endl;
      break;
   case ID_3:
      std::cout << "Button 3 was activated" << std::endl;
      break;
   case ID_4:
      std::cout << "Button with a really really long name was activated"
                << std::endl;
      break;
   case ID_5:
      DoExit();
      break;
   }
}
void splitbuttonTest()
{
   new SplitButtonTest(gClient->GetRoot(),100,100);
}

<commit_msg>Added a new check button for testing enabled/disabled split button state.<commit_after>// A simple example that shows the usage of a TGSplitButton. The
// checkbutton is used to change the split state of the button.
//
// author, Roel Aaij 13/07/2007

#include <iostream>
#include <TApplication.h>
#include <TGClient.h>
#include <TGButton.h>
#include <TGFrame.h>
#include <TGLayout.h>
#include <TGWindow.h>
#include <TGLabel.h>
#include <TString.h>
#include <TGMenu.h>

// A little class to automatically handle the generation of unique
// widget ids.
enum EMenuIds {
   ID_1,
   ID_2,
   ID_3,
   ID_4,
   ID_5
};

class IDList {
private:
   Int_t nID ;               // Generates unique widget IDs.
public:
   IDList() : nID(0) {}
   ~IDList() {}
   Int_t GetUnID(void) { return ++nID ; }
} ;

class SplitButtonTest : public TGMainFrame {

private:
   TGSplitButton *fMButton;  // Split Button
   TGPopupMenu   *fPopMenu;  // TGpopupMenu that will be attached to
                             // the button.
   IDList         IDs ;      // Generator for unique widget IDs.

public:
   SplitButtonTest(const TGWindow *p, UInt_t w, UInt_t h) ;
   virtual ~SplitButtonTest() ;

   void DoExit() ;
   void DoSplit(Bool_t split) ;
   void DoEnable(Bool_t on) ;
   void HandleMenu(Int_t id) ;

   ClassDef(SplitButtonTest, 0)
};

SplitButtonTest::SplitButtonTest(const TGWindow *p, UInt_t w, UInt_t h)
   : TGMainFrame(p, w, h)
{
   SetCleanup(kDeepCleanup) ;

   Connect("CloseWindow()", "SplitButtonTest", this, "DoExit()") ;
   DontCallClose() ;

   TGVerticalFrame *fVL = new TGVerticalFrame(this, 100, 100) ;
   TGHorizontalFrame *fHL = new TGHorizontalFrame(fVL, 100, 40) ;

   // Create a popup menu.
   fPopMenu = new TGPopupMenu(gClient->GetRoot());
   fPopMenu->AddEntry("Button &1", ID_1);
   fPopMenu->AddEntry("Button &2", ID_2);
   fPopMenu->DisableEntry(ID_2);
   fPopMenu->AddEntry("Button &3", ID_3);
   fPopMenu->AddSeparator();

   // Create a split button, the menu is adopted.
   fMButton = new TGSplitButton(fHL, new TGHotString("Button &Options"),
                                fPopMenu, IDs.GetUnID());

   // It is possible to add entries later
   fPopMenu->AddEntry("En&try with really really long name", ID_4);
   fPopMenu->AddEntry("&Exit", ID_5);

   // Connect the special signal for the activation of items in a menu
   // that belongs to a split button to the slot.
   fMButton->Connect("ItemClicked(Int_t)", "SplitButtonTest", this,
                     "HandleMenu(Int_t)");

   TGCheckButton *fCButton = new TGCheckButton(fHL, new TGHotString("Split"),
                                               IDs.GetUnID());
   fCButton->SetState(kButtonDown);
   fCButton->Connect("Toggled(Bool_t)", "SplitButtonTest", this, "DoSplit(Bool_t)");

   // Add frames to their parent for layout.
   fHL->AddFrame(fCButton, new TGLayoutHints(kLHintsCenterX | kLHintsCenterY,
                                             0, 10, 0, 0)) ;
   TGCheckButton *fEButton = new TGCheckButton(fHL, new TGHotString("Enable"),
                                               IDs.GetUnID());
   fEButton->SetState(kButtonDown);
   fEButton->Connect("Toggled(Bool_t)", "SplitButtonTest", this, "DoEnable(Bool_t)");

   // Add frames to their parent for layout.
   fHL->AddFrame(fEButton, new TGLayoutHints(kLHintsCenterX | kLHintsCenterY,
                                             0, 10, 0, 0)) ;
   fHL->AddFrame(fMButton, new TGLayoutHints(kLHintsCenterX | kLHintsCenterY));
   fVL->AddFrame(fHL, new TGLayoutHints(kLHintsCenterX | kLHintsCenterY)) ;
   AddFrame(fVL, new TGLayoutHints(kLHintsCenterX | kLHintsCenterY)) ;

   SetWindowName("SplitButton Test") ;
   MapSubwindows() ;
   Resize(GetDefaultSize()) ;
   MapWindow() ;

} ;

SplitButtonTest::~SplitButtonTest()
{
   // Destructor
   Cleanup() ;
}

void SplitButtonTest::DoExit()
{
   // Exit this application via the Exit button or Window Manager.
   // Use one of the both lines according to your needs.
   // Please note to re-run this macro in the same ROOT session,
   // you have to compile it to get signals/slots 'on place'.

   //DeleteWindow();            // to stay in the ROOT session
   gApplication->Terminate();   // to exit and close the ROOT session
}

void SplitButtonTest::DoSplit(Bool_t split)
{
   fMButton->SetSplit(split);
}

void SplitButtonTest::DoEnable(Bool_t on)
{
   if (on)
      fMButton->SetState(kButtonUp);
   else
      fMButton->SetState(kButtonDisabled);
}

void SplitButtonTest::HandleMenu(Int_t id)
{
   // Activation of menu items in the popup menu are handled in a user
   // defined slot to which the ItemClicked(Int_t) signal is
   // connected.

   switch (id) {
   case ID_1:
      std::cout << "Button 1 was activated" << std::endl;
      break;
   case ID_2:
      std::cout << "Button 2 was activated" << std::endl;
      break;
   case ID_3:
      std::cout << "Button 3 was activated" << std::endl;
      break;
   case ID_4:
      std::cout << "Button with a really really long name was activated"
                << std::endl;
      break;
   case ID_5:
      DoExit();
      break;
   }
}
void splitbuttonTest()
{
   new SplitButtonTest(gClient->GetRoot(),100,100);
}

<|endoftext|>


<commit_before><commit_msg>Clean up how nStateVal is smuggled in<commit_after><|endoftext|>


<commit_before>/*! \file main.cpp
 *  \brief Program to run the grid code. */

#ifdef MPI_CHOLLA
#include <mpi.h>
#include "mpi_routines.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "global.h"
#include "grid3D.h"
#include "io.h"
#include "error_handling.h"

#define OUTPUT
//#define CPU_TIME

int main(int argc, char *argv[])
{
  // timing variables
  double start_total, stop_total, start_step, stop_step;
  #ifdef CPU_TIME
  double stop_init, init_min, init_max, init_avg;
  double start_bound, stop_bound, bound_min, bound_max, bound_avg;
  double start_hydro, stop_hydro, hydro_min, hydro_max, hydro_avg;
  double init, bound, hydro;
  init = bound = hydro = 0;
  #endif //CPU_TIME

  // start the total time
  start_total = get_time();

  /* Initialize MPI communication */
  #ifdef MPI_CHOLLA
  InitializeChollaMPI(&argc, &argv);
  #endif /*MPI_CHOLLA*/

  Real dti = 0; // inverse time step, 1.0 / dt

  // input parameter variables
  char *param_file;
  struct parameters P;
  int nfile = 0; // number of output files
  Real outtime = 0; // current output time

  // read in command line arguments
  if (argc != 2)
  {
    chprintf("usage: %s <parameter_file>\n", argv[0]);
    chexit(-1);
  } else {
    param_file = argv[1];
  }

  // create the grid
  Grid3D G;

  // read in the parameters
  parse_params (param_file, &P);
  // and output to screen
  chprintf ("Parameter values:  nx = %d, ny = %d, nz = %d, tout = %f, init = %s, boundaries = %d %d %d %d %d %d\n",
    P.nx, P.ny, P.nz, P.tout, P.init, P.xl_bcnd, P.xu_bcnd, P.yl_bcnd, P.yu_bcnd, P.zl_bcnd, P.zu_bcnd);
  chprintf ("Output directory:  %s\n", P.outdir);

  //Create a Log file to output run-time messages
  Create_Log_File(P);

  // initialize the grid
  G.Initialize(&P);
  chprintf("Local number of grid cells: %d %d %d %d\n", G.H.nx_real, G.H.ny_real, G.H.nz_real, G.H.n_cells);

  // Set initial conditions and calculate first dt
  chprintf("Setting initial conditions...\n");
  G.Set_Initial_Conditions(P);
  chprintf("Initial conditions set.\n");
  // set main variables for Read_Grid inital conditions
  if (strcmp(P.init, "Read_Grid") == 0) {
    dti = C_cfl / G.H.dt;
    outtime += G.H.t;
    nfile = P.nfile*P.nfull;
  }

  #ifdef DE
  chprintf("\nUsing Dual Energy Formalism:\n eta_1: %0.3f   eta_2: %0.4f \n", DE_ETA_1, DE_ETA_2);
  char *message = (char*)malloc(50 * sizeof(char));
  sprintf(message, " eta_1: %0.3f   eta_2: %0.3f   ", DE_ETA_1, DE_ETA_2 );
  Write_Message_To_Log_File( message );
  #endif

  #ifdef CPU_TIME
  G.Timer.Initialize();
  #endif

  #ifdef GRAVITY
  G.Initialize_Gravity(&P);
  #endif

  #ifdef PARTICLES
  G.Initialize_Particles(&P);
  #endif

  #ifdef COSMOLOGY
  G.Initialize_Cosmology(&P);
  #endif

  #ifdef COOLING_GRACKLE
  G.Initialize_Grackle(&P);
  #endif

  #ifdef GRAVITY
  G.Compute_Gravitational_Potential( &P);
  #endif

  // set boundary conditions (assign appropriate values to ghost cells)
  chprintf("Setting boundary conditions...\n");
  G.Set_Boundary_Conditions_All(P);
  chprintf("Boundary conditions set.\n");

  #ifdef PARTICLES
  G.Get_Particles_Accelration();
  #endif

  chprintf("Dimensions of each cell: dx = %f dy = %f dz = %f\n", G.H.dx, G.H.dy, G.H.dz);
  chprintf("Ratio of specific heats gamma = %f\n",gama);
  chprintf("Nstep = %d  Timestep = %f  Simulation time = %f\n", G.H.n_step, G.H.dt, G.H.t);

  #ifdef OUTPUT
  if (strcmp(P.init, "Read_Grid") != 0 || G.H.Output_Now ) {
  // write the initial conditions to file
  chprintf("Writing initial conditions to file...\n");
  WriteData(G, P, nfile);
  }
  // add one to the output file count
  nfile++;
  #endif //OUTPUT
  // increment the next output time
  outtime += P.outstep;

  #ifdef CPU_TIME
  stop_init = get_time();
  init = stop_init - start_total;
  #ifdef MPI_CHOLLA
  init_min = ReduceRealMin(init);
  init_max = ReduceRealMax(init);
  init_avg = ReduceRealAvg(init);
  chprintf("Init  min: %9.4f  max: %9.4f  avg: %9.4f\n", init_min, init_max, init_avg);
  #else
  printf("Init %9.4f\n", init);
  #endif //MPI_CHOLLA
  #endif //CPU_TIME

  // Evolve the grid, one timestep at a time
  chprintf("Starting calculations.\n");
  while (G.H.t < P.tout)
  // while (G.H.n_step < 0)
  {
    chprintf("n_step: %d \n", G.H.n_step + 1 );
    // get the start time
    start_step = get_time();

    // calculate the timestep
    G.set_dt(dti);

    if (G.H.t + G.H.dt > outtime) G.H.dt = outtime - G.H.t;

    #ifdef PARTICLES
    //Advance the particles KDK( first step )
    G.Advance_Particles( 1 );
    //Transfer the particles boundaries
    G.Transfer_Particles_Boundaries(P);
    #endif

    // Advance the grid by one timestep
    dti = G.Update_Hydro_Grid();

    // update the simulation time ( t += dt )
    G.Update_Time();

    #ifdef GRAVITY
    //Compute Gravitational potential for next step
    G.Compute_Gravitational_Potential( &P);
    #endif

    // add one to the timestep count
    G.H.n_step++;

    // set boundary conditions for next time step
    G.Set_Boundary_Conditions_All(P);

    #ifdef PARTICLES
    //Advance the particles KDK( second step )
    G.Advance_Particles( 2 );
    #endif

    // Optional:Timestep using DKD for particles
    // #if defined( PARTICLES ) && defined( PARTICLES_DKD )
    // dti = G.Update_Grid_and_Particles_DKD(P);
    // #endif

    #ifdef CPU_TIME
    G.Timer.Print_Times();
    #endif

    // get the time to compute the total timestep
    stop_step = get_time();
    stop_total = get_time();
    G.H.t_wall = stop_total-start_total;
    #ifdef MPI_CHOLLA
    G.H.t_wall = ReduceRealMax(G.H.t_wall);
    #endif
    chprintf("n_step: %d   sim time: %10.7f   sim timestep: %7.4e  timestep time = %9.3f ms   total time = %9.4f s\n\n",
      G.H.n_step, G.H.t, G.H.dt, (stop_step-start_step)*1000, G.H.t_wall);

    #ifdef OUTPUT_ALWAYS
    G.H.Output_Now = true;
    #endif

    if ( P.n_steps_output > 0 && G.H.n_step % P.n_steps_output == 0) G.H.Output_Now = true;

    if (G.H.t == outtime || G.H.Output_Now )
    {
      #ifdef OUTPUT
      /*output the grid data*/
      WriteData(G, P, nfile);
      // add one to the output file count
      nfile++;
      #endif //OUTPUT
      // update to the next output time
      outtime += P.outstep;
    }

    #ifdef CPU_TIME
    G.Timer.n_steps += 1;
    #endif

    #ifdef N_STEPS_LIMIT
    if ( G.H.n_step == N_STEPS_LIMIT) break;
    #endif

    #ifdef COSMOLOGY
    if ( G.Cosmo.current_a >= G.Cosmo.scale_outputs[G.Cosmo.n_outputs-1] ) {
      chprintf( "\nReached Last Cosmological Output: Ending Simulation\n");
      break;
    }
    #endif

  } /*end loop over timesteps*/

  #ifdef CPU_TIME
  G.Timer.Get_Average_Times();
  G.Timer.Print_Average_Times( P );
  #endif

  Write_Message_To_Log_File( "Run completed successfully!");

  // free the grid
  G.Reset();

  #ifdef MPI_CHOLLA
  MPI_Finalize();
  #endif /*MPI_CHOLLA*/

  return 0;

}
<commit_msg>Don't output when n_steps_out<commit_after>/*! \file main.cpp
 *  \brief Program to run the grid code. */

#ifdef MPI_CHOLLA
#include <mpi.h>
#include "mpi_routines.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "global.h"
#include "grid3D.h"
#include "io.h"
#include "error_handling.h"

#define OUTPUT
//#define CPU_TIME

int main(int argc, char *argv[])
{
  // timing variables
  double start_total, stop_total, start_step, stop_step;
  #ifdef CPU_TIME
  double stop_init, init_min, init_max, init_avg;
  double start_bound, stop_bound, bound_min, bound_max, bound_avg;
  double start_hydro, stop_hydro, hydro_min, hydro_max, hydro_avg;
  double init, bound, hydro;
  init = bound = hydro = 0;
  #endif //CPU_TIME

  // start the total time
  start_total = get_time();

  /* Initialize MPI communication */
  #ifdef MPI_CHOLLA
  InitializeChollaMPI(&argc, &argv);
  #endif /*MPI_CHOLLA*/

  Real dti = 0; // inverse time step, 1.0 / dt

  // input parameter variables
  char *param_file;
  struct parameters P;
  int nfile = 0; // number of output files
  Real outtime = 0; // current output time

  // read in command line arguments
  if (argc != 2)
  {
    chprintf("usage: %s <parameter_file>\n", argv[0]);
    chexit(-1);
  } else {
    param_file = argv[1];
  }

  // create the grid
  Grid3D G;

  // read in the parameters
  parse_params (param_file, &P);
  // and output to screen
  chprintf ("Parameter values:  nx = %d, ny = %d, nz = %d, tout = %f, init = %s, boundaries = %d %d %d %d %d %d\n",
    P.nx, P.ny, P.nz, P.tout, P.init, P.xl_bcnd, P.xu_bcnd, P.yl_bcnd, P.yu_bcnd, P.zl_bcnd, P.zu_bcnd);
  chprintf ("Output directory:  %s\n", P.outdir);

  //Create a Log file to output run-time messages
  Create_Log_File(P);

  // initialize the grid
  G.Initialize(&P);
  chprintf("Local number of grid cells: %d %d %d %d\n", G.H.nx_real, G.H.ny_real, G.H.nz_real, G.H.n_cells);

  // Set initial conditions and calculate first dt
  chprintf("Setting initial conditions...\n");
  G.Set_Initial_Conditions(P);
  chprintf("Initial conditions set.\n");
  // set main variables for Read_Grid inital conditions
  if (strcmp(P.init, "Read_Grid") == 0) {
    dti = C_cfl / G.H.dt;
    outtime += G.H.t;
    nfile = P.nfile*P.nfull;
  }

  #ifdef DE
  chprintf("\nUsing Dual Energy Formalism:\n eta_1: %0.3f   eta_2: %0.4f \n", DE_ETA_1, DE_ETA_2);
  char *message = (char*)malloc(50 * sizeof(char));
  sprintf(message, " eta_1: %0.3f   eta_2: %0.3f   ", DE_ETA_1, DE_ETA_2 );
  Write_Message_To_Log_File( message );
  #endif

  #ifdef CPU_TIME
  G.Timer.Initialize();
  #endif

  #ifdef GRAVITY
  G.Initialize_Gravity(&P);
  #endif

  #ifdef PARTICLES
  G.Initialize_Particles(&P);
  #endif

  #ifdef COSMOLOGY
  G.Initialize_Cosmology(&P);
  #endif

  #ifdef COOLING_GRACKLE
  G.Initialize_Grackle(&P);
  #endif

  #ifdef GRAVITY
  G.Compute_Gravitational_Potential( &P);
  #endif

  // set boundary conditions (assign appropriate values to ghost cells)
  chprintf("Setting boundary conditions...\n");
  G.Set_Boundary_Conditions_All(P);
  chprintf("Boundary conditions set.\n");

  #ifdef PARTICLES
  G.Get_Particles_Accelration();
  #endif

  chprintf("Dimensions of each cell: dx = %f dy = %f dz = %f\n", G.H.dx, G.H.dy, G.H.dz);
  chprintf("Ratio of specific heats gamma = %f\n",gama);
  chprintf("Nstep = %d  Timestep = %f  Simulation time = %f\n", G.H.n_step, G.H.dt, G.H.t);

  #ifdef OUTPUT
  if (strcmp(P.init, "Read_Grid") != 0 || G.H.Output_Now ) {
  // write the initial conditions to file
  chprintf("Writing initial conditions to file...\n");
  WriteData(G, P, nfile);
  }
  // add one to the output file count
  nfile++;
  #endif //OUTPUT
  // increment the next output time
  outtime += P.outstep;

  #ifdef CPU_TIME
  stop_init = get_time();
  init = stop_init - start_total;
  #ifdef MPI_CHOLLA
  init_min = ReduceRealMin(init);
  init_max = ReduceRealMax(init);
  init_avg = ReduceRealAvg(init);
  chprintf("Init  min: %9.4f  max: %9.4f  avg: %9.4f\n", init_min, init_max, init_avg);
  #else
  printf("Init %9.4f\n", init);
  #endif //MPI_CHOLLA
  #endif //CPU_TIME

  // Evolve the grid, one timestep at a time
  chprintf("Starting calculations.\n");
  while (G.H.t < P.tout)
  // while (G.H.n_step < 0)
  {
    chprintf("n_step: %d \n", G.H.n_step + 1 );
    // get the start time
    start_step = get_time();

    // calculate the timestep
    G.set_dt(dti);

    if (G.H.t + G.H.dt > outtime) G.H.dt = outtime - G.H.t;

    #ifdef PARTICLES
    //Advance the particles KDK( first step )
    G.Advance_Particles( 1 );
    //Transfer the particles boundaries
    G.Transfer_Particles_Boundaries(P);
    #endif

    // Advance the grid by one timestep
    dti = G.Update_Hydro_Grid();

    // update the simulation time ( t += dt )
    G.Update_Time();

    #ifdef GRAVITY
    //Compute Gravitational potential for next step
    G.Compute_Gravitational_Potential( &P);
    #endif

    // add one to the timestep count
    G.H.n_step++;

    // set boundary conditions for next time step
    G.Set_Boundary_Conditions_All(P);

    #ifdef PARTICLES
    //Advance the particles KDK( second step )
    G.Advance_Particles( 2 );
    #endif

    // Optional:Timestep using DKD for particles
    // #if defined( PARTICLES ) && defined( PARTICLES_DKD )
    // dti = G.Update_Grid_and_Particles_DKD(P);
    // #endif

    #ifdef CPU_TIME
    G.Timer.Print_Times();
    #endif

    // get the time to compute the total timestep
    stop_step = get_time();
    stop_total = get_time();
    G.H.t_wall = stop_total-start_total;
    #ifdef MPI_CHOLLA
    G.H.t_wall = ReduceRealMax(G.H.t_wall);
    #endif
    chprintf("n_step: %d   sim time: %10.7f   sim timestep: %7.4e  timestep time = %9.3f ms   total time = %9.4f s\n\n",
      G.H.n_step, G.H.t, G.H.dt, (stop_step-start_step)*1000, G.H.t_wall);

    #ifdef OUTPUT_ALWAYS
    G.H.Output_Now = true;
    #endif

    // if ( P.n_steps_output > 0 && G.H.n_step % P.n_steps_output == 0) G.H.Output_Now = true;

    if (G.H.t == outtime || G.H.Output_Now )
    {
      #ifdef OUTPUT
      /*output the grid data*/
      WriteData(G, P, nfile);
      // add one to the output file count
      nfile++;
      #endif //OUTPUT
      // update to the next output time
      outtime += P.outstep;
    }

    #ifdef CPU_TIME
    G.Timer.n_steps += 1;
    #endif

    #ifdef N_STEPS_LIMIT
    if ( G.H.n_step == N_STEPS_LIMIT) break;
    #endif

    #ifdef COSMOLOGY
    if ( G.Cosmo.current_a >= G.Cosmo.scale_outputs[G.Cosmo.n_outputs-1] ) {
      chprintf( "\nReached Last Cosmological Output: Ending Simulation\n");
      break;
    }
    #endif

  } /*end loop over timesteps*/

  #ifdef CPU_TIME
  G.Timer.Get_Average_Times();
  G.Timer.Print_Average_Times( P );
  #endif

  Write_Message_To_Log_File( "Run completed successfully!");

  // free the grid
  G.Reset();

  #ifdef MPI_CHOLLA
  MPI_Finalize();
  #endif /*MPI_CHOLLA*/

  return 0;

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: filtask.hxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 05:21:59 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/
#ifndef _FILTASK_HXX_
#define _FILTASK_HXX_
#endif

#include <hash_map>
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef  _COM_SUN_STAR_UCB_DUPLICATECOMMANDIDENTIFIEREXCEPTION_HPP_
#include <com/sun/star/ucb/DuplicateCommandIdentifierException.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCOMMANDENVIRONMENT_HPP_
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XPROGRESSHANDLER_HPP_
#include <com/sun/star/ucb/XProgressHandler.hpp>
#endif
#ifndef  _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_
#include <com/sun/star/task/XInteractionHandler.hpp>
#endif
#ifndef  _COM_SUN_STAR_TASK_XINTERACTIONREQUEST_HPP_
#include <com/sun/star/task/XInteractionRequest.hpp>
#endif
#ifndef _FILERROR_HXX_
#include "filerror.hxx"
#endif

namespace fileaccess
{
    class BaseContent;

    /*
     * This implementation is inherited by class fileaccess::shell.
     * The relevant methods in this class all have as first argument the CommandId,
     * so if necessary, every method has acess to its relevant XInteractionHandler and
     * XProgressHandler, simply by calling directly the method
     * getInteractionHandler( CommandId )
     * and
     * getProgressHandler();
     */

    class TaskManager
    {
    protected:

        class TaskHandling
        {
        private:

            bool m_bAbort,m_bHandled;
            sal_Int32 m_nErrorCode,m_nMinorCode;
            com::sun::star::uno::Reference< com::sun::star::task::XInteractionHandler > m_xInteractionHandler;
            com::sun::star::uno::Reference< com::sun::star::ucb::XProgressHandler >     m_xProgressHandler;
            com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment >  m_xCommandEnvironment;

        public:

            TaskHandling(
                const com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment >&  xCommandEnv
                = com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment >( 0 ) )
                : m_bAbort( false ),
                  m_bHandled( false ),
                  m_nErrorCode( TASKHANDLER_NO_ERROR ),
                  m_nMinorCode( TASKHANDLER_NO_ERROR ),
                  m_xInteractionHandler( 0 ),
                  m_xProgressHandler( 0 ),
                  m_xCommandEnvironment( xCommandEnv )
            {
            }

            void SAL_CALL abort()
            {
                m_bAbort = true;
            }

            bool SAL_CALL isAborted()
            {
                return m_bAbort;
            }

            void setHandled()
            {
                m_bHandled = true;
            }

            bool isHandled()
            {
                return true;
            }

            void clearError()
            {
                m_nErrorCode = TASKHANDLER_NO_ERROR;
                m_nMinorCode =  TASKHANDLER_NO_ERROR;
            }

            void SAL_CALL installError( sal_Int32 nErrorCode,
                                        sal_Int32 nMinorCode = TASKHANDLER_NO_ERROR )
            {
                m_nErrorCode = nErrorCode;
                m_nMinorCode = nMinorCode;
            }

            sal_Int32 SAL_CALL getInstalledError()
            {
                return m_nErrorCode;
            }

            sal_Int32 SAL_CALL getMinorErrorCode()
            {
                return m_nMinorCode;
            }

            com::sun::star::uno::Reference< com::sun::star::ucb::XProgressHandler > SAL_CALL
            getProgressHandler()
            {
                if( ! m_xProgressHandler.is() && m_xCommandEnvironment.is() )
                    m_xProgressHandler = m_xCommandEnvironment->getProgressHandler();

                return m_xProgressHandler;
            }

            com::sun::star::uno::Reference< com::sun::star::task::XInteractionHandler > SAL_CALL
            getInteractionHandler()
            {
                if( ! m_xInteractionHandler.is() && m_xCommandEnvironment.is() )
                    m_xInteractionHandler = m_xCommandEnvironment->getInteractionHandler();

                return m_xInteractionHandler;
            }

            com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment > SAL_CALL
            getCommandEnvironment()
            {
                return m_xCommandEnvironment;
            }

        };  // end class TaskHandling

        typedef std::hash_map< sal_Int32,TaskHandling,std::hash< sal_Int32 > > TaskMap;

    private:

        vos::OMutex                                                         m_aMutex;
        sal_Int32                                                           m_nCommandId;
        TaskMap                                                             m_aTaskMap;

    public:

        TaskManager();
        virtual ~TaskManager();

        void SAL_CALL startTask(
            sal_Int32 CommandId,
            const com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment >&  xCommandEnv )
            throw( com::sun::star::ucb::DuplicateCommandIdentifierException );

        sal_Int32 SAL_CALL getCommandId( void );
        void SAL_CALL abort( sal_Int32 CommandId );
        bool SAL_CALL isAborted( sal_Int32 CommandId );

        /**
         *  The error code may be one of the error codes defined in
         *  filerror.hxx.
         *  The minor code refines the information given in ErrorCode.
         */

        void SAL_CALL clearError();

        void SAL_CALL installError( sal_Int32 CommandId,
                                    sal_Int32 ErrorCode,
                                    sal_Int32 minorCode = TASKHANDLER_NO_ERROR );

//          void SAL_CALL installError( sal_Int32 CommandId,
//                                      sal_Int32 ErrorCode,
//                                      rtl::OUString message );

//          void SAL_CALL installError( sal_Int32 CommandId,
//                                      sal_Int32 ErrorCode,
//                                      rtl::OUString message );

        void SAL_CALL retrieveError( sal_Int32 CommandId,
                                     sal_Int32 &ErrorCode,
                                     sal_Int32 &minorCode);

        /**
         *  Deinstalls the task and evaluates a possibly set error code.
         *  "endTask" throws in case an error code is set the corresponding exception.
         */

        void SAL_CALL endTask( sal_Int32 CommandId,
                               // the physical URL of the object
                               const rtl::OUString& aUnqPath,
                               BaseContent* pContent);

        /**
         *  Handles an interactionrequest
         */

        void SAL_CALL handleTask( sal_Int32 CommandId,
                                  const com::sun::star::uno::Reference< com::sun::star::task::XInteractionRequest >& request );

        /**
         *  Clears any error which are set on the commandid
         */

        void SAL_CALL clearError( sal_Int32 );

        com::sun::star::uno::Reference< com::sun::star::task::XInteractionHandler > SAL_CALL
        getInteractionHandler( sal_Int32 CommandId );

        com::sun::star::uno::Reference< com::sun::star::ucb::XProgressHandler > SAL_CALL
        getProgressHandler( sal_Int32 CommandId );

        com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment > SAL_CALL
        getCommandEnvironment( sal_Int32 CommandId );

    };

} // end namespace TaskHandling
<commit_msg>INTEGRATION: CWS bgdlremove (1.14.62); FILE MERGED 2007/05/11 10:07:45 kso 1.14.62.1: #i76911# - no longer uses VOS.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: filtask.hxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: ihi $ $Date: 2007-06-05 17:56:54 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/
#ifndef _FILTASK_HXX_
#define _FILTASK_HXX_
#endif

#include <hash_map>
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#include "osl/mutex.hxx"

#ifndef  _COM_SUN_STAR_UCB_DUPLICATECOMMANDIDENTIFIEREXCEPTION_HPP_
#include <com/sun/star/ucb/DuplicateCommandIdentifierException.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCOMMANDENVIRONMENT_HPP_
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XPROGRESSHANDLER_HPP_
#include <com/sun/star/ucb/XProgressHandler.hpp>
#endif
#ifndef  _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_
#include <com/sun/star/task/XInteractionHandler.hpp>
#endif
#ifndef  _COM_SUN_STAR_TASK_XINTERACTIONREQUEST_HPP_
#include <com/sun/star/task/XInteractionRequest.hpp>
#endif
#ifndef _FILERROR_HXX_
#include "filerror.hxx"
#endif

namespace fileaccess
{
    class BaseContent;

    /*
     * This implementation is inherited by class fileaccess::shell.
     * The relevant methods in this class all have as first argument the CommandId,
     * so if necessary, every method has acess to its relevant XInteractionHandler and
     * XProgressHandler, simply by calling directly the method
     * getInteractionHandler( CommandId )
     * and
     * getProgressHandler();
     */

    class TaskManager
    {
    protected:

        class TaskHandling
        {
        private:

            bool m_bAbort,m_bHandled;
            sal_Int32 m_nErrorCode,m_nMinorCode;
            com::sun::star::uno::Reference< com::sun::star::task::XInteractionHandler > m_xInteractionHandler;
            com::sun::star::uno::Reference< com::sun::star::ucb::XProgressHandler >     m_xProgressHandler;
            com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment >  m_xCommandEnvironment;

        public:

            TaskHandling(
                const com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment >&  xCommandEnv
                = com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment >( 0 ) )
                : m_bAbort( false ),
                  m_bHandled( false ),
                  m_nErrorCode( TASKHANDLER_NO_ERROR ),
                  m_nMinorCode( TASKHANDLER_NO_ERROR ),
                  m_xInteractionHandler( 0 ),
                  m_xProgressHandler( 0 ),
                  m_xCommandEnvironment( xCommandEnv )
            {
            }

            void SAL_CALL abort()
            {
                m_bAbort = true;
            }

            bool SAL_CALL isAborted()
            {
                return m_bAbort;
            }

            void setHandled()
            {
                m_bHandled = true;
            }

            bool isHandled()
            {
                return true;
            }

            void clearError()
            {
                m_nErrorCode = TASKHANDLER_NO_ERROR;
                m_nMinorCode =  TASKHANDLER_NO_ERROR;
            }

            void SAL_CALL installError( sal_Int32 nErrorCode,
                                        sal_Int32 nMinorCode = TASKHANDLER_NO_ERROR )
            {
                m_nErrorCode = nErrorCode;
                m_nMinorCode = nMinorCode;
            }

            sal_Int32 SAL_CALL getInstalledError()
            {
                return m_nErrorCode;
            }

            sal_Int32 SAL_CALL getMinorErrorCode()
            {
                return m_nMinorCode;
            }

            com::sun::star::uno::Reference< com::sun::star::ucb::XProgressHandler > SAL_CALL
            getProgressHandler()
            {
                if( ! m_xProgressHandler.is() && m_xCommandEnvironment.is() )
                    m_xProgressHandler = m_xCommandEnvironment->getProgressHandler();

                return m_xProgressHandler;
            }

            com::sun::star::uno::Reference< com::sun::star::task::XInteractionHandler > SAL_CALL
            getInteractionHandler()
            {
                if( ! m_xInteractionHandler.is() && m_xCommandEnvironment.is() )
                    m_xInteractionHandler = m_xCommandEnvironment->getInteractionHandler();

                return m_xInteractionHandler;
            }

            com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment > SAL_CALL
            getCommandEnvironment()
            {
                return m_xCommandEnvironment;
            }

        };  // end class TaskHandling

        typedef std::hash_map< sal_Int32,TaskHandling,std::hash< sal_Int32 > > TaskMap;

    private:

        osl::Mutex                                                         m_aMutex;
        sal_Int32                                                           m_nCommandId;
        TaskMap                                                             m_aTaskMap;

    public:

        TaskManager();
        virtual ~TaskManager();

        void SAL_CALL startTask(
            sal_Int32 CommandId,
            const com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment >&  xCommandEnv )
            throw( com::sun::star::ucb::DuplicateCommandIdentifierException );

        sal_Int32 SAL_CALL getCommandId( void );
        void SAL_CALL abort( sal_Int32 CommandId );
        bool SAL_CALL isAborted( sal_Int32 CommandId );

        /**
         *  The error code may be one of the error codes defined in
         *  filerror.hxx.
         *  The minor code refines the information given in ErrorCode.
         */

        void SAL_CALL clearError();

        void SAL_CALL installError( sal_Int32 CommandId,
                                    sal_Int32 ErrorCode,
                                    sal_Int32 minorCode = TASKHANDLER_NO_ERROR );

//          void SAL_CALL installError( sal_Int32 CommandId,
//                                      sal_Int32 ErrorCode,
//                                      rtl::OUString message );

//          void SAL_CALL installError( sal_Int32 CommandId,
//                                      sal_Int32 ErrorCode,
//                                      rtl::OUString message );

        void SAL_CALL retrieveError( sal_Int32 CommandId,
                                     sal_Int32 &ErrorCode,
                                     sal_Int32 &minorCode);

        /**
         *  Deinstalls the task and evaluates a possibly set error code.
         *  "endTask" throws in case an error code is set the corresponding exception.
         */

        void SAL_CALL endTask( sal_Int32 CommandId,
                               // the physical URL of the object
                               const rtl::OUString& aUnqPath,
                               BaseContent* pContent);

        /**
         *  Handles an interactionrequest
         */

        void SAL_CALL handleTask( sal_Int32 CommandId,
                                  const com::sun::star::uno::Reference< com::sun::star::task::XInteractionRequest >& request );

        /**
         *  Clears any error which are set on the commandid
         */

        void SAL_CALL clearError( sal_Int32 );

        com::sun::star::uno::Reference< com::sun::star::task::XInteractionHandler > SAL_CALL
        getInteractionHandler( sal_Int32 CommandId );

        com::sun::star::uno::Reference< com::sun::star::ucb::XProgressHandler > SAL_CALL
        getProgressHandler( sal_Int32 CommandId );

        com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment > SAL_CALL
        getCommandEnvironment( sal_Int32 CommandId );

    };

} // end namespace TaskHandling
<|endoftext|>