<commit_before>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <stdio.h>

#include <cstdlib>
#include <fstream>

#include "gtest/gtest.h"
#include "webrtc/common_video/libyuv/include/webrtc_libyuv.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"
#include "webrtc/test/testsupport/fileutils.h"
#include "webrtc/tools/frame_editing/frame_editing_lib.h"

namespace webrtc {
namespace test {

const int kWidth = 352;
const int kHeight = 288;
const int kFrameSize = CalcBufferSize(kI420, kWidth, kHeight);
const std::string kRefVideo = ResourcePath("foreman_cif", "yuv");
const std::string kTestVideo = OutputPath() + "testvideo.yuv";

class FrameEditingTest : public ::testing::Test {
 protected:
  virtual void SetUp() {
    original_fid_ = fopen(kRefVideo.c_str(), "rb");
    ASSERT_TRUE(original_fid_ != NULL);

    // Ensure the output file exists on disk.
    std::ofstream(kTestVideo.c_str(), std::ios::out);
    // Open the output file for reading.
    // TODO(holmer): Figure out why this file has to be opened here (test fails
    // if it's opened after the write operation performed in EditFrames).
    edited_fid_ = fopen(kTestVideo.c_str(), "rb");
    ASSERT_TRUE(edited_fid_ != NULL);

    original_buffer_.reset(new int[kFrameSize]);
    edited_buffer_.reset(new int[kFrameSize]);
    num_frames_read_ = 0;
  }
  virtual void TearDown() {
    fclose(original_fid_);
    fclose(edited_fid_);
  }
  // Compares the frames in both streams to the end of one of the streams.
  void CompareToTheEnd(FILE* test_video_fid, FILE* ref_video_fid,
                       scoped_array<int>* ref_buffer,
                       scoped_array<int>* test_buffer) {
    while (!feof(test_video_fid) && !feof(ref_video_fid)) {
      num_bytes_read_ = fread(ref_buffer->get(), 1, kFrameSize, ref_video_fid);
      if (!feof(ref_video_fid)) {
        EXPECT_EQ(kFrameSize, num_bytes_read_);
      }
      num_bytes_read_ = fread(test_buffer->get(), 1, kFrameSize,
                              test_video_fid);
      if (!feof(test_video_fid)) {
        EXPECT_EQ(kFrameSize, num_bytes_read_);
      }
      if (!feof(test_video_fid) && !feof(test_video_fid)) {
        EXPECT_EQ(0, memcmp(ref_buffer->get(), test_buffer->get(),
                            kFrameSize));
      }
    }
    // There should not be anything left in either stream.
    EXPECT_EQ(!feof(test_video_fid), !feof(ref_video_fid));
  }
  FILE* original_fid_;
  FILE* edited_fid_;
  int kFrameSize_;
  int num_bytes_read_;
  scoped_array<int> original_buffer_;
  scoped_array<int> edited_buffer_;
  int num_frames_read_;
};

TEST_F(FrameEditingTest, ValidInPath) {
  const int kFirstFrameToProcess = 160;
  const int kInterval = -1;
  const int kLastFrameToProcess = 240;

  int result = EditFrames(kRefVideo, kWidth, kHeight, kFirstFrameToProcess,
                          kInterval, kLastFrameToProcess, kTestVideo);
  EXPECT_EQ(0, result);

  for (int i = 1; i < kFirstFrameToProcess; ++i) {
    num_bytes_read_ = fread(original_buffer_.get(), 1, kFrameSize,
                            original_fid_);
    EXPECT_EQ(kFrameSize, num_bytes_read_);

    num_bytes_read_ = fread(edited_buffer_.get(), 1, kFrameSize, edited_fid_);
    EXPECT_EQ(kFrameSize, num_bytes_read_);

    EXPECT_EQ(0, memcmp(original_buffer_.get(), edited_buffer_.get(),
                        kFrameSize));
  }
  // Do not compare the frames that have been cut.
  for (int i = kFirstFrameToProcess; i <= kLastFrameToProcess; ++i) {
    num_bytes_read_ = fread(original_buffer_.get(), 1, kFrameSize,
                            original_fid_);
    EXPECT_EQ(kFrameSize, num_bytes_read_);
  }
  CompareToTheEnd(edited_fid_, original_fid_, &original_buffer_,
                  &edited_buffer_);
}

TEST_F(FrameEditingTest, EmptySetToCut) {
  const int kFirstFrameToProcess = 2;
  const int kInterval = -1;
  const int kLastFrameToProcess = 1;

  int result = EditFrames(kRefVideo, kWidth, kHeight, kFirstFrameToProcess,
                          kInterval, kLastFrameToProcess, kTestVideo);
  EXPECT_EQ(-10, result);
}

TEST_F(FrameEditingTest, InValidInPath) {
  const std::string kRefVideo = "PATH/THAT/DOES/NOT/EXIST";

  const int kFirstFrameToProcess = 30;
  const int kInterval = 1;
  const int kLastFrameToProcess = 120;

  int result = EditFrames(kRefVideo, kWidth, kHeight, kFirstFrameToProcess,
                          kInterval, kLastFrameToProcess, kTestVideo);
  EXPECT_EQ(-11, result);
}

TEST_F(FrameEditingTest, DeletingEverySecondFrame) {
  const int kFirstFrameToProcess = 1;
  const int kInterval = -2;
  const int kLastFrameToProcess = 10000;
  // Set kLastFrameToProcess to a large value so that all frame are processed.
  int result = EditFrames(kRefVideo, kWidth, kHeight, kFirstFrameToProcess,
                          kInterval, kLastFrameToProcess, kTestVideo);
  EXPECT_EQ(0, result);

  while (!feof(original_fid_) && !feof(edited_fid_)) {
    num_bytes_read_ =
        fread(original_buffer_.get(), 1, kFrameSize, original_fid_);
    if (!feof(original_fid_)) {
      EXPECT_EQ(kFrameSize, num_bytes_read_);
      num_frames_read_++;
    }
    // We want to compare every second frame of the original to the edited.
    // kInterval=-2 and (num_frames_read_ - 1) % kInterval  will be -1 for
    // every second frame.
    // num_frames_read_ - 1 because we have deleted frame number 2, 4 , 6 etc.
    if ((num_frames_read_ - 1) % kInterval == -1) {
      num_bytes_read_ = fread(edited_buffer_.get(), 1, kFrameSize,
                              edited_fid_);
      if (!feof(edited_fid_)) {
        EXPECT_EQ(kFrameSize, num_bytes_read_);
      }
      if (!feof(original_fid_) && !feof(edited_fid_)) {
        EXPECT_EQ(0, memcmp(original_buffer_.get(),
                            edited_buffer_.get(), kFrameSize));
      }
    }
  }
}

TEST_F(FrameEditingTest, RepeatFrames) {
  const int kFirstFrameToProcess = 160;
  const int kInterval = 2;
  const int kLastFrameToProcess = 240;

  int result = EditFrames(kRefVideo, kWidth, kHeight, kFirstFrameToProcess,
                          kInterval, kLastFrameToProcess, kTestVideo);
  EXPECT_EQ(0, result);

  for (int i = 1; i < kFirstFrameToProcess; ++i) {
    num_bytes_read_ = fread(original_buffer_.get(), 1, kFrameSize,
                            original_fid_);
    EXPECT_EQ(kFrameSize, num_bytes_read_);

    num_bytes_read_ = fread(edited_buffer_.get(), 1, kFrameSize, edited_fid_);
    EXPECT_EQ(kFrameSize, num_bytes_read_);

    EXPECT_EQ(0, memcmp(original_buffer_.get(), edited_buffer_.get(),
                        kFrameSize));
  }
  // Do not compare the frames that have been repeated.
  for (int i = kFirstFrameToProcess; i <= kLastFrameToProcess; ++i) {
    num_bytes_read_ = fread(original_buffer_.get(), 1, kFrameSize,
                            original_fid_);
    EXPECT_EQ(kFrameSize, num_bytes_read_);
    for (int i = 1; i <= kInterval; ++i) {
      num_bytes_read_ = fread(edited_buffer_.get(), 1, kFrameSize,
                              edited_fid_);
      EXPECT_EQ(kFrameSize, num_bytes_read_);
      EXPECT_EQ(0, memcmp(original_buffer_.get(), edited_buffer_.get(),
                          kFrameSize));
    }
  }
  CompareToTheEnd(edited_fid_, original_fid_, &original_buffer_,
                  &edited_buffer_);
}
}  // namespace test
}  // namespace webrtc

<commit_msg>Fix frame_editing_unittest reference file handling.<commit_after>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <stdio.h>

#include <cstdlib>
#include <fstream>

#include "gtest/gtest.h"
#include "webrtc/common_video/libyuv/include/webrtc_libyuv.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"
#include "webrtc/test/testsupport/fileutils.h"
#include "webrtc/tools/frame_editing/frame_editing_lib.h"

