<commit_before>#include <rpp/sockets.h>
#include <rpp/tests.h>
#include <thread>

using std::thread;
using namespace rpp;
using Socket = rpp::socket;

TestImpl(test_sockets)
{
    //////////////////////////////////////////////////////////////////

    TestInit(test_sockets) {}

    TestCase(udp_socket_options)
    {
        Socket sock = rpp::make_udp_randomport();
        AssertFalse(sock.is_blocking()); // should be false by default
        AssertTrue(sock.is_nodelay()); // should be nodelay by default

        Assert(sock.set_blocking(true));
        Assert(sock.is_blocking());

        AssertFalse(sock.set_nagle(true)); // cannot set nagle on UDP socket
        AssertTrue(sock.is_nodelay()); // UDP is always nodelay

        print_info("default UDP SO_RCVBUF: %d\n", sock.get_rcv_buf_size());
        print_info("default UDP SO_SNDBUF: %d\n", sock.get_snd_buf_size());

        // NOTE: if there is a mismatch here, then some unix-like kernel didn't double the buffer
        //       which is expected behaviour on non-windows platforms
        Assert(sock.set_snd_buf_size(16384));
        AssertThat(sock.get_snd_buf_size(), 16384);

        Assert(sock.set_rcv_buf_size(32768));
        AssertThat(sock.get_rcv_buf_size(), 32768);

        // check UDP noblock delay, it cannot affect NAGLE
        sock.set_noblock_nodelay();
        AssertFalse(sock.is_blocking());
        AssertTrue(sock.is_nodelay());
    }

    TestCase(tcp_socket_options)
    {
        Socket sock = rpp::make_tcp_randomport();
        AssertFalse(sock.is_blocking()); // should be false by default
        AssertTrue(sock.is_nodelay()); // should be nodelay by default

        Assert(sock.set_blocking(true));
        Assert(sock.is_blocking());

        Assert(sock.set_nagle(true));
        AssertFalse(sock.is_nodelay());

        print_info("default TCP SO_RCVBUF: %d\n", sock.get_rcv_buf_size());
        print_info("default TCP SO_SNDBUF: %d\n", sock.get_snd_buf_size());

        // NOTE: if there is a mismatch here, then some unix-like kernel didn't double the buffer
        //       which is expected behaviour on non-windows platforms
        Assert(sock.set_snd_buf_size(16384));
        AssertThat(sock.get_snd_buf_size(), 16384);

        Assert(sock.set_rcv_buf_size(32768));
        AssertThat(sock.get_rcv_buf_size(), 32768);

        // check TCP noblock delay, it cannot affect NAGLE
        sock.set_noblock_nodelay();
        AssertFalse(sock.is_blocking());
        AssertTrue(sock.is_nodelay());
    }

    TestCase(socket_udp_send_receive)
    {
        vector<uint8_t> msg(4000, 'x');
        Socket send = rpp::make_udp_randomport();
        Socket recv = rpp::make_udp_randomport();
        AssertFalse(send.is_blocking()); // should be false by default
        AssertFalse(recv.is_blocking()); // should be false by default

        auto recv_addr = ipaddress(AF_IPv4, "127.0.0.1", recv.port());
        AssertThat(send.sendto(recv_addr, msg), (int)msg.size());

        vector<uint8_t> buf;
        Assert(recv.recv(buf));

        AssertThat(send.sendto(recv_addr, msg), (int)msg.size());
        AssertThat(send.sendto(recv_addr, msg), (int)msg.size());

        Assert(recv.recv(buf));
        AssertThat(buf, msg);

        Assert(recv.recv(buf));
        AssertThat(buf, msg);
    }

    TestCase(udp_select)
    {
        Socket send = rpp::make_udp_randomport();
        Socket recv = rpp::make_udp_randomport();
        AssertFalse(send.is_blocking()); // should be false by default
        AssertFalse(recv.is_blocking()); // should be false by default
        auto recv_addr = ipaddress(AF_IPv4, "127.0.0.1", recv.port());

        // no data to receive, should return false
        AssertFalse(recv.select(100, rpp::socket::SF_Read));
        send.sendto(recv_addr, "udp_select");

        // must be ready to receive
        AssertTrue(recv.select(100, rpp::socket::SF_Read));
        AssertThat(recv.recv_str(), "udp_select");

        // no data to receive, should return false
        AssertFalse(recv.select(100, rpp::socket::SF_Read));
    }

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

    Socket create(std::string msg, Socket&& s)
    {
        AssertMsg(s.good(), "expected good() for '%s'", msg.c_str());
        AssertMsg(s.connected(), "expected connected() for '%s'", msg.c_str());
        if (!s.good() || !s.connected())
            print_error("%s %s socket error: %s\n", msg.c_str(), s.name().c_str(), s.last_err().c_str());
        else
            print_info("%s %s\n", msg.c_str(), s.name().c_str());
        return std::move(s);
    }
    Socket listen(int port)
    {
        return create("server: listening on " + std::to_string(port), Socket::listen_to(port));
    }
    Socket accept(const Socket& server)
    {
        return create("server: accepted client", server.accept(5000/*ms*/));
    }
    Socket connect(std::string ip, int port)
    {
        return create("remote: connected to "+ip+":"+std::to_string(port),
                      Socket::connect_to(ip.c_str(), port, 5000/*ms*/, AF_IPv4));
    }

    /**
     * This test simulates a very simple client - server setup
     */
    TestCase(nonblocking_sockets)
    {
        Socket server = listen(13337); // this is our server
        thread remote([=] { nonblocking_remote(13337); }); // spawn remote client
        Socket client = accept(server);

        // wait 1ms for a client that will never come
        Socket failClient = server.accept(1);
        Assert(failClient.bad());

        std::string msg = "Server says: Hello!";
        print_info("server: sending '%s'\n", msg.c_str());
        client.send(msg);
        sleep(100);

        string resp = client.recv_str();
        print_info("server: received '%s'\n", resp.c_str());
        AssertNotEqual(resp, "");
        sleep(50);

        print_info("server: closing down\n");
        client.close();
        server.close();
        remote.join(); // wait for remote thread to finish
    }

    void nonblocking_remote(int serverPort) // simulated remote endpoint
    {
        int receivedMessages = 0;
        Socket server = connect("127.0.0.1", serverPort);
        while (server.connected())
        {
            string resp = server.recv_str();
            if (resp != "")
            {
                print_info("remote: received '%s'\n", resp.c_str());
                Assert(server.send("Client says: Thanks!") > 0);
                ++receivedMessages;
                sleep(10);
            }
            //sleep(0);
        }
        AssertThat(receivedMessages, 1);
        print_info("remote: server disconnected: %s\n", server.last_err().c_str());
        print_info("remote: closing down\n");
    }

    static constexpr int TransmitSize = 80000;
    TestCase(transmit_data)
    {
        print_info("========= TRANSMIT DATA =========\n");

        Socket server = listen(14447);
        thread remote([=] { this->transmitting_remote(14447); });
        Socket client = accept(server);
        client.set_rcv_buf_size(TransmitSize*2);

        for (int i = 0; i < 20; ++i)
        {
            string data = client.recv_str();
            if (data != "")
            {
                print_info("server: received %d bytes of data from client ", (int)data.length());
                AssertThat(data.size(), TransmitSize);

                size_t j = 0;
                for (; j < data.length(); ++j)
                {
                    if (data[j] != '$')
                    {
                        print_info("(corrupted at position %d):\n", (int)j);
                        print_info("%.*s\n", 10, &data[j]);
                        print_info("^\n");
                        break;
                    }
                }
                if (j == data.length()) {
                    print_info("(valid)\n");
                }
            }
            sleep(5);
        }

        print_info("server: closing down\n");
        client.close();
        server.close();
        remote.join();
    }

    void transmitting_remote(int serverPort)
    {
        std::vector<char> sendBuffer(TransmitSize, '$');

        Socket server = connect("127.0.0.1", serverPort);
        server.set_snd_buf_size(TransmitSize*2);

        while (server.connected())
        {
            int sentBytes = server.send(sendBuffer.data(), (int)sendBuffer.size());
            if (sentBytes > 0)
                print_info("remote: sent %d bytes of data\n", sentBytes);
            else
                print_info("remote: failed to send data: %s\n", Socket::last_err().c_str());

            // we need to create a large gap in the data
            sleep(15);
        }
        print_info("remote: server disconnected\n");
        print_info("remote: closing down\n");
    }
};
<commit_msg>Set transmit_data packet size to common UDP max MTU<commit_after>#include <rpp/sockets.h>
#include <rpp/tests.h>
#include <thread>

using std::thread;
using namespace rpp;
using Socket = rpp::socket;

