<commit_before>#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>
#include <string>
#include <iomanip>
#include <memory>

#include <sys/ioctl.h>
#include <linux/serial.h>

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/asio/steady_timer.hpp>

void sendTest(const boost::system::error_code &ec);

static const uint32_t DEFAULT_BAUD_RATE = 115200;
static const auto DEFAULT_FLOW_CONTROL = boost::asio::serial_port_base::flow_control::none;
static const auto DEFAULT_STOP_BITS = boost::asio::serial_port_base::stop_bits::one;
static const auto DEFAULT_PARITY = boost::asio::serial_port_base::parity::even;

static boost::asio::io_service io_service;
static boost::asio::steady_timer timer(io_service);

struct TestData {
  std::size_t send_size = 0;
  std::size_t rec_size = 0;
  std::vector<uint8_t> send_data;
  std::vector<uint8_t> rec_data;
};

typedef std::shared_ptr<TestData> TestDataPtr;

class Port {

public:
  Port(boost::asio::io_service &io_service, const std::string & device) :
      serial_port_(io_service, device) {

    boost::asio::serial_port_base::baud_rate br(DEFAULT_BAUD_RATE);
    boost::asio::serial_port_base::flow_control fc(DEFAULT_FLOW_CONTROL);
    boost::asio::serial_port_base::stop_bits sb(DEFAULT_STOP_BITS);
    boost::asio::serial_port_base::parity p(DEFAULT_PARITY);

    serial_port_.set_option(br);
    serial_port_.set_option(fc);
    serial_port_.set_option(sb);
    serial_port_.set_option(p);

    auto nativeHandler = serial_port_.lowest_layer().native_handle();

    serial_rs485 rs485conf;

    rs485conf.flags = (!SER_RS485_ENABLED) | (!SER_RS485_RTS_ON_SEND);

    rs485conf.delay_rts_before_send = 0;
    rs485conf.delay_rts_after_send = 0;

    // set rs485 settings on given tty
    if (ioctl(nativeHandler, TIOCSRS485, &rs485conf) < 0) {
      std::cout << "SerialPort ioctl()  ERROR" << std::endl;
    }

  }