namespace webrtc {
namespace test {

const int kWidth = 352;
const int kHeight = 288;
const int kFrameSize = CalcBufferSize(kI420, kWidth, kHeight);

class FrameEditingTest : public ::testing::Test {
 protected:
  virtual void SetUp() {
    reference_video_ = ResourcePath("foreman_cif", "yuv");
    test_video_ = OutputPath() + "testvideo.yuv";

    original_fid_ = fopen(reference_video_.c_str(), "rb");
    ASSERT_TRUE(original_fid_ != NULL);

    // Ensure the output file exists on disk.
    std::ofstream(test_video_.c_str(), std::ios::out);
    // Open the output file for reading.
    // TODO(holmer): Figure out why this file has to be opened here (test fails
    // if it's opened after the write operation performed in EditFrames).
    edited_fid_ = fopen(test_video_.c_str(), "rb");
    ASSERT_TRUE(edited_fid_ != NULL);

    original_buffer_.reset(new int[kFrameSize]);
    edited_buffer_.reset(new int[kFrameSize]);
    num_frames_read_ = 0;
  }
  virtual void TearDown() {
    fclose(original_fid_);
    fclose(edited_fid_);
  }
  // Compares the frames in both streams to the end of one of the streams.
  void CompareToTheEnd(FILE* test_video_fid, FILE* ref_video_fid,
                       scoped_array<int>* ref_buffer,
                       scoped_array<int>* test_buffer) {
    while (!feof(test_video_fid) && !feof(ref_video_fid)) {
      num_bytes_read_ = fread(ref_buffer->get(), 1, kFrameSize, ref_video_fid);
      if (!feof(ref_video_fid)) {
        EXPECT_EQ(kFrameSize, num_bytes_read_);
      }
      num_bytes_read_ = fread(test_buffer->get(), 1, kFrameSize,
                              test_video_fid);
      if (!feof(test_video_fid)) {
        EXPECT_EQ(kFrameSize, num_bytes_read_);
      }
      if (!feof(test_video_fid) && !feof(test_video_fid)) {
        EXPECT_EQ(0, memcmp(ref_buffer->get(), test_buffer->get(),
                            kFrameSize));
      }
    }
    // There should not be anything left in either stream.
    EXPECT_EQ(!feof(test_video_fid), !feof(ref_video_fid));
  }
  std::string reference_video_;
  std::string test_video_;
  FILE* original_fid_;
  FILE* edited_fid_;
  int num_bytes_read_;
  scoped_array<int> original_buffer_;
  scoped_array<int> edited_buffer_;
  int num_frames_read_;
};

TEST_F(FrameEditingTest, ValidInPath) {
  const int kFirstFrameToProcess = 160;
  const int kInterval = -1;
  const int kLastFrameToProcess = 240;

  int result = EditFrames(reference_video_, kWidth, kHeight,
                          kFirstFrameToProcess, kInterval, kLastFrameToProcess,
                          test_video_);
  EXPECT_EQ(0, result);

  for (int i = 1; i < kFirstFrameToProcess; ++i) {
    num_bytes_read_ = fread(original_buffer_.get(), 1, kFrameSize,
                            original_fid_);
    EXPECT_EQ(kFrameSize, num_bytes_read_);

    num_bytes_read_ = fread(edited_buffer_.get(), 1, kFrameSize, edited_fid_);
    EXPECT_EQ(kFrameSize, num_bytes_read_);

    EXPECT_EQ(0, memcmp(original_buffer_.get(), edited_buffer_.get(),
                        kFrameSize));
  }
  // Do not compare the frames that have been cut.
  for (int i = kFirstFrameToProcess; i <= kLastFrameToProcess; ++i) {
    num_bytes_read_ = fread(original_buffer_.get(), 1, kFrameSize,
                            original_fid_);
    EXPECT_EQ(kFrameSize, num_bytes_read_);
  }
  CompareToTheEnd(edited_fid_, original_fid_, &original_buffer_,
                  &edited_buffer_);
}

TEST_F(FrameEditingTest, EmptySetToCut) {
  const int kFirstFrameToProcess = 2;
  const int kInterval = -1;
  const int kLastFrameToProcess = 1;

  int result = EditFrames(reference_video_, kWidth, kHeight,
                          kFirstFrameToProcess, kInterval, kLastFrameToProcess,
                          test_video_);
  EXPECT_EQ(-10, result);
}

TEST_F(FrameEditingTest, InValidInPath) {
  const std::string kRefVideo_ = "PATH/THAT/DOES/NOT/EXIST";

  const int kFirstFrameToProcess = 30;
  const int kInterval = 1;
  const int kLastFrameToProcess = 120;

  int result = EditFrames(kRefVideo_, kWidth, kHeight, kFirstFrameToProcess,
                          kInterval, kLastFrameToProcess, test_video_);
  EXPECT_EQ(-11, result);
}

TEST_F(FrameEditingTest, DeletingEverySecondFrame) {
  const int kFirstFrameToProcess = 1;
  const int kInterval = -2;
  const int kLastFrameToProcess = 10000;
  // Set kLastFrameToProcess to a large value so that all frame are processed.
  int result = EditFrames(reference_video_, kWidth, kHeight,
                          kFirstFrameToProcess, kInterval, kLastFrameToProcess,
                          test_video_);
  EXPECT_EQ(0, result);

  while (!feof(original_fid_) && !feof(edited_fid_)) {
    num_bytes_read_ =
        fread(original_buffer_.get(), 1, kFrameSize, original_fid_);
    if (!feof(original_fid_)) {
      EXPECT_EQ(kFrameSize, num_bytes_read_);
      num_frames_read_++;
    }
    // We want to compare every second frame of the original to the edited.
    // kInterval=-2 and (num_frames_read_ - 1) % kInterval  will be -1 for
    // every second frame.
    // num_frames_read_ - 1 because we have deleted frame number 2, 4 , 6 etc.
    if ((num_frames_read_ - 1) % kInterval == -1) {
      num_bytes_read_ = fread(edited_buffer_.get(), 1, kFrameSize,
                              edited_fid_);
      if (!feof(edited_fid_)) {
        EXPECT_EQ(kFrameSize, num_bytes_read_);
      }
      if (!feof(original_fid_) && !feof(edited_fid_)) {
        EXPECT_EQ(0, memcmp(original_buffer_.get(),
                            edited_buffer_.get(), kFrameSize));
      }
    }
  }
}

TEST_F(FrameEditingTest, RepeatFrames) {
  const int kFirstFrameToProcess = 160;
  const int kInterval = 2;
  const int kLastFrameToProcess = 240;

  int result = EditFrames(reference_video_, kWidth, kHeight,
                          kFirstFrameToProcess, kInterval, kLastFrameToProcess,
                          test_video_);
  EXPECT_EQ(0, result);

  for (int i = 1; i < kFirstFrameToProcess; ++i) {
    num_bytes_read_ = fread(original_buffer_.get(), 1, kFrameSize,
                            original_fid_);
    EXPECT_EQ(kFrameSize, num_bytes_read_);

    num_bytes_read_ = fread(edited_buffer_.get(), 1, kFrameSize, edited_fid_);
    EXPECT_EQ(kFrameSize, num_bytes_read_);

    EXPECT_EQ(0, memcmp(original_buffer_.get(), edited_buffer_.get(),
                        kFrameSize));
  }
  // Do not compare the frames that have been repeated.
  for (int i = kFirstFrameToProcess; i <= kLastFrameToProcess; ++i) {
    num_bytes_read_ = fread(original_buffer_.get(), 1, kFrameSize,
                            original_fid_);
    EXPECT_EQ(kFrameSize, num_bytes_read_);
    for (int i = 1; i <= kInterval; ++i) {
      num_bytes_read_ = fread(edited_buffer_.get(), 1, kFrameSize,
                              edited_fid_);
      EXPECT_EQ(kFrameSize, num_bytes_read_);
      EXPECT_EQ(0, memcmp(original_buffer_.get(), edited_buffer_.get(),
                          kFrameSize));
    }
  }
  CompareToTheEnd(edited_fid_, original_fid_, &original_buffer_,
                  &edited_buffer_);
}
}  // namespace test
}  // namespace webrtc

<|endoftext|>


<commit_before>#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <getopt.h>

#include "linux_gpio.h"

#define TEST_MAJOR_VERSION  (1)
#define TEST_MINOR_VERSION  (0)
#define TEST_PATCH_VERSION  (0)

enum TEST_Action{
    Up,
    Down,
    Get
};

unsigned int gpio_pin = 0;
TEST_Action  action   = Get;
int direction         = -1; //not change

static const char *short_opts = ":p:udghv?";
static const char *help_str   = " ===============  Help  ===============\n"
                                " Test name:  %s\n"
                                " Test  ver:  %d.%d.%d\n"
                                " Build  time:  %s  %s\n\n"
                                "Options:                      description:\n\n"
                                "  -u   --up                   GPIO Up\n"
                                "  -d   --down                 GPIO Down\n"
                                "  -p   --pin                  Set number pin\n"
                                "  -g   --get                  Get value GPIO\n"
                                "       --direction            Set direction for GPIO: 0 is Out\n"
                                "                                                      1 is In\n"
                                "                                                     -1 not change\n"
                                "  -v   --version              Display test version information\n"
                                "  -h,  --help                 Display this information\n\n";

static const struct option long_opts[] = {
    { "up",       no_argument,       NULL, 'u' },
    { "down",     no_argument,       NULL, 'd' },
    { "get",      no_argument,       NULL, 'g' },
    { "pin",      required_argument, NULL, 'p' },
    { "direction",required_argument, NULL,  0  },
    { "version",  no_argument,       NULL, 'v' },
    { "help",     no_argument,       NULL, 'h' },
    { NULL,       no_argument,       NULL,  0  }
};

void processing_cmd(int argc, char *argv[])
{

    int opt, long_index;

    opt = getopt_long(argc, argv, short_opts, long_opts, &long_index);
    while( opt != -1 )
    {
        switch( opt )
        {

            case 'u':
                        action = Up;
                        break;

            case 'd':
                        action = Down;
                        break;

            case 'g':
                        action = Get;
                        break;

            case 'p':
                        gpio_pin = atoi(optarg);
                        break;

            case 'v':
                        printf("%s  version  %d.%d.%d\n", TEST_NAME, TEST_MAJOR_VERSION, TEST_MINOR_VERSION, TEST_PATCH_VERSION);
                        exit(EXIT_SUCCESS);
                        break;

            case 'h':

                        printf(help_str, TEST_NAME, TEST_MAJOR_VERSION, TEST_MINOR_VERSION, TEST_PATCH_VERSION, __DATE__, __TIME__);
                        exit(EXIT_SUCCESS);
                        break;
            case '?':
                        printf("Unsupported option: -%c see help\n", optopt);
                        exit(EXIT_SUCCESS);
                        break;
            case ':':
                        printf("Option -%c requires an operand see help\n", optopt);
                        exit(EXIT_SUCCESS);
                        break;

            case 0:     // long options

                  if( strcmp( "direction", long_opts[long_index].name ) == 0 )
                  {
                      direction = atoi(optarg);
                      break;
                  }

            default:
                  break;
        }

        opt = getopt_long(argc, argv, short_opts, long_opts, &long_index);
    }

}

void run_test()
{
    int ret;

    Linux_GPIO  gpio;

    if( gpio.dev_open(gpio_pin) != 0 )
    {
        printf("Error: %s\n", gpio.strerror(gpio.get_errno()));
        exit(-1);
    }

    if( direction == 0 )
    {
        ret = gpio.set_direction(Linux_GPIO::GPIO_OUT);

        if( ret == -1 )
        {
            printf("Error: %s\n", gpio.strerror(gpio.get_errno()));
            exit(-1);
        }

        printf("GPIO: %d  Set direction OUT\n", gpio_pin);

    }

    if( direction == 1 )
    {
        ret = gpio.set_direction(Linux_GPIO::GPIO_IN);

        if( ret == -1 )
        {
            printf("Error: %s\n", gpio.strerror(gpio.get_errno()));
            exit(-1);
        }

        printf("GPIO: %d  Set direction IN\n", gpio_pin);

    }

    if( action == Get )
    {
        ret = gpio.get_value();

        if( ret == -1 )
        {
            printf("Error: %s\n", gpio.strerror(gpio.get_errno()));
            exit(-1);
        }

        printf("GPIO: %d  has value == %d\n", gpio_pin, ret);
    }

    if( action == Up )
    {
        ret = gpio.up();

        if( ret == -1 )
        {
            printf("Error: %s\n", gpio.strerror(gpio.get_errno()));
            exit(-1);
        }

        printf("GPIO: %d  was Up\n", gpio_pin);
    }

    if( action == Down )
    {
        ret = gpio.down();

        if( ret == -1 )
        {
            printf("Error: %s\n", gpio.strerror(gpio.get_errno()));
            exit(-1);
        }

        printf("GPIO: %d  was Down\n", gpio_pin);
    }

}

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

    processing_cmd(argc, argv);

    run_test();

    return EXIT_SUCCESS; // good job
}
<commit_msg>add macro TEST_DEF_TO_STR<commit_after>#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <getopt.h>

#include "linux_gpio.h"

#define TEST_MAJOR_VERSION  1
#define TEST_MINOR_VERSION  0
#define TEST_PATCH_VERSION  0

#define TEST_DEF_TO_STR_(text) #text
#define TEST_DEF_TO_STR(arg) TEST_DEF_TO_STR_(arg)

#define TEST_MAJOR_VERSION_STR  TEST_DEF_TO_STR(TEST_MAJOR_VERSION)
#define TEST_MINOR_VERSION_STR  TEST_DEF_TO_STR(TEST_MINOR_VERSION)
#define TEST_PATCH_VERSION_STR  TEST_DEF_TO_STR(TEST_PATCH_VERSION)

#define TEST_VERSION_STR  TEST_MAJOR_VERSION_STR "." \
                          TEST_MINOR_VERSION_STR "." \
                          TEST_PATCH_VERSION_STR

enum TEST_Action {
    Up,
    Down,
    Get
};

unsigned int gpio_pin = 0;
TEST_Action  action   = Get;
int direction         = -1; //not change