TestImpl(test_sockets)
{
    //////////////////////////////////////////////////////////////////

    TestInit(test_sockets) {}

    TestCase(udp_socket_options)
    {
        Socket sock = rpp::make_udp_randomport();
        AssertFalse(sock.is_blocking()); // should be false by default
        AssertTrue(sock.is_nodelay()); // should be nodelay by default

        Assert(sock.set_blocking(true));
        Assert(sock.is_blocking());

        AssertFalse(sock.set_nagle(true)); // cannot set nagle on UDP socket
        AssertTrue(sock.is_nodelay()); // UDP is always nodelay

        print_info("default UDP SO_RCVBUF: %d\n", sock.get_rcv_buf_size());
        print_info("default UDP SO_SNDBUF: %d\n", sock.get_snd_buf_size());

        // NOTE: if there is a mismatch here, then some unix-like kernel didn't double the buffer
        //       which is expected behaviour on non-windows platforms
        Assert(sock.set_snd_buf_size(16384));
        AssertThat(sock.get_snd_buf_size(), 16384);

        Assert(sock.set_rcv_buf_size(32768));
        AssertThat(sock.get_rcv_buf_size(), 32768);

        // check UDP noblock delay, it cannot affect NAGLE
        sock.set_noblock_nodelay();
        AssertFalse(sock.is_blocking());
        AssertTrue(sock.is_nodelay());
    }

    TestCase(tcp_socket_options)
    {
        Socket sock = rpp::make_tcp_randomport();
        AssertFalse(sock.is_blocking()); // should be false by default
        AssertTrue(sock.is_nodelay()); // should be nodelay by default

        Assert(sock.set_blocking(true));
        Assert(sock.is_blocking());

        Assert(sock.set_nagle(true));
        AssertFalse(sock.is_nodelay());

        print_info("default TCP SO_RCVBUF: %d\n", sock.get_rcv_buf_size());
        print_info("default TCP SO_SNDBUF: %d\n", sock.get_snd_buf_size());

        // NOTE: if there is a mismatch here, then some unix-like kernel didn't double the buffer
        //       which is expected behaviour on non-windows platforms
        Assert(sock.set_snd_buf_size(16384));
        AssertThat(sock.get_snd_buf_size(), 16384);

        Assert(sock.set_rcv_buf_size(32768));
        AssertThat(sock.get_rcv_buf_size(), 32768);

        // check TCP noblock delay, it cannot affect NAGLE
        sock.set_noblock_nodelay();
        AssertFalse(sock.is_blocking());
        AssertTrue(sock.is_nodelay());
    }

    TestCase(socket_udp_send_receive)
    {
        vector<uint8_t> msg(4000, 'x');
        Socket send = rpp::make_udp_randomport();
        Socket recv = rpp::make_udp_randomport();
        AssertFalse(send.is_blocking()); // should be false by default
        AssertFalse(recv.is_blocking()); // should be false by default

        auto recv_addr = ipaddress(AF_IPv4, "127.0.0.1", recv.port());
        AssertThat(send.sendto(recv_addr, msg), (int)msg.size());

        vector<uint8_t> buf;
        Assert(recv.recv(buf));

        AssertThat(send.sendto(recv_addr, msg), (int)msg.size());
        AssertThat(send.sendto(recv_addr, msg), (int)msg.size());

        Assert(recv.recv(buf));
        AssertThat(buf, msg);

        Assert(recv.recv(buf));
        AssertThat(buf, msg);
    }

    TestCase(udp_select)
    {
        Socket send = rpp::make_udp_randomport();
        Socket recv = rpp::make_udp_randomport();
        AssertFalse(send.is_blocking()); // should be false by default
        AssertFalse(recv.is_blocking()); // should be false by default
        auto recv_addr = ipaddress(AF_IPv4, "127.0.0.1", recv.port());

        // no data to receive, should return false
        AssertFalse(recv.select(100, rpp::socket::SF_Read));
        send.sendto(recv_addr, "udp_select");

        // must be ready to receive
        AssertTrue(recv.select(100, rpp::socket::SF_Read));
        AssertThat(recv.recv_str(), "udp_select");

        // no data to receive, should return false
        AssertFalse(recv.select(100, rpp::socket::SF_Read));
    }

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

    Socket create(std::string msg, Socket&& s)
    {
        AssertMsg(s.good(), "expected good() for '%s'", msg.c_str());
        AssertMsg(s.connected(), "expected connected() for '%s'", msg.c_str());
        if (!s.good() || !s.connected())
            print_error("%s %s socket error: %s\n", msg.c_str(), s.name().c_str(), s.last_err().c_str());
        else
            print_info("%s %s\n", msg.c_str(), s.name().c_str());
        return std::move(s);
    }
    Socket listen(int port)
    {
        return create("server: listening on " + std::to_string(port), Socket::listen_to(port));
    }
    Socket accept(const Socket& server)
    {
        return create("server: accepted client", server.accept(5000/*ms*/));
    }
    Socket connect(std::string ip, int port)
    {
        return create("remote: connected to "+ip+":"+std::to_string(port),
                      Socket::connect_to(ip.c_str(), port, 5000/*ms*/, AF_IPv4));
    }

    /**
     * This test simulates a very simple client - server setup
     */
    TestCase(nonblocking_sockets)
    {
        Socket server = listen(13337); // this is our server
        thread remote([=] { nonblocking_remote(13337); }); // spawn remote client
        Socket client = accept(server);

        // wait 1ms for a client that will never come
        Socket failClient = server.accept(1);
        Assert(failClient.bad());

        std::string msg = "Server says: Hello!";
        print_info("server: sending '%s'\n", msg.c_str());
        client.send(msg);
        sleep(100);

        string resp = client.recv_str();
        print_info("server: received '%s'\n", resp.c_str());
        AssertNotEqual(resp, "");
        sleep(50);

        print_info("server: closing down\n");
        client.close();
        server.close();
        remote.join(); // wait for remote thread to finish
    }

    void nonblocking_remote(int serverPort) // simulated remote endpoint
    {
        int receivedMessages = 0;
        Socket server = connect("127.0.0.1", serverPort);
        while (server.connected())
        {
            string resp = server.recv_str();
            if (resp != "")
            {
                print_info("remote: received '%s'\n", resp.c_str());
                Assert(server.send("Client says: Thanks!") > 0);
                ++receivedMessages;
                sleep(10);
            }
            //sleep(0);
        }
        AssertThat(receivedMessages, 1);
        print_info("remote: server disconnected: %s\n", server.last_err().c_str());
        print_info("remote: closing down\n");
    }

    // 65536 is the typical localhost MTU for datagrams
    static constexpr int TransmitSize = 65536;

    TestCase(transmit_data)
    {
        print_info("========= TRANSMIT DATA =========\n");

        Socket server = listen(14447);
        thread remote([=] { this->transmitting_remote(14447); });
        Socket client = accept(server);
        client.set_rcv_buf_size(TransmitSize*2);

        for (int i = 0; i < 20; ++i)
        {
            string data = client.recv_str();
            if (data != "")
            {
                print_info("server: received %d bytes of data from client ", (int)data.length());
                AssertThat(data.size(), TransmitSize);

                size_t j = 0;
                for (; j < data.length(); ++j)
                {
                    if (data[j] != '$')
                    {
                        print_info("(corrupted at position %d):\n", (int)j);
                        print_info("%.*s\n", 10, &data[j]);
                        print_info("^\n");
                        break;
                    }
                }
                if (j == data.length()) {
                    print_info("(valid)\n");
                }
            }
            sleep(5);
        }

        print_info("server: closing down\n");
        client.close();
        server.close();
        remote.join();
    }

    void transmitting_remote(int serverPort)
    {
        std::vector<char> sendBuffer(TransmitSize, '$');

        Socket server = connect("127.0.0.1", serverPort);
        server.set_snd_buf_size(TransmitSize*2);

        while (server.connected())
        {
            int sentBytes = server.send(sendBuffer.data(), (int)sendBuffer.size());
            if (sentBytes > 0)
                print_info("remote: sent %d bytes of data\n", sentBytes);
            else
                print_info("remote: failed to send data: %s\n", Socket::last_err().c_str());

            // we need to create a large gap in the data
            sleep(15);
        }
        print_info("remote: server disconnected\n");
        print_info("remote: closing down\n");
    }
};
<|endoftext|>


<commit_before>#include <iostream>
#include <algorithm>
#include <iterator>
#include <ctime>
#include <typeinfo>

#include <boost/random.hpp>
#include <boost/generator_iterator.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/algorithm/string.hpp>

#include "mongoose.h"
#include "json.hpp"

#include "nanocube.h"
#include "nanocube_traversals.h"

using json = nlohmann::json;

static const char *s_http_port = "8000";
static struct mg_serve_http_opts s_http_server_opts;

static int qtreeLevel = 10;
static vector<int> schema = {qtreeLevel*2, qtreeLevel*2};
static Nanocube<int> nc(schema);
static vector<pair<int64_t,int64_t> > dataarray;

// convert lat,lon to quad tree address
static int64_t loc2addr(double lat, double lon, int qtreeLevel)
{
  double xd = (lon + M_PI) / (2.0 * M_PI);
  double yd = (log(tan(M_PI / 4.0 + lat / 2.0)) + M_PI) / (2.0 * M_PI);
  //cout << lat << " " << lon << " " << endl;
  int x = xd * (1 << qtreeLevel), y = yd * (1 << qtreeLevel);

  int64_t z = 0; // z gets the resulting Morton Number.

  for (int i = 0; i < sizeof(x) * 8; i++) {// unroll for more speed...
    z |= (x & 1U << i) << i | (y & 1U << i) << (i + 1);
  }

  return z;
}

static void buildCubes()
{
  cout << "Start building Nanocubes..." << endl;
  using namespace boost::gregorian;
  using namespace boost::posix_time;

  ifstream is("../sample_data/flights_100K.csv.txt");
  string s;

  int i = 0;

  while(std::getline(is, s)) {
    vector<string> output;
    boost::split(output,s,boost::is_any_of("\t"));
    if (output.size() != 4) {
      cerr << "Bad line:" << s << endl;
      continue;
    }

    double ori_lat = atof(output[0].c_str()) * M_PI / 180.0;
    double ori_lon = atof(output[1].c_str()) * M_PI / 180.0;
    double des_lat = atof(output[2].c_str()) * M_PI / 180.0;
    double des_lon = atof(output[3].c_str()) * M_PI / 180.0;

    if(ori_lat > 85.0511 || ori_lat < -85.0511 ||
        des_lat > 85.0511 || des_lat < -85.0511 ) {
      cerr << "Invalid latitude: " << ori_lat << ", " << des_lat;
      cerr << " (should be in [-85.0511, 85.0511])" << endl;
      continue;
    }

    int64_t d1 = loc2addr(ori_lat, ori_lon, qtreeLevel);
    int64_t d2 = loc2addr(des_lat, des_lon, qtreeLevel);

    nc.insert(1, {d1, d2});
    dataarray.push_back({d1,d2});

    if (++i % 10000 == 0) {
      //nc.report_size();
      cout << i << endl;
    }
  }
}

static void handle_sum_call(struct mg_connection *c, struct http_message *hm) {

  json q = json::parse(string(hm->body.p, hm->body.len));
  cout << q.dump(2) << endl;
  json result = NCQuery(q, nc);
  cout << result.dump(2) << endl;

  /* Send result */
  mg_printf(c, "%s", "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n");
  mg_printf_http_chunk(c, "{\"result\": %s}", result.dump().c_str());
  mg_send_http_chunk(c, "", 0); /* Send empty chunk, the end of response */
}

static void ev_handler(struct mg_connection *c, int ev, void *ev_data) {
  struct http_message *hm = (struct http_message *) ev_data;

  switch (ev) {
    case MG_EV_HTTP_REQUEST:
      if (mg_vcmp(&hm->uri, "/query") == 0) {
        handle_sum_call(c, hm); /* Handle RESTful call */
      }
      else {
        mg_serve_http(c, hm, s_http_server_opts); /* Serve static content */
      }
      break;
    default:
      break;
  }
}

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

  struct mg_mgr mgr;
  struct mg_connection *c;

  mg_mgr_init(&mgr, NULL);
  c = mg_bind(&mgr, s_http_port, ev_handler);
  mg_set_protocol_http_websocket(c);

  s_http_server_opts.document_root = "..";  // Serve parent directory
  s_http_server_opts.enable_directory_listing = "yes";

  // build Gaussian Cubes
  buildCubes();

  printf("Starting server on port %s, serving %s\n", s_http_port,
         s_http_server_opts.document_root);

  for (;;) {
    mg_mgr_poll(&mgr, 1000);
  }

  mg_mgr_free(&mgr);

  return 0;
}
<commit_msg>code cleaning<commit_after>#include <iostream>
#include <algorithm>
#include <iterator>
#include <ctime>
#include <typeinfo>

#include <boost/random.hpp>
#include <boost/generator_iterator.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/algorithm/string.hpp>

#include "mongoose.h"
#include "json.hpp"

#include "nanocube.h"
#include "nanocube_traversals.h"

using json = nlohmann::json;

static const char *s_http_port = "8000";
static struct mg_serve_http_opts s_http_server_opts;

static int qtreeLevel = 10;
static vector<int> schema = {qtreeLevel*2, qtreeLevel*2};
static Nanocube<int> nc(schema);
static vector<pair<int64_t,int64_t> > dataarray;

// convert lat,lon to quad tree address
int64_t loc2addr(double lat, double lon, int qtreeLevel)
{
  double xd = (lon + M_PI) / (2.0 * M_PI);
  double yd = (log(tan(M_PI / 4.0 + lat / 2.0)) + M_PI) / (2.0 * M_PI);
  //cout << lat << " " << lon << " " << endl;
  int x = xd * (1 << qtreeLevel), y = yd * (1 << qtreeLevel);

  int64_t z = 0; // z gets the resulting Morton Number.

  for (int i = 0; i < sizeof(x) * 8; i++) {// unroll for more speed...
    z |= (x & 1U << i) << i | (y & 1U << i) << (i + 1);
  }

  return z;
}