  void echo() {
    std::cout << "echo()" << std::endl;
    std::shared_ptr<std::vector<uint8_t> > buffer = std::make_shared<std::vector<uint8_t> >(1);

    serial_port_.async_read_some(boost::asio::buffer(*buffer, buffer->size()),
        boost::bind(&Port::handler_echo_read, this, buffer, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
  }

  void send_test(const std::vector<uint8_t>& pattern) {

    TestDataPtr data = std::make_shared<TestData>();
    data->send_data = std::vector<uint8_t>(pattern);

    serial_port_.async_write_some(boost::asio::buffer(data->send_data, data->send_data.size()),
        boost::bind(&Port::handler_send_test, this, data, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));

  }
  /*

  void send_test_pattern(const std::vector<uint8_t>& pattern) {

    serial_port_.async_write_some(boost::asio::buffer(pattern, pattern.size()),
        boost::bind(&Port::handler_send_test_pattern, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));

  }

  void handler_send_test_pattern(const boost::system::error_code &ec, const std::size_t bytes_recived) {
    if (!ec) {
      std::cout << "handler_send_test_pattern send" << std::to_string(bytes_recived) << std::endl;
      std::chrono::milliseconds dura(500);
      std::this_thread::sleep_for(dura);

      send_test_pattern (test_pattern);

    } else {
      std::cout << "handler_send_test_pattern() " << ec.message() << std::endl;
    }

  }

  void rec_test_pattern(const std::vector<uint8_t>& pattern) {

  }
  */

private:

  void handler_echo_read(std::shared_ptr<std::vector<uint8_t> > buffer, const boost::system::error_code &ec, const std::size_t bytes_recived) {
    if (!ec) {
      std::cout << "handler_echo_read() msg:" << ec.message() << "\t bytes_read " << std::to_string(bytes_recived) << "\t";
      for (int i = 0; i < bytes_recived; i++) {
        int value = (int) (*buffer)[i];
        std::cout << " " << std::hex << std::setfill('0') << std::setw(2) << value;
      }
      std::cout << std::endl;

      serial_port_.async_write_some(boost::asio::buffer(*buffer, bytes_recived),
          boost::bind(&Port::handler_echo_write, this, buffer, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));

    }

    else {
      std::cout << "handler_echo_read() " << ec.message() << std::endl;
    }
  }

  void handler_echo_write(std::shared_ptr<std::vector<uint8_t> > buffer, const boost::system::error_code &ec, const std::size_t bytes_transferd) {

    if (!ec) {

      //buffer.reset();
      //buffer = std::make_shared < std::vector<uint8_t> > (BUFFER_SIZE);
      std::cout << "handler_echo_write() \t written " << std::to_string(bytes_transferd) << std::endl;

      serial_port_.async_read_some(boost::asio::buffer(*buffer, buffer->size()),
          boost::bind(&Port::handler_echo_read, this, buffer, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
    } else {
      std::cout << "handler_echo_write() " << ec.message() << std::endl;
    }

  }

  void handler_send_test(TestDataPtr testData, const boost::system::error_code &ec, const std::size_t bytes_transferd) {
    if (!ec) {
      testData->send_size = bytes_transferd;
      std::cout << "handler_send_test(): bytes_send: \t" << std::to_string(bytes_transferd) << std::endl;

      global_read_buffer = std::vector<uint8_t>(bytes_transferd);

      ///*
      serial_port_.async_read_some(boost::asio::buffer(global_read_buffer, bytes_transferd),
          boost::bind(&Port::handler_read_all, this, testData, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
      //  */

      /*
       boost::asio::async_read(serial_port_, boost::asio::buffer(*receive_buffer, bytes_transferd),
       boost::bind(&Port::handler_receive_test, this, send_buffer, bytes_transferd, receive_buffer, boost::asio::placeholders::error,
       boost::asio::placeholders::bytes_transferred));
       // */
    }
  }

  void handler_read_all(TestDataPtr testData, const boost::system::error_code &ec, const std::size_t bytes_recived) {

    if (!ec) {
      std::cout << "handler_read_all(): bytes_recived: \t" << std::to_string(bytes_recived) << std::endl;
      testData->rec_size += bytes_recived;

      for (int i = 0; i < bytes_recived; i++) {
        testData->rec_data.push_back(global_read_buffer[i]);
      }

      if (testData->send_size > testData->rec_size) {
        std::size_t missing = testData->send_size - testData->rec_size;

        global_read_buffer = std::vector<uint8_t>(missing);
        serial_port_.async_read_some(boost::asio::buffer(global_read_buffer, missing),
            boost::bind(&Port::handler_read_all, this, testData, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));

      } else {
        handler_receive_test(testData);
      }

    } else {
      std::cout << "handler_read_all() " << ec.message() << std::endl;
    }

  }

  void handler_receive_test(TestDataPtr testData) {

    std::cout << "handler_receive_test()" << std::endl;
    bool error = false;

    if (testData->send_size != testData->rec_size) {

      std::cout << "snd: \t" << std::to_string(testData->send_size) << std::endl;
      std::cout << "rec: \t" << std::to_string(testData->rec_size) << std::endl;

    }

    for (int i = 0; i < testData->send_size; i++) {
      uint8_t sendByte = testData->send_data[i];
      uint8_t recivedByte = testData->rec_data[i];

      if (sendByte != recivedByte || error) {
        error = true;
        std::cout << "snd: " << std::hex << std::setfill('0') << std::setw(2) << (int) sendByte;
        std::cout << "\trec: " << std::hex << std::setfill('0') << std::setw(2) << (int) recivedByte;
        std::cout << std::endl;
      } else {

      }
    }
    if (!error) {
      std::cout << "OK ";
      std::cout << "snd: " << std::to_string(testData->send_size);
      std::cout << "\t rec: " << std::to_string(testData->rec_size) << std::endl;
      std::cout << std::endl;

    } else {
      std::cout << "ERROR ";
      std::cout << "snd: " << std::to_string(testData->send_size);
      std::cout << "\t rec: " << std::to_string(testData->rec_size) << std::endl;
      std::cout << std::endl;
    }

    timer.expires_from_now(std::chrono::milliseconds(50));
    timer.async_wait(sendTest);

  }

  boost::asio::serial_port serial_port_;

  std::vector<uint8_t> global_read_buffer;

};
static std::vector<uint8_t> basic_pattern;      //6 bytes
static std::vector<uint8_t> test_pattern;
static Port* port;

void sendTest(const boost::system::error_code &ec) {

  //apennd new testpatterm
  for (int i = 0; i < 7; i++) {
    int8_t v = test_pattern[test_pattern.size() - 1];
    test_pattern.push_back((v - 1));
  }

  //test_pattern.insert(test_pattern.end(), basic_pattern.begin(), basic_pattern.end());

  //if to long reset to basic size
  if (test_pattern.size() > 250) {
    test_pattern = basic_pattern;
  }

  if (!ec && port != 0) {
    port->send_test(test_pattern);

  } else {
    std::cout << "sendTest() " << ec.message() << std::endl;
  }

}

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

  if (std::strcmp(argv[1], "echo") == 0) {

    std::string port_name_a(argv[2]);
    port = new Port(io_service, port_name_a);

    port->echo();

  }
  /*
  else if (std::strcmp(argv[1], "send") == 0) {

    std::string port_name_a(argv[2]);
    port = new Port(io_service, port_name_a);

    test_pattern.push_back(0xFF);
    for (int i = 0; i < 64; i++) {
      int8_t v = test_pattern[test_pattern.size() - 1];
      test_pattern.push_back((v - 1));
    }

    port->send_test_pattern(test_pattern);

  } else if (std::strcmp(argv[1], "rec") == 0) {

    std::string port_name_a(argv[2]);
    port = new Port(io_service, port_name_a);

    test_pattern.push_back(0xFF);
    for (int i = 0; i < 64; i++) {
      int8_t v = test_pattern[test_pattern.size() - 1];
      test_pattern.push_back((v - 1));
    }

    port->rec_test_pattern(test_pattern);

  }
  // */
  else {
    std::string port_name_a(argv[1]);
    port = new Port(io_service, port_name_a);

    basic_pattern.push_back(0xFF);
    basic_pattern.push_back(0xFE);
    basic_pattern.push_back(0xFD);
    basic_pattern.push_back(0xFC);
    basic_pattern.push_back(0xFB);
    basic_pattern.push_back(0xFA);
    basic_pattern.push_back(0xF9);

    test_pattern.insert(test_pattern.end(), basic_pattern.begin(), basic_pattern.end());

    std::cout << "send_test()" << std::endl;
    std::cout << std::endl;
    for (auto i : (test_pattern)) {
      std::cout << " " << std::hex << std::setfill('0') << std::setw(2) << (int) i;
    }
    std::cout << std::endl;

    timer.expires_from_now(std::chrono::seconds(1));
    timer.async_wait(sendTest);

  }
  io_service.run();

  return 0;
}
<commit_msg>FETAURE: set timing to 10ms<commit_after>#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>
#include <string>
#include <iomanip>
#include <memory>

#include <sys/ioctl.h>
#include <linux/serial.h>

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/asio/steady_timer.hpp>

void sendTest(const boost::system::error_code &ec);

static const uint32_t DEFAULT_BAUD_RATE = 115200;
static const auto DEFAULT_FLOW_CONTROL = boost::asio::serial_port_base::flow_control::none;
static const auto DEFAULT_STOP_BITS = boost::asio::serial_port_base::stop_bits::one;
static const auto DEFAULT_PARITY = boost::asio::serial_port_base::parity::even;

static boost::asio::io_service io_service;
static boost::asio::steady_timer timer(io_service);

struct TestData {
  std::size_t send_size = 0;
  std::size_t rec_size = 0;
  std::vector<uint8_t> send_data;
  std::vector<uint8_t> rec_data;
};

typedef std::shared_ptr<TestData> TestDataPtr;

class Port {

public:
  Port(boost::asio::io_service &io_service, const std::string & device) :
      serial_port_(io_service, device) {

    boost::asio::serial_port_base::baud_rate br(DEFAULT_BAUD_RATE);
    boost::asio::serial_port_base::flow_control fc(DEFAULT_FLOW_CONTROL);
    boost::asio::serial_port_base::stop_bits sb(DEFAULT_STOP_BITS);
    boost::asio::serial_port_base::parity p(DEFAULT_PARITY);

    serial_port_.set_option(br);
    serial_port_.set_option(fc);
    serial_port_.set_option(sb);
    serial_port_.set_option(p);

    auto nativeHandler = serial_port_.lowest_layer().native_handle();

    serial_rs485 rs485conf;

    rs485conf.flags = (!SER_RS485_ENABLED) | (!SER_RS485_RTS_ON_SEND);

    rs485conf.delay_rts_before_send = 0;
    rs485conf.delay_rts_after_send = 0;

    // set rs485 settings on given tty
    if (ioctl(nativeHandler, TIOCSRS485, &rs485conf) < 0) {
      std::cout << "SerialPort ioctl()  ERROR" << std::endl;
    }

  }

  void echo() {
    std::cout << "echo()" << std::endl;
    std::shared_ptr<std::vector<uint8_t> > buffer = std::make_shared<std::vector<uint8_t> >(1);

    serial_port_.async_read_some(boost::asio::buffer(*buffer, buffer->size()),
        boost::bind(&Port::handler_echo_read, this, buffer, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
  }

  void send_test(const std::vector<uint8_t>& pattern) {

    TestDataPtr data = std::make_shared<TestData>();
    data->send_data = std::vector<uint8_t>(pattern);

    serial_port_.async_write_some(boost::asio::buffer(data->send_data, data->send_data.size()),
        boost::bind(&Port::handler_send_test, this, data, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));

  }
  /*

  void send_test_pattern(const std::vector<uint8_t>& pattern) {

    serial_port_.async_write_some(boost::asio::buffer(pattern, pattern.size()),
        boost::bind(&Port::handler_send_test_pattern, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));

  }

  void handler_send_test_pattern(const boost::system::error_code &ec, const std::size_t bytes_recived) {
    if (!ec) {
      std::cout << "handler_send_test_pattern send" << std::to_string(bytes_recived) << std::endl;
      std::chrono::milliseconds dura(500);
      std::this_thread::sleep_for(dura);

      send_test_pattern (test_pattern);

    } else {
      std::cout << "handler_send_test_pattern() " << ec.message() << std::endl;
    }

  }

  void rec_test_pattern(const std::vector<uint8_t>& pattern) {

  }
  */

private:

  void handler_echo_read(std::shared_ptr<std::vector<uint8_t> > buffer, const boost::system::error_code &ec, const std::size_t bytes_recived) {
    if (!ec) {
      std::cout << "handler_echo_read() msg:" << ec.message() << "\t bytes_read " << std::to_string(bytes_recived) << "\t";
      for (int i = 0; i < bytes_recived; i++) {
        int value = (int) (*buffer)[i];
        std::cout << " " << std::hex << std::setfill('0') << std::setw(2) << value;
      }
      std::cout << std::endl;

      serial_port_.async_write_some(boost::asio::buffer(*buffer, bytes_recived),
          boost::bind(&Port::handler_echo_write, this, buffer, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));

    }

    else {
      std::cout << "handler_echo_read() " << ec.message() << std::endl;
    }
  }

  void handler_echo_write(std::shared_ptr<std::vector<uint8_t> > buffer, const boost::system::error_code &ec, const std::size_t bytes_transferd) {

    if (!ec) {

      //buffer.reset();
      //buffer = std::make_shared < std::vector<uint8_t> > (BUFFER_SIZE);
      std::cout << "handler_echo_write() \t written " << std::to_string(bytes_transferd) << std::endl;

      serial_port_.async_read_some(boost::asio::buffer(*buffer, buffer->size()),
          boost::bind(&Port::handler_echo_read, this, buffer, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
    } else {
      std::cout << "handler_echo_write() " << ec.message() << std::endl;
    }

  }

  void handler_send_test(TestDataPtr testData, const boost::system::error_code &ec, const std::size_t bytes_transferd) {
    if (!ec) {
      testData->send_size = bytes_transferd;
      std::cout << "handler_send_test(): bytes_send: \t" << std::to_string(bytes_transferd) << std::endl;

      global_read_buffer = std::vector<uint8_t>(bytes_transferd);

      ///*
      serial_port_.async_read_some(boost::asio::buffer(global_read_buffer, bytes_transferd),
          boost::bind(&Port::handler_read_all, this, testData, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
      //  */

      /*
       boost::asio::async_read(serial_port_, boost::asio::buffer(*receive_buffer, bytes_transferd),
       boost::bind(&Port::handler_receive_test, this, send_buffer, bytes_transferd, receive_buffer, boost::asio::placeholders::error,
       boost::asio::placeholders::bytes_transferred));
       // */
    }
  }

  void handler_read_all(TestDataPtr testData, const boost::system::error_code &ec, const std::size_t bytes_recived) {

    if (!ec) {
      std::cout << "handler_read_all(): bytes_recived: \t" << std::to_string(bytes_recived) << std::endl;
      testData->rec_size += bytes_recived;

      for (int i = 0; i < bytes_recived; i++) {
        testData->rec_data.push_back(global_read_buffer[i]);
      }

      if (testData->send_size > testData->rec_size) {
        std::size_t missing = testData->send_size - testData->rec_size;

        global_read_buffer = std::vector<uint8_t>(missing);
        serial_port_.async_read_some(boost::asio::buffer(global_read_buffer, missing),
            boost::bind(&Port::handler_read_all, this, testData, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));

      } else {
        handler_receive_test(testData);
      }

    } else {
      std::cout << "handler_read_all() " << ec.message() << std::endl;
    }

  }

  void handler_receive_test(TestDataPtr testData) {

    std::cout << "handler_receive_test()" << std::endl;
    bool error = false;

    if (testData->send_size != testData->rec_size) {

      std::cout << "snd: \t" << std::to_string(testData->send_size) << std::endl;
      std::cout << "rec: \t" << std::to_string(testData->rec_size) << std::endl;

    }

    for (int i = 0; i < testData->send_size; i++) {
      uint8_t sendByte = testData->send_data[i];
      uint8_t recivedByte = testData->rec_data[i];

      if (sendByte != recivedByte || error) {
        error = true;
        std::cout << "snd: " << std::hex << std::setfill('0') << std::setw(2) << (int) sendByte;
        std::cout << "\trec: " << std::hex << std::setfill('0') << std::setw(2) << (int) recivedByte;
        std::cout << std::endl;
      } else {

      }
    }
    if (!error) {
      std::cout << "OK ";
      std::cout << "snd: " << std::to_string(testData->send_size);
      std::cout << "\t rec: " << std::to_string(testData->rec_size) << std::endl;
      std::cout << std::endl;

    } else {
      std::cout << "ERROR ";
      std::cout << "snd: " << std::to_string(testData->send_size);
      std::cout << "\t rec: " << std::to_string(testData->rec_size) << std::endl;
      std::cout << std::endl;
    }

    timer.expires_from_now(std::chrono::milliseconds(10));
    timer.async_wait(sendTest);

  }

  boost::asio::serial_port serial_port_;

  std::vector<uint8_t> global_read_buffer;

};
static std::vector<uint8_t> basic_pattern;      //6 bytes
static std::vector<uint8_t> test_pattern;
static Port* port;

void sendTest(const boost::system::error_code &ec) {

  //apennd new testpatterm
  for (int i = 0; i < 7; i++) {
    int8_t v = test_pattern[test_pattern.size() - 1];
    test_pattern.push_back((v - 1));
  }

  //test_pattern.insert(test_pattern.end(), basic_pattern.begin(), basic_pattern.end());

  //if to long reset to basic size
  if (test_pattern.size() > 250) {
    test_pattern = basic_pattern;
  }

  if (!ec && port != 0) {
    port->send_test(test_pattern);

  } else {
    std::cout << "sendTest() " << ec.message() << std::endl;
  }

}

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

  if (std::strcmp(argv[1], "echo") == 0) {

    std::string port_name_a(argv[2]);
    port = new Port(io_service, port_name_a);

    port->echo();

  }
  /*
  else if (std::strcmp(argv[1], "send") == 0) {

    std::string port_name_a(argv[2]);
    port = new Port(io_service, port_name_a);

    test_pattern.push_back(0xFF);
    for (int i = 0; i < 64; i++) {
      int8_t v = test_pattern[test_pattern.size() - 1];
      test_pattern.push_back((v - 1));
    }

    port->send_test_pattern(test_pattern);

  } else if (std::strcmp(argv[1], "rec") == 0) {

    std::string port_name_a(argv[2]);
    port = new Port(io_service, port_name_a);

    test_pattern.push_back(0xFF);
    for (int i = 0; i < 64; i++) {
      int8_t v = test_pattern[test_pattern.size() - 1];
      test_pattern.push_back((v - 1));
    }

    port->rec_test_pattern(test_pattern);

  }
  // */
  else {
    std::string port_name_a(argv[1]);
    port = new Port(io_service, port_name_a);

    basic_pattern.push_back(0xFF);
    basic_pattern.push_back(0xFE);
    basic_pattern.push_back(0xFD);
    basic_pattern.push_back(0xFC);
    basic_pattern.push_back(0xFB);
    basic_pattern.push_back(0xFA);
    basic_pattern.push_back(0xF9);

    test_pattern.insert(test_pattern.end(), basic_pattern.begin(), basic_pattern.end());

    std::cout << "send_test()" << std::endl;
    std::cout << std::endl;
    for (auto i : (test_pattern)) {
      std::cout << " " << std::hex << std::setfill('0') << std::setw(2) << (int) i;
    }
    std::cout << std::endl;

    timer.expires_from_now(std::chrono::seconds(1));
    timer.async_wait(sendTest);

  }
  io_service.run();

  return 0;
}
<|endoftext|>


<commit_before>/*****************************************************************************
 *   GATB : Genome Assembly Tool Box
 *   Copyright (C) 2014  INRIA
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/

// We include the header file for the tool
#include <kmerinshort.hpp>

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

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

	if(argc==2 &&  strcmp(argv[1],"--version")==0  ||  strcmp(argv[1],"-v")==0 ){
		printf("KmerInShort version 1.0.1\n");
		return EXIT_SUCCESS;
	}

    try
    {
        // We run the tool with the provided command line arguments.
        kis().run (argc, argv);
    }
    catch (Exception& e)
    {
        std::cout << "EXCEPTION: " << e.getMessage() << std::endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

<commit_msg>Update main.cpp<commit_after>/*****************************************************************************
 *   GATB : Genome Assembly Tool Box
 *   Copyright (C) 2014  INRIA
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/

// We include the header file for the tool
#include <kmerinshort.hpp>

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

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

	if(argc==2 &&  (strcmp(argv[1],"--version")==0  ||  strcmp(argv[1],"-v")==0) ){
		printf("KmerInShort version 1.0.1\n");
		return EXIT_SUCCESS;
	}

    try
    {
        // We run the tool with the provided command line arguments.
        kis().run (argc, argv);
    }
    catch (Exception& e)
    {
        std::cout << "EXCEPTION: " << e.getMessage() << std::endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>#ifndef ORIGEN_SITE_HPP_
#define ORIGEN_SITE_HPP_

#include <string>
using namespace std;

namespace Origen {

class Site {
  string _lotid;
  bool lotidSet;
  int _wafer;
  bool waferSet;
  int _x;
  bool xSet;
  int _y;
  bool ySet;
  int _number;
  int _bin;
  int _softbin;
  bool binSet;
  bool softbinSet;

 public:
  Site(int);
  virtual ~Site();
  string lotid();
  uint64_t lotidInt();
  void lotid(string);
  void lotid(uint64_t);
  int wafer();
  void wafer(int);
  int x();
  void x(int);
  int y();
  void y(int);
  int bin();
  void bin(int);
  void bin(int, bool);
  int softbin();
  void softbin(int);
  void softbin(int, bool);

  /// Returns the site number associated with the given site object
  int number() { return _number; }
};

} /* namespace Origen */
#endif
<commit_msg>Added support for RHEL7 compile.<commit_after>#ifndef ORIGEN_SITE_HPP_
#define ORIGEN_SITE_HPP_

#include <string>
#include <inttypes.h>
using namespace std;

namespace Origen {

class Site {
  string _lotid;
  bool lotidSet;
  int _wafer;
  bool waferSet;
  int _x;
  bool xSet;
  int _y;
  bool ySet;
  int _number;
  int _bin;
  int _softbin;
  bool binSet;
  bool softbinSet;

 public:
  Site(int);
  virtual ~Site();
  string lotid();
  uint64_t lotidInt();
  void lotid(string);
  void lotid(uint64_t);
  int wafer();
  void wafer(int);
  int x();
  void x(int);
  int y();
  void y(int);
  int bin();
  void bin(int);
  void bin(int, bool);
  int softbin();
  void softbin(int);
  void softbin(int, bool);

  /// Returns the site number associated with the given site object
  int number() { return _number; }
};

} /* namespace Origen */
#endif
<|endoftext|>


<commit_before>//=======================================================================
// Copyright 2014-2015 David Simmons-Duffin.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include "SDP_Solver_Parameters.hxx"

#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>

namespace po = boost::program_options;

int solve(const std::vector<boost::filesystem::path> &sdp_files,
          const boost::filesystem::path &out_file,
          const boost::filesystem::path &checkpoint_file_in,
          const boost::filesystem::path &checkpoint_file_out,
          SDP_Solver_Parameters parameters);

int main(int argc, char **argv)
{
  std::vector<boost::filesystem::path> sdp_files;
  boost::filesystem::path out_file;
  boost::filesystem::path checkpoint_file_in;
  boost::filesystem::path checkpoint_file_out;
  boost::filesystem::path param_file;

  SDP_Solver_Parameters parameters;

  po::options_description basicOptions("Basic options");
  basicOptions.add_options()("help,h", "Show this helpful message.")(
  "sdpFile,s",
  po::value<std::vector<boost::filesystem::path>>(&sdp_files)->required(),
  "SDP data file(s) in XML format. Use this option repeatedly to specify "
  "multiple data files.")(
  "paramFile,p", po::value<boost::filesystem::path>(&param_file),
  "Any parameter can optionally be set via this file in key=value "
  "format. Command line arguments override values in the parameter "
  "file.")("outFile,o", po::value<boost::filesystem::path>(&out_file),
           "The optimal solution is saved to this file in Mathematica "
           "format. Defaults to sdpFile with '.out' extension.")(
  "checkpointFile,c", po::value<boost::filesystem::path>(&checkpoint_file_out),
  "Checkpoints are saved to this file every checkpointInterval. Defaults "
  "to sdpFile with '.ck' extension.")(
  "initialCheckpointFile,i",
  po::value<boost::filesystem::path>(&checkpoint_file_in),
  "The initial checkpoint to load. Defaults to checkpointFile.");

  po::options_description solverParamsOptions("Solver parameters");
  solverParamsOptions.add_options()(
  "precision", po::value<int>(&parameters.precision)->default_value(400),
  "Precision in binary digits.  GMP will round up to the nearest "
  "multiple of 64 (or 32 on older systems).")(
  "maxThreads", po::value<int>(&parameters.maxThreads)->default_value(4),
  "Maximum number of threads to use for parallel calculation.")(
  "checkpointInterval",
  po::value<int>(&parameters.checkpointInterval)->default_value(3600),
  "Save checkpoints to checkpointFile every checkpointInterval seconds.")(
  "noFinalCheckpoint",
  po::bool_switch(&parameters.noFinalCheckpoint)->default_value(false),
  "Don't save a final checkpoint after terminating (useful when debugging).")(
  "findPrimalFeasible",
  po::bool_switch(&parameters.findPrimalFeasible)->default_value(false),
  "Terminate once a primal feasible solution is found.")(
  "findDualFeasible",
  po::bool_switch(&parameters.findDualFeasible)->default_value(false),
  "Terminate once a dual feasible solution is found.")(
  "detectPrimalFeasibleJump",
  po::bool_switch(&parameters.detectPrimalFeasibleJump)->default_value(false),
  "Terminate if a primal-step of 1 is taken. This often indicates that a "
  "primal feasible solution would be found if the precision were high "
  "enough. Try increasing either primalErrorThreshold or precision "
  "and run from the latest checkpoint.")(
  "detectDualFeasibleJump",
  po::bool_switch(&parameters.detectDualFeasibleJump)->default_value(false),
  "Terminate if a dual-step of 1 is taken. This often indicates that a "
  "dual feasible solution would be found if the precision were high "
  "enough. Try increasing either dualErrorThreshold or precision "
  "and run from the latest checkpoint.")(
  "maxIterations",
  po::value<int>(&parameters.maxIterations)->default_value(500),
  "Maximum number of iterations to run the solver.")(
  "maxRuntime", po::value<int>(&parameters.maxRuntime)->default_value(86400),
  "Maximum amount of time to run the solver in seconds.")(
  "dualityGapThreshold",
  po::value<Real>(&parameters.dualityGapThreshold)
  ->default_value(Real("1e-30")),
  "Threshold for duality gap (roughly the difference in primal and dual "
  "objective) at which the solution is considered "
  "optimal. Corresponds to SDPA's epsilonStar.")(
  "primalErrorThreshold",
  po::value<Real>(&parameters.primalErrorThreshold)
  ->default_value(Real("1e-30")),
  "Threshold for feasibility of the primal problem. Corresponds to SDPA's "
  "epsilonBar.")(
  "dualErrorThreshold",
  po::value<Real>(&parameters.dualErrorThreshold)->default_value(Real("1e-30")),
  "Threshold for feasibility of the dual problem. Corresponds to SDPA's "
  "epsilonBar.")(
  "initialMatrixScalePrimal",
  po::value<Real>(&parameters.initialMatrixScalePrimal)
  ->default_value(Real("1e20")),
  "The primal matrix X begins at initialMatrixScalePrimal times the "
  "identity matrix. Corresponds to SDPA's lambdaStar.")(
  "initialMatrixScaleDual",
  po::value<Real>(&parameters.initialMatrixScaleDual)
  ->default_value(Real("1e20")),
  "The dual matrix Y begins at initialMatrixScaleDual times the "
  "identity matrix. Corresponds to SDPA's lambdaStar.")(
  "feasibleCenteringParameter",
  po::value<Real>(&parameters.feasibleCenteringParameter)
  ->default_value(Real("0.1")),
  "Shrink the complementarity X Y by this factor when the primal and dual "
  "problems are feasible. Corresponds to SDPA's betaStar.")(
  "infeasibleCenteringParameter",
  po::value<Real>(&parameters.infeasibleCenteringParameter)
  ->default_value(Real("0.3")),
  "Shrink the complementarity X Y by this factor when either the primal "
  "or dual problems are infeasible. Corresponds to SDPA's betaBar.")(
  "stepLengthReduction",
  po::value<Real>(&parameters.stepLengthReduction)->default_value(Real("0.7")),
  "Shrink each newton step by this factor (smaller means slower, more "
  "stable convergence). Corresponds to SDPA's gammaStar.")(
  "choleskyStabilizeThreshold",
  po::value<Real>(&parameters.choleskyStabilizeThreshold)
  ->default_value(Real("1e-40")),
  "Adds stabilizing terms to the cholesky decomposition of the schur "
  "complement "
  "matrix for diagonal entries which are smaller than this threshold times "
  "the "
  "geometric mean of other diagonal entries. Somewhat higher "
  "choleskyStabilizeThreshold "
  "can improve numerical stability but if the threshold is large enough that "
  "a high "
  "proportion of eigenvalues are being stabilized, the computation will slow "
  "substantially.")(
  "maxComplementarity",
  po::value<Real>(&parameters.maxComplementarity)->default_value(Real("1e100")),
  "Terminate if the complementarity mu = Tr(X Y)/dim(X) exceeds this value.");

  po::options_description cmdLineOptions;
  cmdLineOptions.add(basicOptions).add(solverParamsOptions);

  po::variables_map variablesMap;

  try
    {
      po::store(po::parse_command_line(argc, argv, cmdLineOptions),
                variablesMap);

      if(variablesMap.count("help"))
        {
          std::cout << cmdLineOptions << '\n';
          return 0;
        }

      if(variablesMap.count("paramFile"))
        {
          param_file = variablesMap["paramFile"].as<boost::filesystem::path>();
          std::ifstream ifs(param_file.string().c_str());
          po::store(po::parse_config_file(ifs, solverParamsOptions),
                    variablesMap);
        }

      po::notify(variablesMap);

      if(!variablesMap.count("outFile"))
        {
          out_file = sdp_files[0];
          out_file.replace_extension("out");
        }

      if(!variablesMap.count("checkpointFile"))
        {
          checkpoint_file_out = sdp_files[0];
          checkpoint_file_out.replace_extension("ck");
        }

      if(!variablesMap.count("initialCheckpointFile"))
        {
          checkpoint_file_in = checkpoint_file_out;
        }

      std::ofstream ofs(out_file.string().c_str());
      ofs.close();
      if(!ofs)
        {
          std::cerr << "Cannot write to outFile." << '\n';
          return 1;
        }
    }
  catch(po::error &e)
    {
      std::cerr << "ERROR: " << e.what() << '\n';
      std::cerr << cmdLineOptions << '\n';
      return 1;
    }

  return solve(sdp_files, out_file, checkpoint_file_in, checkpoint_file_out,
               parameters);
}
<commit_msg>camelCase -> snake_case<commit_after>//=======================================================================
// Copyright 2014-2015 David Simmons-Duffin.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include "SDP_Solver_Parameters.hxx"

#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>

namespace po = boost::program_options;

int solve(const std::vector<boost::filesystem::path> &sdp_files,
          const boost::filesystem::path &out_file,
          const boost::filesystem::path &checkpoint_file_in,
          const boost::filesystem::path &checkpoint_file_out,
          SDP_Solver_Parameters parameters);

int main(int argc, char **argv)
{
  std::vector<boost::filesystem::path> sdp_files;
  boost::filesystem::path out_file;
  boost::filesystem::path checkpoint_file_in;
  boost::filesystem::path checkpoint_file_out;
  boost::filesystem::path param_file;

  SDP_Solver_Parameters parameters;

  po::options_description basic_options("Basic options");
  basic_options.add_options()("help,h", "Show this helpful message.")(
  "sdpFile,s",
  po::value<std::vector<boost::filesystem::path>>(&sdp_files)->required(),
  "SDP data file(s) in XML format. Use this option repeatedly to specify "
  "multiple data files.")(
  "paramFile,p", po::value<boost::filesystem::path>(&param_file),
  "Any parameter can optionally be set via this file in key=value "
  "format. Command line arguments override values in the parameter "
  "file.")("outFile,o", po::value<boost::filesystem::path>(&out_file),
           "The optimal solution is saved to this file in Mathematica "
           "format. Defaults to sdpFile with '.out' extension.")(
  "checkpointFile,c", po::value<boost::filesystem::path>(&checkpoint_file_out),
  "Checkpoints are saved to this file every checkpointInterval. Defaults "
  "to sdpFile with '.ck' extension.")(
  "initialCheckpointFile,i",
  po::value<boost::filesystem::path>(&checkpoint_file_in),
  "The initial checkpoint to load. Defaults to checkpointFile.");

  po::options_description solver_params_options("Solver parameters");
  solver_params_options.add_options()(
  "precision", po::value<int>(&parameters.precision)->default_value(400),
  "Precision in binary digits.  GMP will round up to the nearest "
  "multiple of 64 (or 32 on older systems).")(
  "maxThreads", po::value<int>(&parameters.maxThreads)->default_value(4),
  "Maximum number of threads to use for parallel calculation.")(
  "checkpointInterval",
  po::value<int>(&parameters.checkpointInterval)->default_value(3600),
  "Save checkpoints to checkpointFile every checkpointInterval seconds.")(
  "noFinalCheckpoint",
  po::bool_switch(&parameters.noFinalCheckpoint)->default_value(false),
  "Don't save a final checkpoint after terminating (useful when debugging).")(
  "findPrimalFeasible",
  po::bool_switch(&parameters.findPrimalFeasible)->default_value(false),
  "Terminate once a primal feasible solution is found.")(
  "findDualFeasible",
  po::bool_switch(&parameters.findDualFeasible)->default_value(false),
  "Terminate once a dual feasible solution is found.")(
  "detectPrimalFeasibleJump",
  po::bool_switch(&parameters.detectPrimalFeasibleJump)->default_value(false),
  "Terminate if a primal-step of 1 is taken. This often indicates that a "
  "primal feasible solution would be found if the precision were high "
  "enough. Try increasing either primalErrorThreshold or precision "
  "and run from the latest checkpoint.")(
  "detectDualFeasibleJump",
  po::bool_switch(&parameters.detectDualFeasibleJump)->default_value(false),
  "Terminate if a dual-step of 1 is taken. This often indicates that a "
  "dual feasible solution would be found if the precision were high "
  "enough. Try increasing either dualErrorThreshold or precision "
  "and run from the latest checkpoint.")(
  "maxIterations",
  po::value<int>(&parameters.maxIterations)->default_value(500),
  "Maximum number of iterations to run the solver.")(
  "maxRuntime", po::value<int>(&parameters.maxRuntime)->default_value(86400),
  "Maximum amount of time to run the solver in seconds.")(
  "dualityGapThreshold",
  po::value<Real>(&parameters.dualityGapThreshold)
  ->default_value(Real("1e-30")),
  "Threshold for duality gap (roughly the difference in primal and dual "
  "objective) at which the solution is considered "
  "optimal. Corresponds to SDPA's epsilonStar.")(
  "primalErrorThreshold",
  po::value<Real>(&parameters.primalErrorThreshold)
  ->default_value(Real("1e-30")),
  "Threshold for feasibility of the primal problem. Corresponds to SDPA's "
  "epsilonBar.")(
  "dualErrorThreshold",
  po::value<Real>(&parameters.dualErrorThreshold)->default_value(Real("1e-30")),
  "Threshold for feasibility of the dual problem. Corresponds to SDPA's "
  "epsilonBar.")(
  "initialMatrixScalePrimal",
  po::value<Real>(&parameters.initialMatrixScalePrimal)
  ->default_value(Real("1e20")),
  "The primal matrix X begins at initialMatrixScalePrimal times the "
  "identity matrix. Corresponds to SDPA's lambdaStar.")(
  "initialMatrixScaleDual",
  po::value<Real>(&parameters.initialMatrixScaleDual)
  ->default_value(Real("1e20")),
  "The dual matrix Y begins at initialMatrixScaleDual times the "
  "identity matrix. Corresponds to SDPA's lambdaStar.")(
  "feasibleCenteringParameter",
  po::value<Real>(&parameters.feasibleCenteringParameter)
  ->default_value(Real("0.1")),
  "Shrink the complementarity X Y by this factor when the primal and dual "
  "problems are feasible. Corresponds to SDPA's betaStar.")(
  "infeasibleCenteringParameter",
  po::value<Real>(&parameters.infeasibleCenteringParameter)
  ->default_value(Real("0.3")),
  "Shrink the complementarity X Y by this factor when either the primal "
  "or dual problems are infeasible. Corresponds to SDPA's betaBar.")(
  "stepLengthReduction",
  po::value<Real>(&parameters.stepLengthReduction)->default_value(Real("0.7")),
  "Shrink each newton step by this factor (smaller means slower, more "
  "stable convergence). Corresponds to SDPA's gammaStar.")(
  "choleskyStabilizeThreshold",
  po::value<Real>(&parameters.choleskyStabilizeThreshold)
  ->default_value(Real("1e-40")),
  "Adds stabilizing terms to the cholesky decomposition of the schur "
  "complement "
  "matrix for diagonal entries which are smaller than this threshold times "
  "the "
  "geometric mean of other diagonal entries. Somewhat higher "
  "choleskyStabilizeThreshold "
  "can improve numerical stability but if the threshold is large enough that "
  "a high "
  "proportion of eigenvalues are being stabilized, the computation will slow "
  "substantially.")(
  "maxComplementarity",
  po::value<Real>(&parameters.maxComplementarity)->default_value(Real("1e100")),
  "Terminate if the complementarity mu = Tr(X Y)/dim(X) exceeds this value.");

  po::options_description cmd_line_options;
  cmd_line_options.add(basic_options).add(solver_params_options);

  po::variables_map variables_map;

  try
    {
      po::store(po::parse_command_line(argc, argv, cmd_line_options),
                variables_map);

      if(variables_map.count("help"))
        {
          std::cout << cmd_line_options << '\n';
          return 0;
        }

      if(variables_map.count("paramFile"))
        {
          param_file = variables_map["paramFile"].as<boost::filesystem::path>();
          std::ifstream ifs(param_file.string().c_str());
          po::store(po::parse_config_file(ifs, solver_params_options),
                    variables_map);
        }

      po::notify(variables_map);

      if(!variables_map.count("outFile"))
        {
          out_file = sdp_files[0];
          out_file.replace_extension("out");
        }

      if(!variables_map.count("checkpointFile"))
        {
          checkpoint_file_out = sdp_files[0];
          checkpoint_file_out.replace_extension("ck");
        }

      if(!variables_map.count("initialCheckpointFile"))
        {
          checkpoint_file_in = checkpoint_file_out;
        }

      std::ofstream ofs(out_file.string().c_str());
      ofs.close();
      if(!ofs)
        {
          std::cerr << "Cannot write to outFile." << '\n';
          return 1;
        }
    }
  catch(po::error &e)
    {
      std::cerr << "ERROR: " << e.what() << '\n';
      std::cerr << cmd_line_options << '\n';
      return 1;
    }

  return solve(sdp_files, out_file, checkpoint_file_in, checkpoint_file_out,
               parameters);
}
<|endoftext|>


<commit_before>#include "../../../shared/generated/cpp/WebViewBase.h"
#include "../../../shared/System.h"
#include "common/RhodesApp.h"
#include "common/RhoConf.h"
#include "rubyext/WebView.h"

//extern "C" HWND getMainWnd();
extern "C" const wchar_t* rho_wmimpl_getNavTimeOutVal();
extern "C" const wchar_t* rho_wmimpl_sharedconfig_getvalue(const wchar_t* szName);

namespace rho {

using namespace apiGenerator;
using namespace common;

class CWebViewImpl: public CWebViewSingletonBase
{
    int m_nNavigationTimeout;
    double m_dZoomPage;
    int m_nTextZoom;
public:

    CWebViewImpl(): m_nNavigationTimeout(0), m_dZoomPage(1.0), m_nTextZoom(1), CWebViewSingletonBase()
    {
        convertFromStringW( rho_wmimpl_getNavTimeOutVal(), m_nNavigationTimeout );
    }

    virtual void getFramework(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set(System::getWebviewFramework());
    }

    virtual void getFullScreen(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set(rho_webview_get_full_screen() != 0 ? true : false );
    }

    virtual void setFullScreen( bool value, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_full_screen_mode(value ? 1 : 0);
    }

    //Android only
    virtual void getEnableZoom(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set(true);
    }

    virtual void setEnableZoom( bool value, rho::apiGenerator::CMethodResult& oResult){}
    virtual void getEnablePageLoadingIndication(rho::apiGenerator::CMethodResult& oResult)
    {
        //oResult.set(false);
        int nValue = 0;
        convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"GUI\\HourglassEnabled" ), nValue );
        oResult.set( nValue ? true : false );
    }

    virtual void setEnablePageLoadingIndication( bool value, rho::apiGenerator::CMethodResult& oResult)
    {
        //Do nothing. It can be set only in config.xml
    }

    virtual void getEnableWebPlugins(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set(true);
    }

    virtual void setEnableWebPlugins( bool value, rho::apiGenerator::CMethodResult& oResult){}
    //

    virtual void getNavigationTimeout(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set(m_nNavigationTimeout);
    }

    virtual void setNavigationTimeout( int value, rho::apiGenerator::CMethodResult& oResult)
    {
        m_nNavigationTimeout = value;
        rho_webview_setNavigationTimeout(m_nNavigationTimeout);
    }

    virtual void getScrollTechnique(rho::apiGenerator::CMethodResult& oResult)
    {
        //oResult.set( RHOCONF().getString("WebView.scrollTechnique") );
        oResult.set( convertToStringA( rho_wmimpl_sharedconfig_getvalue( L"Scrolling\\ScrollTechnique" ) ) );
    }

    virtual void getFontFamily(rho::apiGenerator::CMethodResult& oResult)
    {
        //oResult.set( RHOCONF().getString("Webview.fontFamily") );
        oResult.set( convertToStringA( rho_wmimpl_sharedconfig_getvalue( L"HTMLStyles\\FontFamily" ) ) );
    }

    virtual void getUserAgent(rho::apiGenerator::CMethodResult& oResult)
    {
        //oResult.set( RHOCONF().getString("WebView.userAgent") );
        oResult.set( convertToStringA( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\UserAgent" ) ) );
    }

    virtual void getViewportEnabled(rho::apiGenerator::CMethodResult& oResult)
    {
        //oResult.set( RHOCONF().getBool("WebView.viewportEnabled") );
        int nValue = 0;
        convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\ViewportEnabled" ), nValue );
        oResult.set( nValue ? true : false );
    }

    virtual void getViewportWidth(rho::apiGenerator::CMethodResult& oResult)
    {
        //oResult.set( RHOCONF().getInt("WebView.viewportWidth") );
        int nValue = 0;
        convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\ViewportWidth" ), nValue );
        oResult.set( nValue );
    }

    virtual void getCacheSize(rho::apiGenerator::CMethodResult& oResult)
    {
        int nValue = 0;
        convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\Cache" ), nValue );
        oResult.set( nValue );

        //oResult.set( RHOCONF().getInt("WebView.cacheSize") );
    }

    //TODO: EnableCache - does it supported by Moto Webkit ?
    virtual void getEnableCache(rho::apiGenerator::CMethodResult& oResult){}
    virtual void setEnableCache( bool value, rho::apiGenerator::CMethodResult& oResult){}

    //TODO: AcceptLanguage - does it supported by Moto Webkit ?
    virtual void getAcceptLanguage(rho::apiGenerator::CMethodResult& oResult){}
    virtual void setAcceptLanguage( const rho::String& value, rho::apiGenerator::CMethodResult& oResult){}

    virtual void getZoomPage(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set(m_dZoomPage);
    }

    virtual void setZoomPage( double value, rho::apiGenerator::CMethodResult& oResult)
    {
        m_dZoomPage = value;
        RHODESAPP().getExtManager().zoomPage( (float)m_dZoomPage);
    }

    virtual void getTextZoomLevel(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( m_nTextZoom );
    }

    virtual void setTextZoomLevel( int value, rho::apiGenerator::CMethodResult& oResult)
    {
        m_nTextZoom = value;
        RHODESAPP().getExtManager().zoomText( m_nTextZoom );
    }

    virtual void refresh( int tabIndex, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_refresh(tabIndex);
    }

    virtual void navigate( const rho::String& url,  int tabIndex, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_navigate(url.c_str(), tabIndex);
    }

    virtual void navigateBack( int tabIndex, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_navigate_back_with_tab(tabIndex);
    }

    virtual void currentLocation( int tabIndex, rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( rho_webview_current_location(tabIndex) );
    }

    //iOS, Android only
    virtual void currentURL( int tabIndex, rho::apiGenerator::CMethodResult& oResult){}

    virtual void executeJavascript( const rho::String& javascriptText,  int tabIndex, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_execute_js( javascriptText.c_str(), tabIndex );
    }

    virtual void active_tab(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( rho_webview_active_tab() );
    }

    virtual void getActiveTab(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( rho_webview_active_tab() );
    }

    virtual void full_screen_mode( bool enable, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_full_screen_mode(enable ? 1 : 0);
    }

    virtual void setCookie( const rho::String& url,  const rho::String& cookie, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_set_cookie( url.c_str(), cookie.c_str() );
    }

    //Android only
    virtual void save( const rho::String& format,  const rho::String& path,  int tabIndex, rho::apiGenerator::CMethodResult& oResult){}
    //
};

////////////////////////////////////////////////////////////////////////

class CWebViewFactory: public CWebViewFactoryBase
{
public:
    ~CWebViewFactory(){}

    IWebViewSingleton* createModuleSingleton()
    {
        return new CWebViewImpl();
    }
};

}

extern "C" void Init_WebView()
{
    rho::CWebViewFactory::setInstance( new rho::CWebViewFactory() );
    rho::Init_WebView_API();

    RHODESAPP().getExtManager().requireRubyFile("RhoWebViewApi");

}
<commit_msg>Update WebViewImpl.cpp<commit_after>#include "../../../shared/generated/cpp/WebViewBase.h"
#include "../../../shared/System.h"
#include "common/RhodesApp.h"
#include "common/RhoConf.h"
#include "rubyext/WebView.h"

//extern "C" HWND getMainWnd();
extern "C" const wchar_t* rho_wmimpl_getNavTimeOutVal();
extern "C" const wchar_t* rho_wmimpl_sharedconfig_getvalue(const wchar_t* szName);

namespace rho {

using namespace apiGenerator;
using namespace common;

class CWebViewImpl: public CWebViewSingletonBase
{
    int m_nNavigationTimeout;
    double m_dZoomPage;
    int m_nTextZoom;
public:

    CWebViewImpl(): m_nNavigationTimeout(45000), m_dZoomPage(1.0), m_nTextZoom(1), CWebViewSingletonBase()
    {
        convertFromStringW( rho_wmimpl_getNavTimeOutVal(), m_nNavigationTimeout );
		if(m_nNavigationTimeout<=0)
		{
			LOG(WARNING)+" NavigationTimeout  value  from config.xml not correct "+m_nNavigationTimeout;
			m_nNavigationTimeout=45000;
		}
    }

    virtual void getFramework(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set(System::getWebviewFramework());
    }

    virtual void getFullScreen(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set(rho_webview_get_full_screen() != 0 ? true : false );
    }

    virtual void setFullScreen( bool value, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_full_screen_mode(value ? 1 : 0);
    }

    //Android only
    virtual void getEnableZoom(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set(true);
    }

    virtual void setEnableZoom( bool value, rho::apiGenerator::CMethodResult& oResult){}
    virtual void getEnablePageLoadingIndication(rho::apiGenerator::CMethodResult& oResult)
    {
        //oResult.set(false);
        int nValue = 0;
        convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"GUI\\HourglassEnabled" ), nValue );
        oResult.set( nValue ? true : false );
    }

    virtual void setEnablePageLoadingIndication( bool value, rho::apiGenerator::CMethodResult& oResult)
    {
        //Do nothing. It can be set only in config.xml
    }

    virtual void getEnableWebPlugins(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set(true);
    }

    virtual void setEnableWebPlugins( bool value, rho::apiGenerator::CMethodResult& oResult){}
    //

    virtual void getNavigationTimeout(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set(m_nNavigationTimeout);
    }

    virtual void setNavigationTimeout( int value, rho::apiGenerator::CMethodResult& oResult)
    {
        m_nNavigationTimeout = value;
        rho_webview_setNavigationTimeout(m_nNavigationTimeout);
    }

    virtual void getScrollTechnique(rho::apiGenerator::CMethodResult& oResult)
    {
        //oResult.set( RHOCONF().getString("WebView.scrollTechnique") );
        oResult.set( convertToStringA( rho_wmimpl_sharedconfig_getvalue( L"Scrolling\\ScrollTechnique" ) ) );
    }

    virtual void getFontFamily(rho::apiGenerator::CMethodResult& oResult)
    {
        //oResult.set( RHOCONF().getString("Webview.fontFamily") );
        oResult.set( convertToStringA( rho_wmimpl_sharedconfig_getvalue( L"HTMLStyles\\FontFamily" ) ) );
    }

    virtual void getUserAgent(rho::apiGenerator::CMethodResult& oResult)
    {
        //oResult.set( RHOCONF().getString("WebView.userAgent") );
        oResult.set( convertToStringA( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\UserAgent" ) ) );
    }

    virtual void getViewportEnabled(rho::apiGenerator::CMethodResult& oResult)
    {
        //oResult.set( RHOCONF().getBool("WebView.viewportEnabled") );
        int nValue = 0;
        convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\ViewportEnabled" ), nValue );
        oResult.set( nValue ? true : false );
    }

    virtual void getViewportWidth(rho::apiGenerator::CMethodResult& oResult)
    {
        //oResult.set( RHOCONF().getInt("WebView.viewportWidth") );
        int nValue = 0;
        convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\ViewportWidth" ), nValue );
        oResult.set( nValue );
    }

    virtual void getCacheSize(rho::apiGenerator::CMethodResult& oResult)
    {
        int nValue = 0;
        convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\Cache" ), nValue );
        oResult.set( nValue );

        //oResult.set( RHOCONF().getInt("WebView.cacheSize") );
    }

    //TODO: EnableCache - does it supported by Moto Webkit ?
    virtual void getEnableCache(rho::apiGenerator::CMethodResult& oResult){}
    virtual void setEnableCache( bool value, rho::apiGenerator::CMethodResult& oResult){}

    //TODO: AcceptLanguage - does it supported by Moto Webkit ?
    virtual void getAcceptLanguage(rho::apiGenerator::CMethodResult& oResult){}
    virtual void setAcceptLanguage( const rho::String& value, rho::apiGenerator::CMethodResult& oResult){}

    virtual void getZoomPage(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set(m_dZoomPage);
    }

    virtual void setZoomPage( double value, rho::apiGenerator::CMethodResult& oResult)
    {
        m_dZoomPage = value;
        RHODESAPP().getExtManager().zoomPage( (float)m_dZoomPage);
    }

    virtual void getTextZoomLevel(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( m_nTextZoom );
    }

    virtual void setTextZoomLevel( int value, rho::apiGenerator::CMethodResult& oResult)
    {
        m_nTextZoom = value;
        RHODESAPP().getExtManager().zoomText( m_nTextZoom );
    }

    virtual void refresh( int tabIndex, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_refresh(tabIndex);
    }

    virtual void navigate( const rho::String& url,  int tabIndex, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_navigate(url.c_str(), tabIndex);
    }

    virtual void navigateBack( int tabIndex, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_navigate_back_with_tab(tabIndex);
    }

    virtual void currentLocation( int tabIndex, rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( rho_webview_current_location(tabIndex) );
    }

    //iOS, Android only
    virtual void currentURL( int tabIndex, rho::apiGenerator::CMethodResult& oResult){}

    virtual void executeJavascript( const rho::String& javascriptText,  int tabIndex, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_execute_js( javascriptText.c_str(), tabIndex );
    }

    virtual void active_tab(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( rho_webview_active_tab() );
    }

    virtual void getActiveTab(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( rho_webview_active_tab() );
    }

    virtual void full_screen_mode( bool enable, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_full_screen_mode(enable ? 1 : 0);
    }

    virtual void setCookie( const rho::String& url,  const rho::String& cookie, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_set_cookie( url.c_str(), cookie.c_str() );
    }

    //Android only
    virtual void save( const rho::String& format,  const rho::String& path,  int tabIndex, rho::apiGenerator::CMethodResult& oResult){}
    //
};

////////////////////////////////////////////////////////////////////////

class CWebViewFactory: public CWebViewFactoryBase
{
public:
    ~CWebViewFactory(){}

    IWebViewSingleton* createModuleSingleton()
    {
        return new CWebViewImpl();
    }
};

}

extern "C" void Init_WebView()
{
    rho::CWebViewFactory::setInstance( new rho::CWebViewFactory() );
    rho::Init_WebView_API();

    RHODESAPP().getExtManager().requireRubyFile("RhoWebViewApi");

}
<|endoftext|>


<commit_before>#include "../../../shared/generated/cpp/WebViewBase.h"
#include "../../../shared/System.h"
#include "common/RhodesApp.h"
#include "common/RhoConf.h"
#include "rubyext/WebView.h"

//extern "C" HWND getMainWnd();
extern "C" const wchar_t* rho_wmimpl_getNavTimeOutVal(const wchar_t* szName);
extern "C" const wchar_t* rho_wmimpl_sharedconfig_getvalue(const wchar_t* szName);

namespace rho {

using namespace apiGenerator;
using namespace common;

class CWebViewImpl: public CWebViewSingletonBase
{
    int m_nNavigationTimeout;
    double m_dZoomPage;
    int m_nTextZoom;
public:

    CWebViewImpl(): m_nNavigationTimeout(0), m_dZoomPage(1.0), m_nTextZoom(1), CWebViewSingletonBase()
    {
        convertFromStringW( rho_wmimpl_getNavTimeOutVal( L"Navigation\\NavTimeout" ), m_nNavigationTimeout );
    }

    virtual void getFramework(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set(System::getWebviewFramework());
    }

    virtual void getFullScreen(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set(rho_webview_get_full_screen() != 0 ? true : false );
    }

    virtual void setFullScreen( bool value, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_full_screen_mode(value ? 1 : 0);
    }

    //Android only
    virtual void getEnableZoom(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set(true);
    }

    virtual void setEnableZoom( bool value, rho::apiGenerator::CMethodResult& oResult){}
    virtual void getEnablePageLoadingIndication(rho::apiGenerator::CMethodResult& oResult)
    {
        //oResult.set(false);
        int nValue = 0;
        convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"GUI\\HourglassEnabled" ), nValue );
        oResult.set( nValue ? true : false );
    }

    virtual void setEnablePageLoadingIndication( bool value, rho::apiGenerator::CMethodResult& oResult)
    {
        //Do nothing. It can be set only in config.xml
    }

    virtual void getEnableWebPlugins(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set(true);
    }

    virtual void setEnableWebPlugins( bool value, rho::apiGenerator::CMethodResult& oResult){}
    //

    virtual void getNavigationTimeout(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set(m_nNavigationTimeout);
    }

    virtual void setNavigationTimeout( int value, rho::apiGenerator::CMethodResult& oResult)
    {
        m_nNavigationTimeout = value;
        rho_webview_setNavigationTimeout(m_nNavigationTimeout);
    }

    virtual void getScrollTechnique(rho::apiGenerator::CMethodResult& oResult)
    {
        //oResult.set( RHOCONF().getString("WebView.scrollTechnique") );
        oResult.set( convertToStringA( rho_wmimpl_sharedconfig_getvalue( L"Scrolling\\ScrollTechnique" ) ) );
    }

    virtual void getFontFamily(rho::apiGenerator::CMethodResult& oResult)
    {
        //oResult.set( RHOCONF().getString("Webview.fontFamily") );
        oResult.set( convertToStringA( rho_wmimpl_sharedconfig_getvalue( L"HTMLStyles\\FontFamily" ) ) );
    }

    virtual void getUserAgent(rho::apiGenerator::CMethodResult& oResult)
    {
        //oResult.set( RHOCONF().getString("WebView.userAgent") );
        oResult.set( convertToStringA( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\UserAgent" ) ) );
    }

    virtual void getViewportEnabled(rho::apiGenerator::CMethodResult& oResult)
    {
        //oResult.set( RHOCONF().getBool("WebView.viewportEnabled") );
        int nValue = 0;
        convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\ViewportEnabled" ), nValue );
        oResult.set( nValue ? true : false );
    }

    virtual void getViewportWidth(rho::apiGenerator::CMethodResult& oResult)
    {
        //oResult.set( RHOCONF().getInt("WebView.viewportWidth") );
        int nValue = 0;
        convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\ViewportWidth" ), nValue );
        oResult.set( nValue );
    }

    virtual void getCacheSize(rho::apiGenerator::CMethodResult& oResult)
    {
        int nValue = 0;
        convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\Cache" ), nValue );
        oResult.set( nValue );

        //oResult.set( RHOCONF().getInt("WebView.cacheSize") );
    }

    //TODO: EnableCache - does it supported by Moto Webkit ?
    virtual void getEnableCache(rho::apiGenerator::CMethodResult& oResult){}
    virtual void setEnableCache( bool value, rho::apiGenerator::CMethodResult& oResult){}

    //TODO: AcceptLanguage - does it supported by Moto Webkit ?
    virtual void getAcceptLanguage(rho::apiGenerator::CMethodResult& oResult){}
    virtual void setAcceptLanguage( const rho::String& value, rho::apiGenerator::CMethodResult& oResult){}

    virtual void getZoomPage(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set(m_dZoomPage);
    }

    virtual void setZoomPage( double value, rho::apiGenerator::CMethodResult& oResult)
    {
        m_dZoomPage = value;
        RHODESAPP().getExtManager().zoomPage( (float)m_dZoomPage);
    }

    virtual void getTextZoomLevel(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( m_nTextZoom );
    }

    virtual void setTextZoomLevel( int value, rho::apiGenerator::CMethodResult& oResult)
    {
        m_nTextZoom = value;
        RHODESAPP().getExtManager().zoomText( m_nTextZoom );
    }

    virtual void refresh( int tabIndex, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_refresh(tabIndex);
    }

    virtual void navigate( const rho::String& url,  int tabIndex, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_navigate(url.c_str(), tabIndex);
    }

    virtual void navigateBack( int tabIndex, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_navigate_back_with_tab(tabIndex);
    }

    virtual void currentLocation( int tabIndex, rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( rho_webview_current_location(tabIndex) );
    }

    //iOS, Android only
    virtual void currentURL( int tabIndex, rho::apiGenerator::CMethodResult& oResult){}

    virtual void executeJavascript( const rho::String& javascriptText,  int tabIndex, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_execute_js( javascriptText.c_str(), tabIndex );
    }

    virtual void active_tab(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( rho_webview_active_tab() );
    }

    virtual void getActiveTab(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( rho_webview_active_tab() );
    }

    virtual void full_screen_mode( bool enable, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_full_screen_mode(enable ? 1 : 0);
    }

    virtual void setCookie( const rho::String& url,  const rho::String& cookie, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_set_cookie( url.c_str(), cookie.c_str() );
    }

    //Android only
    virtual void save( const rho::String& format,  const rho::String& path,  int tabIndex, rho::apiGenerator::CMethodResult& oResult){}
    //
};

////////////////////////////////////////////////////////////////////////

class CWebViewFactory: public CWebViewFactoryBase
{
public:
    ~CWebViewFactory(){}

    IWebViewSingleton* createModuleSingleton()
    {
        return new CWebViewImpl();
    }
};

}

extern "C" void Init_WebView()
{
    rho::CWebViewFactory::setInstance( new rho::CWebViewFactory() );
    rho::Init_WebView_API();

    RHODESAPP().getExtManager().requireRubyFile("RhoWebViewApi");

}
<commit_msg>Update WebViewImpl.cpp<commit_after>#include "../../../shared/generated/cpp/WebViewBase.h"
#include "../../../shared/System.h"
#include "common/RhodesApp.h"
#include "common/RhoConf.h"
#include "rubyext/WebView.h"

//extern "C" HWND getMainWnd();
extern "C" const wchar_t* rho_wmimpl_getNavTimeOutVal();
extern "C" const wchar_t* rho_wmimpl_sharedconfig_getvalue(const wchar_t* szName);

namespace rho {

using namespace apiGenerator;
using namespace common;

class CWebViewImpl: public CWebViewSingletonBase
{
    int m_nNavigationTimeout;
    double m_dZoomPage;
    int m_nTextZoom;
public:

    CWebViewImpl(): m_nNavigationTimeout(0), m_dZoomPage(1.0), m_nTextZoom(1), CWebViewSingletonBase()
    {
        convertFromStringW( rho_wmimpl_getNavTimeOutVal(), m_nNavigationTimeout );
    }

    virtual void getFramework(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set(System::getWebviewFramework());
    }

    virtual void getFullScreen(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set(rho_webview_get_full_screen() != 0 ? true : false );
    }

    virtual void setFullScreen( bool value, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_full_screen_mode(value ? 1 : 0);
    }

    //Android only
    virtual void getEnableZoom(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set(true);
    }

    virtual void setEnableZoom( bool value, rho::apiGenerator::CMethodResult& oResult){}
    virtual void getEnablePageLoadingIndication(rho::apiGenerator::CMethodResult& oResult)
    {
        //oResult.set(false);
        int nValue = 0;
        convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"GUI\\HourglassEnabled" ), nValue );
        oResult.set( nValue ? true : false );
    }

    virtual void setEnablePageLoadingIndication( bool value, rho::apiGenerator::CMethodResult& oResult)
    {
        //Do nothing. It can be set only in config.xml
    }

    virtual void getEnableWebPlugins(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set(true);
    }

    virtual void setEnableWebPlugins( bool value, rho::apiGenerator::CMethodResult& oResult){}
    //

    virtual void getNavigationTimeout(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set(m_nNavigationTimeout);
    }

    virtual void setNavigationTimeout( int value, rho::apiGenerator::CMethodResult& oResult)
    {
        m_nNavigationTimeout = value;
        rho_webview_setNavigationTimeout(m_nNavigationTimeout);
    }

    virtual void getScrollTechnique(rho::apiGenerator::CMethodResult& oResult)
    {
        //oResult.set( RHOCONF().getString("WebView.scrollTechnique") );
        oResult.set( convertToStringA( rho_wmimpl_sharedconfig_getvalue( L"Scrolling\\ScrollTechnique" ) ) );
    }

    virtual void getFontFamily(rho::apiGenerator::CMethodResult& oResult)
    {
        //oResult.set( RHOCONF().getString("Webview.fontFamily") );
        oResult.set( convertToStringA( rho_wmimpl_sharedconfig_getvalue( L"HTMLStyles\\FontFamily" ) ) );
    }

    virtual void getUserAgent(rho::apiGenerator::CMethodResult& oResult)
    {
        //oResult.set( RHOCONF().getString("WebView.userAgent") );
        oResult.set( convertToStringA( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\UserAgent" ) ) );
    }

    virtual void getViewportEnabled(rho::apiGenerator::CMethodResult& oResult)
    {
        //oResult.set( RHOCONF().getBool("WebView.viewportEnabled") );
        int nValue = 0;
        convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\ViewportEnabled" ), nValue );
        oResult.set( nValue ? true : false );
    }

    virtual void getViewportWidth(rho::apiGenerator::CMethodResult& oResult)
    {
        //oResult.set( RHOCONF().getInt("WebView.viewportWidth") );
        int nValue = 0;
        convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\ViewportWidth" ), nValue );
        oResult.set( nValue );
    }

    virtual void getCacheSize(rho::apiGenerator::CMethodResult& oResult)
    {
        int nValue = 0;
        convertFromStringW( rho_wmimpl_sharedconfig_getvalue( L"Navigation\\Cache" ), nValue );
        oResult.set( nValue );

        //oResult.set( RHOCONF().getInt("WebView.cacheSize") );
    }

    //TODO: EnableCache - does it supported by Moto Webkit ?
    virtual void getEnableCache(rho::apiGenerator::CMethodResult& oResult){}
    virtual void setEnableCache( bool value, rho::apiGenerator::CMethodResult& oResult){}

    //TODO: AcceptLanguage - does it supported by Moto Webkit ?
    virtual void getAcceptLanguage(rho::apiGenerator::CMethodResult& oResult){}
    virtual void setAcceptLanguage( const rho::String& value, rho::apiGenerator::CMethodResult& oResult){}

    virtual void getZoomPage(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set(m_dZoomPage);
    }

    virtual void setZoomPage( double value, rho::apiGenerator::CMethodResult& oResult)
    {
        m_dZoomPage = value;
        RHODESAPP().getExtManager().zoomPage( (float)m_dZoomPage);
    }

    virtual void getTextZoomLevel(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( m_nTextZoom );
    }

    virtual void setTextZoomLevel( int value, rho::apiGenerator::CMethodResult& oResult)
    {
        m_nTextZoom = value;
        RHODESAPP().getExtManager().zoomText( m_nTextZoom );
    }

    virtual void refresh( int tabIndex, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_refresh(tabIndex);
    }

    virtual void navigate( const rho::String& url,  int tabIndex, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_navigate(url.c_str(), tabIndex);
    }

    virtual void navigateBack( int tabIndex, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_navigate_back_with_tab(tabIndex);
    }

    virtual void currentLocation( int tabIndex, rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( rho_webview_current_location(tabIndex) );
    }

    //iOS, Android only
    virtual void currentURL( int tabIndex, rho::apiGenerator::CMethodResult& oResult){}

    virtual void executeJavascript( const rho::String& javascriptText,  int tabIndex, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_execute_js( javascriptText.c_str(), tabIndex );
    }

    virtual void active_tab(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( rho_webview_active_tab() );
    }

    virtual void getActiveTab(rho::apiGenerator::CMethodResult& oResult)
    {
        oResult.set( rho_webview_active_tab() );
    }

    virtual void full_screen_mode( bool enable, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_full_screen_mode(enable ? 1 : 0);
    }

    virtual void setCookie( const rho::String& url,  const rho::String& cookie, rho::apiGenerator::CMethodResult& oResult)
    {
        rho_webview_set_cookie( url.c_str(), cookie.c_str() );
    }

    //Android only
    virtual void save( const rho::String& format,  const rho::String& path,  int tabIndex, rho::apiGenerator::CMethodResult& oResult){}
    //
};

////////////////////////////////////////////////////////////////////////

class CWebViewFactory: public CWebViewFactoryBase
{
public:
    ~CWebViewFactory(){}

    IWebViewSingleton* createModuleSingleton()
    {
        return new CWebViewImpl();
    }
};

}

extern "C" void Init_WebView()
{
    rho::CWebViewFactory::setInstance( new rho::CWebViewFactory() );
    rho::Init_WebView_API();

    RHODESAPP().getExtManager().requireRubyFile("RhoWebViewApi");

}
<|endoftext|>


<commit_before>#ifndef BOOST_THREAD_PTHREAD_MUTEX_HPP
#define BOOST_THREAD_PTHREAD_MUTEX_HPP
// (C) Copyright 2007-8 Anthony Williams
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#include <pthread.h>
#include <boost/utility.hpp>
#include <boost/thread/exceptions.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/thread_time.hpp>
#include <boost/thread/xtime.hpp>
#include <boost/assert.hpp>
#include <errno.h>
#include "timespec.hpp"
#include "pthread_mutex_scoped_lock.hpp"

#ifdef _POSIX_TIMEOUTS
#if _POSIX_TIMEOUTS >= 0
#define BOOST_PTHREAD_HAS_TIMEDLOCK
#endif
#endif

#include <boost/config/abi_prefix.hpp>

namespace boost
{
    class mutex:
        boost::noncopyable
    {
    private:
        pthread_mutex_t m;
    public:
        mutex()
        {
            int const res=pthread_mutex_init(&m,NULL);
            if(res)
            {
                throw thread_resource_error("Cannot initialize a mutex", res);
            }
        }
        ~mutex()
        {
            BOOST_VERIFY(!pthread_mutex_destroy(&m));
        }

        void lock()
        {
            BOOST_VERIFY(!pthread_mutex_lock(&m));
        }

        void unlock()
        {
            BOOST_VERIFY(!pthread_mutex_unlock(&m));
        }

        bool try_lock()
        {
            int const res=pthread_mutex_trylock(&m);
            BOOST_ASSERT(!res || res==EBUSY);
            return !res;
        }

        typedef pthread_mutex_t* native_handle_type;
        native_handle_type native_handle()
        {
            return &m;
        }

        typedef unique_lock<mutex> scoped_lock;
        typedef detail::try_lock_wrapper<mutex> scoped_try_lock;
    };

    typedef mutex try_mutex;

    class timed_mutex:
        boost::noncopyable
    {
    private:
        pthread_mutex_t m;
#ifndef BOOST_PTHREAD_HAS_TIMEDLOCK
        pthread_cond_t cond;
        bool is_locked;
#endif
    public:
        timed_mutex()
        {
            int const res=pthread_mutex_init(&m,NULL);
            if(res)
            {
                throw thread_resource_error("Cannot initialize a mutex", res);
            }
#ifndef BOOST_PTHREAD_HAS_TIMEDLOCK
            int const res2=pthread_cond_init(&cond,NULL);
            if(res2)
            {
                BOOST_VERIFY(!pthread_mutex_destroy(&m));
                throw thread_resource_error("Cannot initialize a condition variable", res2);
            }
            is_locked=false;
#endif
        }
        ~timed_mutex()
        {
            BOOST_VERIFY(!pthread_mutex_destroy(&m));
#ifndef BOOST_PTHREAD_HAS_TIMEDLOCK
            BOOST_VERIFY(!pthread_cond_destroy(&cond));
#endif
        }

        template<typename TimeDuration>
        bool timed_lock(TimeDuration const & relative_time)
        {
            return timed_lock(get_system_time()+relative_time);
        }
        bool timed_lock(boost::xtime const & absolute_time)
        {
            return timed_lock(system_time(absolute_time));
        }

#ifdef BOOST_PTHREAD_HAS_TIMEDLOCK
        void lock()
        {
            BOOST_VERIFY(!pthread_mutex_lock(&m));
        }

        void unlock()
        {
            BOOST_VERIFY(!pthread_mutex_unlock(&m));
        }

        bool try_lock()
        {
            int const res=pthread_mutex_trylock(&m);
            BOOST_ASSERT(!res || res==EBUSY);
            return !res;
        }
        bool timed_lock(system_time const & abs_time)
        {
            struct timespec const timeout=detail::get_timespec(abs_time);
            int const res=pthread_mutex_timedlock(&m,&timeout);
            BOOST_ASSERT(!res || res==ETIMEDOUT);
            return !res;
        }

        typedef pthread_mutex_t* native_handle_type;
        native_handle_type native_handle()
        {
            return &m;
        }

#else
        void lock()
        {
            boost::pthread::pthread_mutex_scoped_lock const local_lock(&m);
            while(is_locked)
            {
                BOOST_VERIFY(!pthread_cond_wait(&cond,&m));
            }
            is_locked=true;
        }

        void unlock()
        {
            boost::pthread::pthread_mutex_scoped_lock const local_lock(&m);
            is_locked=false;
            BOOST_VERIFY(!pthread_cond_signal(&cond));
        }

        bool try_lock()
        {
            boost::pthread::pthread_mutex_scoped_lock const local_lock(&m);
            if(is_locked)
            {
                return false;
            }
            is_locked=true;
            return true;
        }

        bool timed_lock(system_time const & abs_time)
        {
            struct timespec const timeout=detail::get_timespec(abs_time);
            boost::pthread::pthread_mutex_scoped_lock const local_lock(&m);
            while(is_locked)
            {
                int const cond_res=pthread_cond_timedwait(&cond,&m,&timeout);
                if(cond_res==ETIMEDOUT)
                {
                    return false;
                }
                BOOST_ASSERT(!cond_res);
            }
            is_locked=true;
            return true;
        }
#endif

        typedef unique_lock<timed_mutex> scoped_timed_lock;
        typedef detail::try_lock_wrapper<timed_mutex> scoped_try_lock;
        typedef scoped_timed_lock scoped_lock;
    };

}

#include <boost/config/abi_suffix.hpp>

#endif
<commit_msg>Make boost::mutex handle EINTR gracefully.<commit_after>#ifndef BOOST_THREAD_PTHREAD_MUTEX_HPP
#define BOOST_THREAD_PTHREAD_MUTEX_HPP
// (C) Copyright 2007-8 Anthony Williams
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#include <pthread.h>
#include <boost/utility.hpp>
#include <boost/thread/exceptions.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/thread_time.hpp>
#include <boost/thread/xtime.hpp>
#include <boost/assert.hpp>
#include <errno.h>
#include "timespec.hpp"
#include "pthread_mutex_scoped_lock.hpp"

#ifdef _POSIX_TIMEOUTS
#if _POSIX_TIMEOUTS >= 0
#define BOOST_PTHREAD_HAS_TIMEDLOCK
#endif
#endif

#include <boost/config/abi_prefix.hpp>

namespace boost
{
    class mutex:
        boost::noncopyable
    {
    private:
        pthread_mutex_t m;
    public:
        mutex()
        {
            int const res=pthread_mutex_init(&m,NULL);
            if(res)
            {
                throw thread_resource_error("Cannot initialize a mutex", res);
            }
        }
        ~mutex()
        {
            int ret;
            do {
                ret = pthread_mutex_destroy(&m);
            } while (ret == EINTR);
            BOOST_VERIFY(!ret);
        }

        void lock()
        {
            int ret;
            do {
                ret = pthread_mutex_lock(&m);
            } while (ret == EINTR);
            BOOST_VERIFY(!ret);
        }

        void unlock()
        {
            int ret;
            do {
                ret = pthread_mutex_unlock(&m);
            } while (ret == EINTR);
            BOOST_VERIFY(!ret);
        }

        bool try_lock()
        {
            int res;
            do {
                res = pthread_mutex_trylock(&m);
            } while (res == EINTR);
            BOOST_ASSERT(!res || res==EBUSY);
            return !res;
        }

        typedef pthread_mutex_t* native_handle_type;
        native_handle_type native_handle()
        {
            return &m;
        }

        typedef unique_lock<mutex> scoped_lock;
        typedef detail::try_lock_wrapper<mutex> scoped_try_lock;
    };

    typedef mutex try_mutex;

    class timed_mutex:
        boost::noncopyable
    {
    private:
        pthread_mutex_t m;
#ifndef BOOST_PTHREAD_HAS_TIMEDLOCK
        pthread_cond_t cond;
        bool is_locked;
#endif
    public:
        timed_mutex()
        {
            int const res=pthread_mutex_init(&m,NULL);
            if(res)
            {
                throw thread_resource_error("Cannot initialize a mutex", res);
            }
#ifndef BOOST_PTHREAD_HAS_TIMEDLOCK
            int const res2=pthread_cond_init(&cond,NULL);
            if(res2)
            {
                BOOST_VERIFY(!pthread_mutex_destroy(&m));
                throw thread_resource_error("Cannot initialize a condition variable", res2);
            }
            is_locked=false;
#endif
        }
        ~timed_mutex()
        {
            BOOST_VERIFY(!pthread_mutex_destroy(&m));
#ifndef BOOST_PTHREAD_HAS_TIMEDLOCK
            BOOST_VERIFY(!pthread_cond_destroy(&cond));
#endif
        }

        template<typename TimeDuration>
        bool timed_lock(TimeDuration const & relative_time)
        {
            return timed_lock(get_system_time()+relative_time);
        }
        bool timed_lock(boost::xtime const & absolute_time)
        {
            return timed_lock(system_time(absolute_time));
        }

#ifdef BOOST_PTHREAD_HAS_TIMEDLOCK
        void lock()
        {
            BOOST_VERIFY(!pthread_mutex_lock(&m));
        }

        void unlock()
        {
            BOOST_VERIFY(!pthread_mutex_unlock(&m));
        }

        bool try_lock()
        {
            int const res=pthread_mutex_trylock(&m);
            BOOST_ASSERT(!res || res==EBUSY);
            return !res;
        }
        bool timed_lock(system_time const & abs_time)
        {
            struct timespec const timeout=detail::get_timespec(abs_time);
            int const res=pthread_mutex_timedlock(&m,&timeout);
            BOOST_ASSERT(!res || res==ETIMEDOUT);
            return !res;
        }

        typedef pthread_mutex_t* native_handle_type;
        native_handle_type native_handle()
        {
            return &m;
        }

#else
        void lock()
        {
            boost::pthread::pthread_mutex_scoped_lock const local_lock(&m);
            while(is_locked)
            {
                BOOST_VERIFY(!pthread_cond_wait(&cond,&m));
            }
            is_locked=true;
        }

        void unlock()
        {
            boost::pthread::pthread_mutex_scoped_lock const local_lock(&m);
            is_locked=false;
            BOOST_VERIFY(!pthread_cond_signal(&cond));
        }

        bool try_lock()
        {
            boost::pthread::pthread_mutex_scoped_lock const local_lock(&m);
            if(is_locked)
            {
                return false;
            }
            is_locked=true;
            return true;
        }

        bool timed_lock(system_time const & abs_time)
        {
            struct timespec const timeout=detail::get_timespec(abs_time);
            boost::pthread::pthread_mutex_scoped_lock const local_lock(&m);
            while(is_locked)
            {
                int const cond_res=pthread_cond_timedwait(&cond,&m,&timeout);
                if(cond_res==ETIMEDOUT)
                {
                    return false;
                }
                BOOST_ASSERT(!cond_res);
            }
            is_locked=true;
            return true;
        }
#endif

        typedef unique_lock<timed_mutex> scoped_timed_lock;
        typedef detail::try_lock_wrapper<timed_mutex> scoped_try_lock;
        typedef scoped_timed_lock scoped_lock;
    };

}

#include <boost/config/abi_suffix.hpp>

#endif
<|endoftext|>


<commit_before>#include "fastlib/fastlib.h"

#define A 1

#define epsilon 1e-4

void save_correctly(const char *filename, Matrix a) {
  Matrix a_transpose;
  la::TransposeInit(a, &a_transpose);
  data::Save(filename, a_transpose);
}

void rand_vector(Vector &v) {

  index_t d = v.length();
  v.SetZero();

  for(index_t i = 0; i+1 < d; i+=2) {
    double a = drand48();
    double b = drand48();
    double first_term = sqrt(-2 * log(a));
    double second_term = 2 * M_PI * b;
    v[i] =   first_term * cos(second_term);
    v[i+1] = first_term * sin(second_term);
  }

  if((d % 2) == 1) {
    v[d - 1] = sqrt(-2 * log(drand48())) * cos(2 * M_PI * drand48());
  }

  la::Scale(1/sqrt(la::Dot(v, v)), &v);

}

void center(Matrix X, Matrix &X_centered) {
  Vector col_vector_sum;
  col_vector_sum.Init(X.n_rows());
  col_vector_sum.SetZero();

  index_t n = X.n_cols();

  for(index_t i = 0; i < n; i++) {
    Vector cur_col_vector;
    X.MakeColumnVector(i, &cur_col_vector);
    la::AddTo(cur_col_vector, &col_vector_sum);
  }

  la::Scale(1/(double)n, &col_vector_sum);

  X_centered.CopyValues(X);

  for(index_t i = 0; i < n; i++) {
    Vector cur_col_vector;
    X_centered.MakeColumnVector(i, &cur_col_vector);
    la::SubFrom(col_vector_sum, &cur_col_vector);
  }

}

void whiten(Matrix X, Matrix &whitening, Matrix &X_whitened) {
  Matrix X_transpose, X_cov, D, E, E_times_D;
  Vector D_vector;

  la::TransposeInit(X, &X_transpose);
  la::MulInit(X, X_transpose, &X_cov);

  la::Scale(1 / (double) (X.n_cols() - 1), &X_cov);

  X_cov.PrintDebug("X_cov");

  la::EigenvectorsInit(X_cov, &D_vector, &E);
  D.InitDiagonal(D_vector);

  index_t d = D.n_rows();
  for(index_t i = 0; i < d; i++) {
    D.set(i, i, pow(D.get(i, i), -.5));
  }

  la::MulInit(E, D, &E_times_D);
  la::MulTransBOverwrite(E_times_D, E, &whitening);

  la::MulOverwrite(whitening, X, &X_whitened);
}

void univariate_FastICA(Matrix X,
			double (*contrast_function)(double),
			Matrix fixed_subspace,
			index_t dim_num,
			double tolerance,
			Vector &w) {
  index_t n_fixed = dim_num;
  Vector w_old;
  index_t d = X.n_rows();
  index_t n = X.n_cols();
  rand_vector(w);

  w_old.Init(d);
  w_old.SetZero();

  bool converged = false;

  for(index_t epoch = 0; !converged; epoch++) {

    w.PrintDebug("w at beginning of epoch");

    printf("epoch %d\n", epoch);

    Vector first_sum;
    first_sum.Init(d);
    first_sum.SetZero();

    Vector tanh_dots;
    tanh_dots.Init(n);

    for(index_t i = 0; i < n; i++) {
      Vector x;
      X.MakeColumnVector(i, &x);
      tanh_dots[i] = contrast_function(la::Dot(w, x));
      //printf("%f\t", tanh_dots[i]);
      la::AddExpert(tanh_dots[i], x, &first_sum);
    }

    //first_sum.PrintDebug("first_sum");

    la::Scale((double)1/(double)n, &first_sum);

    printf("first_sum: %f %f\n", first_sum[0], first_sum[1]);

    double second_sum = 0;
    for(index_t i = 0; i < n; i++) {
      second_sum += A * (1 - (tanh_dots[i] * tanh_dots[i]));
    }
    la::Scale(-second_sum/(double)n, &w);

    printf("second_sum: %f\n", second_sum / (double)n);

    w.PrintDebug("w before adding first_sum");

    la::AddTo(first_sum, &w);

    w.PrintDebug("w after adding first_sum");

    // normalize
    la::Scale(1/sqrt(la::Dot(w, w)), &w);

    w.PrintDebug("before correction");

    // make orthogonal to fixed_subspace

    for(index_t i = 0; i < n_fixed; i++) {
      Vector w_i;
      fixed_subspace.MakeColumnVector(i, &w_i);

      la::AddExpert(-la::Dot(w_i, w), w_i, &w);

    }

    // normalize
    la::Scale(1/sqrt(la::Dot(w, w)), &w);

    w.PrintDebug("after correction");

    // check for convergence

    Vector w_diff;
    la::SubInit(w_old, w, &w_diff);

    if(la::Dot(w_diff, w_diff) < epsilon) {
      converged = true;
    }
    else {
      la::AddOverwrite(w_old, w, &w_diff);

      if(la::Dot(w_diff, w_diff) < epsilon) {
	converged = true;
      }
    }

    w_old.CopyValues(w);

  }

}

void deflationICA(Matrix X,
		  double (*contrast_function)(double),
		  double tolerance, Matrix &fixed_subspace) {
  index_t d = X.n_rows();

  printf("d = %d\n", d);

  for(index_t i = 0; i < d; i++) {
    printf("i = %d\n", i);
    Vector w;
    w.Init(d);
    univariate_FastICA(X, contrast_function, fixed_subspace, i, tolerance, w);
    Vector fixed_subspace_vector_i;
    fixed_subspace.MakeColumnVector(i, &fixed_subspace_vector_i);
    fixed_subspace_vector_i.CopyValues(w);
  }

  // fixed_subspace is the transpose of the postwhitening unmixing matrix W~
  // saving fixed_subspace really saves the transpose, so we simply save
  data::Save("fixed_subspace.dat", fixed_subspace);

}

double d_logcosh(double u) {
  return tanh(A * u);
}

double d_exp(double u) {
  return u * exp(-u*u/2);
}

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

  srand48(time(0));

  const char *data = fx_param_str(NULL, "data", NULL);

  Matrix X, X_centered, whitening, X_whitened;
  data::Load(data, &X);

  index_t d = X.n_rows(); // number of dimensions
  index_t n = X.n_cols(); // number of points

  X_centered.Init(d, n);
  X_whitened.Init(d, n);
  whitening.Init(d, d);

  printf("%d,%d\n", X.n_rows(), X.n_cols());

  printf("centering\n");
  center(X, X_centered);

  printf("whitening\n");

  whiten(X_centered, whitening, X_whitened);

  double tolerance = 1e-4;

  Matrix post_whitening_W_transpose;
  post_whitening_W_transpose.Init(d, d);

  printf("deflationICA\n");

  deflationICA(X_whitened, &d_logcosh, tolerance, post_whitening_W_transpose);

  Matrix post_whitening_W;
  la::TransposeInit(post_whitening_W_transpose, &post_whitening_W);

  Matrix W;
  la::MulInit(post_whitening_W, whitening, &W);

  Matrix Y;
  la::MulInit(post_whitening_W, X_whitened, &Y);

  save_correctly("post_whitening_W.dat", post_whitening_W);
  save_correctly("whitening.dat", whitening);

  save_correctly("W.dat", W);

  save_correctly("X_centered.dat", X_centered);
  save_correctly("X_whitened.dat", X_whitened);
  save_correctly("Y.dat", Y);

  //  fx_done();

  return 0;
}
<commit_msg>updated niche/fastica<commit_after>#include "fastlib/fastlib.h"

#define A 1

#define epsilon 1e-4

#define LOGCOSH 0
#define EXP 1

// n indicates number of points
// d indicates number of dimensions (number of components or variables)

namespace {

  void SaveCorrectly(const char *filename, Matrix a) {
    Matrix a_transpose;
    la::TransposeInit(a, &a_transpose);
    data::Save(filename, a_transpose);
  }

  void RandVector(Vector &v) {

    index_t d = v.length();
    v.SetZero();

    for(index_t i = 0; i+1 < d; i+=2) {
      double a = drand48();
      double b = drand48();
      double first_term = sqrt(-2 * log(a));
      double second_term = 2 * M_PI * b;
      v[i] =   first_term * cos(second_term);
      v[i+1] = first_term * sin(second_term);
    }

    if((d % 2) == 1) {
      v[d - 1] = sqrt(-2 * log(drand48())) * cos(2 * M_PI * drand48());
    }

    la::Scale(1/sqrt(la::Dot(v, v)), &v);

  }

  void Center(Matrix X, Matrix &X_centered) {
    Vector col_vector_sum;
    col_vector_sum.Init(X.n_rows());
    col_vector_sum.SetZero();

    index_t n = X.n_cols();

    for(index_t i = 0; i < n; i++) {
      Vector cur_col_vector;
      X.MakeColumnVector(i, &cur_col_vector);
      la::AddTo(cur_col_vector, &col_vector_sum);
    }

    la::Scale(1/(double)n, &col_vector_sum);

    X_centered.CopyValues(X);

    for(index_t i = 0; i < n; i++) {
      Vector cur_col_vector;
      X_centered.MakeColumnVector(i, &cur_col_vector);
      la::SubFrom(col_vector_sum, &cur_col_vector);
    }

  }

  void Whiten(Matrix X, Matrix &whitening, Matrix &X_whitened) {
    Matrix X_transpose, X_cov, D, E, E_times_D;
    Vector D_vector;

    la::TransposeInit(X, &X_transpose);
    la::MulInit(X, X_transpose, &X_cov);

    la::Scale(1 / (double) (X.n_cols() - 1), &X_cov);

    X_cov.PrintDebug("X_cov");

    la::EigenvectorsInit(X_cov, &D_vector, &E);
    D.InitDiagonal(D_vector);

    index_t d = D.n_rows();
    for(index_t i = 0; i < d; i++) {
      D.set(i, i, pow(D.get(i, i), -.5));
    }

    la::MulInit(E, D, &E_times_D);
    la::MulTransBOverwrite(E_times_D, E, &whitening);

    la::MulOverwrite(whitening, X, &X_whitened);
  }

  void UnivariateFastICA(Matrix X, int contrast_type, Matrix fixed_subspace,
			 index_t dim_num, double tolerance, Vector &w) {
    index_t d = X.n_rows();
    index_t n = X.n_cols();

    RandVector(w);

    Vector w_old;
    w_old.Init(d);
    w_old.SetZero();

    bool converged = false;

    for(index_t epoch = 0; !converged; epoch++) {

      printf("\nEPOCH %"LI"d\n", epoch);

      w.PrintDebug("w at beginning of epoch");

      Vector first_sum;
      first_sum.Init(d);
      first_sum.SetZero();

      double second_sum = 0;

      if(contrast_type == LOGCOSH) {

	Vector first_deriv_dots;
	first_deriv_dots.Init(n);

	for(index_t i = 0; i < n; i++) {
	  Vector x;
	  X.MakeColumnVector(i, &x);
	  first_deriv_dots[i] = tanh(A * la::Dot(w, x));
	  la::AddExpert(first_deriv_dots[i], x, &first_sum);
	}
	la::Scale(1/(double)n, &first_sum);

	for(index_t i = 0; i < n; i++) {
	  second_sum += first_deriv_dots[i] * first_deriv_dots[i];
	}

	second_sum *= A / (double) n;
	second_sum -= A;

      }
      else if(contrast_type == EXP) {

	Vector dots;
	Vector exp_dots;
	dots.Init(n);
	exp_dots.Init(n);

	for(index_t i = 0; i < n; i++) {
	  Vector x;
	  X.MakeColumnVector(i, &x);

	  double dot = la::Dot(w, x);
	  dots[i] = dot;
	  exp_dots[i] = exp(-dot * dot/2);

	  la::AddExpert(dot * exp_dots[i], x, &first_sum);
	}
	la::Scale(1/(double)n, &first_sum);

	for(index_t i = 0; i < n; i++) {
	  second_sum += exp_dots[i] * (dots[i] * dots[i] - 1);
	}

	second_sum /= (double) n;

      }
      else {
	printf("ERROR: invalid contrast function: contrast_type = %d\n",
	       contrast_type);
	exit(SUCCESS_FAIL);
      }

      la::Scale(second_sum, &w);
      la::AddTo(first_sum, &w);

      first_sum.PrintDebug("first_sum");
      printf("second_sum = %f\n", second_sum);

      // normalize
      la::Scale(1/sqrt(la::Dot(w, w)), &w);

      w.PrintDebug("before correction");

      // make orthogonal to fixed_subspace

      for(index_t i = 0; i < dim_num; i++) {
	Vector w_i;
	fixed_subspace.MakeColumnVector(i, &w_i);

	la::AddExpert(-la::Dot(w_i, w), w_i, &w);

      }

      // normalize
      la::Scale(1/sqrt(la::Dot(w, w)), &w);

      w.PrintDebug("after correction");

      // check for convergence

      Vector w_diff;
      la::SubInit(w_old, w, &w_diff);

      if(la::Dot(w_diff, w_diff) < epsilon) {
	converged = true;
      }
      else {
	la::AddOverwrite(w_old, w, &w_diff);

	if(la::Dot(w_diff, w_diff) < epsilon) {
	  converged = true;
	}
      }

      w_old.CopyValues(w);

    }

  }

  void DeflationICA(Matrix X, int contrast_type,
		     double tolerance, Matrix &fixed_subspace) {
    index_t d = X.n_rows();

    printf("%"LI"d Components\n", d);

    for(index_t i = 0; i < d; i++) {
      printf("\n\nExtracting component %"LI"d\n", i);
      Vector w;
      w.Init(d);
      UnivariateFastICA(X, contrast_type, fixed_subspace, i, tolerance, w);
      Vector fixed_subspace_vector_i;
      fixed_subspace.MakeColumnVector(i, &fixed_subspace_vector_i);
      fixed_subspace_vector_i.CopyValues(w);
    }

  }

  double DLogCosh(double u) {
    return tanh(A * u);
  }

  double DExp(double u) {
    return u * exp(-u*u/2);
  }

}

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

  srand48(time(0));

  const char *data = fx_param_str(NULL, "data", NULL);

  Matrix X, X_centered, whitening, X_whitened;
  data::Load(data, &X);

  index_t d = X.n_rows(); // number of dimensions
  index_t n = X.n_cols(); // number of points

  printf("d = %d, n = %d\n", d, n);

  X_centered.Init(d, n);
  X_whitened.Init(d, n);
  whitening.Init(d, d);

  printf("centering\n");
  Center(X, X_centered);

  printf("whitening\n");

  Whiten(X_centered, whitening, X_whitened);

  double tolerance = 1e-4;

  Matrix post_whitening_W_transpose;
  post_whitening_W_transpose.Init(d, d);

  printf("deflation ICA\n");

  DeflationICA(X_whitened, EXP, tolerance, post_whitening_W_transpose);

  Matrix post_whitening_W;
  la::TransposeInit(post_whitening_W_transpose, &post_whitening_W);

  Matrix W;
  la::MulInit(post_whitening_W, whitening, &W);

  Matrix Y;
  la::MulInit(post_whitening_W, X_whitened, &Y);

  SaveCorrectly("post_whitening_W.dat", post_whitening_W);
  SaveCorrectly("whitening.dat", whitening);

  SaveCorrectly("W.dat", W);

  SaveCorrectly("X_centered.dat", X_centered);
  SaveCorrectly("X_whitened.dat", X_whitened);
  SaveCorrectly("Y.dat", Y);

  //  fx_done();

  return 0;
}
<|endoftext|>