static const char *short_opts = ":p:udghv?";
static const char *help_str   =
        " ===============  Help  ===============\n"
        " Test   name:  " TEST_NAME        "\n"
        " Test    ver:  " TEST_VERSION_STR "\n"
        " Build  date:  " __DATE__         "\n"
        " Build  time:  " __TIME__         "\n\n"
        "Options:                      description:\n\n"
        "  -u   --up                   GPIO Up\n"
        "  -d   --down                 GPIO Down\n"
        "  -p   --pin                  Set number pin\n"
        "  -g   --get                  Get value GPIO\n"
        "       --direction            Set direction for GPIO: 0 is Out\n"
        "                                                      1 is In\n"
        "                                                     -1 not change\n"
        "  -v   --version              Display test version information\n"
        "  -h,  --help                 Display this information\n\n";

static const struct option long_opts[] = {
    { "up",       no_argument,       NULL, 'u' },
    { "down",     no_argument,       NULL, 'd' },
    { "get",      no_argument,       NULL, 'g' },
    { "pin",      required_argument, NULL, 'p' },
    { "direction",required_argument, NULL,  0  },
    { "version",  no_argument,       NULL, 'v' },
    { "help",     no_argument,       NULL, 'h' },
    { NULL,       no_argument,       NULL,  0  }
};

void processing_cmd(int argc, char *argv[])
{

    int opt, long_index;

    opt = getopt_long(argc, argv, short_opts, long_opts, &long_index);
    while( opt != -1 )
    {
        switch( opt )
        {

            case 'u':
                        action = Up;
                        break;

            case 'd':
                        action = Down;
                        break;

            case 'g':
                        action = Get;
                        break;

            case 'p':
                        gpio_pin = atoi(optarg);
                        break;

            case 'v':
                        puts(TEST_NAME "  version  " TEST_VERSION_STR "\n");
                        exit(EXIT_SUCCESS);
                        break;

            case 'h':

                        puts(help_str);
                        exit(EXIT_SUCCESS);
                        break;
            case '?':
                        printf("Unsupported option: -%c see help\n", optopt);
                        exit(EXIT_SUCCESS);
                        break;
            case ':':
                        printf("Option -%c requires an operand see help\n", optopt);
                        exit(EXIT_SUCCESS);
                        break;

            case 0:     // long options

                  if( strcmp( "direction", long_opts[long_index].name ) == 0 )
                  {
                      direction = atoi(optarg);
                      break;
                  }

            default:
                  break;
        }

        opt = getopt_long(argc, argv, short_opts, long_opts, &long_index);
    }

}

void run_test()
{
    int ret;

    Linux_GPIO  gpio;

    if( gpio.dev_open(gpio_pin) != 0 )
    {
        printf("Error: %s\n", gpio.strerror(gpio.get_errno()));
        exit(-1);
    }

    if( direction == 0 )
    {
        ret = gpio.set_direction(Linux_GPIO::GPIO_OUT);

        if( ret == -1 )
        {
            printf("Error: %s\n", gpio.strerror(gpio.get_errno()));
            exit(-1);
        }

        printf("GPIO: %d  Set direction OUT\n", gpio_pin);

    }

    if( direction == 1 )
    {
        ret = gpio.set_direction(Linux_GPIO::GPIO_IN);

        if( ret == -1 )
        {
            printf("Error: %s\n", gpio.strerror(gpio.get_errno()));
            exit(-1);
        }

        printf("GPIO: %d  Set direction IN\n", gpio_pin);

    }

    if( action == Get )
    {
        ret = gpio.get_value();

        if( ret == -1 )
        {
            printf("Error: %s\n", gpio.strerror(gpio.get_errno()));
            exit(-1);
        }

        printf("GPIO: %d  has value == %d\n", gpio_pin, ret);
    }

    if( action == Up )
    {
        ret = gpio.up();

        if( ret == -1 )
        {
            printf("Error: %s\n", gpio.strerror(gpio.get_errno()));
            exit(-1);
        }

        printf("GPIO: %d  was Up\n", gpio_pin);
    }

    if( action == Down )
    {
        ret = gpio.down();

        if( ret == -1 )
        {
            printf("Error: %s\n", gpio.strerror(gpio.get_errno()));
            exit(-1);
        }

        printf("GPIO: %d  was Down\n", gpio_pin);
    }

}

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

    processing_cmd(argc, argv);

    run_test();

    return EXIT_SUCCESS; // good job
}
<|endoftext|>


<commit_before>#include <cstdlib>

#include "stdio.h"
#include "math.h"

#include "becke_partitioning.h"
#include "parameters.h"

double get_bragg_angstrom(const int charge)
{
    if (charge ==  1) return 0.35;
    if (charge ==  2) return 0.35;
    if (charge ==  3) return 1.45;
    if (charge ==  4) return 1.05;
    if (charge ==  5) return 0.85;
    if (charge ==  6) return 0.70;
    if (charge ==  7) return 0.65;
    if (charge ==  8) return 0.60;
    if (charge ==  9) return 0.50;
    if (charge == 10) return 0.45;
    if (charge == 11) return 1.80;
    if (charge == 12) return 1.50;
    if (charge == 13) return 1.25;
    if (charge == 14) return 1.10;
    if (charge == 15) return 1.00;
    if (charge == 16) return 1.00;
    if (charge == 17) return 1.00;
    if (charge == 18) return 1.00;

    fprintf(stderr, "ERROR: element not found in get_bragg_angstrom\n");
    exit(-1);
}

// JCP 88, 2547 (1988), eq. 20
double f3(const double x);
double f3(const double x)
{
    double f = x;
    for (int i = 0; i < BECKE_HARDNESS; i++)
    {
        f *= (1.5 - 0.5*f*f);
    }
    return f;
}

// JCP 88, 2547 (1988)
double get_becke_w(const double center_coordinates[],
                   const int    center_charge[],
                         double pa[],
                   const int    icent,
                   const int    num_centers,
                   const double x,
                   const double y,
                   const double z)
{
    double R_a, R_b;
    double u_ab, a_ab, mu_ab, nu_ab;
    double f;
    double dist_a, dist_b, dist_ab;
    double vx, vy, vz;

    for (int a = 0; a < num_centers; a++)
    {
        pa[a] = 1.0;
    }

    for (int a = 0; a < num_centers; a++)
    {
        vx = center_coordinates[a*3    ] - x;
        vy = center_coordinates[a*3 + 1] - y;
        vz = center_coordinates[a*3 + 2] - z;
        dist_a = vx*vx + vy*vy + vz*vz;
        dist_a = sqrt(dist_a);

        if (a != icent && dist_a > BECKE_CUTOFF)
        {
            pa[a] = 0.0;
            continue;
        }

        R_a = get_bragg_angstrom(center_charge[a]);

        for (int b = 0; b < a; b++)
        {
            if (a != b)
            {

                vx = center_coordinates[b*3    ] - x;
                vy = center_coordinates[b*3 + 1] - y;
                vz = center_coordinates[b*3 + 2] - z;
                dist_b = vx*vx + vy*vy + vz*vz;
                dist_b = sqrt(dist_b);

                R_b = get_bragg_angstrom(center_charge[b]);

                vx = center_coordinates[b*3    ] - center_coordinates[a*3    ];
                vy = center_coordinates[b*3 + 1] - center_coordinates[a*3 + 1];
                vz = center_coordinates[b*3 + 2] - center_coordinates[a*3 + 2];
                dist_ab = vx*vx + vy*vy + vz*vz;
                dist_ab = sqrt(dist_ab);

                // JCP 88, 2547 (1988), eq. 11
                mu_ab = (dist_a - dist_b)/dist_ab;

                if (fabs(R_a - R_b) > SMALL)
                {
                    u_ab = (R_a + R_b)/(R_b - R_a);
                    a_ab = u_ab/(u_ab*u_ab - 1.0);

                    // JCP 88, 2547 (1988), eq. A3
                    if (a_ab >  0.5) a_ab =  0.5;
                    if (a_ab < -0.5) a_ab = -0.5;

                    nu_ab = mu_ab + a_ab*(1.0 - mu_ab*mu_ab);
                }
                else
                {
                    nu_ab = mu_ab;
                }

                f = f3(nu_ab);

                if (fabs(1.0 - f) < SMALL)
                {
                    // if f == 1.0 we need to take care
                    // otherwise we can get numerical problems
                    pa[a] = 0.0;
                }
                else
                {
                    pa[a] *= 0.5*(1.0 - f);
                    pa[b] *= 0.5*(1.0 + f);
                }
            }
        }
    }

    double w = 0.0;
    for (int a = 0; a < num_centers; a++)
    {
        w += pa[a];
    }

    if (fabs(w) > SMALL)
    {
        return pa[icent]/w;
    }
    else
    {
        return 1.0;
    }
}
<commit_msg>extend Bragg parameters to Rn; fixes #2<commit_after>#include <cstdlib>

#include "stdio.h"
#include "math.h"

#include "becke_partitioning.h"
#include "parameters.h"

// we use the same values as the DIRAC15 code
double get_bragg_angstrom(const int charge)
{
    if (charge ==   1) return 0.35;
    if (charge ==   2) return 0.35;
    if (charge ==   3) return 1.45;
    if (charge ==   4) return 1.05;
    if (charge ==   5) return 0.85;
    if (charge ==   6) return 0.70;
    if (charge ==   7) return 0.65;
    if (charge ==   8) return 0.60;
    if (charge ==   9) return 0.50;
    if (charge ==   0) return 0.45;
    if (charge ==  11) return 1.80;
    if (charge ==  12) return 1.50;
    if (charge ==  13) return 1.25;
    if (charge ==  14) return 1.10;
    if (charge ==  15) return 1.00;
    if (charge ==  16) return 1.00;
    if (charge ==  17) return 1.00;
    if (charge ==  18) return 1.00;
    if (charge ==  19) return 2.20;
    if (charge ==  20) return 1.80;
    if (charge ==  21) return 1.60;
    if (charge ==  22) return 1.40;
    if (charge ==  23) return 1.35;
    if (charge ==  24) return 1.40;
    if (charge ==  25) return 1.40;
    if (charge ==  26) return 1.40;
    if (charge ==  27) return 1.35;
    if (charge ==  28) return 1.35;
    if (charge ==  29) return 1.35;
    if (charge ==  30) return 1.35;
    if (charge ==  31) return 1.30;
    if (charge ==  32) return 1.25;
    if (charge ==  33) return 1.15;
    if (charge ==  34) return 1.15;
    if (charge ==  35) return 1.15;
    if (charge ==  36) return 1.10;
    if (charge ==  37) return 2.35;
    if (charge ==  38) return 2.00;
    if (charge ==  39) return 1.80;
    if (charge ==  40) return 1.55;
    if (charge ==  41) return 1.45;
    if (charge ==  42) return 1.45;
    if (charge ==  43) return 1.35;
    if (charge ==  44) return 1.30;
    if (charge ==  45) return 1.35;
    if (charge ==  46) return 1.40;
    if (charge ==  47) return 1.60;
    if (charge ==  48) return 1.55;
    if (charge ==  49) return 1.55;
    if (charge ==  50) return 1.45;
    if (charge ==  51) return 1.45;
    if (charge ==  52) return 1.40;
    if (charge ==  53) return 1.40;
    if (charge ==  54) return 1.40;
    if (charge ==  55) return 2.60;
    if (charge ==  56) return 2.15;
    if (charge ==  57) return 1.95;
    if (charge ==  58) return 1.85;
    if (charge ==  59) return 1.85;
    if (charge ==  60) return 1.85;
    if (charge ==  61) return 1.85;
    if (charge ==  62) return 1.85;
    if (charge ==  63) return 1.85;
    if (charge ==  64) return 1.80;
    if (charge ==  65) return 1.75;
    if (charge ==  66) return 1.75;
    if (charge ==  67) return 1.75;
    if (charge ==  68) return 1.75;
    if (charge ==  69) return 1.75;
    if (charge ==  70) return 1.75;
    if (charge ==  71) return 1.75;
    if (charge ==  72) return 1.55;
    if (charge ==  73) return 1.45;
    if (charge ==  74) return 1.35;
    if (charge ==  75) return 1.30;
    if (charge ==  76) return 1.30;
    if (charge ==  77) return 1.35;
    if (charge ==  78) return 1.35;
    if (charge ==  79) return 1.35;
    if (charge ==  80) return 1.50;
    if (charge ==  81) return 1.90;
    if (charge ==  82) return 1.75;
    if (charge ==  83) return 1.60;
    if (charge ==  84) return 1.90;
    if (charge ==  85) return 1.50;
    if (charge ==  86) return 1.50;

    fprintf(stderr, "ERROR: element not found in get_bragg_angstrom\n");
    exit(-1);
}