void buildCubes()
{
  cout << "Start building Nanocubes..." << endl;
  using namespace boost::gregorian;
  using namespace boost::posix_time;

  ifstream is("../sample_data/flights_100K.csv.txt");
  string s;

  int i = 0;

  while(std::getline(is, s)) {
    vector<string> output;
    boost::split(output,s,boost::is_any_of("\t"));
    if (output.size() != 4) {
      cerr << "Bad line:" << s << endl;
      continue;
    }

    double ori_lat = atof(output[0].c_str()) * M_PI / 180.0;
    double ori_lon = atof(output[1].c_str()) * M_PI / 180.0;
    double des_lat = atof(output[2].c_str()) * M_PI / 180.0;
    double des_lon = atof(output[3].c_str()) * M_PI / 180.0;

    if(ori_lat > 85.0511 || ori_lat < -85.0511 ||
        des_lat > 85.0511 || des_lat < -85.0511 ) {
      cerr << "Invalid latitude: " << ori_lat << ", " << des_lat;
      cerr << " (should be in [-85.0511, 85.0511])" << endl;
      continue;
    }

    int64_t d1 = loc2addr(ori_lat, ori_lon, qtreeLevel);
    int64_t d2 = loc2addr(des_lat, des_lon, qtreeLevel);

    nc.insert(1, {d1, d2});
    dataarray.push_back({d1,d2});

    if (++i % 10000 == 0) {
      //nc.report_size();
      cout << i << endl;
    }
  }
}

static void handle_sum_call(struct mg_connection *c, struct http_message *hm) {

  json q = json::parse(string(hm->body.p, hm->body.len));
  cout << q.dump(2) << endl;
  json result = NCQuery(q, nc);
  cout << result.dump(2) << endl;

  /* Send result */
  mg_printf(c, "%s", "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n");
  mg_printf_http_chunk(c, "{\"result\": %s}", result.dump().c_str());
  mg_send_http_chunk(c, "", 0); /* Send empty chunk, the end of response */
}

static void ev_handler(struct mg_connection *c, int ev, void *ev_data) {
  struct http_message *hm = (struct http_message *) ev_data;

  switch (ev) {
    case MG_EV_HTTP_REQUEST:
      if (mg_vcmp(&hm->uri, "/query") == 0) {
        handle_sum_call(c, hm); /* Handle RESTful call */
      }
      else {
        mg_serve_http(c, hm, s_http_server_opts); /* Serve static content */
      }
      break;
    default:
      break;
  }
}

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

  struct mg_mgr mgr;
  struct mg_connection *c;

  mg_mgr_init(&mgr, NULL);
  c = mg_bind(&mgr, s_http_port, ev_handler);
  mg_set_protocol_http_websocket(c);

  s_http_server_opts.document_root = "..";  // Serve parent directory
  s_http_server_opts.enable_directory_listing = "yes";

  // build Gaussian Cubes
  buildCubes();

  printf("Starting server on port %s, serving %s\n", s_http_port,
         s_http_server_opts.document_root);

  for (;;) {
    mg_mgr_poll(&mgr, 1000);
  }

  mg_mgr_free(&mgr);

  return 0;
}
<|endoftext|>


<commit_before>#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/fb.h>
#include <sys/mman.h>
#include <sys/ioctl.h>

// STL includes
#include <iostream>

// Local includes
#include <grabber/FramebufferFrameGrabber.h>

FramebufferFrameGrabber::FramebufferFrameGrabber(const QString & device, const unsigned width, const unsigned height)
	: Grabber("FRAMEBUFFERGRABBER", width, height)
	, _fbfd(0)
	, _fbp(0)
	, _fbDevice()
{
	setDevicePath(device);
}

FramebufferFrameGrabber::~FramebufferFrameGrabber()
{
}

int FramebufferFrameGrabber::grabFrame(Image<ColorRgb> & image)
{
	if (!_enabled) return 0;

	struct fb_var_screeninfo vinfo;
	unsigned capSize, bytesPerPixel;
	PixelFormat pixelFormat;

	/* Open the framebuffer device */
	_fbfd = open(QSTRING_CSTR(_fbDevice), O_RDONLY);

	/* get variable screen information */
	ioctl (_fbfd, FBIOGET_VSCREENINFO, &vinfo);

	bytesPerPixel = vinfo.bits_per_pixel / 8;
	capSize = vinfo.xres * vinfo.yres * bytesPerPixel;

	switch (vinfo.bits_per_pixel)
	{
		case 16: pixelFormat = PIXELFORMAT_BGR16; break;
		case 24: pixelFormat = PIXELFORMAT_BGR24; break;
		case 32: pixelFormat = PIXELFORMAT_BGR32; break;
		default:
			Error(_log, "Unknown pixel format: %d bits per pixel", vinfo.bits_per_pixel);
			close(_fbfd);
			return -1;
	}

	/* map the device to memory */
	_fbp = (unsigned char*)mmap(0, capSize, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, _fbfd, 0);

	_imageResampler.setHorizontalPixelDecimation(vinfo.xres/_width);
	_imageResampler.setVerticalPixelDecimation(vinfo.yres/_height);
	_imageResampler.processImage(_fbp,
								vinfo.xres,
								vinfo.yres,
								vinfo.xres * bytesPerPixel,
								pixelFormat,
								image);

	munmap(_fbp, capSize);
	close(_fbfd);

	return 0;
}

void FramebufferFrameGrabber::setDevicePath(const QString& path)
{
	if(_fbDevice != path)
	{
		_fbDevice = path;
		int result;
		struct fb_var_screeninfo vinfo;

		// Check if the framebuffer device can be opened and display the current resolution
		_fbfd = open(QSTRING_CSTR(_fbDevice), O_RDONLY);
		if (_fbfd == 0)
		{
			Error(_log, "Error openning %s", QSTRING_CSTR(_fbDevice));
		}
		else
		{
			// get variable screen information
			result = ioctl (_fbfd, FBIOGET_VSCREENINFO, &vinfo);
			if (result != 0)
			{
				Error(_log, "Could not get screen information");
			}
			else
			{
				Info(_log, "Display opened with resolution: %dx%d@%dbit", vinfo.xres, vinfo.yres, vinfo.bits_per_pixel);
			}
			close(_fbfd);
		}

	}
}
<commit_msg>Fixed Amlogic framebuffer pixel format<commit_after>#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/fb.h>
#include <sys/mman.h>
#include <sys/ioctl.h>

// STL includes
#include <iostream>

// Local includes
#include <grabber/FramebufferFrameGrabber.h>

FramebufferFrameGrabber::FramebufferFrameGrabber(const QString & device, const unsigned width, const unsigned height)
	: Grabber("FRAMEBUFFERGRABBER", width, height)
	, _fbfd(0)
	, _fbp(0)
	, _fbDevice()
{
	setDevicePath(device);
}

FramebufferFrameGrabber::~FramebufferFrameGrabber()
{
}

int FramebufferFrameGrabber::grabFrame(Image<ColorRgb> & image)
{
	if (!_enabled) return 0;

	struct fb_var_screeninfo vinfo;
	unsigned capSize, bytesPerPixel;
	PixelFormat pixelFormat;

	/* Open the framebuffer device */
	_fbfd = open(QSTRING_CSTR(_fbDevice), O_RDONLY);

	/* get variable screen information */
	ioctl (_fbfd, FBIOGET_VSCREENINFO, &vinfo);

	bytesPerPixel = vinfo.bits_per_pixel / 8;
	capSize = vinfo.xres * vinfo.yres * bytesPerPixel;

	switch (vinfo.bits_per_pixel)
	{
		case 16: pixelFormat = PIXELFORMAT_BGR16; break;
		case 24: pixelFormat = PIXELFORMAT_BGR24; break;
#ifdef ENABLE_AMLOGIC
		case 32: pixelFormat = PIXELFORMAT_RGB32; break;
#else
		case 32: pixelFormat = PIXELFORMAT_BGR32; break;
#endif
		default:
			Error(_log, "Unknown pixel format: %d bits per pixel", vinfo.bits_per_pixel);
			close(_fbfd);
			return -1;
	}

	/* map the device to memory */
	_fbp = (unsigned char*)mmap(0, capSize, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, _fbfd, 0);

	_imageResampler.setHorizontalPixelDecimation(vinfo.xres/_width);
	_imageResampler.setVerticalPixelDecimation(vinfo.yres/_height);
	_imageResampler.processImage(_fbp,
								vinfo.xres,
								vinfo.yres,
								vinfo.xres * bytesPerPixel,
								pixelFormat,
								image);

	munmap(_fbp, capSize);
	close(_fbfd);

	return 0;
}