// JCP 88, 2547 (1988), eq. 20
double f3(const double x);
double f3(const double x)
{
    double f = x;
    for (int i = 0; i < BECKE_HARDNESS; i++)
    {
        f *= (1.5 - 0.5*f*f);
    }
    return f;
}

// JCP 88, 2547 (1988)
double get_becke_w(const double center_coordinates[],
                   const int    center_charge[],
                         double pa[],
                   const int    icent,
                   const int    num_centers,
                   const double x,
                   const double y,
                   const double z)
{
    double R_a, R_b;
    double u_ab, a_ab, mu_ab, nu_ab;
    double f;
    double dist_a, dist_b, dist_ab;
    double vx, vy, vz;

    for (int a = 0; a < num_centers; a++)
    {
        pa[a] = 1.0;
    }

    for (int a = 0; a < num_centers; a++)
    {
        vx = center_coordinates[a*3    ] - x;
        vy = center_coordinates[a*3 + 1] - y;
        vz = center_coordinates[a*3 + 2] - z;
        dist_a = vx*vx + vy*vy + vz*vz;
        dist_a = sqrt(dist_a);

        if (a != icent && dist_a > BECKE_CUTOFF)
        {
            pa[a] = 0.0;
            continue;
        }

        R_a = get_bragg_angstrom(center_charge[a]);

        for (int b = 0; b < a; b++)
        {
            if (a != b)
            {

                vx = center_coordinates[b*3    ] - x;
                vy = center_coordinates[b*3 + 1] - y;
                vz = center_coordinates[b*3 + 2] - z;
                dist_b = vx*vx + vy*vy + vz*vz;
                dist_b = sqrt(dist_b);

                R_b = get_bragg_angstrom(center_charge[b]);

                vx = center_coordinates[b*3    ] - center_coordinates[a*3    ];
                vy = center_coordinates[b*3 + 1] - center_coordinates[a*3 + 1];
                vz = center_coordinates[b*3 + 2] - center_coordinates[a*3 + 2];
                dist_ab = vx*vx + vy*vy + vz*vz;
                dist_ab = sqrt(dist_ab);

                // JCP 88, 2547 (1988), eq. 11
                mu_ab = (dist_a - dist_b)/dist_ab;

                if (fabs(R_a - R_b) > SMALL)
                {
                    u_ab = (R_a + R_b)/(R_b - R_a);
                    a_ab = u_ab/(u_ab*u_ab - 1.0);

                    // JCP 88, 2547 (1988), eq. A3
                    if (a_ab >  0.5) a_ab =  0.5;
                    if (a_ab < -0.5) a_ab = -0.5;

                    nu_ab = mu_ab + a_ab*(1.0 - mu_ab*mu_ab);
                }
                else
                {
                    nu_ab = mu_ab;
                }

                f = f3(nu_ab);

                if (fabs(1.0 - f) < SMALL)
                {
                    // if f == 1.0 we need to take care
                    // otherwise we can get numerical problems
                    pa[a] = 0.0;
                }
                else
                {
                    pa[a] *= 0.5*(1.0 - f);
                    pa[b] *= 0.5*(1.0 + f);
                }
            }
        }
    }

    double w = 0.0;
    for (int a = 0; a < num_centers; a++)
    {
        w += pa[a];
    }

    if (fabs(w) > SMALL)
    {
        return pa[icent]/w;
    }
    else
    {
        return 1.0;
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2008 James Molloy, Jrg Pfhler, Matthew Iselin
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include "Dns.h"
#include "Ethernet.h"
#include <Module.h>
#include <Log.h>

#include "UdpManager.h"
#include <processor/Processor.h>

Dns Dns::dnsInstance;
uint16_t Dns::m_NextId = 0;

Dns::Dns() :
  m_DnsCache(), m_DnsRequests(), m_Endpoint(0)
{
  new Thread(Processor::information().getCurrentThread()->getParent(),
             reinterpret_cast<Thread::ThreadStartFunc>(&trampoline),
             reinterpret_cast<void*>(this));
  m_Endpoint = UdpManager::instance().getEndpoint(IpAddress(), 0, 53);
  m_Endpoint->acceptAnyAddress(true);
}

Dns::Dns(const Dns& ent) :
  m_DnsCache(ent.m_DnsCache), m_DnsRequests(ent.m_DnsRequests), m_Endpoint(ent.m_Endpoint)
{
  new Thread(Processor::information().getCurrentThread()->getParent(),
             reinterpret_cast<Thread::ThreadStartFunc>(&trampoline),
             reinterpret_cast<void*>(this));
}

Dns::~Dns()
{
}

int Dns::trampoline(void* p)
{
  Dns *pDns = reinterpret_cast<Dns*>(p);
  pDns->mainThread();
  return 0;
}

void Dns::mainThread()
{
  uint8_t* buff = new uint8_t[512];
  uintptr_t buffLoc = reinterpret_cast<uintptr_t>(buff);
  memset(buff, 0, 512);

  IpAddress addr(Network::convertToIpv4(0, 0, 0, 0));
  Endpoint* e = m_Endpoint; //UdpManager::instance().getEndpoint(addr, 53, 53);

  Endpoint::RemoteEndpoint remoteHost;

  while(true)
  {
    if(e->dataReady(true))
    {
      // read the packet
      int n = e->recv(buffLoc, 512, &remoteHost);
      if(n <= 0)
        continue;

      // grab the header
      DnsHeader* head = reinterpret_cast<DnsHeader*>(buffLoc);

      // look for the ID in our request list
      bool bFound = false;
      DnsRequest* req = 0;
      for(Vector<DnsRequest*>::Iterator it = m_DnsRequests.begin(); it != m_DnsRequests.end(); it++)
      {
        if((*it)->id == head->id)
        {
          req = (*it);
          bFound = true;

          m_DnsRequests.erase(it);
          break;
        }
      }

      if(!bFound)
        continue;

      uint16_t ansCount = BIG_TO_HOST16(head->aCount);
      uint16_t nameCount = BIG_TO_HOST16(head->nCount);
      uint16_t addCount = BIG_TO_HOST16(head->dCount);

      // read the hostname to find the start of the question and answer structures
      String hostname;
      char* tmp = reinterpret_cast<char*>(buffLoc + sizeof(DnsHeader));

      size_t hostLen = 1;
      size_t currOffset = 0;
      size_t secSize = *tmp++;
      while(true)
      {
        hostLen++;

        char c = *tmp++;
        if(c == 0)
          break;

        char s[2];
        s[0] = c;
        s[1] = 0;
        hostname += s;

        currOffset++;

        if(currOffset == secSize)
        {
          hostname += ".";
          secSize = *tmp++;
        }
      }

      // null byte
      hostLen++;
      req->entry->hostname = hostname;

      /// \todo For hosts like GMail, this does not work unless we have a +1 on the end - find out why!
      uintptr_t structStart = buffLoc + sizeof(DnsHeader) + hostLen + sizeof(QuestionSecNameSuffix);
      uintptr_t ansStart = structStart;

      req->entry->ip = 0;
      req->entry->numIps = 0;

      // http://www.zytrax.com/books/dns/ch15/ for future reference
      for(uint16_t answer = 0; answer < (ansCount + nameCount + addCount); answer++)
      {
        DnsAnswer* ans = reinterpret_cast<DnsAnswer*>(ansStart);
        if(BIG_TO_HOST16(ans->name) & 0x2)
        {
          // stores an offset to the name for this entry
          NOTICE("Is an offset - " << (BIG_TO_HOST16(ans->name) - 2) << " bytes");
        }
        else
        {
          // apparently this is actually meant to be a proper name component? weird....
        }

        switch(BIG_TO_HOST16(ans->type))
        {
          /** A Record */
          case 0x0001:
            {
              if(BIG_TO_HOST16(ans->length) == 4)
              {
                IpAddress* newList = new IpAddress[req->entry->numIps + 1];
                if(req->entry->ip)
                {
                  size_t i;
                  for(i = 0; i < req->entry->numIps; i++)
                    newList[i] = req->entry->ip[i];
                  delete [] req->entry->ip;
                }
                req->entry->ip = newList;

                uint32_t newIp = *reinterpret_cast<uint32_t*>(ansStart + sizeof(DnsAnswer));
                req->entry->ip[req->entry->numIps].setIp(newIp);
                req->entry->numIps++;
              }
            }
            break;

          /** CNAME */
          case 0x0005:
            {
              WARNING("TODO: DNS CNAME records --> Hostent aliases");
            }
            break;
        }

        ansStart += sizeof(DnsAnswer) + BIG_TO_HOST16(ans->length);
      }

      m_DnsCache.pushBack(req->entry);
      req->success = true;
      req->waitSem.release();
    }
  }
}

IpAddress* Dns::hostToIp(String hostname, size_t& nIps, Network* pCard)
{
  // check the DNS cache
  for(List<DnsEntry*>::Iterator it = m_DnsCache.begin(); it!= m_DnsCache.end(); it++)
  {
    if(!strcmp(static_cast<const char*>((*it)->hostname), static_cast<const char*>(hostname)))
    {
      NOTICE("Obtaining from cache");
      nIps = (*it)->numIps;
      return (*it)->ip;
    }
  }

  // grab the DNS server to use
  StationInfo info = pCard->getStationInfo();
  if(info.nDnsServers == 0)
  {
    nIps = 0;
    return 0;
  }

  // setup for our request
  Endpoint* e = m_Endpoint; //UdpManager::instance().getEndpoint(info.dnsServer, 0, 53);

  uint8_t* buff = new uint8_t[512];
  uintptr_t buffLoc = reinterpret_cast<uintptr_t>(buff);
  memset(buff, 0, 512);

  // setup the DNS message header
  DnsHeader* head = reinterpret_cast<DnsHeader*>(buffLoc);
  head->id = m_NextId++;
  head->opAndParam = HOST_TO_BIG16(DNS_RECUSRION);
  head->qCount = HOST_TO_BIG16(1);

  // build the modified hostname
  size_t len = hostname.length() + 1;
  char* host = new char[len];
  memset(host, 0, len);

  size_t top = hostname.length();
  size_t prevSize = 0;
  for(ssize_t i = top - 1; i >= 0; i--)
  {
    if(hostname[i] == '.')
    {
      host[i+1] = prevSize;
      prevSize = 0;
    }
    else
    {
      host[i+1] = hostname[i];
      prevSize++;
    }
  }
  host[0] = prevSize;

  memcpy(reinterpret_cast<char*>(buffLoc + sizeof(DnsHeader)), host, len);

  delete [] host;

  // requesting the host address
  QuestionSecNameSuffix* q = reinterpret_cast<QuestionSecNameSuffix*>(buffLoc + sizeof(DnsHeader) + len + 1);
  q->type = HOST_TO_BIG16(1);
  q->cls = HOST_TO_BIG16(1);

  Endpoint::RemoteEndpoint remoteHost;
  remoteHost.remotePort = 53;
  remoteHost.ip = info.dnsServers[0];

  // shove all this into a DnsRequest ready for replies
  DnsRequest* req = new DnsRequest;
  DnsEntry* ent = new DnsEntry;
  req->id = head->id;
  req->entry = ent;

  m_DnsRequests.pushBack(req);

  e->send(sizeof(DnsHeader) + sizeof(QuestionSecNameSuffix) + len + 1, buffLoc, remoteHost, false, pCard);

  req->waitSem.acquire();

  if(!req->success)
  {
    delete ent;
    delete req;
  }
  else
  {
    delete req;

    nIps = ent->numIps;
    return ent->ip;
  }

  return 0;
}
<commit_msg>DNS requests handle CNAMEs properly now.<commit_after>/*
 * Copyright (c) 2008 James Molloy, Jrg Pfhler, Matthew Iselin
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include "Dns.h"
#include "Ethernet.h"
#include <Module.h>
#include <Log.h>

#include "UdpManager.h"
#include <processor/Processor.h>

Dns Dns::dnsInstance;
uint16_t Dns::m_NextId = 0;

Dns::Dns() :
  m_DnsCache(), m_DnsRequests(), m_Endpoint(0)
{
  new Thread(Processor::information().getCurrentThread()->getParent(),
             reinterpret_cast<Thread::ThreadStartFunc>(&trampoline),
             reinterpret_cast<void*>(this));
  m_Endpoint = UdpManager::instance().getEndpoint(IpAddress(), 0, 53);
  m_Endpoint->acceptAnyAddress(true);
}

Dns::Dns(const Dns& ent) :
  m_DnsCache(ent.m_DnsCache), m_DnsRequests(ent.m_DnsRequests), m_Endpoint(ent.m_Endpoint)
{
  new Thread(Processor::information().getCurrentThread()->getParent(),
             reinterpret_cast<Thread::ThreadStartFunc>(&trampoline),
             reinterpret_cast<void*>(this));
}

Dns::~Dns()
{
}

int Dns::trampoline(void* p)
{
  Dns *pDns = reinterpret_cast<Dns*>(p);
  pDns->mainThread();
  return 0;
}

void Dns::mainThread()
{
  uint8_t* buff = new uint8_t[512];
  uintptr_t buffLoc = reinterpret_cast<uintptr_t>(buff);
  memset(buff, 0, 512);

  IpAddress addr(Network::convertToIpv4(0, 0, 0, 0));
  Endpoint* e = m_Endpoint; //UdpManager::instance().getEndpoint(addr, 53, 53);

  Endpoint::RemoteEndpoint remoteHost;

  while(true)
  {
    if(e->dataReady(true))
    {
      // read the packet
      int n = e->recv(buffLoc, 512, &remoteHost);
      if(n <= 0)
        continue;

      // grab the header
      DnsHeader* head = reinterpret_cast<DnsHeader*>(buffLoc);

      // look for the ID in our request list
      bool bFound = false;
      DnsRequest* req = 0;
      for(Vector<DnsRequest*>::Iterator it = m_DnsRequests.begin(); it != m_DnsRequests.end(); it++)
      {
        if((*it)->id == head->id)
        {
          req = (*it);
          bFound = true;

          m_DnsRequests.erase(it);
          break;
        }
      }

      if(!bFound)
        continue;

      uint16_t ansCount = BIG_TO_HOST16(head->aCount);
      uint16_t nameCount = BIG_TO_HOST16(head->nCount);
      uint16_t addCount = BIG_TO_HOST16(head->dCount);

      // read the hostname to find the start of the question and answer structures
      String hostname;
      char* tmp = reinterpret_cast<char*>(buffLoc + sizeof(DnsHeader));

      size_t hostLen = 1;
      size_t currOffset = 0;
      size_t secSize = *tmp++;
      while(true)
      {
        hostLen++;

        char c = *tmp++;
        if(c == 0)
          break;

        char s[2];
        s[0] = c;
        s[1] = 0;
        hostname += s;

        if(currOffset++ == secSize)
        {
          hostname += ".";
          secSize = *tmp++;
        }
      }

      // null byte
      hostLen++;
      req->entry->hostname = hostname;

      NOTICE("Obtained hostname " << hostname << " len " << hostLen << ".");

      /// \todo For hosts like GMail, this does not work unless we have a +1 on the end - find out why!
      uintptr_t structStart = buffLoc + sizeof(DnsHeader) + hostLen + sizeof(QuestionSecNameSuffix);
      uintptr_t ansStart = structStart;

      req->entry->ip = 0;
      req->entry->numIps = 0;

      // http://www.zytrax.com/books/dns/ch15/ for future reference
      for(uint16_t answer = 0; answer < (ansCount + nameCount + addCount); answer++)
      {
        DnsAnswer* ans = reinterpret_cast<DnsAnswer*>(ansStart);
        if(BIG_TO_HOST16(ans->name) & 0x2)
        {
          // stores an offset to the name for this entry
          NOTICE("Is an offset - " << (BIG_TO_HOST16(ans->name) - 2) << " bytes");
        }
        else
        {
          // apparently this is actually meant to be a proper name component? weird....
        }

        switch(BIG_TO_HOST16(ans->type))
        {
          /** A Record */
          case 0x0001:
            {
              if(BIG_TO_HOST16(ans->length) == 4)
              {
                IpAddress* newList = new IpAddress[req->entry->numIps + 1];
                if(req->entry->ip)
                {
                  size_t i;
                  for(i = 0; i < req->entry->numIps; i++)
                    newList[i] = req->entry->ip[i];
                  delete [] req->entry->ip;
                }
                req->entry->ip = newList;

                uint32_t newIp = *reinterpret_cast<uint32_t*>(ansStart + sizeof(DnsAnswer));
                req->entry->ip[req->entry->numIps].setIp(newIp);
                req->entry->numIps++;
              }
            }
            break;

          /** CNAME */
          case 0x0005:
            {
              WARNING("TODO: DNS CNAME records --> Hostent aliases");
            }
            break;
        }

        ansStart += sizeof(DnsAnswer) + BIG_TO_HOST16(ans->length);
      }

      m_DnsCache.pushBack(req->entry);
      req->success = true;
      req->waitSem.release();
    }
  }
}