void FramebufferFrameGrabber::setDevicePath(const QString& path)
{
	if(_fbDevice != path)
	{
		_fbDevice = path;
		int result;
		struct fb_var_screeninfo vinfo;

		// Check if the framebuffer device can be opened and display the current resolution
		_fbfd = open(QSTRING_CSTR(_fbDevice), O_RDONLY);
		if (_fbfd == 0)
		{
			Error(_log, "Error openning %s", QSTRING_CSTR(_fbDevice));
		}
		else
		{
			// get variable screen information
			result = ioctl (_fbfd, FBIOGET_VSCREENINFO, &vinfo);
			if (result != 0)
			{
				Error(_log, "Could not get screen information");
			}
			else
			{
				Info(_log, "Display opened with resolution: %dx%d@%dbit", vinfo.xres, vinfo.yres, vinfo.bits_per_pixel);
			}
			close(_fbfd);
		}

	}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: svdmark.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2007-07-18 10:50:48 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SVDMARK_HXX
#define _SVDMARK_HXX

#ifndef _CONTNR_HXX //autogen
#include <tools/contnr.hxx>
#endif

#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif

#ifndef _LIST_HXX //autogen
#include <tools/list.hxx>
#endif

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

#ifndef _SDR_OBJECTUSER_HXX
#include <svx/sdrobjectuser.hxx>
#endif

#include <set>

class Rectangle;
class SdrPage;
class SdrObjList;
class SdrObject;
class SdrPageView;

// Ein Container fuer USHORTs (im Prinzip ein dynamisches Array)
class SVX_DLLPUBLIC SdrUShortCont
{
    Container                                           maArray;
    sal_Bool                                            mbSorted;

private:
    void CheckSort(ULONG nPos);

public:
    SdrUShortCont(sal_uInt16 nBlock, sal_uInt16 nInit, sal_uInt16 nResize)
    :   maArray(nBlock, nInit, nResize),
    mbSorted(sal_True)
    {}

    SdrUShortCont(const SdrUShortCont& rCont)
    :   maArray(rCont.maArray),
        mbSorted(rCont.mbSorted)
    {}

    /** helper to migrate to stl containers */
    std::set< sal_uInt16 > getContainer();

    SdrUShortCont& operator=(const SdrUShortCont& rCont)
    {
        maArray = rCont.maArray;
        mbSorted = rCont.mbSorted;
        return *this;
    }

    sal_Bool operator==(const SdrUShortCont& rCont) const
    {
        return maArray == rCont.maArray;
    }

    sal_Bool operator!=(const SdrUShortCont& rCont) const
    {
        return maArray != rCont.maArray;
    }

    void Clear()
    {
        maArray.Clear();
        mbSorted = sal_True;
    }

    void Sort() const;

    void ForceSort() const
    {
        if(!mbSorted)
        {
            Sort();
        }
    }

    void Insert(sal_uInt16 nElem, ULONG nPos = CONTAINER_APPEND)
    {
        maArray.Insert((void*)ULONG(nElem),nPos);

        if(mbSorted)
        {
            CheckSort(nPos);
        }
    }

    void Remove(ULONG nPos)
    {
        maArray.Remove(nPos);
    }

    void Replace(sal_uInt16 nElem, ULONG nPos)
    {
        maArray.Replace((void*)ULONG(nElem), nPos);

        if(mbSorted)
        {
            CheckSort(nPos);
        }
    }

    sal_uInt16 GetObject(ULONG nPos) const
    {
        return sal_uInt16(sal_uIntPtr(maArray.GetObject(nPos)));
    }

    ULONG GetPos(sal_uInt16 nElem) const
    {
        return maArray.GetPos((void*)(ULONG)nElem);
    }

    ULONG GetCount() const
    {
        return maArray.Count();
    }

    sal_Bool Exist(sal_uInt16 nElem) const
    {
        return (CONTAINER_ENTRY_NOTFOUND != maArray.GetPos((void*)(ULONG)nElem));
    }
};

// Alles was eine View ueber ein markiertes Objekt wissen muss
class SVX_DLLPUBLIC SdrMark : public sdr::ObjectUser
{
protected:
    SdrObject*                                          mpSelectedSdrObject;    // the seleceted object
    SdrPageView*                                        mpPageView;
    SdrUShortCont*                                      mpPoints;     // Markierte Punkte
    SdrUShortCont*                                      mpLines;      // Markierte Linienabschnitte
    SdrUShortCont*                                      mpGluePoints; // Markierte Klebepunkte (deren Id's)
    sal_Bool                                            mbCon1;       // fuer Connectoren
    sal_Bool                                            mbCon2;       // fuer Connectoren
    sal_uInt16                                          mnUser;       // z.B. fuer CopyObjects, mitkopieren von Edges

public:
    SdrMark(SdrObject* pNewObj = 0L, SdrPageView* pNewPageView = 0L);
    SdrMark(const SdrMark& rMark);
    virtual ~SdrMark();

    // derived from ObjectUser
    virtual void ObjectInDestruction(const SdrObject& rObject);

    SdrMark& operator=(const SdrMark& rMark);
    sal_Bool operator==(const SdrMark& rMark) const;
    sal_Bool operator!=(const SdrMark& rMark) const
    {
        return !(operator==(rMark));
    }

    void SetMarkedSdrObj(SdrObject* pNewObj);
    SdrObject* GetMarkedSdrObj() const;

    SdrPage* GetPage() const;
    SdrObjList* GetObjList() const;
    SdrPageView* GetPageView() const
    {
        return mpPageView;
    }

    void SetPageView(SdrPageView* pNewPageView)
    {
        mpPageView = pNewPageView;
    }

    void SetCon1(sal_Bool bOn)
    {
        mbCon1 = bOn;
    }

    sal_Bool IsCon1() const
    {
        return mbCon1;
    }

    void SetCon2(sal_Bool bOn)
    {
        mbCon2 = bOn;
    }

    sal_Bool IsCon2() const
    {
        return mbCon2;
    }

    void SetUser(sal_uInt16 nVal)
    {
        mnUser = nVal;
    }

    sal_uInt16 GetUser() const
    {
        return mnUser;
    }

    const SdrUShortCont* GetMarkedPoints() const
    {
        return mpPoints;
    }

    const SdrUShortCont* GetMarkedLines() const
    {
        return mpLines;
    }

    const SdrUShortCont* GetMarkedGluePoints() const
    {
        return mpGluePoints;
    }

    SdrUShortCont* GetMarkedPoints()
    {
        return mpPoints;
    }

    SdrUShortCont* GetMarkedLines()
    {
        return mpLines;
    }

    SdrUShortCont* GetMarkedGluePoints()
    {
        return mpGluePoints;
    }

    SdrUShortCont* ForceMarkedPoints()
    {
        if(!mpPoints)
            mpPoints = new SdrUShortCont(1024, 32, 32);

        return mpPoints;
    }

    SdrUShortCont* ForceMarkedLines()
    {
        if(!mpLines)
            mpLines = new SdrUShortCont(1024, 32, 32);

        return mpLines;
    }

    SdrUShortCont* ForceMarkedGluePoints()
    {
        if(!mpGluePoints)
            mpGluePoints = new SdrUShortCont(1024, 32, 32);

        return mpGluePoints;
    }
};

class SVX_DLLPUBLIC SdrMarkList
{
protected:
    Container                                           maList;

    String                                              maMarkName;
    String                                              maPointName;
    String                                              maGluePointName;

    sal_Bool                                            mbPointNameOk;
    sal_Bool                                            mbGluePointNameOk;
    sal_Bool                                            mbNameOk;
    sal_Bool                                            mbSorted;

private:
    SVX_DLLPRIVATE sal_Bool operator==(const SdrMarkList& rCmpMarkList) const;
    SVX_DLLPRIVATE void ImpForceSort();

private:
    SVX_DLLPRIVATE const XubString& GetPointMarkDescription(sal_Bool bGlue) const;

public:
    SdrMarkList()
    :   maList(1024, 64, 64),
        mbPointNameOk(sal_False),
        mbGluePointNameOk(sal_False),
        mbNameOk(sal_False),
        mbSorted(sal_True)
    {
    }

    SdrMarkList(const SdrMarkList& rLst)
    :   maList(1024, 64, 64)
    {
        *this = rLst;
    }

    ~SdrMarkList()
    {
        Clear();
    }

    void Clear();
    void ForceSort() const;
    void SetUnsorted()
    {
        mbSorted = sal_False;
    }

    ULONG GetMarkCount() const
    {
        return maList.Count();
    }

    SdrMark* GetMark(ULONG nNum) const
    {
        return (SdrMark*)(maList.GetObject(nNum));
    }

    ULONG FindObject(const SdrObject* pObj) const;
    void InsertEntry(const SdrMark& rMark, sal_Bool bChkSort = sal_True);
    void DeleteMark(ULONG nNum);
    void ReplaceMark(const SdrMark& rNewMark, ULONG nNum);
    void Merge(const SdrMarkList& rSrcList, sal_Bool bReverse = sal_False);
    sal_Bool DeletePageView(const SdrPageView& rPV);
    sal_Bool InsertPageView(const SdrPageView& rPV);

    void SetNameDirty()
    {
        mbNameOk = sal_False;
        mbPointNameOk = sal_False;
        mbGluePointNameOk = sal_False;
    }

    // Eine verbale Beschreibung der markierten Objekte z.B.:
    // "27 Linien", "12 Objekte", "Polygon" oder auch "Kein Objekt"
    const String& GetMarkDescription() const;
    const String& GetPointMarkDescription() const
    {
        return GetPointMarkDescription(sal_False);
    }

    const String& GetGluePointMarkDescription() const
    {
        return GetPointMarkDescription(sal_True);
    }

    // pPage=0L: Die Markierungen aller! Seiten beruecksichtigen
    sal_Bool TakeBoundRect(SdrPageView* pPageView, Rectangle& rRect) const;
    sal_Bool TakeSnapRect(SdrPageView* pPageView, Rectangle& rRect) const;

    // Es werden saemtliche Entries kopiert!
    void operator=(const SdrMarkList& rLst);
};

////////////////////////////////////////////////////////////////////////////////////////////////////
// migrate selections

namespace sdr
{
    class SVX_DLLPUBLIC ViewSelection
    {
        SdrMarkList                 maMarkedObjectList;
        SdrMarkList                 maEdgesOfMarkedNodes;
        SdrMarkList                 maMarkedEdgesOfMarkedNodes;
        List                        maAllMarkedObjects;

        // bitfield
        unsigned                    mbEdgesOfMarkedNodesDirty : 1;

        SVX_DLLPRIVATE void ImpForceEdgesOfMarkedNodes();
        SVX_DLLPRIVATE void ImplCollectCompleteSelection(SdrObject* pObj);

    public:
        ViewSelection();

        void SetEdgesOfMarkedNodesDirty();

        const SdrMarkList& GetMarkedObjectList() const
        {
            return maMarkedObjectList;
        }

        const SdrMarkList& GetEdgesOfMarkedNodes() const;
        const SdrMarkList& GetMarkedEdgesOfMarkedNodes() const;
        const List& GetAllMarkedObjects() const;

        SdrMarkList& GetMarkedObjectListWriteAccess()
        {
            return maMarkedObjectList;
        }
    };
} // end of namespace sdr

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

#endif //_SVDMARK_HXX
// eof
<commit_msg>INTEGRATION: CWS changefileheader (1.4.340); FILE MERGED 2008/04/01 15:49:38 thb 1.4.340.3: #i85898# Stripping all external header guards 2008/04/01 12:46:54 thb 1.4.340.2: #i85898# Stripping all external header guards 2008/03/31 14:18:17 rt 1.4.340.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: svdmark.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SVDMARK_HXX
#define _SVDMARK_HXX

#include <tools/contnr.hxx>
#include <tools/string.hxx>
#include <tools/list.hxx>
#include "svx/svxdllapi.h"
#include <svx/sdrobjectuser.hxx>

#include <set>

class Rectangle;
class SdrPage;
class SdrObjList;
class SdrObject;
class SdrPageView;

// Ein Container fuer USHORTs (im Prinzip ein dynamisches Array)
class SVX_DLLPUBLIC SdrUShortCont
{
    Container                                           maArray;
    sal_Bool                                            mbSorted;

private:
    void CheckSort(ULONG nPos);

public:
    SdrUShortCont(sal_uInt16 nBlock, sal_uInt16 nInit, sal_uInt16 nResize)
    :   maArray(nBlock, nInit, nResize),
    mbSorted(sal_True)
    {}

    SdrUShortCont(const SdrUShortCont& rCont)
    :   maArray(rCont.maArray),
        mbSorted(rCont.mbSorted)
    {}

    /** helper to migrate to stl containers */
    std::set< sal_uInt16 > getContainer();

    SdrUShortCont& operator=(const SdrUShortCont& rCont)
    {
        maArray = rCont.maArray;
        mbSorted = rCont.mbSorted;
        return *this;
    }

    sal_Bool operator==(const SdrUShortCont& rCont) const
    {
        return maArray == rCont.maArray;
    }

    sal_Bool operator!=(const SdrUShortCont& rCont) const
    {
        return maArray != rCont.maArray;
    }

    void Clear()
    {
        maArray.Clear();
        mbSorted = sal_True;
    }

    void Sort() const;

    void ForceSort() const
    {
        if(!mbSorted)
        {
            Sort();
        }
    }

    void Insert(sal_uInt16 nElem, ULONG nPos = CONTAINER_APPEND)
    {
        maArray.Insert((void*)ULONG(nElem),nPos);

        if(mbSorted)
        {
            CheckSort(nPos);
        }
    }

    void Remove(ULONG nPos)
    {
        maArray.Remove(nPos);
    }

    void Replace(sal_uInt16 nElem, ULONG nPos)
    {
        maArray.Replace((void*)ULONG(nElem), nPos);

        if(mbSorted)
        {
            CheckSort(nPos);
        }
    }

    sal_uInt16 GetObject(ULONG nPos) const
    {
        return sal_uInt16(sal_uIntPtr(maArray.GetObject(nPos)));
    }

    ULONG GetPos(sal_uInt16 nElem) const
    {
        return maArray.GetPos((void*)(ULONG)nElem);
    }

    ULONG GetCount() const
    {
        return maArray.Count();
    }

    sal_Bool Exist(sal_uInt16 nElem) const
    {
        return (CONTAINER_ENTRY_NOTFOUND != maArray.GetPos((void*)(ULONG)nElem));
    }
};

// Alles was eine View ueber ein markiertes Objekt wissen muss
class SVX_DLLPUBLIC SdrMark : public sdr::ObjectUser
{
protected:
    SdrObject*                                          mpSelectedSdrObject;    // the seleceted object
    SdrPageView*                                        mpPageView;
    SdrUShortCont*                                      mpPoints;     // Markierte Punkte
    SdrUShortCont*                                      mpLines;      // Markierte Linienabschnitte
    SdrUShortCont*                                      mpGluePoints; // Markierte Klebepunkte (deren Id's)
    sal_Bool                                            mbCon1;       // fuer Connectoren
    sal_Bool                                            mbCon2;       // fuer Connectoren
    sal_uInt16                                          mnUser;       // z.B. fuer CopyObjects, mitkopieren von Edges

public:
    SdrMark(SdrObject* pNewObj = 0L, SdrPageView* pNewPageView = 0L);
    SdrMark(const SdrMark& rMark);
    virtual ~SdrMark();

    // derived from ObjectUser
    virtual void ObjectInDestruction(const SdrObject& rObject);

    SdrMark& operator=(const SdrMark& rMark);
    sal_Bool operator==(const SdrMark& rMark) const;
    sal_Bool operator!=(const SdrMark& rMark) const
    {
        return !(operator==(rMark));
    }

    void SetMarkedSdrObj(SdrObject* pNewObj);
    SdrObject* GetMarkedSdrObj() const;

    SdrPage* GetPage() const;
    SdrObjList* GetObjList() const;
    SdrPageView* GetPageView() const
    {
        return mpPageView;
    }

    void SetPageView(SdrPageView* pNewPageView)
    {
        mpPageView = pNewPageView;
    }

    void SetCon1(sal_Bool bOn)
    {
        mbCon1 = bOn;
    }

    sal_Bool IsCon1() const
    {
        return mbCon1;
    }

    void SetCon2(sal_Bool bOn)
    {
        mbCon2 = bOn;
    }

    sal_Bool IsCon2() const
    {
        return mbCon2;
    }

    void SetUser(sal_uInt16 nVal)
    {
        mnUser = nVal;
    }

    sal_uInt16 GetUser() const
    {
        return mnUser;
    }

    const SdrUShortCont* GetMarkedPoints() const
    {
        return mpPoints;
    }

    const SdrUShortCont* GetMarkedLines() const
    {
        return mpLines;
    }

    const SdrUShortCont* GetMarkedGluePoints() const
    {
        return mpGluePoints;
    }

    SdrUShortCont* GetMarkedPoints()
    {
        return mpPoints;
    }

    SdrUShortCont* GetMarkedLines()
    {
        return mpLines;
    }

    SdrUShortCont* GetMarkedGluePoints()
    {
        return mpGluePoints;
    }

    SdrUShortCont* ForceMarkedPoints()
    {
        if(!mpPoints)
            mpPoints = new SdrUShortCont(1024, 32, 32);

        return mpPoints;
    }

    SdrUShortCont* ForceMarkedLines()
    {
        if(!mpLines)
            mpLines = new SdrUShortCont(1024, 32, 32);

        return mpLines;
    }

    SdrUShortCont* ForceMarkedGluePoints()
    {
        if(!mpGluePoints)
            mpGluePoints = new SdrUShortCont(1024, 32, 32);

        return mpGluePoints;
    }
};

class SVX_DLLPUBLIC SdrMarkList
{
protected:
    Container                                           maList;

    String                                              maMarkName;
    String                                              maPointName;
    String                                              maGluePointName;

    sal_Bool                                            mbPointNameOk;
    sal_Bool                                            mbGluePointNameOk;
    sal_Bool                                            mbNameOk;
    sal_Bool                                            mbSorted;

private:
    SVX_DLLPRIVATE sal_Bool operator==(const SdrMarkList& rCmpMarkList) const;
    SVX_DLLPRIVATE void ImpForceSort();

private:
    SVX_DLLPRIVATE const XubString& GetPointMarkDescription(sal_Bool bGlue) const;

public:
    SdrMarkList()
    :   maList(1024, 64, 64),
        mbPointNameOk(sal_False),
        mbGluePointNameOk(sal_False),
        mbNameOk(sal_False),
        mbSorted(sal_True)
    {
    }

    SdrMarkList(const SdrMarkList& rLst)
    :   maList(1024, 64, 64)
    {
        *this = rLst;
    }

    ~SdrMarkList()
    {
        Clear();
    }

    void Clear();
    void ForceSort() const;
    void SetUnsorted()
    {
        mbSorted = sal_False;
    }

    ULONG GetMarkCount() const
    {
        return maList.Count();
    }

    SdrMark* GetMark(ULONG nNum) const
    {
        return (SdrMark*)(maList.GetObject(nNum));
    }

    ULONG FindObject(const SdrObject* pObj) const;
    void InsertEntry(const SdrMark& rMark, sal_Bool bChkSort = sal_True);
    void DeleteMark(ULONG nNum);
    void ReplaceMark(const SdrMark& rNewMark, ULONG nNum);
    void Merge(const SdrMarkList& rSrcList, sal_Bool bReverse = sal_False);
    sal_Bool DeletePageView(const SdrPageView& rPV);
    sal_Bool InsertPageView(const SdrPageView& rPV);

    void SetNameDirty()
    {
        mbNameOk = sal_False;
        mbPointNameOk = sal_False;
        mbGluePointNameOk = sal_False;
    }

    // Eine verbale Beschreibung der markierten Objekte z.B.:
    // "27 Linien", "12 Objekte", "Polygon" oder auch "Kein Objekt"
    const String& GetMarkDescription() const;
    const String& GetPointMarkDescription() const
    {
        return GetPointMarkDescription(sal_False);
    }

    const String& GetGluePointMarkDescription() const
    {
        return GetPointMarkDescription(sal_True);
    }

    // pPage=0L: Die Markierungen aller! Seiten beruecksichtigen
    sal_Bool TakeBoundRect(SdrPageView* pPageView, Rectangle& rRect) const;
    sal_Bool TakeSnapRect(SdrPageView* pPageView, Rectangle& rRect) const;

    // Es werden saemtliche Entries kopiert!
    void operator=(const SdrMarkList& rLst);
};

////////////////////////////////////////////////////////////////////////////////////////////////////
// migrate selections

namespace sdr
{
    class SVX_DLLPUBLIC ViewSelection
    {
        SdrMarkList                 maMarkedObjectList;
        SdrMarkList                 maEdgesOfMarkedNodes;
        SdrMarkList                 maMarkedEdgesOfMarkedNodes;
        List                        maAllMarkedObjects;

        // bitfield
        unsigned                    mbEdgesOfMarkedNodesDirty : 1;

        SVX_DLLPRIVATE void ImpForceEdgesOfMarkedNodes();
        SVX_DLLPRIVATE void ImplCollectCompleteSelection(SdrObject* pObj);

    public:
        ViewSelection();

        void SetEdgesOfMarkedNodesDirty();

        const SdrMarkList& GetMarkedObjectList() const
        {
            return maMarkedObjectList;
        }

        const SdrMarkList& GetEdgesOfMarkedNodes() const;
        const SdrMarkList& GetMarkedEdgesOfMarkedNodes() const;
        const List& GetAllMarkedObjects() const;

        SdrMarkList& GetMarkedObjectListWriteAccess()
        {
            return maMarkedObjectList;
        }
    };
} // end of namespace sdr

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

#endif //_SVDMARK_HXX
// eof
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SwCapObjType.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: ihi $ $Date: 2007-11-21 18:17:01 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SWCAPOBJTYPE_HXX
#define _SWCAPOBJTYPE_HXX

enum SwCapObjType
{
        FRAME_CAP, GRAPHIC_CAP, TABLE_CAP, OLE_CAP
};

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.2.184); FILE MERGED 2008/03/31 16:52:33 rt 1.2.184.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: SwCapObjType.hxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _SWCAPOBJTYPE_HXX
#define _SWCAPOBJTYPE_HXX

enum SwCapObjType
{
        FRAME_CAP, GRAPHIC_CAP, TABLE_CAP, OLE_CAP
};

#endif
<|endoftext|>


<commit_before>// C/C++
#include <stdio.h>
#include <string.h>
#include <map>

// E
#include <e/endian.h>
#include <e/unpacker.h>
#include <e/intrusive_ptr.h>

// HyperDex
#include <hyperdex/client.hpp>

// WTF
#include "client/file.h"

using namespace std;

hyperdex::Client* h;
const char* WTF_SPACE = "wtf";
bool verbose = true;
const struct hyperdex_client_attribute* attrs;
size_t attrs_sz;
hyperdex_client_returncode status;
int64_t retval;

void
print_return()
{
    if (verbose) printf("first retval %ld status %d:", retval, status);
    if (verbose) cout << status << endl;
    retval = h->loop(-1, &status);
    if (verbose) printf("final retval %ld status %d:", retval, status);
    if (verbose) cout << status << endl;
}

void
read()
{
    if (status == HYPERDEX_CLIENT_SEARCHDONE) return;

    // Reading
    if (verbose) cout << "[" << attrs_sz << "] attributes" << endl;
    if (attrs == NULL)
    {
        cout << "attrs is NULL" << endl;
    }
    else
    {
        e::intrusive_ptr<wtf::file> f = new wtf::file("", 0);
        for (size_t i = 0; i < attrs_sz; ++i)
        {
            if (verbose) cout << i << ". [" << attrs[i].attr << "]:";
            if (strcmp(attrs[i].attr, "path") == 0)
            {
                string path(attrs[i].value, attrs[i].value_sz);
                cout << "[" << path << "]" << endl;
                f->path(path.c_str());
            }
            else if (strcmp(attrs[i].attr, "blockmap") == 0)
            {
                e::unpacker up(attrs[i].value, attrs[i].value_sz);
                if (attrs[i].value_sz == 0)
                {
                    cout << endl;
                }
                else
                {
                    cout << "[" << up.as_slice().hex() << "]" << endl;
                    up = up >> f;
                }
            }
            else if (strcmp(attrs[i].attr, "directory") == 0)
            {
                uint64_t is_dir;

                e::unpacker up(attrs[i].value, attrs[i].value_sz);
                up = up >> is_dir;
                e::unpack64be((uint8_t*)&is_dir, &is_dir);
                cout << "[" << is_dir << "]" << endl;
                f->is_directory = is_dir == 0 ? false : true;
            }
            else if (strcmp(attrs[i].attr, "mode") == 0)
            {
                uint64_t mode;

                e::unpacker up(attrs[i].value, attrs[i].value_sz);
                up = up >> mode;
                e::unpack64be((uint8_t*)&mode, &mode);
                cout << "[" << mode << "]" << endl;
                f->mode = mode;
            }
            else
            {
                cout << "<unexpected attribute>" << endl;
            }
        }
        cout << *f << endl;
    }
}

void
search(const char* attr, const char* value, hyperpredicate predicate)
{
    if (verbose) cout << ">>>>searching [" << attr << "] for [" << value << "] with [" << predicate << "]" << endl;
    struct hyperdex_client_attribute_check check;
    check.attr = attr;
    check.value = value;
    check.value_sz = strlen(check.value);
    check.datatype = HYPERDATATYPE_STRING;
    check.predicate = predicate;

    status = (hyperdex_client_returncode)NULL;
    // TODO max_int64 results
    retval = h->sorted_search(WTF_SPACE, &check, 1, "path", 100, false, &status, &attrs, &attrs_sz);

    int counter = 0;
    while (status != HYPERDEX_CLIENT_SEARCHDONE && status != HYPERDEX_CLIENT_NONEPENDING)
    {
        if (verbose) cout << "(" << ++counter << ")" << endl;
        print_return();
        read();
    }
    if (verbose) cout << endl;
}

int
main(int argc, const char* argv[])
{
    //hyperdex::connect_opts conn;
    //h = new hyperdex::Client(conn.host(), conn.port());
    h = new hyperdex::Client("127.0.0.1", 1982);

    if (argc > 1)
    {
        if (argc > 2) verbose = true;

        string query("^");
        query += string(argv[1]);

        search("path", query.c_str(), HYPERPREDICATE_REGEX);
    }
    else
    {
        cout << "Usage: ./wtf-stat <file_name_regex>" << endl;
        cout << "Set up: echo 'space wtf key path attributes string blockmap, int directory, int mode' | hyperdex add-space -h 127.0.0.1 -p 1982" << endl;
    }

    return EXIT_SUCCESS;
}
<commit_msg>add options for hyperdex host and port, as well as verbose<commit_after>//#define __STDC_LIMIT_MACROS

// C/C++
#include <stdio.h>
#include <string.h>
#include <map>
//#include <stdint.h>