IpAddress* Dns::hostToIp(String hostname, size_t& nIps, Network* pCard)
{
  // check the DNS cache
  for(List<DnsEntry*>::Iterator it = m_DnsCache.begin(); it!= m_DnsCache.end(); it++)
  {
    if(!strcmp(static_cast<const char*>((*it)->hostname), static_cast<const char*>(hostname)))
    {
      nIps = (*it)->numIps;
      return (*it)->ip;
    }
  }

  // grab the DNS server to use
  StationInfo info = pCard->getStationInfo();
  if(info.nDnsServers == 0)
  {
    nIps = 0;
    return 0;
  }

  // setup for our request
  Endpoint* e = m_Endpoint; //UdpManager::instance().getEndpoint(info.dnsServer, 0, 53);

  uint8_t* buff = new uint8_t[512];
  uintptr_t buffLoc = reinterpret_cast<uintptr_t>(buff);
  memset(buff, 0, 512);

  // setup the DNS message header
  DnsHeader* head = reinterpret_cast<DnsHeader*>(buffLoc);
  head->id = m_NextId++;
  head->opAndParam = HOST_TO_BIG16(DNS_RECUSRION);
  head->qCount = HOST_TO_BIG16(1);

  // build the modified hostname
  size_t len = hostname.length() + 1;
  char* host = new char[len];
  memset(host, 0, len);

  size_t top = hostname.length();
  size_t prevSize = 0;
  for(ssize_t i = top - 1; i >= 0; i--)
  {
    if(hostname[i] == '.')
    {
      host[i+1] = prevSize;
      prevSize = 0;
    }
    else
    {
      host[i+1] = hostname[i];
      prevSize++;
    }
  }
  host[0] = prevSize;

  memcpy(reinterpret_cast<char*>(buffLoc + sizeof(DnsHeader)), host, len);

  delete [] host;

  // requesting the host address
  QuestionSecNameSuffix* q = reinterpret_cast<QuestionSecNameSuffix*>(buffLoc + sizeof(DnsHeader) + len + 1);
  q->type = HOST_TO_BIG16(1);
  q->cls = HOST_TO_BIG16(1);

  Endpoint::RemoteEndpoint remoteHost;
  remoteHost.remotePort = 53;
  remoteHost.ip = info.dnsServers[0];

  // shove all this into a DnsRequest ready for replies
  DnsRequest* req = new DnsRequest;
  DnsEntry* ent = new DnsEntry;
  req->id = head->id;
  req->entry = ent;

  m_DnsRequests.pushBack(req);

  e->send(sizeof(DnsHeader) + sizeof(QuestionSecNameSuffix) + len + 1, buffLoc, remoteHost, false, pCard);

  req->waitSem.acquire();

  if(!req->success)
  {
    delete ent;
    delete req;
  }
  else
  {
    delete req;

    nIps = ent->numIps;
    return ent->ip;
  }

  return 0;
}
<|endoftext|>


<commit_before>#include "dict.h"

#include <string>
#include <vector>
#include <sstream>

using namespace std;

namespace cnn {

std::vector<int> ReadSentence(const std::string& line, Dict* sd) {
  std::istringstream in(line);
  std::string word;
  std::string sep = "|||";
  std::vector<int> res;
  while(in) {
    in >> word;
    if (word.empty()) break;
    res.push_back(sd->Convert(word));
  }
  return res;
}

void ReadSentencePair(const std::string& line, std::vector<int>* s, Dict* sd, std::vector<int>* t, Dict* td) {
  std::istringstream in(line);
  std::string word;
  std::string sep = "|||";
  Dict* d = sd;
  std::vector<int>* v = s;
  while(in) {
    in >> word;
    if (!in) break;
    if (word == sep) { d = td; v = t; continue; }
    v->push_back(d->Convert(word));
  }
}

} // namespace cnn

<commit_msg>Fixed repeating of final symbol when using ReadSentence<commit_after>#include "dict.h"

#include <string>
#include <vector>
#include <sstream>

using namespace std;

namespace cnn {

std::vector<int> ReadSentence(const std::string& line, Dict* sd) {
  std::istringstream in(line);
  std::string word;
  std::vector<int> res;
  while(in) {
    in >> word;
    if (!in || word.empty()) break;
    res.push_back(sd->Convert(word));
  }
  return res;
}

void ReadSentencePair(const std::string& line, std::vector<int>* s, Dict* sd, std::vector<int>* t, Dict* td) {
  std::istringstream in(line);
  std::string word;
  std::string sep = "|||";
  Dict* d = sd;
  std::vector<int>* v = s;
  while(in) {
    in >> word;
    if (!in) break;
    if (word == sep) { d = td; v = t; continue; }
    v->push_back(d->Convert(word));
  }
}

} // namespace cnn

<|endoftext|>


<commit_before>/*
 * Copyright 2011 Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

#include "settingshelper.h"

SettingsHelper *SettingsHelper::mSelf = 0;

SettingsHelper::SettingsHelper(QObject *parent) :
    QObject(parent), mSettings("MeeGo", "MeeGoIM")
{
}

SettingsHelper *SettingsHelper::self()
{
    if (!mSelf) {
        mSelf = new SettingsHelper();
    }

    return mSelf;
}

bool SettingsHelper::showOfflineContacts()
{
    mSettings.sync();
    return mSettings.value("ShowOfflineContacts", true).toBool();
}

void SettingsHelper::setShowOfflineContacts(bool show)
{
    mSettings.setValue("ShowOfflineContacts", show);
    mSettings.sync();
    emit showOfflineContactsChanged();
}

bool SettingsHelper::enableAudioAlerts()
{
    mSettings.sync();
    return mSettings.value("EnableAudioAlerts", true).toBool();
}

void SettingsHelper::setEnableAudioAlerts(bool enable)
{
    mSettings.setValue("EnableAudioAlerts", enable);
    mSettings.sync();
    emit enableAudioAlertsChanged();
}

bool SettingsHelper::enableNotifications()
{
    mSettings.sync();
    return mSettings.value("EnableNotifications", true).toBool();
}

void SettingsHelper::setEnableNotifications(bool enable)
{
    mSettings.setValue("EnableNotifications", enable);
    mSettings.sync();
    emit enableNotificationsChanged();
}

bool SettingsHelper::enableVibrate()
{
    mSettings.sync();
    return mSettings.value("EnableVibrate", true).toBool();
}

void SettingsHelper::setEnableVibrate(bool enable)
{
    mSettings.setValue("EnableVibrate", enable);
    mSettings.sync();
    emit enableVibrateChanged();
}

QVariant SettingsHelper::value(const QString &prop, const QVariant &defaultValue)
{
    mSettings.sync();
    return mSettings.value(prop, defaultValue);
}

void SettingsHelper::setValue(const QString &prop, const QVariant &value)
{
    mSettings.setValue(prop, value);
    mSettings.sync();
    emit valueUpdated(prop);
}
<commit_msg>Fixed name of config file to follow MeeGo UX App conventions<commit_after>/*
 * Copyright 2011 Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

#include "settingshelper.h"

SettingsHelper *SettingsHelper::mSelf = 0;

SettingsHelper::SettingsHelper(QObject *parent) :
    QObject(parent), mSettings("MeeGo", "meego-app-im")
{
}

SettingsHelper *SettingsHelper::self()
{
    if (!mSelf) {
        mSelf = new SettingsHelper();
    }

    return mSelf;
}

bool SettingsHelper::showOfflineContacts()
{
    mSettings.sync();
    return mSettings.value("ShowOfflineContacts", true).toBool();
}

void SettingsHelper::setShowOfflineContacts(bool show)
{
    mSettings.setValue("ShowOfflineContacts", show);
    mSettings.sync();
    emit showOfflineContactsChanged();
}

bool SettingsHelper::enableAudioAlerts()
{
    mSettings.sync();
    return mSettings.value("EnableAudioAlerts", true).toBool();
}

void SettingsHelper::setEnableAudioAlerts(bool enable)
{
    mSettings.setValue("EnableAudioAlerts", enable);
    mSettings.sync();
    emit enableAudioAlertsChanged();
}

bool SettingsHelper::enableNotifications()
{
    mSettings.sync();
    return mSettings.value("EnableNotifications", true).toBool();
}

void SettingsHelper::setEnableNotifications(bool enable)
{
    mSettings.setValue("EnableNotifications", enable);
    mSettings.sync();
    emit enableNotificationsChanged();
}

bool SettingsHelper::enableVibrate()
{
    mSettings.sync();
    return mSettings.value("EnableVibrate", true).toBool();
}

void SettingsHelper::setEnableVibrate(bool enable)
{
    mSettings.setValue("EnableVibrate", enable);
    mSettings.sync();
    emit enableVibrateChanged();
}

QVariant SettingsHelper::value(const QString &prop, const QVariant &defaultValue)
{
    mSettings.sync();
    return mSettings.value(prop, defaultValue);
}

void SettingsHelper::setValue(const QString &prop, const QVariant &value)
{
    mSettings.setValue(prop, value);
    mSettings.sync();
    emit valueUpdated(prop);
}
<|endoftext|>


<commit_before>// StlSolid.cpp
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include "stdafx.h"
#include "StlSolid.h"

using namespace std;

CStlTri::CStlTri(const float* t)
{
	memcpy(x[0], t, 9*sizeof(float));
}

CStlTri::CStlTri(const double* t)
{
	x[0][0] = (float)t[0];
	x[0][1] = (float)t[1];
	x[0][2] = (float)t[2];
	x[1][0] = (float)t[3];
	x[1][1] = (float)t[4];
	x[1][2] = (float)t[5];
	x[2][0] = (float)t[6];
	x[2][1] = (float)t[7];
	x[2][2] = (float)t[8];
}

CStlSolid::CStlSolid(const HeeksColor* col):m_color(*col), m_gl_list(0){
	m_title.assign(GetTypeString());
}

CStlSolid::CStlSolid(const wxChar* filepath, const HeeksColor* col):m_color(*col), m_gl_list(0){
	m_title.assign(GetTypeString());
	read_from_file(filepath);

	if(wxGetApp().m_in_OpenFile && wxGetApp().m_file_open_matrix)
	{
		ModifyByMatrix(wxGetApp().m_file_open_matrix);
	}
}

void CStlSolid::read_from_file(const wxChar* filepath)
{
	// read the stl file
	ifstream ifs(Ttc(filepath), ios::binary);
	if(!ifs)return;

	char solid_string[6] = "aaaaa";
	ifs.read(solid_string, 5);
	if(ifs.eof())return;
	if(strcmp(solid_string, "solid"))
	{
		// try binary file read

		// read the header
		char header[81];
		header[80] = 0;
		memcpy(header, solid_string, 5);
		ifs.read(&header[5], 75);

		unsigned int num_facets = 0;
		ifs.read((char*)(&num_facets), 4);

		for(unsigned int i = 0; i<num_facets; i++)
		{
			CStlTri tri;
			float n[3];
			ifs.read((char*)(n), 12);
			ifs.read((char*)(tri.x[0]), 36);
			short attr;
			ifs.read((char*)(&attr), 2);
			m_list.push_back(tri);
		}
	}
	else
	{
		// "solid" already found
		char str[1024] = "solid";
		ifs.getline(&str[5], 1024);
		char title[1024];
		if(sscanf(str, "solid %s", title) == 1)
			m_title.assign(Ctt(title));

		CStlTri t;
		char five_chars[6] = "aaaaa";

		int vertex = 0;

		while(!ifs.eof())
		{
			ifs.getline(str, 1024);

			int i = 0, j = 0;
			for(; i<5; i++, j++)
			{
				if(str[j] == 0)break;
				while(str[j] == ' ' || str[j] == '\t')j++;
				five_chars[i] = str[j];
			}
			if(i == 5)
			{
				if(!strcmp(five_chars, "verte"))
				{
#ifdef WIN32
					sscanf(str, " vertex %f %f %f", &(t.x[vertex][0]), &(t.x[vertex][1]), &(t.x[vertex][2]));
#else
					std::istringstream ss(str);
					ss.imbue(std::locale("C"));
					while(ss.peek() == ' ') ss.seekg(1, ios_base::cur);
					ss.seekg(std::string("vertex").size(), ios_base::cur);
					ss >> t.x[vertex][0] >> t.x[vertex][1] >> t.x[vertex][2];
#endif
					vertex++;
					if(vertex > 2)vertex = 2;
				}
				else if(!strcmp(five_chars, "facet"))
				{
					vertex = 0;
				}
				else if(!strcmp(five_chars, "endfa"))
				{
					if(vertex == 2)
					{
						m_list.push_back(t);
					}
				}
			}
		}
	}
}

CStlSolid::~CStlSolid(){
	KillGLLists();
}

const CStlSolid& CStlSolid::operator=(const CStlSolid& s)
{
    HeeksObj::operator = (s);

	// don't copy id
	m_box = s.m_box;
	m_title = s.m_title;
	KillGLLists();

	m_color = s.m_color;

	m_list.clear();
	std::copy( s.m_list.begin(), s.m_list.end(), std::inserter( m_list, m_list.begin() ));

	return *this;
}

bool CStlSolid::IsDifferent(HeeksObj* other)
{
	CStlSolid* shape = (CStlSolid*)other;
	if(shape->m_color.COLORREF_color() != m_color.COLORREF_color() || shape->m_title.CompareTo(m_title) || shape->m_box != m_box)
		return true;

	return HeeksObj::IsDifferent(other);
}

void CStlSolid::KillGLLists()
{
	if (m_gl_list)
	{
		glDeleteLists(m_gl_list, 1);
		m_gl_list = 0;
		m_box = CBox();
	}
}

const wxBitmap &CStlSolid::GetIcon()
{
	static wxBitmap* icon = NULL;
	if(icon == NULL)icon = new wxBitmap(wxImage(wxGetApp().GetResFolder() + _T("/icons/stlsolid.png")));
	return *icon;
}

void CStlSolid::glCommands(bool select, bool marked, bool no_color){
	glEnable(GL_LIGHTING);
	Material(m_color).glMaterial(1.0);

	if(m_gl_list)
	{
		glCallList(m_gl_list);
	}
	else{
		m_gl_list = glGenLists(1);
		glNewList(m_gl_list, GL_COMPILE_AND_EXECUTE);

		// render all the triangles
		glBegin(GL_TRIANGLES);
		for(std::list<CStlTri>::iterator It = m_list.begin(); It != m_list.end(); It++)
		{
			CStlTri &t = *It;
			gp_Pnt p0(t.x[0][0], t.x[0][1], t.x[0][2]);
			gp_Pnt p1(t.x[1][0], t.x[1][1], t.x[1][2]);
			gp_Pnt p2(t.x[2][0], t.x[2][1], t.x[2][2]);
			gp_Vec v1(p0, p1);
			gp_Vec v2(p0, p2);
			try
			{
				gp_Vec norm = (v1 ^ v2).Normalized();
				float n[3];
				n[0] = (float)(norm.X());
				n[1] = (float)(norm.Y());
				n[2] = (float)(norm.Z());
				glNormal3fv(n);
				glVertex3fv(t.x[0]);
				glVertex3fv(t.x[1]);
				glVertex3fv(t.x[2]);
			}
			catch(...)
			{
			}
		}
		glEnd();

		glEndList();
	}

	glDisable(GL_LIGHTING);
}

void CStlSolid::GetBox(CBox &box){
	if(!m_box.m_valid)
	{
		// calculate the box for all the triangles
		for(std::list<CStlTri>::iterator It = m_list.begin(); It != m_list.end(); It++)
		{
			CStlTri &t = *It;
			m_box.Insert(t.x[0][0], t.x[0][1], t.x[0][2]);
			m_box.Insert(t.x[1][0], t.x[1][1], t.x[1][2]);
			m_box.Insert(t.x[2][0], t.x[2][1], t.x[2][2]);
		}
	}

	box.Insert(m_box);
}

void CStlSolid::ModifyByMatrix(const double* m){
	gp_Trsf mat = make_matrix(m);
	for(std::list<CStlTri>::iterator It = m_list.begin(); It != m_list.end(); It++)
	{
		CStlTri &t = *It;
		for(int i = 0; i<3; i++){
			gp_Pnt vx;
			vx = gp_Pnt(t.x[i][0], t.x[i][1], t.x[i][2]);
			vx.Transform(mat);
			t.x[i][0] = (float)vx.X();
			t.x[i][1] = (float)vx.Y();
			t.x[i][2] = (float)vx.Z();
		}
	}

	KillGLLists();
}

CStlSolid::CStlSolid( const CStlSolid & rhs )
{
    *this = rhs;    // Call the assignment operator.
}

HeeksObj *CStlSolid::MakeACopy(void)const{
	CStlSolid *new_object = new CStlSolid(*this);
	return new_object;
}

void CStlSolid::CopyFrom(const HeeksObj* object)
{
	operator=(*((CStlSolid*)object));
}

void CStlSolid::OnEditString(const wxChar* str){
	m_title.assign(str);
	wxGetApp().Changed();
}

void CStlSolid::GetTriangles(void(*callbackfunc)(const double* x, const double* n), double cusp, bool just_one_average_normal){
	double x[9];
	double n[9];
	for(std::list<CStlTri>::iterator It = m_list.begin(); It != m_list.end(); It++)
	{
		CStlTri &t = *It;
		x[0] = t.x[0][0];
		x[1] = t.x[0][1];
		x[2] = t.x[0][2];
		x[3] = t.x[1][0];
		x[4] = t.x[1][1];
		x[5] = t.x[1][2];
		x[6] = t.x[2][0];
		x[7] = t.x[2][1];
		x[8] = t.x[2][2];
		gp_Pnt p0(t.x[0][0], t.x[0][1], t.x[0][2]);
		gp_Pnt p1(t.x[1][0], t.x[1][1], t.x[1][2]);
		gp_Pnt p2(t.x[2][0], t.x[2][1], t.x[2][2]);
		gp_Vec v1(p0, p1);
		gp_Vec v2(p0, p2);
		try
		{
			gp_Vec norm = (v1 ^ v2).Normalized();
			n[0] = norm.X();
			n[1] = norm.Y();
			n[2] = norm.Z();
			if(!just_one_average_normal)
			{
				n[3] = n[0];
				n[4] = n[1];
				n[5] = n[2];
				n[6] = n[0];
				n[7] = n[1];
				n[8] = n[2];
			}
			(*callbackfunc)(x, n);
		}
		catch(...)
		{
		}
	}
}

void CStlSolid::WriteXML(TiXmlNode *root)
{
	TiXmlElement * element;
	element = new TiXmlElement( "STLSolid" );
	root->LinkEndChild( element );
	element->SetAttribute("col", m_color.COLORREF_color());

	for(std::list<CStlTri>::iterator It = m_list.begin(); It != m_list.end(); It++)
	{
		CStlTri &t = *It;
		TiXmlElement * child_element;
		child_element = new TiXmlElement( "tri" );
		element->LinkEndChild( child_element );
		child_element->SetDoubleAttribute("p1x", t.x[0][0]);
		child_element->SetDoubleAttribute("p1y", t.x[0][1]);
		child_element->SetDoubleAttribute("p1z", t.x[0][2]);
		child_element->SetDoubleAttribute("p2x", t.x[1][0]);
		child_element->SetDoubleAttribute("p2y", t.x[1][1]);
		child_element->SetDoubleAttribute("p2z", t.x[1][2]);
		child_element->SetDoubleAttribute("p3x", t.x[2][0]);
		child_element->SetDoubleAttribute("p3y", t.x[2][1]);
		child_element->SetDoubleAttribute("p3z", t.x[2][2]);
	}

	WriteBaseXML(element);
}

// static member function
HeeksObj* CStlSolid::ReadFromXMLElement(TiXmlElement* pElem)
{
	HeeksColor c;
	CStlTri t;

	// get the attributes
	for(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next())
	{
		std::string name(a->Name());
		if(name == "col"){c = HeeksColor((long)(a->IntValue()));}
	}

	CStlSolid* new_object = new CStlSolid(&c);

	// loop through all the "tri" objects
	double x[3][3];

	for(TiXmlElement* pTriElem = TiXmlHandle(pElem).FirstChildElement().Element(); pTriElem;	pTriElem = pTriElem->NextSiblingElement())
	{
		// get the attributes
		pTriElem->Attribute("p1x", &x[0][0]);
		pTriElem->Attribute("p1y", &x[0][1]);
		pTriElem->Attribute("p1z", &x[0][2]);
		pTriElem->Attribute("p2x", &x[1][0]);
		pTriElem->Attribute("p2y", &x[1][1]);
		pTriElem->Attribute("p2z", &x[1][2]);
		pTriElem->Attribute("p3x", &x[2][0]);
		pTriElem->Attribute("p3y", &x[2][1]);
		pTriElem->Attribute("p3z", &x[2][2]);
		new_object->m_list.push_back(CStlTri(&x[0][0]));
	}

	new_object->ReadBaseXML(pElem);

	return new_object;
}

void CStlSolid::AddTriangle(float* t)
{
	CStlTri tri(t);
	m_list.push_back(tri);
}

<commit_msg>Initialize StlSolid::m_gl_list in copy constructor<commit_after>// StlSolid.cpp
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include "stdafx.h"
#include "StlSolid.h"

using namespace std;

CStlTri::CStlTri(const float* t)
{
	memcpy(x[0], t, 9*sizeof(float));
}

CStlTri::CStlTri(const double* t)
{
	x[0][0] = (float)t[0];
	x[0][1] = (float)t[1];
	x[0][2] = (float)t[2];
	x[1][0] = (float)t[3];
	x[1][1] = (float)t[4];
	x[1][2] = (float)t[5];
	x[2][0] = (float)t[6];
	x[2][1] = (float)t[7];
	x[2][2] = (float)t[8];
}

CStlSolid::CStlSolid(const HeeksColor* col):m_color(*col), m_gl_list(0){
	m_title.assign(GetTypeString());
}

CStlSolid::CStlSolid(const wxChar* filepath, const HeeksColor* col):m_color(*col), m_gl_list(0){
	m_title.assign(GetTypeString());
	read_from_file(filepath);

	if(wxGetApp().m_in_OpenFile && wxGetApp().m_file_open_matrix)
	{
		ModifyByMatrix(wxGetApp().m_file_open_matrix);
	}
}

void CStlSolid::read_from_file(const wxChar* filepath)
{
	// read the stl file
	ifstream ifs(Ttc(filepath), ios::binary);
	if(!ifs)return;

	char solid_string[6] = "aaaaa";
	ifs.read(solid_string, 5);
	if(ifs.eof())return;
	if(strcmp(solid_string, "solid"))
	{
		// try binary file read

		// read the header
		char header[81];
		header[80] = 0;
		memcpy(header, solid_string, 5);
		ifs.read(&header[5], 75);

		unsigned int num_facets = 0;
		ifs.read((char*)(&num_facets), 4);

		for(unsigned int i = 0; i<num_facets; i++)
		{
			CStlTri tri;
			float n[3];
			ifs.read((char*)(n), 12);
			ifs.read((char*)(tri.x[0]), 36);
			short attr;
			ifs.read((char*)(&attr), 2);
			m_list.push_back(tri);
		}
	}
	else
	{
		// "solid" already found
		char str[1024] = "solid";
		ifs.getline(&str[5], 1024);
		char title[1024];
		if(sscanf(str, "solid %s", title) == 1)
			m_title.assign(Ctt(title));

		CStlTri t;
		char five_chars[6] = "aaaaa";

		int vertex = 0;

		while(!ifs.eof())
		{
			ifs.getline(str, 1024);

			int i = 0, j = 0;
			for(; i<5; i++, j++)
			{
				if(str[j] == 0)break;
				while(str[j] == ' ' || str[j] == '\t')j++;
				five_chars[i] = str[j];
			}
			if(i == 5)
			{
				if(!strcmp(five_chars, "verte"))
				{
#ifdef WIN32
					sscanf(str, " vertex %f %f %f", &(t.x[vertex][0]), &(t.x[vertex][1]), &(t.x[vertex][2]));
#else
					std::istringstream ss(str);
					ss.imbue(std::locale("C"));
					while(ss.peek() == ' ') ss.seekg(1, ios_base::cur);
					ss.seekg(std::string("vertex").size(), ios_base::cur);
					ss >> t.x[vertex][0] >> t.x[vertex][1] >> t.x[vertex][2];
#endif
					vertex++;
					if(vertex > 2)vertex = 2;
				}
				else if(!strcmp(five_chars, "facet"))
				{
					vertex = 0;
				}
				else if(!strcmp(five_chars, "endfa"))
				{
					if(vertex == 2)
					{
						m_list.push_back(t);
					}
				}
			}
		}
	}
}

CStlSolid::~CStlSolid(){
	KillGLLists();
}

const CStlSolid& CStlSolid::operator=(const CStlSolid& s)
{
    HeeksObj::operator = (s);

	// don't copy id
	m_box = s.m_box;
	m_title = s.m_title;
	KillGLLists();

	m_color = s.m_color;

	m_list.clear();
	std::copy( s.m_list.begin(), s.m_list.end(), std::inserter( m_list, m_list.begin() ));

	return *this;
}

bool CStlSolid::IsDifferent(HeeksObj* other)
{
	CStlSolid* shape = (CStlSolid*)other;
	if(shape->m_color.COLORREF_color() != m_color.COLORREF_color() || shape->m_title.CompareTo(m_title) || shape->m_box != m_box)
		return true;

	return HeeksObj::IsDifferent(other);
}

void CStlSolid::KillGLLists()
{
	if (m_gl_list)
	{
		glDeleteLists(m_gl_list, 1);
		m_gl_list = 0;
		m_box = CBox();
	}
}

const wxBitmap &CStlSolid::GetIcon()
{
	static wxBitmap* icon = NULL;
	if(icon == NULL)icon = new wxBitmap(wxImage(wxGetApp().GetResFolder() + _T("/icons/stlsolid.png")));
	return *icon;
}

void CStlSolid::glCommands(bool select, bool marked, bool no_color){
	glEnable(GL_LIGHTING);
	Material(m_color).glMaterial(1.0);

	if(m_gl_list)
	{
		glCallList(m_gl_list);
	}
	else{
		m_gl_list = glGenLists(1);
		glNewList(m_gl_list, GL_COMPILE_AND_EXECUTE);

		// render all the triangles
		glBegin(GL_TRIANGLES);
		for(std::list<CStlTri>::iterator It = m_list.begin(); It != m_list.end(); It++)
		{
			CStlTri &t = *It;
			gp_Pnt p0(t.x[0][0], t.x[0][1], t.x[0][2]);
			gp_Pnt p1(t.x[1][0], t.x[1][1], t.x[1][2]);
			gp_Pnt p2(t.x[2][0], t.x[2][1], t.x[2][2]);
			gp_Vec v1(p0, p1);
			gp_Vec v2(p0, p2);
			try
			{
				gp_Vec norm = (v1 ^ v2).Normalized();
				float n[3];
				n[0] = (float)(norm.X());
				n[1] = (float)(norm.Y());
				n[2] = (float)(norm.Z());
				glNormal3fv(n);
				glVertex3fv(t.x[0]);
				glVertex3fv(t.x[1]);
				glVertex3fv(t.x[2]);
			}
			catch(...)
			{
			}
		}
		glEnd();

		glEndList();
	}

	glDisable(GL_LIGHTING);
}

void CStlSolid::GetBox(CBox &box){
	if(!m_box.m_valid)
	{
		// calculate the box for all the triangles
		for(std::list<CStlTri>::iterator It = m_list.begin(); It != m_list.end(); It++)
		{
			CStlTri &t = *It;
			m_box.Insert(t.x[0][0], t.x[0][1], t.x[0][2]);
			m_box.Insert(t.x[1][0], t.x[1][1], t.x[1][2]);
			m_box.Insert(t.x[2][0], t.x[2][1], t.x[2][2]);
		}
	}

	box.Insert(m_box);
}

void CStlSolid::ModifyByMatrix(const double* m){
	gp_Trsf mat = make_matrix(m);
	for(std::list<CStlTri>::iterator It = m_list.begin(); It != m_list.end(); It++)
	{
		CStlTri &t = *It;
		for(int i = 0; i<3; i++){
			gp_Pnt vx;
			vx = gp_Pnt(t.x[i][0], t.x[i][1], t.x[i][2]);
			vx.Transform(mat);
			t.x[i][0] = (float)vx.X();
			t.x[i][1] = (float)vx.Y();
			t.x[i][2] = (float)vx.Z();
		}
	}

	KillGLLists();
}

CStlSolid::CStlSolid( const CStlSolid & rhs ) : m_gl_list(0)
{
    *this = rhs;    // Call the assignment operator.
}

HeeksObj *CStlSolid::MakeACopy(void)const{
	CStlSolid *new_object = new CStlSolid(*this);
	return new_object;
}

void CStlSolid::CopyFrom(const HeeksObj* object)
{
	operator=(*((CStlSolid*)object));
}

void CStlSolid::OnEditString(const wxChar* str){
	m_title.assign(str);
	wxGetApp().Changed();
}

void CStlSolid::GetTriangles(void(*callbackfunc)(const double* x, const double* n), double cusp, bool just_one_average_normal){
	double x[9];
	double n[9];
	for(std::list<CStlTri>::iterator It = m_list.begin(); It != m_list.end(); It++)
	{
		CStlTri &t = *It;
		x[0] = t.x[0][0];
		x[1] = t.x[0][1];
		x[2] = t.x[0][2];
		x[3] = t.x[1][0];
		x[4] = t.x[1][1];
		x[5] = t.x[1][2];
		x[6] = t.x[2][0];
		x[7] = t.x[2][1];
		x[8] = t.x[2][2];
		gp_Pnt p0(t.x[0][0], t.x[0][1], t.x[0][2]);
		gp_Pnt p1(t.x[1][0], t.x[1][1], t.x[1][2]);
		gp_Pnt p2(t.x[2][0], t.x[2][1], t.x[2][2]);
		gp_Vec v1(p0, p1);
		gp_Vec v2(p0, p2);
		try
		{
			gp_Vec norm = (v1 ^ v2).Normalized();
			n[0] = norm.X();
			n[1] = norm.Y();
			n[2] = norm.Z();
			if(!just_one_average_normal)
			{
				n[3] = n[0];
				n[4] = n[1];
				n[5] = n[2];
				n[6] = n[0];
				n[7] = n[1];
				n[8] = n[2];
			}
			(*callbackfunc)(x, n);
		}
		catch(...)
		{
		}
	}
}

void CStlSolid::WriteXML(TiXmlNode *root)
{
	TiXmlElement * element;
	element = new TiXmlElement( "STLSolid" );
	root->LinkEndChild( element );
	element->SetAttribute("col", m_color.COLORREF_color());

	for(std::list<CStlTri>::iterator It = m_list.begin(); It != m_list.end(); It++)
	{
		CStlTri &t = *It;
		TiXmlElement * child_element;
		child_element = new TiXmlElement( "tri" );
		element->LinkEndChild( child_element );
		child_element->SetDoubleAttribute("p1x", t.x[0][0]);
		child_element->SetDoubleAttribute("p1y", t.x[0][1]);
		child_element->SetDoubleAttribute("p1z", t.x[0][2]);
		child_element->SetDoubleAttribute("p2x", t.x[1][0]);
		child_element->SetDoubleAttribute("p2y", t.x[1][1]);
		child_element->SetDoubleAttribute("p2z", t.x[1][2]);
		child_element->SetDoubleAttribute("p3x", t.x[2][0]);
		child_element->SetDoubleAttribute("p3y", t.x[2][1]);
		child_element->SetDoubleAttribute("p3z", t.x[2][2]);
	}

	WriteBaseXML(element);
}

// static member function
HeeksObj* CStlSolid::ReadFromXMLElement(TiXmlElement* pElem)
{
	HeeksColor c;
	CStlTri t;

	// get the attributes
	for(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next())
	{
		std::string name(a->Name());
		if(name == "col"){c = HeeksColor((long)(a->IntValue()));}
	}

	CStlSolid* new_object = new CStlSolid(&c);

	// loop through all the "tri" objects
	double x[3][3];

	for(TiXmlElement* pTriElem = TiXmlHandle(pElem).FirstChildElement().Element(); pTriElem;	pTriElem = pTriElem->NextSiblingElement())
	{
		// get the attributes
		pTriElem->Attribute("p1x", &x[0][0]);
		pTriElem->Attribute("p1y", &x[0][1]);
		pTriElem->Attribute("p1z", &x[0][2]);
		pTriElem->Attribute("p2x", &x[1][0]);
		pTriElem->Attribute("p2y", &x[1][1]);
		pTriElem->Attribute("p2z", &x[1][2]);
		pTriElem->Attribute("p3x", &x[2][0]);
		pTriElem->Attribute("p3y", &x[2][1]);
		pTriElem->Attribute("p3z", &x[2][2]);
		new_object->m_list.push_back(CStlTri(&x[0][0]));
	}

	new_object->ReadBaseXML(pElem);

	return new_object;
}

void CStlSolid::AddTriangle(float* t)
{
	CStlTri tri(t);
	m_list.push_back(tri);
}

<|endoftext|>


<commit_before>#include "debug.h"
#include <stdio.h>
#include <stdarg.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include "timeops.h"
#include <pthread.h>
#include "cmm_thread.h"
#include <sstream>
#include <string>
#include <iomanip>
using std::ostringstream; using std::string;
using std::setw; using std::setfill;

#ifdef ANDROID
#define LIBCMM_LOGFILE "/sdcard/intnw/intnw.log"
#  ifdef NDK_BUILD
#  include <android/log.h>
#  else
#  include <cutils/logd.h>
#  endif
#endif

pthread_key_t thread_name_key;
static pthread_once_t key_once = PTHREAD_ONCE_INIT;

static void delete_name_string(void *arg)
{
    char *name_str = (char*)arg;
    delete [] name_str;
}

static void make_key()
{
    (void)pthread_key_create(&thread_name_key, delete_name_string);
    pthread_setspecific(thread_name_key, NULL);
}

void set_thread_name(const char *name)
{
    (void) pthread_once(&key_once, make_key);

    ASSERT(name);
    char *old_name = (char*)pthread_getspecific(thread_name_key);
    delete [] old_name;

    char *name_str = new char[MAX_NAME_LEN+1];
    memset(name_str, 0, MAX_NAME_LEN+1);
    strncpy(name_str, name, MAX_NAME_LEN);
    pthread_setspecific(thread_name_key, name_str);
}

char * get_thread_name()
{
    (void) pthread_once(&key_once, make_key);

    char * name_str = (char*)pthread_getspecific(thread_name_key);
    if (!name_str) {
        char *name = new char[12];
        sprintf(name, "%08lx", pthread_self());
        pthread_setspecific(thread_name_key, name);
        name_str = name;
    }

    return name_str;
}

static void vdbgprintf(bool plain, const char *fmt, va_list ap)
{
    ostringstream stream;
    if (!plain) {
        struct timeval now;
        TIME(now);
        stream << "[" << now.tv_sec << "." << setw(6) << setfill('0') << now.tv_usec << "]";
        stream << "[" << getpid() << "]";
        stream << "[";
#ifdef CMM_UNIT_TESTING
        stream << "(unit testing)";
#else
        stream << get_thread_name();
#endif
        stream << "] ";
    }

    string fmtstr(stream.str());
    fmtstr += fmt;

#ifdef ANDROID
    //int rc = vprintf(fmtstr.c_str(), ap);
    //__android_log_vprint(ANDROID_LOG_INFO, "libcmm", fmtstr.c_str(), ap);
    FILE *out = fopen(LIBCMM_LOGFILE, "a");
    if (out) {
        vfprintf(out, fmtstr.c_str(), ap);
        fclose(out);
    } else {
        __android_log_vprint(ANDROID_LOG_INFO, "libcmm", fmtstr.c_str(), ap);
    }
#else
    vfprintf(stderr, fmtstr.c_str(), ap);
#endif
}

void dbgprintf_always(const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    vdbgprintf(true, fmt, ap);
    va_end(ap);
}

#ifdef CMM_DEBUG
static bool debugging = true;

bool is_debugging_on()
{
    return debugging;
}

void set_debugging(bool value)
{
    debugging = value;
}

void dbgprintf(const char *fmt, ...)
{
    if (debugging) {
        va_list ap;
        va_start(ap, fmt);
        vdbgprintf(false, fmt, ap);
        va_end(ap);
    }
}

void dbgprintf_plain(const char *fmt, ...)
{
    if (debugging) {
        va_list ap;
        va_start(ap, fmt);
        vdbgprintf(true, fmt, ap);
        va_end(ap);
    }
}
#endif
<commit_msg>Added reason for log file open failure when doing fallback to logcat.<commit_after>#include "debug.h"
#include <stdio.h>
#include <stdarg.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include "timeops.h"
#include <pthread.h>
#include "cmm_thread.h"
#include <sstream>
#include <string>
#include <iomanip>
using std::ostringstream; using std::string;
using std::setw; using std::setfill;

#ifdef ANDROID
#define LIBCMM_LOGFILE "/sdcard/intnw/intnw.log"
#  ifdef NDK_BUILD
#  include <android/log.h>
#  else
#  include <cutils/logd.h>
#  endif
#endif

pthread_key_t thread_name_key;
static pthread_once_t key_once = PTHREAD_ONCE_INIT;

static void delete_name_string(void *arg)
{
    char *name_str = (char*)arg;
    delete [] name_str;
}

static void make_key()
{
    (void)pthread_key_create(&thread_name_key, delete_name_string);
    pthread_setspecific(thread_name_key, NULL);
}

void set_thread_name(const char *name)
{
    (void) pthread_once(&key_once, make_key);

    ASSERT(name);
    char *old_name = (char*)pthread_getspecific(thread_name_key);
    delete [] old_name;

    char *name_str = new char[MAX_NAME_LEN+1];
    memset(name_str, 0, MAX_NAME_LEN+1);
    strncpy(name_str, name, MAX_NAME_LEN);
    pthread_setspecific(thread_name_key, name_str);
}

char * get_thread_name()
{
    (void) pthread_once(&key_once, make_key);

    char * name_str = (char*)pthread_getspecific(thread_name_key);
    if (!name_str) {
        char *name = new char[12];
        sprintf(name, "%08lx", pthread_self());
        pthread_setspecific(thread_name_key, name);
        name_str = name;
    }

    return name_str;
}

static void vdbgprintf(bool plain, const char *fmt, va_list ap)
{
    ostringstream stream;
    if (!plain) {
        struct timeval now;
        TIME(now);
        stream << "[" << now.tv_sec << "." << setw(6) << setfill('0') << now.tv_usec << "]";
        stream << "[" << getpid() << "]";
        stream << "[";
#ifdef CMM_UNIT_TESTING
        stream << "(unit testing)";
#else
        stream << get_thread_name();
#endif
        stream << "] ";
    }

    string fmtstr(stream.str());
    fmtstr += fmt;

#ifdef ANDROID
    //int rc = vprintf(fmtstr.c_str(), ap);
    //__android_log_vprint(ANDROID_LOG_INFO, "libcmm", fmtstr.c_str(), ap);
    FILE *out = fopen(LIBCMM_LOGFILE, "a");
    if (out) {
        vfprintf(out, fmtstr.c_str(), ap);
        fclose(out);
    } else {
        int e = errno;
        stream.str("Failed opening intnw log file: ");
        stream << strerror(e) << " ** " << fmtstr;
        fmtstr = stream.str();

        __android_log_vprint(ANDROID_LOG_INFO, "libcmm", fmtstr.c_str(), ap);
    }
#else
    vfprintf(stderr, fmtstr.c_str(), ap);
#endif
}

void dbgprintf_always(const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    vdbgprintf(true, fmt, ap);
    va_end(ap);
}

#ifdef CMM_DEBUG
static bool debugging = true;

bool is_debugging_on()
{
    return debugging;
}

void set_debugging(bool value)
{
    debugging = value;
}

void dbgprintf(const char *fmt, ...)
{
    if (debugging) {
        va_list ap;
        va_start(ap, fmt);
        vdbgprintf(false, fmt, ap);
        va_end(ap);
    }
}

void dbgprintf_plain(const char *fmt, ...)
{
    if (debugging) {
        va_list ap;
        va_start(ap, fmt);
        vdbgprintf(true, fmt, ap);
        va_end(ap);
    }
}
#endif
<|endoftext|>