// E
#include <e/endian.h>
#include <e/unpacker.h>
#include <e/intrusive_ptr.h>
#include <e/popt.h>

// HyperDex
#include <hyperdex/client.hpp>

// WTF
#include "client/file.h"

using namespace std;

static long _hyper_port = 1982;
static const char* _hyper_host = "127.0.0.1";
static const char* _query = "";
static bool _verbose = false;

hyperdex::Client* h;
const char* WTF_SPACE = "wtf";
const struct hyperdex_client_attribute* attrs;
size_t attrs_sz;
hyperdex_client_returncode status;
int64_t retval;

void
print_return()
{
    if (_verbose) printf("first retval %ld status %d:", retval, status);
    if (_verbose) cout << status << endl;
    retval = h->loop(-1, &status);
    if (_verbose) printf("final retval %ld status %d:", retval, status);
    if (_verbose) cout << status << endl;
}

void
read()
{
    if (status == HYPERDEX_CLIENT_SEARCHDONE) return;

    // Reading
    if (_verbose) cout << "[" << attrs_sz << "] attributes" << endl;
    if (attrs == NULL)
    {
        cout << "attrs is NULL" << endl;
    }
    else
    {
        e::intrusive_ptr<wtf::file> f = new wtf::file("", 0);
        for (size_t i = 0; i < attrs_sz; ++i)
        {
            if (_verbose) cout << i << ". [" << attrs[i].attr << "]:";
            if (strcmp(attrs[i].attr, "path") == 0)
            {
                string path(attrs[i].value, attrs[i].value_sz);
                if (_verbose) cout << "[" << path << "]" << endl;
                f->path(path.c_str());
            }
            else if (strcmp(attrs[i].attr, "blockmap") == 0)
            {
                e::unpacker up(attrs[i].value, attrs[i].value_sz);
                if (attrs[i].value_sz == 0)
                {
                    if (_verbose) cout << endl;
                }
                else
                {
                    if (_verbose) cout << "[" << up.as_slice().hex() << "]" << endl;
                    up = up >> f;
                }
            }
            else if (strcmp(attrs[i].attr, "directory") == 0)
            {
                uint64_t is_dir;

                e::unpacker up(attrs[i].value, attrs[i].value_sz);
                up = up >> is_dir;
                e::unpack64be((uint8_t*)&is_dir, &is_dir);
                if (_verbose) cout << "[" << is_dir << "]" << endl;
                f->is_directory = is_dir == 0 ? false : true;
            }
            else if (strcmp(attrs[i].attr, "mode") == 0)
            {
                uint64_t mode;

                e::unpacker up(attrs[i].value, attrs[i].value_sz);
                up = up >> mode;
                e::unpack64be((uint8_t*)&mode, &mode);
                if (_verbose) cout << "[" << mode << "]" << endl;
                f->mode = mode;
            }
            else
            {
                if (_verbose) cout << "<unexpected attribute>" << endl;
            }
        }
        cout << *f << endl;
    }
}

void
search(const char* attr, const char* value, hyperpredicate predicate)
{
    cout << ">>>>searching [" << attr << "] for [" << value << "] with [" << predicate << "]" << endl;
    struct hyperdex_client_attribute_check check;
    check.attr = attr;
    check.value = value;
    check.value_sz = strlen(check.value);
    check.datatype = HYPERDATATYPE_STRING;
    check.predicate = predicate;

    status = (hyperdex_client_returncode)NULL;
    // TODO max_int64 results
    retval = h->sorted_search(WTF_SPACE, &check, 1, "path", 100, false, &status, &attrs, &attrs_sz);

    int counter = 0;
    while (status != HYPERDEX_CLIENT_SEARCHDONE && status != HYPERDEX_CLIENT_NONEPENDING)
    {
        cout << "(" << ++counter << ")" << endl;
        print_return();
        read();
    }
    cout << "\nSearch finished successfully" << endl;
}

int
main(int argc, const char* argv[])
{
    e::argparser ap;
    ap.autohelp();
    ap.arg().name('p', "port")
        .description("port on the hyperdex coordinator")
        .metavar("p")
        .as_long(&_hyper_port);
    ap.arg().name('h', "host")
        .description("address of hyperdex coordinator")
        .metavar("p")
        .as_string(&_hyper_host);
    ap.arg().name('q', "query")
        .description("file name regex")
        .metavar("q")
        .as_string(&_query);
    ap.arg().name('v', "verbose")
        .description("verbose outputs")
        .metavar("v")
        .set_true(&_verbose);

    if (!ap.parse(argc, argv))
    {
        return EXIT_FAILURE;
    }
    else
    {
        h = new hyperdex::Client(_hyper_host, _hyper_port);
        string query("^");
        query += string(_query);
        search("path", query.c_str(), HYPERPREDICATE_REGEX);

        //cout << "Usage: wtf-stat <file_name_regex>" << endl;
        //cout << "Type wtf-stat --help to see options" << endl;
        //cout << "Set up: echo 'space wtf key path attributes string blockmap, int directory, int mode' | hyperdex add-space -h 127.0.0.1 -p 1982" << endl;
    }

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
 * preprocessor.hpp
 *
 *  Created on: Jun 29, 2015
 *      Author: hugo
 */

#ifndef SRC_PREPROCESSOR_HPP_
#define SRC_PREPROCESSOR_HPP_

#include <cassert>
#include <string>

#include "../../log/easylogging++.h"
#include "mapped_stream.hpp"
#include "splitterbuffer.hpp"

namespace mflash{

template <class IdType>
class EdgeConversor{
	public:
		template <class Splitter>
		static void process (const std::string file_graph, const char separator, const bool edgelist, Splitter &splitter);
};

template <class IdType>
template <class Splitter>
void EdgeConversor<IdType>::process(const std::string file_graph, const char separator, const bool edgelist, Splitter &splitter){
	MappedStream in(file_graph);

	IdType v1 = 		0;
	IdType v2 = 		0;
	bool isQuantity = !edgelist;
	bool isInVertice = 	true;

	const char comment = '#';
	const char comment2 = '%';
	const char end_line = '\n';
	const char end_line2 = '\r';
	//char separator = ' ';
	const char separator2 = '\t';
	const char separator3 = ' ';

	EmptyField value;

/*

	const int64 MEGABYTE = 1024 * 1024;
	const int64 STEP_INFO = 500 * MEGABYTE;
*/

	while(in.has_remain()){
		char b = in.next();
		/*if( (in.current_ptr-in.ptr) % STEP_INFO ==0){
			LOG(INFO)<<"Processed: " << (in.current_ptr-in.ptr) / MEGABYTE << "MB";
		}*/
		//removing comment line
	  if(b == comment || b == comment2){
		while(b != end_line){
		  b = in.next();
		}
		b = in.next();
		//when the line content \n\r
		while( b == end_line || b==end_line2){
			b = in.next();
		}
		in.set_position(in.position()- sizeof(char));
		continue;
	  }
	  if (b == separator || b == separator2 || b == separator3){
		if(!isInVertice && !isQuantity){ //
			splitter.add(v1, v2, &value);
		}else{
			if(isInVertice) isInVertice = false;
			else if(isQuantity) isQuantity = false;
		}
		v2 = 0;
		continue;
	  }
		if (b == end_line || b == end_line2){
			b = in.next();
			//when the line content \r\n
			while( b == end_line || b==end_line2){
				b = in.next();
			}
			in.set_position(in.position()- sizeof(char));

			if(!isQuantity || edgelist){
				splitter.add(v1, v2, &value);
			}
			v1 = 0;
			v2 = 0;
			isInVertice = true;
			isQuantity = !edgelist;
			continue;
		}
		if(b<48 || b > 57){
			LOG(ERROR) << "The character '" << b << "' was not recognized.";
			assert(false);
		}

		if(isInVertice){
			v1 = (v1<< 3) + (v1 << 1) + (0xF & b);
		}else{
			v2 = (v2<< 3) + (v2 << 1) + (0xF & b);
		}
	}
	in.close_stream();
	splitter.flush();
	LOG(INFO)<<"Graph Binarization was succesfully";
}

}

#endif /* SRC_PREPROCESSOR_HPP_ */
<commit_msg>Method next() was change to next_char()<commit_after>/*
 * preprocessor.hpp
 *
 *  Created on: Jun 29, 2015
 *      Author: hugo
 */

#ifndef SRC_PREPROCESSOR_HPP_
#define SRC_PREPROCESSOR_HPP_

#include <cassert>
#include <string>

#include "../../log/easylogging++.h"
#include "mapped_stream.hpp"
#include "splitterbuffer.hpp"

namespace mflash{

template <class IdType>
class EdgeConversor{
	public:
		template <class Splitter>
		static void process (const std::string file_graph, const char separator, const bool edgelist, Splitter &splitter);
};

template <class IdType>
template <class Splitter>
void EdgeConversor<IdType>::process(const std::string file_graph, const char separator, const bool edgelist, Splitter &splitter){
	MappedStream in(file_graph);

	IdType v1 = 		0;
	IdType v2 = 		0;
	bool isQuantity = !edgelist;
	bool isInVertice = 	true;

	const char comment = '#';
	const char comment2 = '%';
	const char end_line = '\n';
	const char end_line2 = '\r';
	//char separator = ' ';
	const char separator2 = '\t';
	const char separator3 = ' ';

	EmptyField value;

/*

	const int64 MEGABYTE = 1024 * 1024;
	const int64 STEP_INFO = 500 * MEGABYTE;
*/

	while(in.has_remain()){
		char b = in.next_char();
		/*if( (in.current_ptr-in.ptr) % STEP_INFO ==0){
			LOG(INFO)<<"Processed: " << (in.current_ptr-in.ptr) / MEGABYTE << "MB";
		}*/
		//removing comment line
	  if(b == comment || b == comment2){
		while(b != end_line){
		  b = in.next_char();
		}
		b = in.next_char();
		//when the line content \n\r
		while( b == end_line || b==end_line2){
			b = in.next_char();
		}
		in.set_position(in.position()- sizeof(char));
		continue;
	  }
	  if (b == separator || b == separator2 || b == separator3){
		if(!isInVertice && !isQuantity){ //
			splitter.add(v1, v2, &value);
		}else{
			if(isInVertice) isInVertice = false;
			else if(isQuantity) isQuantity = false;
		}
		v2 = 0;
		continue;
	  }
		if (b == end_line || b == end_line2){
			b = in.next_char();
			//when the line content \r\n
			while( b == end_line || b==end_line2){
				b = in.next_char();
			}
			in.set_position(in.position()- sizeof(char));

			if(!isQuantity || edgelist){
				splitter.add(v1, v2, &value);
			}
			v1 = 0;
			v2 = 0;
			isInVertice = true;
			isQuantity = !edgelist;
			continue;
		}
		if(b<48 || b > 57){
			LOG(ERROR) << "The character '" << b << "' was not recognized.";
			assert(false);
		}

		if(isInVertice){
			v1 = (v1<< 3) + (v1 << 1) + (0xF & b);
		}else{
			v2 = (v2<< 3) + (v2 << 1) + (0xF & b);
		}
	}
	in.close_stream();
	splitter.flush();
	LOG(INFO)<<"Graph Binarization was succesfully";
}

}

#endif /* SRC_PREPROCESSOR_HPP_ */
<|endoftext|>


<commit_before>#include "extract_input.h"
#include "datafactory.h"

/*!
 * String list of output formats for this analytic that correspond exactly
 * to its enumeration. Used for handling the output format argument for this
 * input object.
 */
const QStringList Extract::Input::FORMAT_NAMES
{
   "text"
   ,"graphml"
};

/*!
 * Construct a new input object with the given analytic as its parent.
 *
 * @param parent
 */
Extract::Input::Input(Extract* parent):
   EAbstractAnalytic::Input(parent),
   _base(parent)
{
   EDEBUG_FUNC(this,parent);
}

/*!
 * Return the total number of arguments this analytic type contains.
 */
int Extract::Input::size() const
{
   EDEBUG_FUNC(this);

   return Total;
}

/*!
 * Return the argument type for a given index.
 *
 * @param index
 */
EAbstractAnalytic::Input::Type Extract::Input::type(int index) const
{
   EDEBUG_FUNC(this,index);

   switch (index)
   {
   case ExpressionData: return Type::DataIn;
   case ClusterData: return Type::DataIn;
   case CorrelationData: return Type::DataIn;
   case OutputFormatArg: return Type::Selection;
   case OutputFile: return Type::FileOut;
   case MinCorrelation: return Type::Double;
   case MaxCorrelation: return Type::Double;
   default: return Type::Boolean;
   }
}

/*!
 * Return data for a given role on an argument with the given index.
 *
 * @param index
 * @param role
 */
QVariant Extract::Input::data(int index, Role role) const
{
   EDEBUG_FUNC(this,index,role);

   switch (index)
   {
   case ExpressionData:
      switch (role)
      {
      case Role::CommandLineName: return QString("emx");
      case Role::Title: return tr("Expression Matrix:");
      case Role::WhatsThis: return tr("Input expression matrix containing gene expression data.");
      case Role::DataType: return DataFactory::ExpressionMatrixType;
      default: return QVariant();
      }
   case ClusterData:
      switch (role)
      {
      case Role::CommandLineName: return QString("ccm");
      case Role::Title: return tr("Cluster Matrix:");
      case Role::WhatsThis: return tr("Input cluster matrix containing cluster composition data.");
      case Role::DataType: return DataFactory::CCMatrixType;
      default: return QVariant();
      }
   case CorrelationData:
      switch (role)
      {
      case Role::CommandLineName: return QString("cmx");
      case Role::Title: return tr("Correlation Matrix:");
      case Role::WhatsThis: return tr("Input correlation matrix containing correlation data.");
      case Role::DataType: return DataFactory::CorrelationMatrixType;
      default: return QVariant();
      }
   case OutputFormatArg:
      switch (role)
      {
      case Role::CommandLineName: return QString("format");
      case Role::Title: return tr("Output Format:");
      case Role::WhatsThis: return tr("Format to use for the output file.");
      case Role::SelectionValues: return FORMAT_NAMES;
      case Role::Default: return "text";
      default: return QVariant();
      }
   case OutputFile:
      switch (role)
      {
      case Role::CommandLineName: return QString("output");
      case Role::Title: return tr("GraphML File:");
      case Role::WhatsThis: return tr("Output file that will contain network in the specified format.");
      default: return QVariant();
      }
   case MinCorrelation:
      switch (role)
      {
      case Role::CommandLineName: return QString("mincorr");
      case Role::Title: return tr("Minimum Correlation:");
      case Role::WhatsThis: return tr("Minimum (absolute) correlation threshold for gene pairs.");
      case Role::Default: return 0.85;
      case Role::Minimum: return 0;
      case Role::Maximum: return 1;
      default: return QVariant();
      }
   case MaxCorrelation:
      switch (role)
      {
      case Role::CommandLineName: return QString("maxcorr");
      case Role::Title: return tr("Maximum Correlation:");
      case Role::WhatsThis: return tr("Maximum (absolute) correlation threshold for gene pairs.");
      case Role::Default: return 1;
      case Role::Minimum: return 0;
      case Role::Maximum: return 1;
      default: return QVariant();
      }
   default: return QVariant();
   }
}

/*!
 * Set an argument with the given index to the given value.
 *
 * @param index
 * @param value
 */
void Extract::Input::set(int index, const QVariant& value)
{
   EDEBUG_FUNC(this,index,&value);

   switch (index)
   {
   case OutputFormatArg:
      _base->_outputFormat = static_cast<OutputFormat>(FORMAT_NAMES.indexOf(value.toString()));
      break;
   case MinCorrelation:
      _base->_minCorrelation = value.toFloat();
      break;
   case MaxCorrelation:
      _base->_maxCorrelation = value.toFloat();
      break;
   }
}

/*!
 * Set a data argument with the given index to the given data object pointer.
 *
 * @param index
 * @param data
 */
void Extract::Input::set(int index, EAbstractData* data)
{
   EDEBUG_FUNC(this,index,data);

   if ( index == ExpressionData )
   {
      _base->_emx = data->cast<ExpressionMatrix>();
   }
   else if ( index == ClusterData )
   {
      _base->_ccm = data->cast<CCMatrix>();
   }
   else if ( index == CorrelationData )
   {
      _base->_cmx = data->cast<CorrelationMatrix>();
   }
}

/*!
 * Set a file argument with the given index to the given qt file pointer.
 *
 * @param index
 * @param file
 */
void Extract::Input::set(int index, QFile* file)
{
   EDEBUG_FUNC(this,index,file);

   if ( index == OutputFile )
   {
      _base->_output = file;
   }
}
<commit_msg>Fixed input field in Extract Analytic<commit_after>#include "extract_input.h"
#include "datafactory.h"

/*!
 * String list of output formats for this analytic that correspond exactly
 * to its enumeration. Used for handling the output format argument for this
 * input object.
 */
const QStringList Extract::Input::FORMAT_NAMES
{
   "text"
   ,"graphml"
};

/*!
 * Construct a new input object with the given analytic as its parent.
 *
 * @param parent
 */
Extract::Input::Input(Extract* parent):
   EAbstractAnalytic::Input(parent),
   _base(parent)
{
   EDEBUG_FUNC(this,parent);
}

/*!
 * Return the total number of arguments this analytic type contains.
 */
int Extract::Input::size() const
{
   EDEBUG_FUNC(this);

   return Total;
}

/*!
 * Return the argument type for a given index.
 *
 * @param index
 */
EAbstractAnalytic::Input::Type Extract::Input::type(int index) const
{
   EDEBUG_FUNC(this,index);

   switch (index)
   {
   case ExpressionData: return Type::DataIn;
   case ClusterData: return Type::DataIn;
   case CorrelationData: return Type::DataIn;
   case OutputFormatArg: return Type::Selection;
   case OutputFile: return Type::FileOut;
   case MinCorrelation: return Type::Double;
   case MaxCorrelation: return Type::Double;
   default: return Type::Boolean;
   }
}

/*!
 * Return data for a given role on an argument with the given index.
 *
 * @param index
 * @param role
 */
QVariant Extract::Input::data(int index, Role role) const
{
   EDEBUG_FUNC(this,index,role);

   switch (index)
   {
   case ExpressionData:
      switch (role)
      {
      case Role::CommandLineName: return QString("emx");
      case Role::Title: return tr("Expression Matrix:");
      case Role::WhatsThis: return tr("Input expression matrix containing gene expression data.");
      case Role::DataType: return DataFactory::ExpressionMatrixType;
      default: return QVariant();
      }
   case ClusterData:
      switch (role)
      {
      case Role::CommandLineName: return QString("ccm");
      case Role::Title: return tr("Cluster Matrix:");
      case Role::WhatsThis: return tr("Input cluster matrix containing cluster composition data.");
      case Role::DataType: return DataFactory::CCMatrixType;
      default: return QVariant();
      }
   case CorrelationData:
      switch (role)
      {
      case Role::CommandLineName: return QString("cmx");
      case Role::Title: return tr("Correlation Matrix:");
      case Role::WhatsThis: return tr("Input correlation matrix containing correlation data.");
      case Role::DataType: return DataFactory::CorrelationMatrixType;
      default: return QVariant();
      }
   case OutputFormatArg:
      switch (role)
      {
      case Role::CommandLineName: return QString("format");
      case Role::Title: return tr("Output Format:");
      case Role::WhatsThis: return tr("Format to use for the output file.");
      case Role::SelectionValues: return FORMAT_NAMES;
      case Role::Default: return "text";
      default: return QVariant();
      }
   case OutputFile:
      switch (role)
      {
      case Role::CommandLineName: return QString("output");
      case Role::Title: return tr("Output File:");
      case Role::WhatsThis: return tr("Output file that will contain network in the specified format.");
      default: return QVariant();
      }
   case MinCorrelation:
      switch (role)
      {
      case Role::CommandLineName: return QString("mincorr");
      case Role::Title: return tr("Minimum Correlation:");
      case Role::WhatsThis: return tr("Minimum (absolute) correlation threshold for gene pairs.");
      case Role::Default: return 0.85;
      case Role::Minimum: return 0;
      case Role::Maximum: return 1;
      default: return QVariant();
      }
   case MaxCorrelation:
      switch (role)
      {
      case Role::CommandLineName: return QString("maxcorr");
      case Role::Title: return tr("Maximum Correlation:");
      case Role::WhatsThis: return tr("Maximum (absolute) correlation threshold for gene pairs.");
      case Role::Default: return 1;
      case Role::Minimum: return 0;
      case Role::Maximum: return 1;
      default: return QVariant();
      }
   default: return QVariant();
   }
}

/*!
 * Set an argument with the given index to the given value.
 *
 * @param index
 * @param value
 */
void Extract::Input::set(int index, const QVariant& value)
{
   EDEBUG_FUNC(this,index,&value);

   switch (index)
   {
   case OutputFormatArg:
      _base->_outputFormat = static_cast<OutputFormat>(FORMAT_NAMES.indexOf(value.toString()));
      break;
   case MinCorrelation:
      _base->_minCorrelation = value.toFloat();
      break;
   case MaxCorrelation:
      _base->_maxCorrelation = value.toFloat();
      break;
   }
}

/*!
 * Set a data argument with the given index to the given data object pointer.
 *
 * @param index
 * @param data
 */
void Extract::Input::set(int index, EAbstractData* data)
{
   EDEBUG_FUNC(this,index,data);

   if ( index == ExpressionData )
   {
      _base->_emx = data->cast<ExpressionMatrix>();
   }
   else if ( index == ClusterData )
   {
      _base->_ccm = data->cast<CCMatrix>();
   }
   else if ( index == CorrelationData )
   {
      _base->_cmx = data->cast<CorrelationMatrix>();
   }
}

/*!
 * Set a file argument with the given index to the given qt file pointer.
 *
 * @param index
 * @param file
 */
void Extract::Input::set(int index, QFile* file)
{
   EDEBUG_FUNC(this,index,file);

   if ( index == OutputFile )
   {
      _base->_output = file;
   }
}
<|endoftext|>


<commit_before>/*
 * Funambol is a mobile platform developed by Funambol, Inc.
 * Copyright (C) 2003 - 2007 Funambol, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
 * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA.
 *
 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by Funambol" logo. If the display of the logo is not reasonably
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by Funambol".
 */

#include "base/globalsdef.h"
#include "base/posixlog.h"
#include "base/fscapi.h"
#include "base/util/utils.h"

#include <unistd.h>

USE_NAMESPACE

//char logmsg[512];

POSIXLog::POSIXLog() :
    logFile(NULL),
    logFileStdout(false),
    logName(LOG_NAME),
    logRedirectStderr(false),
    fderr(-1),
    prefix("")
{
}

void POSIXLog::setLogPath(const char*  configLogPath) {
    logPath.sprintf("%s/", configLogPath ? configLogPath : "./");
}

void POSIXLog::setLogName(const char*  configLogName) {
    logName.sprintf("%s", configLogName ? configLogName : LOG_NAME);
}

void POSIXLog::setLogFile(const char *path, const char* name, bool redirectStderr) {
    if (path != logPath.c_str()) {
        setLogPath(path);
    }
    if (name != logName.c_str()) {
        setLogName(name);
    }
    logRedirectStderr = redirectStderr;

    if (logFile != NULL) {
        fclose(logFile);
        logFile = NULL;
    }
    logFileStdout = false;

    if (!strcmp(name, "-")) {
        // write to stdout
        logFileStdout = true;
    } else if (path) {
        char *filename = new char[strlen(path) + strlen(name) + 3];

        sprintf(filename, "%s/%s", path, name);
        logFile = fopen(filename, "a+" );
        delete [] filename;
    } else {
        logFile = fopen(name, "a+" );
    }

    if (logFile) {
        char buffer[256];
        struct tm tm;
        time_t t = time(NULL);

        // We log UTC at the start of each line.
        // Log the current user's time offset.
        localtime_r(&t, &tm);
        strftime(buffer, sizeof(buffer),
                 "local timezone: %Z = GMT %z",
                 &tm);
        developer("%s", buffer);
        asctime_r(&tm, buffer);
        developer("local time: %s", buffer);
        gmtime_r(&t, &tm);
        asctime_r(&tm, buffer);
        developer("world time: %s", buffer);
    }

    if (redirectStderr && logFile) {
        if (fderr == -1) {
            // remember original stderr
            fderr = dup(2);
        }
        // overwrite stderr with log file fd,
        // closing the current stderr if necessary
        dup2(fileno(logFile), 2);
    } else {
        if (fderr != -1) {
            // restore original stderr
            dup2(fderr, 2);
        }
    }
}

POSIXLog::~POSIXLog() {
    if (logFile != NULL) {
        fclose(logFile);
    }
}

void POSIXLog::error(const char*  msg, ...) {
    va_list argList;
    va_start (argList, msg);
    printMessage(LOG_LEVEL_NONE, LOG_ERROR, msg, argList);
    va_end(argList);
}

void POSIXLog::info(const char*  msg, ...) {
    if (isLoggable(LOG_LEVEL_INFO)) {
        va_list argList;
        va_start (argList, msg);
        printMessage(LOG_LEVEL_INFO, LOG_INFO, msg, argList);
        va_end(argList);
    }
}

void POSIXLog::developer(const char*  msg, ...) {
    if (isLoggable(LOG_LEVEL_INFO)) {
        va_list argList;
        va_start (argList, msg);
        printMessage(LOG_LEVEL_DEBUG, LOG_DEBUG, msg, argList);
        va_end(argList);
    }
}

void POSIXLog::debug(const char*  msg, ...) {
    if (isLoggable(LOG_LEVEL_DEBUG)) {
        va_list argList;
        va_start (argList, msg);
        printMessage(LOG_LEVEL_DEBUG, LOG_DEBUG, msg, argList);
        va_end(argList);
    }
}

void POSIXLog::printLine(bool firstLine,
                         time_t time,
                         const char *fullTime,
                         const char *shortTime,
                         const char *utcTime,
                         LogLevel level,
                         const char *levelPrefix,
                         const char *line)
{
    FILE *out = getLogFile();
    if (!out) {
        out = stdout;
    }
    if (firstLine) {
        fprintf(out, "%s [%s] %s%s\n",
                logFile ? utcTime : shortTime,
                levelPrefix,
                getPrefix().c_str(),
                line);
    } else {
        fprintf(out, "[%s] %s%s\n",
                levelPrefix,
                getPrefix().c_str(),
                line);
    }
    fflush(out);
}

void POSIXLog::printMessage(LogLevel level, const char* levelPrefix, const char* msg, va_list argList) {
    time_t t = time(NULL);
    struct tm sys_time;
    struct tm utc_time;
    char fullTime[64], shortTime[32];
    char utcTime[32];

    localtime_r(&t, &sys_time);
    gmtime_r(&t, &utc_time);

    strftime(fullTime, sizeof(fullTime), "%F %T GMT %z", &sys_time);
    strftime(shortTime, sizeof(shortTime), "%T", &sys_time);
    sprintf(utcTime, "%02d:%02d:%02d GMT",
            utc_time.tm_hour,
            utc_time.tm_min,
            utc_time.tm_sec);

    if (!logFileStdout && !logFile) {
         setLogFile(logPath, logName, logRedirectStderr);
    }

    StringBuffer buffer;
    buffer.vsprintf(msg, argList);
    const char *start = buffer.c_str();
    const char *eol = strchr(start, '\n');
    bool firstLine = true;
    while (eol) {
        /* hack: StringBuffer does not really allow write access, but do it anyway */
        *(char *)eol = 0;
        printLine(firstLine,
                  t,
                  fullTime,
                  shortTime,
                  utcTime,
                  level,
                  levelPrefix,
                  start);
        firstLine = false;
        *(char *)eol = '\n';
        start = eol + 1;
        eol = strchr(start, '\n');
    }
    printLine(firstLine,
              t,
              fullTime,
              shortTime,
              utcTime,
              level,
              levelPrefix,
              start);
}

void POSIXLog::reset(const char*  title) {
    setLogFile(logPath, logName, logRedirectStderr);

    if (logFile) {
        ftruncate(fileno(logFile), 0);
    }
}

size_t POSIXLog::getLogSize() {
    size_t ret = 0;

    if (logFile) {
        ret = fgetsize(logFile);
        fclose(logFile);
    }
    return ret;
}

Log *Log::logger;

Log &Log::instance() {
    if (!logger) {
        logger = new POSIXLog();
    }
    return *logger;
}

<commit_msg>minor fixes<commit_after>/*
 * Funambol is a mobile platform developed by Funambol, Inc.
 * Copyright (C) 2003 - 2007 Funambol, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
 * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA.
 *
 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by Funambol" logo. If the display of the logo is not reasonably
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by Funambol".
 */

#include "base/globalsdef.h"
#include "base/posixlog.h"
#include "base/fscapi.h"
#include "base/util/utils.h"

#include <unistd.h>

USE_NAMESPACE

//char logmsg[512];

POSIXLog::POSIXLog() :
    logFile(NULL),
    logPath(NULL),
    logFileStdout(false),
    logName(LOG_NAME),
    logRedirectStderr(false),
    fderr(-1),
    prefix("")
{
}

void POSIXLog::setLogPath(const char*  configLogPath) {
    logPath.sprintf("%s/", configLogPath ? configLogPath : "./");
}

void POSIXLog::setLogName(const char*  configLogName) {
    logName.sprintf("%s", configLogName ? configLogName : LOG_NAME);
}

void POSIXLog::setLogFile(const char *path, const char* name, bool redirectStderr) {
    if (logPath != path) {
        setLogPath(path);
    }
    if (logName != name) {
        setLogName(name);
    }
    logRedirectStderr = redirectStderr;

    if (logFile != NULL) {
        fclose(logFile);
        logFile = NULL;
    }
    logFileStdout = false;

    if (!strcmp(name, "-")) {
        // write to stdout
        logFileStdout = true;
    } else if (path) {
        char *filename = new char[strlen(path) + strlen(name) + 3];

        sprintf(filename, "%s/%s", path, name);
        logFile = fopen(filename, "a+" );
        delete [] filename;
    } else {
        logFile = fopen(name, "a+" );
    }

    if (logFile) {
        char buffer[256];
        struct tm tm;
        time_t t = time(NULL);

        // We log UTC at the start of each line.
        // Log the current user's time offset.
        localtime_r(&t, &tm);
        strftime(buffer, sizeof(buffer),
                 "local timezone: %Z = GMT %z",
                 &tm);
        developer("%s", buffer);
        asctime_r(&tm, buffer);
        developer("local time: %s", buffer);
        gmtime_r(&t, &tm);
        asctime_r(&tm, buffer);
        developer("world time: %s", buffer);
    }

    if (redirectStderr && logFile) {
        if (fderr == -1) {
            // remember original stderr
            fderr = dup(2);
        }
        // overwrite stderr with log file fd,
        // closing the current stderr if necessary
        dup2(fileno(logFile), 2);
    } else {
        if (fderr != -1) {
            // restore original stderr
            dup2(fderr, 2);
        }
    }
}

POSIXLog::~POSIXLog() {
    if (logFile != NULL) {
        fclose(logFile);
    }
}

void POSIXLog::error(const char*  msg, ...) {
    va_list argList;
    va_start (argList, msg);
    printMessage(LOG_LEVEL_NONE, LOG_ERROR, msg, argList);
    va_end(argList);
}

void POSIXLog::info(const char*  msg, ...) {
    if (isLoggable(LOG_LEVEL_INFO)) {
        va_list argList;
        va_start (argList, msg);
        printMessage(LOG_LEVEL_INFO, LOG_INFO, msg, argList);
        va_end(argList);
    }
}

void POSIXLog::developer(const char*  msg, ...) {
    if (isLoggable(LOG_LEVEL_INFO)) {
        va_list argList;
        va_start (argList, msg);
        printMessage(LOG_LEVEL_DEBUG, LOG_DEBUG, msg, argList);
        va_end(argList);
    }
}

void POSIXLog::debug(const char*  msg, ...) {
    if (isLoggable(LOG_LEVEL_DEBUG)) {
        va_list argList;
        va_start (argList, msg);
        printMessage(LOG_LEVEL_DEBUG, LOG_DEBUG, msg, argList);
        va_end(argList);
    }
}

void POSIXLog::printLine(bool firstLine,
                         time_t time,
                         const char *fullTime,
                         const char *shortTime,
                         const char *utcTime,
                         LogLevel level,
                         const char *levelPrefix,
                         const char *line)
{
    FILE *out = getLogFile();
    if (!out) {
        out = stdout;
    }
    if (firstLine) {
        fprintf(out, "%s [%s] %s%s\n",
                logFile ? utcTime : shortTime,
                levelPrefix,
                getPrefix().c_str(),
                line);
    } else {
        fprintf(out, "[%s] %s%s\n",
                levelPrefix,
                getPrefix().c_str(),
                line);
    }
    fflush(out);
}

void POSIXLog::printMessage(LogLevel level, const char* levelPrefix, const char* msg, va_list argList) {
    time_t t = time(NULL);
    struct tm sys_time;
    struct tm utc_time;
    char fullTime[64], shortTime[32];
    char utcTime[32];

    localtime_r(&t, &sys_time);
    gmtime_r(&t, &utc_time);

    strftime(fullTime, sizeof(fullTime), "%F %T GMT %z", &sys_time);
    strftime(shortTime, sizeof(shortTime), "%T", &sys_time);
    sprintf(utcTime, "%02d:%02d:%02d GMT",
            utc_time.tm_hour,
            utc_time.tm_min,
            utc_time.tm_sec);

    if (!logFileStdout && !logFile) {
         setLogFile(logPath, logName, logRedirectStderr);
    }

    StringBuffer buffer;
    buffer.vsprintf(msg, argList);
    const char *start = buffer.c_str();
    const char *eol = strchr(start, '\n');
    bool firstLine = true;
    while (eol) {
        /* hack: StringBuffer does not really allow write access, but do it anyway */
        *(char *)eol = 0;
        printLine(firstLine,
                  t,
                  fullTime,
                  shortTime,
                  utcTime,
                  level,
                  levelPrefix,
                  start);
        firstLine = false;
        *(char *)eol = '\n';
        start = eol + 1;
        eol = strchr(start, '\n');
    }
    printLine(firstLine,
              t,
              fullTime,
              shortTime,
              utcTime,
              level,
              levelPrefix,
              start);
}

void POSIXLog::reset(const char*  title) {
    setLogFile(logPath, logName, logRedirectStderr);

    if (logFile) {
        ftruncate(fileno(logFile), 0);
    }
}

size_t POSIXLog::getLogSize() {
    size_t ret = 0;

    if (logFile) {
        ret = fgetsize(logFile);
        fclose(logFile);
    }
    return ret;
}

Log *Log::logger;

Log &Log::instance() {
    if (!logger) {
        logger = new POSIXLog();
    }
    return *logger;
}

<|endoftext|>