<commit_before>#include <assert.h>
#include <stdio.h>
#include <atomic>
#include <new>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include <pthread.h>
#include <signal.h>
#include <setjmp.h>
#include <errno.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include "mtrace.h"
#include "fstest.h"
#include "libutil.h"
#include "spinbarrier.hh"

extern char _end[];
__thread sigjmp_buf pf_jmpbuf;
__thread int pf_active;

class double_barrier {
  spin_barrier enter_;
  spin_barrier exit_;

public:
  double_barrier() : enter_(2), exit_(2) {}
  void sync() { enter(); exit(); }
  void enter() { enter_.join(); }
  void exit() { exit_.join(); }
};

struct testproc {
  double_barrier setup;
  std::atomic<void (*)(void)> setupf1;
  std::atomic<void (*)(void)> setupf2;

  testproc(void (*s1)(void), void (*s2)(void)) : setupf1(s1), setupf2(s2) {}
  void run() {
    setup.enter();
    setupf1();
    setupf2();
    setup.exit();
  }
};

struct testfunc {
  double_barrier start;
  double_barrier stop;

  std::atomic<int (*)(void)> func;
  std::atomic<int> retval;

  testfunc(int (*f)(void)) : func(f) {}
  void run() {
#ifndef XV6_USER
    errno = 0;
#endif
    start.sync();
    retval = func();
    stop.sync();
  }
};

static void*
testfunc_thread(void* arg)
{
  madvise(0, (size_t) _end, MADV_WILLNEED);
  testfunc* f = (testfunc*) arg;
  f->run();
  return nullptr;
}

static void
run_test(testproc* tp, testfunc* tf, fstest* t, int first_func, bool do_pin)
{
  assert(first_func == 0 || first_func == 1);
  if (do_pin)
    setaffinity(2);

  for (int i = 0; i < 2; i++)
    new (&tp[i]) testproc(t->proc[i].setup_proc, t->setup_procfinal);
  for (int i = 0; i < 2; i++)
    new (&tf[i]) testfunc(t->func[i].call);

  t->setup_common();

  pid_t pids[2] = { 0, 0 };
  for (int p = 0; p < 2; p++) {
    int nfunc = 0;
    for (int f = 0; f < 2; f++)
      if (t->func[f].callproc == p)
        nfunc++;
    if (nfunc == 0)
      continue;

    fflush(stdout);
    pids[p] = fork();
    assert(pids[p] >= 0);

    if (pids[p] == 0) {
      madvise(0, (size_t) _end, MADV_WILLNEED);
      tp[p].run();

      int ndone = 0;
      pthread_t tid[2];
      for (int f = 0; f < 2; f++) {
        if (t->func[f].callproc == p) {
          if (do_pin)
            setaffinity(f);
          ndone++;
          if (ndone == nfunc)
            testfunc_thread(&tf[f]);
          else
            pthread_create(&tid[f], 0, testfunc_thread, (void*) &tf[f]);
        }
      }

      if (nfunc == 2)
        pthread_join(tid[0], nullptr);
      exit(0);
    }
  }

  for (int p = 0; p < 2; p++) if (pids[p]) tp[p].setup.sync();
  t->setup_final();

  for (int i = 0; i < 2; i++) tf[i].start.enter();

  char mtname[64];
  snprintf(mtname, sizeof(mtname), "%s", t->testname);
  mtenable_type(mtrace_record_ascope, mtname);

  for (int i = 0; i < 2; i++) {
    tf[first_func ^ i].start.exit();
    tf[first_func ^ i].stop.enter();
  }

  mtdisable(mtname);

  for (int i = 0; i < 2; i++) tf[i].stop.exit();

  for (int p = 0; p < 2; p++)
    if (pids[p])
      assert(waitpid(pids[p], nullptr, 0) >= 0);

  t->cleanup();
}

static void
pf_handler(int signo)
{
  if (pf_active)
    siglongjmp(pf_jmpbuf, signo);
  // Let the error happen
  signal(signo, SIG_DFL);
}

static bool verbose = false;
static bool check_commutativity = false;
static bool run_threads = false;
static bool check_results = false;
static fstest *cur_test = nullptr;

void
expect_result(const char *varname, long got, long expect)
{
  if (!check_results) return;
  if (got == expect) return;
  auto name = cur_test->testname;
#ifdef XV6_USER
  printf("%s: expected %s == %ld, got %ld\n",
         name, varname, expect, got);
#else
  printf("%s: expected %s == %ld, got %ld (errno %s)\n",
         name, varname, expect, got, strerror(errno));
#endif
}

void
expect_errno(int expect)
{
#ifndef XV6_USER
  if (!check_results) return;
  if (errno == expect) return;
  auto name = cur_test->testname;
  printf("%s: expected errno == %s, got %s\n",
         name, strerror(expect), strerror(errno));
#endif
}

static void
usage(const char* prog)
{
  fprintf(stderr, "Usage: %s [-v] [-c] [-t] [-r] [-n NPARTS] [-p THISPART] [min[-max]]\n", prog);
}

int
main(int ac, char** av)
{
  uint32_t min = 0;
  uint32_t max;
  int nparts = -1;
  int thispart = -1;

  uint32_t ntests = 0;
  for (ntests = min; fstests[ntests].testname; ntests++)
    ;
  max = ntests - 1;

  for (;;) {
    int opt = getopt(ac, av, "vctrp:n:");
    if (opt == -1)
      break;

    switch (opt) {
    case 'v':
      verbose = true;
      break;

    case 'c':
      check_commutativity = true;
      break;

    case 't':
      run_threads = true;
      break;

    case 'r':
      run_threads = true;
      check_results = true;
      break;

    case 'n':
      nparts = atoi(optarg);
      break;

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

    default:
      usage(av[0]);
      return -1;
    }
  }

  if (optind < ac) {
    char* dash = strchr(av[optind], '-');
    if (!dash) {
      min = max = atoi(av[optind]);
    } else {
      *dash = '\0';
      if (av[optind])
        min = atoi(av[optind]);
      if (*(dash + 1))
        max = atoi(dash + 1);
    }
  } else if (nparts >= 0 || thispart >= 0) {
    if (nparts < 0 || thispart < 0) {
      usage(av[0]);
      return -1;
    }

    uint32_t partsize = (ntests + nparts - 1) /nparts;
    min = partsize * thispart;
    max = partsize * (thispart + 1) - 1;
  }

  if (!check_commutativity && !run_threads) {
    fprintf(stderr, "Must specify one of -c or -t\n");
    usage(av[0]);
    return -1;
  }

  printf("fstest:");
  if (verbose)
    printf(" verbose");
  if (check_commutativity)
    printf(" check");
  if (run_threads)
    printf(" threads");
  if (check_results)
    printf(" results");
  if (min == 0 && max == ntests - 1)
    printf(" all");
  else if (min == max)
    printf(" %d", min);
  else
    printf(" %d-%d", min, max);
  printf("\n");

  testproc* tp = (testproc*) mmap(nullptr, 4096, PROT_READ | PROT_WRITE,
                                  MAP_SHARED | MAP_ANONYMOUS, -1, 0);
  assert(tp != MAP_FAILED);
  assert(2*sizeof(*tp) <= 4096);

  testfunc* tf = (testfunc*) mmap(nullptr, 4096, PROT_READ | PROT_WRITE,
                                  MAP_SHARED | MAP_ANONYMOUS, -1, 0);
  assert(tf != MAP_FAILED);
  assert(2*sizeof(*tf) <= 4096);

  madvise(0, (size_t) _end, MADV_WILLNEED);

  signal(SIGPIPE, SIG_IGN);
  signal(SIGBUS, pf_handler);
  signal(SIGSEGV, pf_handler);

  for (uint32_t t = min; t <= max && t < ntests; t++) {
    cur_test = &fstests[t];

#ifdef XV6_USER
    // XXX xv6 does not support mprotect, so skip mprotect tests
    if (strstr(fstests[t].testname, "mprotect")) {
      printf("skipping %s (test %d)\n", fstests[t].testname, t);
      continue;
    }
#endif

    if (verbose)
      printf("%s (test %d) starting\n", fstests[t].testname, t);

    if (check_commutativity) {
      run_test(tp, tf, &fstests[t], 0, false);
      int ra0 = tf[0].retval;
      int ra1 = tf[1].retval;

      run_test(tp, tf, &fstests[t], 1, false);
      int rb0 = tf[0].retval;
      int rb1 = tf[1].retval;

      if (ra0 == rb0 && ra1 == rb1) {
        if (verbose)
          printf("%s: commutes: %s->%d %s->%d\n",
                 fstests[t].testname,
                 fstests[t].func[0].callname, ra0, fstests[t].func[1].callname, ra1);
      } else {
        printf("%s: diverges: %s->%d %s->%d vs %s->%d %s->%d\n",
               fstests[t].testname,
               fstests[t].func[0].callname, ra0, fstests[t].func[1].callname, ra1,
               fstests[t].func[1].callname, rb1, fstests[t].func[0].callname, rb0);
      }
    }

    if (run_threads) {
      run_test(tp, tf, &fstests[t], 0, true);
    }
  }

  printf("fstest: done\n");
}
<commit_msg>fstest: Pre-expand the VM radix tree<commit_after>#include <assert.h>
#include <stdio.h>
#include <atomic>
#include <new>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include <pthread.h>
#include <signal.h>
#include <setjmp.h>
#include <errno.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include "mtrace.h"
#include "fstest.h"
#include "libutil.h"
#include "spinbarrier.hh"

extern char _end[];
__thread sigjmp_buf pf_jmpbuf;
__thread int pf_active;

class double_barrier {
  spin_barrier enter_;
  spin_barrier exit_;

public:
  double_barrier() : enter_(2), exit_(2) {}
  void sync() { enter(); exit(); }
  void enter() { enter_.join(); }
  void exit() { exit_.join(); }
};

struct testproc {
  double_barrier setup;
  std::atomic<void (*)(void)> setupf1;
  std::atomic<void (*)(void)> setupf2;

  testproc(void (*s1)(void), void (*s2)(void)) : setupf1(s1), setupf2(s2) {}
  void run() {
    setup.enter();
    setupf1();
    setupf2();
    setup.exit();
  }
};

struct testfunc {
  double_barrier start;
  double_barrier stop;

  std::atomic<int (*)(void)> func;
  std::atomic<int> retval;

  testfunc(int (*f)(void)) : func(f) {}
  void run() {
#ifndef XV6_USER
    errno = 0;
#endif
    start.sync();
    retval = func();
    stop.sync();
  }
};

static void*
testfunc_thread(void* arg)
{
  madvise(0, (size_t) _end, MADV_WILLNEED);
  testfunc* f = (testfunc*) arg;
  f->run();
  return nullptr;
}

static void
run_test(testproc* tp, testfunc* tf, fstest* t, int first_func, bool do_pin)
{
  assert(first_func == 0 || first_func == 1);
  if (do_pin)
    setaffinity(2);

  for (int i = 0; i < 2; i++)
    new (&tp[i]) testproc(t->proc[i].setup_proc, t->setup_procfinal);
  for (int i = 0; i < 2; i++)
    new (&tf[i]) testfunc(t->func[i].call);

  t->setup_common();

  pid_t pids[2] = { 0, 0 };
  for (int p = 0; p < 2; p++) {
    int nfunc = 0;
    for (int f = 0; f < 2; f++)
      if (t->func[f].callproc == p)
        nfunc++;
    if (nfunc == 0)
      continue;

    fflush(stdout);
    pids[p] = fork();
    assert(pids[p] >= 0);

    if (pids[p] == 0) {
      // Get all text and data structures
      madvise(0, (size_t) _end, MADV_WILLNEED);
      // Prime the VM system (this must be kept in sync with
      // fs_testgen.py)
      void *r = mmap((void*)0x12345600000, 4 * 4096, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
      if (r == (void*)-1)
        setup_error("mmap");
      munmap(r, 4 * 4096);

      // Run setup
      tp[p].run();

      int ndone = 0;
      pthread_t tid[2];
      for (int f = 0; f < 2; f++) {
        if (t->func[f].callproc == p) {
          if (do_pin)
            setaffinity(f);
          ndone++;
          if (ndone == nfunc)
            testfunc_thread(&tf[f]);
          else
            pthread_create(&tid[f], 0, testfunc_thread, (void*) &tf[f]);
        }
      }

      if (nfunc == 2)
        pthread_join(tid[0], nullptr);
      exit(0);
    }
  }

  for (int p = 0; p < 2; p++) if (pids[p]) tp[p].setup.sync();
  t->setup_final();

  for (int i = 0; i < 2; i++) tf[i].start.enter();

  char mtname[64];
  snprintf(mtname, sizeof(mtname), "%s", t->testname);
  mtenable_type(mtrace_record_ascope, mtname);

  for (int i = 0; i < 2; i++) {
    tf[first_func ^ i].start.exit();
    tf[first_func ^ i].stop.enter();
  }

  mtdisable(mtname);

  for (int i = 0; i < 2; i++) tf[i].stop.exit();

  for (int p = 0; p < 2; p++)
    if (pids[p])
      assert(waitpid(pids[p], nullptr, 0) >= 0);

  t->cleanup();
}

static void
pf_handler(int signo)
{
  if (pf_active)
    siglongjmp(pf_jmpbuf, signo);
  // Let the error happen
  signal(signo, SIG_DFL);
}

static bool verbose = false;
static bool check_commutativity = false;
static bool run_threads = false;
static bool check_results = false;
static fstest *cur_test = nullptr;

void
expect_result(const char *varname, long got, long expect)
{
  if (!check_results) return;
  if (got == expect) return;
  auto name = cur_test->testname;
#ifdef XV6_USER
  printf("%s: expected %s == %ld, got %ld\n",
         name, varname, expect, got);
#else
  printf("%s: expected %s == %ld, got %ld (errno %s)\n",
         name, varname, expect, got, strerror(errno));
#endif
}

void
expect_errno(int expect)
{
#ifndef XV6_USER
  if (!check_results) return;
  if (errno == expect) return;
  auto name = cur_test->testname;
  printf("%s: expected errno == %s, got %s\n",
         name, strerror(expect), strerror(errno));
#endif
}

static void
usage(const char* prog)
{
  fprintf(stderr, "Usage: %s [-v] [-c] [-t] [-r] [-n NPARTS] [-p THISPART] [min[-max]]\n", prog);
}

int
main(int ac, char** av)
{
  uint32_t min = 0;
  uint32_t max;
  int nparts = -1;
  int thispart = -1;

  uint32_t ntests = 0;
  for (ntests = min; fstests[ntests].testname; ntests++)
    ;
  max = ntests - 1;

  for (;;) {
    int opt = getopt(ac, av, "vctrp:n:");
    if (opt == -1)
      break;

    switch (opt) {
    case 'v':
      verbose = true;
      break;

    case 'c':
      check_commutativity = true;
      break;

    case 't':
      run_threads = true;
      break;

    case 'r':
      run_threads = true;
      check_results = true;
      break;

    case 'n':
      nparts = atoi(optarg);
      break;

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

    default:
      usage(av[0]);
      return -1;
    }
  }

  if (optind < ac) {
    char* dash = strchr(av[optind], '-');
    if (!dash) {
      min = max = atoi(av[optind]);
    } else {
      *dash = '\0';
      if (av[optind])
        min = atoi(av[optind]);
      if (*(dash + 1))
        max = atoi(dash + 1);
    }
  } else if (nparts >= 0 || thispart >= 0) {
    if (nparts < 0 || thispart < 0) {
      usage(av[0]);
      return -1;
    }

    uint32_t partsize = (ntests + nparts - 1) /nparts;
    min = partsize * thispart;
    max = partsize * (thispart + 1) - 1;
  }

  if (!check_commutativity && !run_threads) {
    fprintf(stderr, "Must specify one of -c or -t\n");
    usage(av[0]);
    return -1;
  }

  printf("fstest:");
  if (verbose)
    printf(" verbose");
  if (check_commutativity)
    printf(" check");
  if (run_threads)
    printf(" threads");
  if (check_results)
    printf(" results");
  if (min == 0 && max == ntests - 1)
    printf(" all");
  else if (min == max)
    printf(" %d", min);
  else
    printf(" %d-%d", min, max);
  printf("\n");

  testproc* tp = (testproc*) mmap(nullptr, 4096, PROT_READ | PROT_WRITE,
                                  MAP_SHARED | MAP_ANONYMOUS, -1, 0);
  assert(tp != MAP_FAILED);
  assert(2*sizeof(*tp) <= 4096);

  testfunc* tf = (testfunc*) mmap(nullptr, 4096, PROT_READ | PROT_WRITE,
                                  MAP_SHARED | MAP_ANONYMOUS, -1, 0);
  assert(tf != MAP_FAILED);
  assert(2*sizeof(*tf) <= 4096);

  madvise(0, (size_t) _end, MADV_WILLNEED);

  signal(SIGPIPE, SIG_IGN);
  signal(SIGBUS, pf_handler);
  signal(SIGSEGV, pf_handler);

  for (uint32_t t = min; t <= max && t < ntests; t++) {
    cur_test = &fstests[t];

#ifdef XV6_USER
    // XXX xv6 does not support mprotect, so skip mprotect tests
    if (strstr(fstests[t].testname, "mprotect")) {
      printf("skipping %s (test %d)\n", fstests[t].testname, t);
      continue;
    }
#endif

    if (verbose)
      printf("%s (test %d) starting\n", fstests[t].testname, t);

    if (check_commutativity) {
      run_test(tp, tf, &fstests[t], 0, false);
      int ra0 = tf[0].retval;
      int ra1 = tf[1].retval;

      run_test(tp, tf, &fstests[t], 1, false);
      int rb0 = tf[0].retval;
      int rb1 = tf[1].retval;

      if (ra0 == rb0 && ra1 == rb1) {
        if (verbose)
          printf("%s: commutes: %s->%d %s->%d\n",
                 fstests[t].testname,
                 fstests[t].func[0].callname, ra0, fstests[t].func[1].callname, ra1);
      } else {
        printf("%s: diverges: %s->%d %s->%d vs %s->%d %s->%d\n",
               fstests[t].testname,
               fstests[t].func[0].callname, ra0, fstests[t].func[1].callname, ra1,
               fstests[t].func[1].callname, rb1, fstests[t].func[0].callname, rb0);
      }
    }

    if (run_threads) {
      run_test(tp, tf, &fstests[t], 0, true);
    }
  }

  printf("fstest: done\n");
}
<|endoftext|>


<commit_before><commit_msg>`Font2D::printText2D`: added check for invalid font texture file format.<commit_after><|endoftext|>


<commit_before><commit_msg>Converted from kyotocabinet to Berkeley DB.<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (c) 2008-2013 Juli Mallett. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/time.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#ifdef	USE_SYSLOG
#include <syslog.h>
#endif

#include <common/thread/mutex.h>

#include <iostream>
#include <list>
#include <sstream>

/* Collapse repeating log messages for up to 2 seconds.  */
#define	LOG_REPEAT_COLLAPSE_SECONDS	(2)

namespace {
	struct LogMask {
		regex_t regex_;
		enum Log::Priority priority_;
	};

	static Mutex log_mutex("Log");

	static std::list<LogMask> log_masks;
	static std::pair<std::string, std::string> last_log;
	static unsigned last_log_count;
	static struct timeval last_log_start;

#ifdef	USE_SYSLOG
	static int syslog_priority(const Log::Priority&);
#endif
}

static std::ostream& operator<< (std::ostream&, const Log::Priority&);
static std::ostream& operator<< (std::ostream&, const struct timeval&);

void
Log::log(const Priority& priority, const LogHandle& handle,
	 const std::string& message)
{
	std::list<LogMask>::const_iterator it;
	std::string handle_string = (std::string)handle;

	ConditionLock _(&log_mutex, priority != Log::Emergency);

	/*
	 * XXX
	 * Skip this all if we're in a HALT or NOTREACHED, since we can
	 * generate those here.  Critical logs cannot ever be masked, right?
	 */
	for (it = log_masks.begin(); it != log_masks.end(); ++it) {
		const LogMask& mask = *it;
		int rv;

		rv = regexec(&mask.regex_, handle_string.c_str(), 0, NULL, 0);
		switch (rv) {
		case 0:
			if (priority <= mask.priority_)
				goto done;
			return;
		case REG_NOMATCH:
			continue;
		default:
			HALT("/log") << "Could not match regex: " << rv;
			return;
		}
		NOTREACHED("/log");
	}

done:
#ifdef	USE_SYSLOG
	std::string syslog_message;

	syslog_message += "[";
	syslog_message += (std::string)handle;
	syslog_message += "] ";
	syslog_message += message;

	syslog(syslog_priority(priority), "%s", syslog_message.c_str());
#endif

	struct timeval now;
	int rv;

	rv = gettimeofday(&now, NULL);
	if (rv == -1)
		memset(&now, 0, sizeof now);

	if (last_log.first == handle_string && last_log.second == message &&
	    now.tv_sec - last_log_start.tv_sec <= LOG_REPEAT_COLLAPSE_SECONDS) {
		last_log_count++;
		return;
	} else {
		if (last_log_count != 0) {
			std::cerr << now << " [" << last_log.first << "] " <<
				"last message repeated " << last_log_count <<
				" times." << std::endl;
			last_log_count = 0;
		}
		last_log.first = handle_string;
		last_log.second = message;
		last_log_start = now;
	}

	std::cerr << now << " [" << handle_string << "] " <<
		priority << ": " <<
		message <<
		std::endl;
}

bool
Log::mask(const std::string& handle_regex, const Log::Priority& priority)
{
	LogMask mask;

	if (::regcomp(&mask.regex_, handle_regex.c_str(),
		      REG_NOSUB | REG_EXTENDED) != 0) {
		return (false);
	}
	mask.priority_ = priority;

	log_masks.push_back(mask);

	return (true);
}

#ifdef	USE_SYSLOG
static int
syslog_priority(const Log::Priority& priority)
{
	switch (priority) {
	case Log::Emergency:
		return (LOG_EMERG);
	case Log::Alert:
		return (LOG_ALERT);
	case Log::Critical:
		return (LOG_CRIT);
	case Log::Error:
		return (LOG_ERR);
	case Log::Warning:
		return (LOG_WARNING);
	case Log::Notice:
		return (LOG_NOTICE);
	case Log::Info:
		return (LOG_INFO);
	case Log::Debug:
	case Log::Trace:
		return (LOG_DEBUG);
	default:
		HALT("/log") << "Unhandled log priority!";
		return (-1);
	}
}
#endif

static std::ostream&
operator<< (std::ostream& os, const Log::Priority& priority)
{
	switch (priority) {
	case Log::Emergency:
		return (os << "EMERG");
	case Log::Alert:
		return (os << "ALERT");
	case Log::Critical:
		return (os << "CRIT");
	case Log::Error:
		return (os << "ERR");
	case Log::Warning:
		return (os << "WARNING");
	case Log::Notice:
		return (os << "NOTICE");
	case Log::Info:
		return (os << "INFO");
	case Log::Debug:
		return (os << "DEBUG");
	case Log::Trace:
		return (os << "TRACE");
	default:
		HALT("/log") << "Unhandled log priority!";
		return (os);
	}
}

static std::ostream&
operator<< (std::ostream& os, const struct timeval& tv)
{
	char buf[20];

	snprintf(buf, sizeof buf, "%u.%06u", (unsigned)tv.tv_sec,
		 (unsigned)tv.tv_usec);
	return (os << buf);
}
<commit_msg>Don't use Log locking if !THREADS.<commit_after>/*
 * Copyright (c) 2008-2013 Juli Mallett. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/time.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#ifdef	USE_SYSLOG
#include <syslog.h>
#endif

#include <common/thread/mutex.h>

#include <iostream>
#include <list>
#include <sstream>

/* Collapse repeating log messages for up to 2 seconds.  */
#define	LOG_REPEAT_COLLAPSE_SECONDS	(2)

namespace {
	struct LogMask {
		regex_t regex_;
		enum Log::Priority priority_;
	};

#ifdef THREADS
	static Mutex log_mutex("Log");
#endif

	static std::list<LogMask> log_masks;
	static std::pair<std::string, std::string> last_log;
	static unsigned last_log_count;
	static struct timeval last_log_start;

#ifdef	USE_SYSLOG
	static int syslog_priority(const Log::Priority&);
#endif
}

static std::ostream& operator<< (std::ostream&, const Log::Priority&);
static std::ostream& operator<< (std::ostream&, const struct timeval&);

void
Log::log(const Priority& priority, const LogHandle& handle,
	 const std::string& message)
{
	std::list<LogMask>::const_iterator it;
	std::string handle_string = (std::string)handle;

#ifdef THREADS
	ConditionLock _(&log_mutex, priority != Log::Emergency);
#endif

	/*
	 * XXX
	 * Skip this all if we're in a HALT or NOTREACHED, since we can
	 * generate those here.  Critical logs cannot ever be masked, right?
	 */
	for (it = log_masks.begin(); it != log_masks.end(); ++it) {
		const LogMask& mask = *it;
		int rv;

		rv = regexec(&mask.regex_, handle_string.c_str(), 0, NULL, 0);
		switch (rv) {
		case 0:
			if (priority <= mask.priority_)
				goto done;
			return;
		case REG_NOMATCH:
			continue;
		default:
			HALT("/log") << "Could not match regex: " << rv;
			return;
		}
		NOTREACHED("/log");
	}

done:
#ifdef	USE_SYSLOG
	std::string syslog_message;

	syslog_message += "[";
	syslog_message += (std::string)handle;
	syslog_message += "] ";
	syslog_message += message;

	syslog(syslog_priority(priority), "%s", syslog_message.c_str());
#endif

	struct timeval now;
	int rv;

	rv = gettimeofday(&now, NULL);
	if (rv == -1)
		memset(&now, 0, sizeof now);

	if (last_log.first == handle_string && last_log.second == message &&
	    now.tv_sec - last_log_start.tv_sec <= LOG_REPEAT_COLLAPSE_SECONDS) {
		last_log_count++;
		return;
	} else {
		if (last_log_count != 0) {
			std::cerr << now << " [" << last_log.first << "] " <<
				"last message repeated " << last_log_count <<
				" times." << std::endl;
			last_log_count = 0;
		}
		last_log.first = handle_string;
		last_log.second = message;
		last_log_start = now;
	}

	std::cerr << now << " [" << handle_string << "] " <<
		priority << ": " <<
		message <<
		std::endl;
}

bool
Log::mask(const std::string& handle_regex, const Log::Priority& priority)
{
	LogMask mask;

	if (::regcomp(&mask.regex_, handle_regex.c_str(),
		      REG_NOSUB | REG_EXTENDED) != 0) {
		return (false);
	}
	mask.priority_ = priority;

	log_masks.push_back(mask);

	return (true);
}

#ifdef	USE_SYSLOG
static int
syslog_priority(const Log::Priority& priority)
{
	switch (priority) {
	case Log::Emergency:
		return (LOG_EMERG);
	case Log::Alert:
		return (LOG_ALERT);
	case Log::Critical:
		return (LOG_CRIT);
	case Log::Error:
		return (LOG_ERR);
	case Log::Warning:
		return (LOG_WARNING);
	case Log::Notice:
		return (LOG_NOTICE);
	case Log::Info:
		return (LOG_INFO);
	case Log::Debug:
	case Log::Trace:
		return (LOG_DEBUG);
	default:
		HALT("/log") << "Unhandled log priority!";
		return (-1);
	}
}
#endif

static std::ostream&
operator<< (std::ostream& os, const Log::Priority& priority)
{
	switch (priority) {
	case Log::Emergency:
		return (os << "EMERG");
	case Log::Alert:
		return (os << "ALERT");
	case Log::Critical:
		return (os << "CRIT");
	case Log::Error:
		return (os << "ERR");
	case Log::Warning:
		return (os << "WARNING");
	case Log::Notice:
		return (os << "NOTICE");
	case Log::Info:
		return (os << "INFO");
	case Log::Debug:
		return (os << "DEBUG");
	case Log::Trace:
		return (os << "TRACE");
	default:
		HALT("/log") << "Unhandled log priority!";
		return (os);
	}
}

static std::ostream&
operator<< (std::ostream& os, const struct timeval& tv)
{
	char buf[20];

	snprintf(buf, sizeof buf, "%u.%06u", (unsigned)tv.tv_sec,
		 (unsigned)tv.tv_usec);
	return (os << buf);
}
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/common/apollo_app.h"

#include <csignal>
#include <memory>
#include <string>
#include <vector>

#include "gflags/gflags.h"
#include "modules/common/log.h"
#include "modules/common/status/status.h"
#include "modules/common/util/string_util.h"

#include "ros/include/ros/ros.h"

DECLARE_string(log_dir);

namespace apollo {
namespace common {

void ApolloApp::SetCallbackThreadNumber(uint32_t callback_thread_num) {
  CHECK_GE(callback_thread_num, 1);
  callback_thread_num_ = callback_thread_num;
}

void ApolloApp::ExportFlags() const {
  const auto export_file = util::StrCat(FLAGS_log_dir, "/", Name(), ".flags");
  std::ofstream fout(export_file);
  CHECK(fout) << "Cannot open file " << export_file;

  std::vector<gflags::CommandLineFlagInfo> flags;
  gflags::GetAllFlags(&flags);
  for (const auto& flag : flags) {
    fout << "# " << flag.type << ", default=" << flag.default_value << "\n"
         << "# " << flag.description << "\n"
         << "--" << flag.name << "=" << flag.current_value << "\n"
         << std::endl;
  }
}

int ApolloApp::Spin() {
  std::unique_ptr<ros::AsyncSpinner> spinner;
  if (callback_thread_num_ > 1) {
    spinner = std::unique_ptr<ros::AsyncSpinner>(
        new ros::AsyncSpinner(callback_thread_num_));
  }
  auto status = Init();
  if (!status.ok()) {
    AERROR << Name() << " Init failed: " << status;
    return -1;
  }
  status = Start();
  if (!status.ok()) {
    AERROR << Name() << " Start failed: " << status;
    return -2;
  }
  ExportFlags();
  if (spinner) {
    spinner->start();
  } else {
    ros::spin();
  }
  ros::waitForShutdown();
  Stop();
  AINFO << Name() << " exited.";
  return 0;
}

void apollo_app_sigint_handler(int signal_num) {
  AINFO << "Received signal: " << signal_num;
  if (signal_num != SIGINT) {
    return;
  }
  bool static is_stopping = false;
  if (is_stopping) {
    return;
  }
  is_stopping = true;
  ros::shutdown();
}

}  // namespace common
}  // namespace apollo
<commit_msg>Common: fixed a bug in apollo_app.cc (#3173)<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/common/apollo_app.h"

#include <csignal>
#include <memory>
#include <string>
#include <vector>

#include "gflags/gflags.h"
#include "modules/common/log.h"
#include "modules/common/status/status.h"
#include "modules/common/util/string_util.h"

#include "ros/include/ros/ros.h"

DECLARE_string(log_dir);

namespace apollo {
namespace common {

void ApolloApp::SetCallbackThreadNumber(uint32_t callback_thread_num) {
  CHECK_GE(callback_thread_num, 1);
  callback_thread_num_ = callback_thread_num;
}

void ApolloApp::ExportFlags() const {
  const auto export_file = util::StrCat(FLAGS_log_dir, "/", Name(), ".flags");
  std::ofstream fout(export_file);
  CHECK(fout) << "Cannot open file " << export_file;

  std::vector<gflags::CommandLineFlagInfo> flags;
  gflags::GetAllFlags(&flags);
  for (const auto& flag : flags) {
    fout << "# " << flag.type << ", default=" << flag.default_value << "\n"
         << "# " << flag.description << "\n"
         << "--" << flag.name << "=" << flag.current_value << "\n"
         << std::endl;
  }
}

int ApolloApp::Spin() {
  auto status = Init();
  if (!status.ok()) {
    AERROR << Name() << " Init failed: " << status;
    return -1;
  }

  std::unique_ptr<ros::AsyncSpinner> spinner;
  if (callback_thread_num_ > 1) {
    spinner = std::unique_ptr<ros::AsyncSpinner>(
        new ros::AsyncSpinner(callback_thread_num_));
  }

  status = Start();
  if (!status.ok()) {
    AERROR << Name() << " Start failed: " << status;
    return -2;
  }
  ExportFlags();
  if (spinner) {
    spinner->start();
  } else {
    ros::spin();
  }
  ros::waitForShutdown();
  Stop();
  AINFO << Name() << " exited.";
  return 0;
}

void apollo_app_sigint_handler(int signal_num) {
  AINFO << "Received signal: " << signal_num;
  if (signal_num != SIGINT) {
    return;
  }
  bool static is_stopping = false;
  if (is_stopping) {
    return;
  }
  is_stopping = true;
  ros::shutdown();
}

}  // namespace common
}  // namespace apollo
<|endoftext|>


<commit_before>/***********************************************************************************************************************
 * ClassIcon.cpp
 *
 *  Created on: Feb 7, 2011
 *      Author: Dimitar Asenov
 **********************************************************************************************************************/

#include "icons/ClassIcon.h"

#include <QtGui/QPainter>

#include <cmath>

namespace OOVisualization {

ITEM_COMMON_DEFINITIONS(ClassIcon)

ClassIcon::ClassIcon(Item* parent, const ClassIconStyle *style) :
	Icon(parent, style)
{
}

void ClassIcon::updateGeometry(int, int)
{
	setInnerSize(style()->width(), style()->width());
}

void ClassIcon::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
	Icon::paint(painter, option, widget);

	int width = style()->width();
	int halfWidth = width / 2;

	QRadialGradient gradient(halfWidth, halfWidth, halfWidth);
	gradient.setColorAt(0, Qt::white);
	gradient.setColorAt(0.3, Qt::white);
	gradient.setColorAt(1, Qt::transparent);
	painter->setBrush(QBrush(gradient));
	painter->setPen(Qt::NoPen);
	painter->drawRect(xOffset(), yOffset(), style()->width(), style()->width());

	painter->setBrush(Qt::white);
	painter->setPen( style()->outline());

	qreal x = xOffset();
	qreal y = yOffset();

	// Move the figure when using antialiasing. The outline will start at a pixel boundary. This makes it sharper.
	qreal outlineWidth = style()->outline().width();
	if ( painter->testRenderHint(QPainter::Antialiasing) || painter->testRenderHint(QPainter::HighQualityAntialiasing) )
		if ( style()->outline() != Qt::NoPen )
		{
			qreal intPart;
			qreal fracPart = std::modf(outlineWidth / 2.0, &intPart);

			x += fracPart;
			y += fracPart;
		}

	int restX = (halfWidth - style()->rectWidth())/2;
	int restY = (halfWidth - style()->rectHeight())/2;

	// Draw the lines exactly in the middle. These are independent of how big the rectangles are.
	painter->drawLine(QLineF(x + halfWidth / 2, y + halfWidth, x + halfWidth*3 / 2, y + halfWidth));
	painter->drawLine(QLineF(x + halfWidth, y + halfWidth, x + halfWidth, y+ halfWidth/2));
	painter->drawLine(QLineF(x + halfWidth/2, y + halfWidth, x + halfWidth/2, y + halfWidth*3/2));
	painter->drawLine(QLineF(x + halfWidth*3/2, y + halfWidth, x + halfWidth*3/2, y + halfWidth*3/2));

	painter->drawRect(QRectF(x + ((width - style()->rectWidth()) / 2), y + restY, style()->rectWidth(), style()->rectHeight()));
	painter->drawRect(QRectF(x + restX, y + halfWidth + restY, style()->rectWidth(), style()->rectHeight()));
	painter->drawRect(QRectF(x + halfWidth + restX, y + halfWidth + restY, style()->rectWidth(), style()->rectHeight()));

}

}
<commit_msg>Fixed the icon visualization for classes.<commit_after>/***********************************************************************************************************************
 * ClassIcon.cpp
 *
 *  Created on: Feb 7, 2011
 *      Author: Dimitar Asenov
 **********************************************************************************************************************/

#include "icons/ClassIcon.h"

#include <QtGui/QPainter>

#include <cmath>

namespace OOVisualization {

ITEM_COMMON_DEFINITIONS(ClassIcon)

ClassIcon::ClassIcon(Item* parent, const ClassIconStyle *style) :
	Icon(parent, style)
{
}

void ClassIcon::updateGeometry(int, int)
{
	setInnerSize(style()->width(), style()->width());
}

void ClassIcon::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
	Icon::paint(painter, option, widget);

	int width = style()->width();
	int halfWidth = width / 2;

	QRadialGradient gradient(halfWidth, halfWidth, halfWidth);
	gradient.setColorAt(0, Qt::white);
	gradient.setColorAt(0.3, Qt::white);
	gradient.setColorAt(1, Qt::transparent);
	painter->setBrush(QBrush(gradient));
	painter->setPen(Qt::NoPen);
	painter->drawRect(xOffset(), yOffset(), style()->width(), style()->width());

	painter->setBrush(Qt::white);
	painter->setPen( style()->outline());

	qreal x = xOffset();
	qreal y = yOffset();

	// Move the figure when using antialiasing. The outline will start at a pixel boundary. This makes it sharper.
	qreal outlineWidth = style()->outline().width();
	if ( painter->testRenderHint(QPainter::Antialiasing) || painter->testRenderHint(QPainter::HighQualityAntialiasing) )
		if ( style()->outline() != Qt::NoPen )
		{
			qreal intPart;
			qreal fracPart = std::modf(outlineWidth / 2.0, &intPart);

			x += fracPart;
			y += fracPart;
		}

	int restX = (halfWidth - style()->rectWidth())/2;
	int restY = (halfWidth - style()->rectHeight())/2;

	// Draw the lines exactly in the middle. These are independent of how big the rectangles are.
	painter->drawLine(QLineF(x + halfWidth / 2, y + halfWidth, x + halfWidth*3 / 2, y + halfWidth));
	painter->drawLine(QLineF(x + halfWidth, y + halfWidth, x + halfWidth, y+ halfWidth/2));
	painter->drawLine(QLineF(x + halfWidth/2, y + halfWidth, x + halfWidth/2, y + halfWidth*3/2));
	painter->drawLine(QLineF(x + halfWidth*3/2, y + halfWidth, x + halfWidth*3/2, y + halfWidth*3/2));

	painter->drawRect(QRectF(x + ((width - style()->rectWidth()) / 2), y + restY, style()->rectWidth(), style()->rectHeight()));
	painter->drawRect(QRectF(x + restX, y + halfWidth + restY, style()->rectWidth(), style()->rectHeight()));
	painter->drawRect(QRectF(x + halfWidth + restX, y + halfWidth + restY, style()->rectWidth(), style()->rectHeight()));
}

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: xmlmod_import.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2004-04-13 16:19:35 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include "imp_share.hxx"

#include <osl/diagnose.h>

#include <rtl/ustrbuf.hxx>

#include <xmlscript/xml_import.hxx>
#include <comphelper/processfactory.hxx>

namespace xmlscript
{

//##################################################################################################

//__________________________________________________________________________________________________
Reference< xml::input::XElement > ModuleElement::getParent()
    throw (RuntimeException)
{
    return static_cast< xml::input::XElement * >( _pParent );
}
//__________________________________________________________________________________________________
OUString ModuleElement::getLocalName()
    throw (RuntimeException)
{
    return _aLocalName;
}
//__________________________________________________________________________________________________
sal_Int32 ModuleElement::getUid()
    throw (RuntimeException)
{
    return _pImport->XMLNS_SCRIPT_UID;
}
//__________________________________________________________________________________________________
Reference< xml::input::XAttributes > ModuleElement::getAttributes()
    throw (RuntimeException)
{
    return _xAttributes;
}
//__________________________________________________________________________________________________
void ModuleElement::ignorableWhitespace(
    OUString const & rWhitespaces )
    throw (xml::sax::SAXException, RuntimeException)
{
    // not used
}
//__________________________________________________________________________________________________
void ModuleElement::characters( OUString const & rChars )
    throw (xml::sax::SAXException, RuntimeException)
{
    _StrBuffer.append( rChars );
}
//__________________________________________________________________________________________________
void ModuleElement::processingInstruction(
    OUString const & rTarget, OUString const & rData )
    throw (xml::sax::SAXException, RuntimeException)
{
}
//__________________________________________________________________________________________________
void ModuleElement::endElement()
    throw (xml::sax::SAXException, RuntimeException)
{
    _pImport->mrModuleDesc.aCode = _StrBuffer.makeStringAndClear();
}
//__________________________________________________________________________________________________
Reference< xml::input::XElement > ModuleElement::startChildElement(
    sal_Int32 nUid, OUString const & rLocalName,
    Reference< xml::input::XAttributes > const & xAttributes )
    throw (xml::sax::SAXException, RuntimeException)
{
    throw xml::sax::SAXException(
        OUString( RTL_CONSTASCII_USTRINGPARAM("unexpected element!") ),
        Reference< XInterface >(), Any() );
}

//__________________________________________________________________________________________________
ModuleElement::ModuleElement(
    OUString const & rLocalName,
    Reference< xml::input::XAttributes > const & xAttributes,
    ModuleElement * pParent, ModuleImport * pImport )
    SAL_THROW( () )
    : _pImport( pImport )
    , _pParent( pParent )
    , _aLocalName( rLocalName )
    , _xAttributes( xAttributes )
{
    _pImport->acquire();

    if (_pParent)
    {
        _pParent->acquire();
    }
}
//__________________________________________________________________________________________________
ModuleElement::~ModuleElement()
    SAL_THROW( () )
{
    _pImport->release();

    if (_pParent)
    {
        _pParent->release();
    }

#if OSL_DEBUG_LEVEL > 1
    OString aStr( OUStringToOString( _aLocalName, RTL_TEXTENCODING_ASCII_US ) );
    OSL_TRACE( "ModuleElement::~ModuleElement(): %s\n", aStr.getStr() );
#endif
}

//##################################################################################################

// XRoot

//______________________________________________________________________________
void ModuleImport::startDocument(
    Reference< xml::input::XNamespaceMapping > const & xNamespaceMapping )
    throw (xml::sax::SAXException, RuntimeException)
{
    XMLNS_SCRIPT_UID = xNamespaceMapping->getUidByUri(
        OUSTR(XMLNS_SCRIPT_URI) );
    XMLNS_LIBRARY_UID = xNamespaceMapping->getUidByUri(
        OUSTR(XMLNS_LIBRARY_URI) );
    XMLNS_XLINK_UID = xNamespaceMapping->getUidByUri(
        OUSTR(XMLNS_XLINK_URI) );
}

//__________________________________________________________________________________________________
void ModuleImport::endDocument()
    throw (xml::sax::SAXException, RuntimeException)
{
    // ignored
}
//__________________________________________________________________________________________________
void ModuleImport::processingInstruction(
    OUString const & rTarget, OUString const & rData )
    throw (xml::sax::SAXException, RuntimeException)
{
}
//__________________________________________________________________________________________________
void ModuleImport::setDocumentLocator(
    Reference< xml::sax::XLocator > const & xLocator )
    throw (xml::sax::SAXException, RuntimeException)
{
}
//__________________________________________________________________________________________________
Reference< xml::input::XElement > ModuleImport::startRootElement(
    sal_Int32 nUid, OUString const & rLocalName,
    Reference< xml::input::XAttributes > const & xAttributes )
    throw (xml::sax::SAXException, RuntimeException)
{
    if (XMLNS_SCRIPT_UID != nUid)
    {
        throw xml::sax::SAXException(
            OUString( RTL_CONSTASCII_USTRINGPARAM("illegal namespace!") ),
            Reference< XInterface >(), Any() );
    }
    // window
    else if (rLocalName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM("module") ))
    {
        mrModuleDesc.aName = xAttributes->getValueByUidName(
            XMLNS_LIBRARY_UID,
            OUString( RTL_CONSTASCII_USTRINGPARAM("name") ) );
        mrModuleDesc.aLanguage = xAttributes->getValueByUidName(
            XMLNS_XLINK_UID,
            OUString( RTL_CONSTASCII_USTRINGPARAM("language") ) );

        return new ModuleElement( rLocalName, xAttributes, 0, this );
    }
    else
    {
        throw xml::sax::SAXException(
            OUString( RTL_CONSTASCII_USTRINGPARAM(
                          "illegal root element (expected module) given: ") ) +
            rLocalName, Reference< XInterface >(), Any() );
    }
}
//__________________________________________________________________________________________________
ModuleImport::~ModuleImport()
    SAL_THROW( () )
{
#if OSL_DEBUG_LEVEL > 1
    OSL_TRACE( "ModuleImport::~ModuleImport().\n" );
#endif
}

//##################################################################################################

SAL_DLLEXPORT Reference< xml::sax::XDocumentHandler >
SAL_CALL importScriptModule( ModuleDescriptor& rMod )
    SAL_THROW( (Exception) )
{
    return ::xmlscript::createDocumentHandler(
        static_cast< xml::input::XRoot * >( new ModuleImport( rMod ) ) );
}

};

<commit_msg>INTEGRATION: CWS tune03 (1.6.18); FILE MERGED 2004/07/22 19:07:42 mhu 1.6.18.1: #i29979# Removed usage of SAL_DLLEXPORT (see @ sal/types.h)<commit_after>/*************************************************************************
 *
 *  $RCSfile: xmlmod_import.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2004-08-23 09:15:11 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include "imp_share.hxx"

#include <osl/diagnose.h>

#include <rtl/ustrbuf.hxx>

#include <xmlscript/xml_import.hxx>
#include <comphelper/processfactory.hxx>

namespace xmlscript
{

//##################################################################################################

//__________________________________________________________________________________________________
Reference< xml::input::XElement > ModuleElement::getParent()
    throw (RuntimeException)
{
    return static_cast< xml::input::XElement * >( _pParent );
}
//__________________________________________________________________________________________________
OUString ModuleElement::getLocalName()
    throw (RuntimeException)
{
    return _aLocalName;
}
//__________________________________________________________________________________________________
sal_Int32 ModuleElement::getUid()
    throw (RuntimeException)
{
    return _pImport->XMLNS_SCRIPT_UID;
}
//__________________________________________________________________________________________________
Reference< xml::input::XAttributes > ModuleElement::getAttributes()
    throw (RuntimeException)
{
    return _xAttributes;
}
//__________________________________________________________________________________________________
void ModuleElement::ignorableWhitespace(
    OUString const & rWhitespaces )
    throw (xml::sax::SAXException, RuntimeException)
{
    // not used
}
//__________________________________________________________________________________________________
void ModuleElement::characters( OUString const & rChars )
    throw (xml::sax::SAXException, RuntimeException)
{
    _StrBuffer.append( rChars );
}
//__________________________________________________________________________________________________
void ModuleElement::processingInstruction(
    OUString const & rTarget, OUString const & rData )
    throw (xml::sax::SAXException, RuntimeException)
{
}
//__________________________________________________________________________________________________
void ModuleElement::endElement()
    throw (xml::sax::SAXException, RuntimeException)
{
    _pImport->mrModuleDesc.aCode = _StrBuffer.makeStringAndClear();
}
//__________________________________________________________________________________________________
Reference< xml::input::XElement > ModuleElement::startChildElement(
    sal_Int32 nUid, OUString const & rLocalName,
    Reference< xml::input::XAttributes > const & xAttributes )
    throw (xml::sax::SAXException, RuntimeException)
{
    throw xml::sax::SAXException(
        OUString( RTL_CONSTASCII_USTRINGPARAM("unexpected element!") ),
        Reference< XInterface >(), Any() );
}

//__________________________________________________________________________________________________
ModuleElement::ModuleElement(
    OUString const & rLocalName,
    Reference< xml::input::XAttributes > const & xAttributes,
    ModuleElement * pParent, ModuleImport * pImport )
    SAL_THROW( () )
    : _pImport( pImport )
    , _pParent( pParent )
    , _aLocalName( rLocalName )
    , _xAttributes( xAttributes )
{
    _pImport->acquire();

    if (_pParent)
    {
        _pParent->acquire();
    }
}
//__________________________________________________________________________________________________
ModuleElement::~ModuleElement()
    SAL_THROW( () )
{
    _pImport->release();

    if (_pParent)
    {
        _pParent->release();
    }

#if OSL_DEBUG_LEVEL > 1
    OString aStr( OUStringToOString( _aLocalName, RTL_TEXTENCODING_ASCII_US ) );
    OSL_TRACE( "ModuleElement::~ModuleElement(): %s\n", aStr.getStr() );
#endif
}

//##################################################################################################

// XRoot

//______________________________________________________________________________
void ModuleImport::startDocument(
    Reference< xml::input::XNamespaceMapping > const & xNamespaceMapping )
    throw (xml::sax::SAXException, RuntimeException)
{
    XMLNS_SCRIPT_UID = xNamespaceMapping->getUidByUri(
        OUSTR(XMLNS_SCRIPT_URI) );
    XMLNS_LIBRARY_UID = xNamespaceMapping->getUidByUri(
        OUSTR(XMLNS_LIBRARY_URI) );
    XMLNS_XLINK_UID = xNamespaceMapping->getUidByUri(
        OUSTR(XMLNS_XLINK_URI) );
}

//__________________________________________________________________________________________________
void ModuleImport::endDocument()
    throw (xml::sax::SAXException, RuntimeException)
{
    // ignored
}
//__________________________________________________________________________________________________
void ModuleImport::processingInstruction(
    OUString const & rTarget, OUString const & rData )
    throw (xml::sax::SAXException, RuntimeException)
{
}
//__________________________________________________________________________________________________
void ModuleImport::setDocumentLocator(
    Reference< xml::sax::XLocator > const & xLocator )
    throw (xml::sax::SAXException, RuntimeException)
{
}
//__________________________________________________________________________________________________
Reference< xml::input::XElement > ModuleImport::startRootElement(
    sal_Int32 nUid, OUString const & rLocalName,
    Reference< xml::input::XAttributes > const & xAttributes )
    throw (xml::sax::SAXException, RuntimeException)
{
    if (XMLNS_SCRIPT_UID != nUid)
    {
        throw xml::sax::SAXException(
            OUString( RTL_CONSTASCII_USTRINGPARAM("illegal namespace!") ),
            Reference< XInterface >(), Any() );
    }
    // window
    else if (rLocalName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM("module") ))
    {
        mrModuleDesc.aName = xAttributes->getValueByUidName(
            XMLNS_LIBRARY_UID,
            OUString( RTL_CONSTASCII_USTRINGPARAM("name") ) );
        mrModuleDesc.aLanguage = xAttributes->getValueByUidName(
            XMLNS_XLINK_UID,
            OUString( RTL_CONSTASCII_USTRINGPARAM("language") ) );

        return new ModuleElement( rLocalName, xAttributes, 0, this );
    }
    else
    {
        throw xml::sax::SAXException(
            OUString( RTL_CONSTASCII_USTRINGPARAM(
                          "illegal root element (expected module) given: ") ) +
            rLocalName, Reference< XInterface >(), Any() );
    }
}
//__________________________________________________________________________________________________
ModuleImport::~ModuleImport()
    SAL_THROW( () )
{
#if OSL_DEBUG_LEVEL > 1
    OSL_TRACE( "ModuleImport::~ModuleImport().\n" );
#endif
}

//##################################################################################################

Reference< xml::sax::XDocumentHandler >
SAL_CALL importScriptModule( ModuleDescriptor& rMod )
    SAL_THROW( (Exception) )
{
    return ::xmlscript::createDocumentHandler(
        static_cast< xml::input::XRoot * >( new ModuleImport( rMod ) ) );
}

};

<|endoftext|>


<commit_before><commit_msg>[visual studio] gray-code/implem seems to be due to a compiler bug<commit_after><|endoftext|>


<commit_before>#ifndef ST_LAYER_HPP_
#define ST_LAYER_HPP_

#include <boost/shared_ptr.hpp>
#include <gflags/gflags.h>
#include <glog/logging.h>

#include <cmath>

#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"

namespace caffe {

template <typename Dtype>
class SpatialTransformerLayer : public Layer<Dtype> {

public:
	explicit SpatialTransformerLayer(const LayerParameter& param)
      : Layer<Dtype>(param) {
	      to_compute_dU_ = false;
	      global_debug = false;
	      pre_defined_count = 0;
      }
	virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);
	virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);

	virtual inline const char* type() const { return "SpatialTransformer"; }
	virtual inline int ExactNumBottomBlobs() const { return 2; }
	virtual inline int ExactNumTopBlobs() const { return 1; }

protected:
	virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);
	virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);
	virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
	virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);

private:
	inline Dtype abs(Dtype x) {
		if(x < 0) return -x; return x;
	}
	inline Dtype max(Dtype x, Dtype y) {
		if(x < y) return y; return x;
	}

	Dtype transform_forward_cpu(const Dtype* pic, Dtype px, Dtype py);
	void transform_backward_cpu(Dtype dV, const Dtype* U, const Dtype px,
			const Dtype py, Dtype* dU, Dtype& dpx, Dtype& dpy);

	string transform_type_;
	string sampler_type_;

	int output_H_;
	int output_W_;

	int N, C, H, W;

	bool global_debug;
	bool to_compute_dU_;

	Blob<Dtype> dTheta_tmp;	// used for back propagation part in GPU implementation
	Blob<Dtype> all_ones_2;	// used for back propagation part in GPU implementation

	Blob<Dtype> full_theta;	// used for storing data and diff for full six-dim theta
	Dtype pre_defined_theta[6];
	bool is_pre_defined_theta[6];
	int pre_defined_count;

	Blob<Dtype> output_grid;	// standard output coordinate system, [0, 1) by [0, 1).
	Blob<Dtype> input_grid;	// corresponding coordinate on input image after projection for each output pixel.
};

}  // namespace caffe

#endif  // CAFFE_COMMON_HPP_
<commit_msg>Delete st_layer.hpp<commit_after><|endoftext|>


<commit_before>#include "KickEvaluator.hpp"
#include <Utils.hpp>
#include <Geometry2d/Util.hpp>

#include <algorithm>
#include <vector>
#include <math.h>
#include <cmath>

REGISTER_CONFIGURABLE(KickEvaluator)

using namespace std;
using namespace Geometry2d;

ConfigDouble* KickEvaluator::kick_std_dev;
ConfigDouble* KickEvaluator::kick_mean;
ConfigDouble* KickEvaluator::robot_std_dev;
ConfigDouble* KickEvaluator::start_x_offset;

// Fast exp function, valid within 4% at +- 100
inline double fast_exp(double x) {
    double d;
    *((int*)(&d) + 0) = 0;
    *((int*)(&d) + 1) = (int)(1512775 * x + 1072632447);
    return d;
}

void KickEvaluator::createConfiguration(Configuration* cfg) {
    kick_std_dev = new ConfigDouble(cfg, "KickEvaluator/kick_std_dev", 0.04);
    kick_mean = new ConfigDouble(cfg, "KickEvaluator/kick_mean", 0);
    robot_std_dev = new ConfigDouble(cfg, "KickEvaluator/robot_std_dev", 0.3);
    start_x_offset = new ConfigDouble(cfg, "KickEvaluator/start_x_offset", 0.1);
}

KickEvaluator::KickEvaluator(SystemState* systemState) : system(systemState) {}

KickResults KickEvaluator::eval_pt_to_pt(Point origin, Point target,
                                         float targetWidth) {
    Point dir = (target - origin).perpCCW().normalized();
    Segment seg = Segment{target + dir * (targetWidth / 2),
                          target - dir * (targetWidth / 2)};

    return eval_pt_to_seg(origin, seg);
}

KickResults KickEvaluator::eval_pt_to_robot(Point origin, Point target) {
    return eval_pt_to_pt(origin, target, 2 * Robot_Radius);
}

KickResults KickEvaluator::eval_pt_to_opp_goal(Point origin) {
    Segment their_goal{
        Point{-Field_Dimensions::Current_Dimensions.GoalWidth() / 2,
              Field_Dimensions::Current_Dimensions.Length()},
        Point{Field_Dimensions::Current_Dimensions.GoalWidth() / 2,
              Field_Dimensions::Current_Dimensions.Length()}};

    return eval_pt_to_seg(origin, their_goal);
}

KickResults KickEvaluator::eval_pt_to_our_goal(Point origin) {
    Segment our_goal{
        Point{-Field_Dimensions::Current_Dimensions.GoalWidth() / 2, 0},
        Point{Field_Dimensions::Current_Dimensions.GoalWidth() / 2, 0}};

    return eval_pt_to_seg(origin, our_goal);
}

KickResults KickEvaluator::eval_pt_to_seg(Point origin, Segment target) {
    Point center = target.center();
    float targetWidth = get_target_angle(origin, target);

    // Polar bot locations
    // <Dist, Angle>
    vector<tuple<float, float> > botLocations =
        convert_robots_to_polar(origin, center);

    // Convert polar to mean / std_dev / Vertical Scales
    vector<float> botMeans;
    vector<float> botStDevs;
    vector<float> botVertScales;

    botMeans.reserve(botLocations.size());
    botStDevs.reserve(botLocations.size());
    botVertScales.reserve(botLocations.size());

    float distPastTarget;

    for (tuple<float, float>& loc : botLocations) {
        botMeans.push_back(get<1>(loc));
        // Want std_dev in radians, not XY distance
        botStDevs.push_back(atan(*robot_std_dev / get<0>(loc)));

        // Robot Past Target
        distPastTarget = get<0>(loc) - (origin - center).mag();

        // If robot is past target, only use the chance at the target segment
        if (distPastTarget > 0 && fabs(get<1>(loc)) < M_PI / 2) {
            // Evaluate a normal distribution at dist away and scale
            float stdev2 = pow(*robot_std_dev, 2);
            botVertScales.push_back(
                fast_exp(-0.5 * pow(distPastTarget, 2) / stdev2));
        } else {
            botVertScales.push_back(1);
        }
    }

    // Create function with only 1 input
    // Rest are bound to constant values
    function<tuple<float, float>(float)> keFunc =
        bind(&eval_calculation, std::placeholders::_1, (*kick_mean),
             (*kick_std_dev), cref(botMeans), cref(botStDevs),
             cref(botVertScales), targetWidth / -2, targetWidth / 2);

    // No opponent robots on the field
    if (botMeans.size() == 0) {
        // Push it off to the side
        botMeans.push_back(4);
        // Must be non-zero as 1 / botStDev is used
        botStDevs.push_back(0.1);
        botVertScales.push_back(0.001);

        // Center will always be the best target X with no robots
        return pair<Point, float>(center, get<0>(keFunc(0)));
    }

    ParallelGradient1DConfig parallelConfig;
    init_gradient_configs(parallelConfig, keFunc, botMeans, botStDevs,
                          targetWidth / -2, targetWidth / 2);

    // Create Gradient Ascent Optimizer and run it
    ParallelGradientAscent1D optimizer(&parallelConfig);

    optimizer.execute();

    // Grab the lcoal max values and their X location
    vector<float> maxXValues = optimizer.getMaxXValues();
    vector<float> maxValues = optimizer.getMaxValues();

    // Default to a local max
    int index = distance(maxValues.begin(),
                         max_element(maxValues.begin(), maxValues.end()));
    float maxX = maxXValues.at(index);
    float maxChance = maxValues.at(index);

    // See if there is a segment which is longer
    // Since local maxes stop on either side of the segment
    if (maxXValues.size() > 1) {
        for (int i = 0; i < maxXValues.size() - 1; i++) {
            // Finds the score at the average between two local maxes
            float midPoint = (maxXValues.at(i) + maxXValues.at(i + 1)) / 2;
            float chance = get<0>(keFunc(midPoint));

            // chance >= maxChance
            if (chance > maxChance || nearlyEqual(chance, maxChance)) {
                maxX = midPoint;
                maxChance = chance;
            }
        }
    }

    // Angle in reference to the field
    float realMaxAngle = maxX + (center - origin).angle();
    Line bestKickLine(origin, Point{cos(realMaxAngle), sin(realMaxAngle)});

    // Return point on target segment and chance
    return pair<Point, float>(target.nearestPoint(bestKickLine), maxChance);
}

tuple<float, float> KickEvaluator::eval_calculation(
    const float x, const float kmean, const float kstdev,
    const vector<float>& robotMeans, const vector<float>& robotStDevs,
    const vector<float>& robotVertScales, const float bLeft,
    const float bRight) {
    // 3 Main distribution sets
    // Set #1 : A set of each normal distribution for the obstacles
    // Set #2 : A band pass style distribution that represents a valid target
    // kick
    // Set #3 : A normal distribution representing a kick

    // Set #1 and #2 are combined. To keep the convolution simple, Set #2 is
    // represented using
    //      a Unit step function and just added/subtracted to/from Set #1
    // This will cause problems along the edges when a robot is near since it
    // will go negative
    // But it is not /super/ significant

    // The resulting F(X) represents the convolution of Set #12 and Set #3
    // All of this is calculated with Mathematica

    // We want the worst chance of success
    float minResults = 1.0f;
    int minIndex = 0;

    // Shortcuts for repeated operations
    float kstdev2 = kstdev * kstdev;

    const float sqrt2pi = 2.50662827f;        // sqrt(2*PI)
    const float sqrtpi_2 = 1.253314137f;      // sqrt(PI/2)
    float sqrt2_kstdev = (1.4142f * kstdev);  // sqrt(2) * kstdev
    float sqrt1_kstdev2 = 1.0f / sqrt(1.0f / kstdev2);

    float rmean;
    float rstdev;
    float rstdev2;
    float robotV;

    float kx = kmean - x;

    float fterm;  // First term,  Robot normal distribution
    float sterm;  // Second term, Left boundary
    float tterm;  // Third term,  Right Boundary

    float results;
    float derivative;

    sterm =
        sqrtpi_2 * (sqrt1_kstdev2 - kstdev * erf((kx + bLeft) / sqrt2_kstdev));

    tterm =
        sqrtpi_2 * (sqrt1_kstdev2 - kstdev * erf((kx + bRight) / sqrt2_kstdev));

    // For each robot distribution in Set #1
    for (int i = 0; i < robotMeans.size(); i++) {
        rmean = robotMeans[i];
        rstdev = robotStDevs[i];
        rstdev2 = rstdev * rstdev;
        robotV = robotVertScales[i];

        fterm = -1.0f * fast_exp(-0.5f * (kx + rmean) * (kx + rmean) /
                                 (kstdev2 + rstdev2)) *
                robotV * sqrt2pi;
        fterm = fterm / sqrt(1.0f / kstdev2 + 1.0f / rstdev2);

        results = 1.0f / (kstdev * sqrt2pi) * (fterm + sterm - tterm);

        if (results < minResults) {
            minResults = results;
            minIndex = i;
        }
    }

    // Calculate derivative of the convolution
    rmean = robotMeans[minIndex];
    rstdev = robotStDevs[minIndex];
    rstdev2 = rstdev * rstdev;
    robotV = robotVertScales[minIndex];

    fterm =
        fast_exp(-0.5f * (kx + rmean) * (kx + rmean) / (kstdev2 + rstdev2)) *
        robotV * sqrt2pi * (kx + rmean);
    fterm =
        fterm / (sqrt(1.0f / kstdev2 + 1.0f / rstdev2) * (kstdev2 + rstdev2));

    sterm = fast_exp(-0.5f * (kx + bLeft) * (kx + bLeft) / kstdev2);

    tterm = fast_exp(-0.5f * (kx + bRight) * (kx + bRight) / kstdev2);

    derivative = 1.0f / (kstdev * sqrt2pi) * (sterm - tterm - fterm);

    return make_tuple(minResults, derivative);
}

float KickEvaluator::get_target_angle(const Point origin,
                                      const Segment target) {
    Point left = target.pt[0] - origin;
    Point right = target.pt[1] - origin;

    float angle = left.dot(right) / (left.mag() * right.mag());
    angle = std::min(std::max(angle, -1.0f), 1.0f);

    return abs(acos(angle));
}

vector<Robot*> KickEvaluator::get_valid_robots() {
    vector<Robot*> bots(system->self.size() + system->opp.size());

    auto filter_predicate = [&](const Robot* bot) -> bool {
        return bot != nullptr && bot->visible &&
               find(excluded_robots.begin(), excluded_robots.end(), bot) ==
                   excluded_robots.end();
    };

    auto end_it = copy_if(system->self.begin(), system->self.end(),
                          bots.begin(), filter_predicate);

    end_it = copy_if(system->opp.begin(), system->opp.end(), end_it,
                     filter_predicate);

    bots.resize(distance(bots.begin(), end_it));

    return bots;
}

tuple<float, float> KickEvaluator::rect_to_polar(const Point origin,
                                                 const Point target,
                                                 const Point obstacle) {
    Point obstacleDir = obstacle - origin;
    Point targetDir = target - origin;
    float angle =
        targetDir.dot(obstacleDir) / (targetDir.mag() * obstacleDir.mag());
    angle = std::min(std::max(angle, -1.0f), 1.0f);

    return make_tuple(obstacleDir.mag(), fixAngleRadians(acos(angle)));
}

vector<tuple<float, float> > KickEvaluator::convert_robots_to_polar(
    const Point origin, const Point target) {
    vector<Robot*> bots = get_valid_robots();
    vector<tuple<float, float> > botLocations;
    botLocations.reserve(bots.size() + botLocations.size());

    // Convert each bot position to polar
    transform(bots.begin(), bots.end(), back_inserter(botLocations),
              [target, origin, this](Robot* bot) {
                  return rect_to_polar(origin, target, bot->pos);
              });

    // Convert imaginary obstacles to polar
    transform(hypothetical_robot_locations.begin(),
              hypothetical_robot_locations.end(), back_inserter(botLocations),
              [target, origin, this](Point obstacle) {
                  return rect_to_polar(origin, target, obstacle);
              });

    return botLocations;
}

void KickEvaluator::init_gradient_configs(
    ParallelGradient1DConfig& pConfig,
    function<tuple<float, float>(float)>& func, const vector<float>& robotMeans,
    const vector<float>& robotStDevs, const float boundaryLower,
    const float boundaryUpper) {
    pConfig.GA1DConfig.reserve(robotStDevs.size());

    // Standard Gradient Configs
    const float dxError = 0.05;
    float maxXMovement =
        *min_element(robotStDevs.begin(), robotStDevs.end()) * 2;
    const float temperatureDescent = 0.5;
    const float temperatureMin = 0.01;
    const int maxIterations = 20;
    const float maxValue = 1;
    const float maxThresh = 0.05;

    // <PrevStart, Start>
    vector<tuple<float, float> > xStarts;
    xStarts.reserve(robotStDevs.size());

    // Add left boundary
    float startX = boundaryLower + *start_x_offset * *kick_std_dev;
    xStarts.emplace_back(boundaryLower, startX);

    // Add right boundary
    startX = boundaryUpper - *start_x_offset * *kick_std_dev;
    xStarts.emplace_back(boundaryUpper, startX);

    // For each robot
    for (int i = 0; i < robotMeans.size(); i++) {
        // -1 or 1
        for (int side = -1; side <= 1; side += 2) {
            startX =
                robotMeans.at(i) + side * *start_x_offset * robotStDevs.at(i);

            xStarts.emplace_back(robotMeans.at(i), startX);
        }
    }

    // Force into ascending order to make things simpler later on
    sort(xStarts.begin(), xStarts.end(),
         [&](tuple<float, float> a, tuple<float, float> b) {
             return get<1>(a) < get<1>(b);
         });

    // Create list of configs
    for (tuple<float, float> xStart : xStarts) {
        pConfig.GA1DConfig.emplace_back(&func, get<1>(xStart), get<0>(xStart),
                                        dxError, maxXMovement,
                                        temperatureDescent, temperatureMin,
                                        maxIterations, maxValue, maxThresh);
    }

    pConfig.xCombineThresh =
        *min_element(robotStDevs.begin(), robotStDevs.end()) * *start_x_offset /
        2;
}<commit_msg>Used actual angleBetween function<commit_after>#include "KickEvaluator.hpp"
#include <Utils.hpp>
#include <Geometry2d/Util.hpp>

#include <algorithm>
#include <vector>
#include <math.h>
#include <cmath>

REGISTER_CONFIGURABLE(KickEvaluator)

using namespace std;
using namespace Geometry2d;

ConfigDouble* KickEvaluator::kick_std_dev;
ConfigDouble* KickEvaluator::kick_mean;
ConfigDouble* KickEvaluator::robot_std_dev;
ConfigDouble* KickEvaluator::start_x_offset;

// Fast exp function, valid within 4% at +- 100
inline double fast_exp(double x) {
    double d;
    *((int*)(&d) + 0) = 0;
    *((int*)(&d) + 1) = (int)(1512775 * x + 1072632447);
    return d;
}

void KickEvaluator::createConfiguration(Configuration* cfg) {
    kick_std_dev = new ConfigDouble(cfg, "KickEvaluator/kick_std_dev", 0.04);
    kick_mean = new ConfigDouble(cfg, "KickEvaluator/kick_mean", 0);
    robot_std_dev = new ConfigDouble(cfg, "KickEvaluator/robot_std_dev", 0.3);
    start_x_offset = new ConfigDouble(cfg, "KickEvaluator/start_x_offset", 0.1);
}

KickEvaluator::KickEvaluator(SystemState* systemState) : system(systemState) {}

KickResults KickEvaluator::eval_pt_to_pt(Point origin, Point target,
                                         float targetWidth) {
    Point dir = (target - origin).perpCCW().normalized();
    Segment seg = Segment{target + dir * (targetWidth / 2),
                          target - dir * (targetWidth / 2)};

    return eval_pt_to_seg(origin, seg);
}

KickResults KickEvaluator::eval_pt_to_robot(Point origin, Point target) {
    return eval_pt_to_pt(origin, target, 2 * Robot_Radius);
}

KickResults KickEvaluator::eval_pt_to_opp_goal(Point origin) {
    Segment their_goal{
        Point{-Field_Dimensions::Current_Dimensions.GoalWidth() / 2,
              Field_Dimensions::Current_Dimensions.Length()},
        Point{Field_Dimensions::Current_Dimensions.GoalWidth() / 2,
              Field_Dimensions::Current_Dimensions.Length()}};

    return eval_pt_to_seg(origin, their_goal);
}

KickResults KickEvaluator::eval_pt_to_our_goal(Point origin) {
    Segment our_goal{
        Point{-Field_Dimensions::Current_Dimensions.GoalWidth() / 2, 0},
        Point{Field_Dimensions::Current_Dimensions.GoalWidth() / 2, 0}};

    return eval_pt_to_seg(origin, our_goal);
}

KickResults KickEvaluator::eval_pt_to_seg(Point origin, Segment target) {
    Point center = target.center();
    float targetWidth = get_target_angle(origin, target);

    // Polar bot locations
    // <Dist, Angle>
    vector<tuple<float, float> > botLocations =
        convert_robots_to_polar(origin, center);

    // Convert polar to mean / std_dev / Vertical Scales
    vector<float> botMeans;
    vector<float> botStDevs;
    vector<float> botVertScales;

    botMeans.reserve(botLocations.size());
    botStDevs.reserve(botLocations.size());
    botVertScales.reserve(botLocations.size());

    float distPastTarget;

    for (tuple<float, float>& loc : botLocations) {
        botMeans.push_back(get<1>(loc));
        // Want std_dev in radians, not XY distance
        botStDevs.push_back(atan(*robot_std_dev / get<0>(loc)));

        // Robot Past Target
        distPastTarget = get<0>(loc) - (origin - center).mag();

        // If robot is past target, only use the chance at the target segment
        if (distPastTarget > 0 && fabs(get<1>(loc)) < M_PI / 2) {
            // Evaluate a normal distribution at dist away and scale
            float stdev2 = pow(*robot_std_dev, 2);
            botVertScales.push_back(
                fast_exp(-0.5 * pow(distPastTarget, 2) / stdev2));
        } else {
            botVertScales.push_back(1);
        }
    }

    // Create function with only 1 input
    // Rest are bound to constant values
    function<tuple<float, float>(float)> keFunc =
        bind(&eval_calculation, std::placeholders::_1, (*kick_mean),
             (*kick_std_dev), cref(botMeans), cref(botStDevs),
             cref(botVertScales), targetWidth / -2, targetWidth / 2);

    // No opponent robots on the field
    if (botMeans.size() == 0) {
        // Push it off to the side
        botMeans.push_back(4);
        // Must be non-zero as 1 / botStDev is used
        botStDevs.push_back(0.1);
        botVertScales.push_back(0.001);

        // Center will always be the best target X with no robots
        return pair<Point, float>(center, get<0>(keFunc(0)));
    }

    ParallelGradient1DConfig parallelConfig;
    init_gradient_configs(parallelConfig, keFunc, botMeans, botStDevs,
                          targetWidth / -2, targetWidth / 2);

    // Create Gradient Ascent Optimizer and run it
    ParallelGradientAscent1D optimizer(&parallelConfig);

    optimizer.execute();

    // Grab the lcoal max values and their X location
    vector<float> maxXValues = optimizer.getMaxXValues();
    vector<float> maxValues = optimizer.getMaxValues();

    // Default to a local max
    int index = distance(maxValues.begin(),
                         max_element(maxValues.begin(), maxValues.end()));
    float maxX = maxXValues.at(index);
    float maxChance = maxValues.at(index);

    // See if there is a segment which is longer
    // Since local maxes stop on either side of the segment
    if (maxXValues.size() > 1) {
        for (int i = 0; i < maxXValues.size() - 1; i++) {
            // Finds the score at the average between two local maxes
            float midPoint = (maxXValues.at(i) + maxXValues.at(i + 1)) / 2;
            float chance = get<0>(keFunc(midPoint));

            // chance >= maxChance
            if (chance > maxChance || nearlyEqual(chance, maxChance)) {
                maxX = midPoint;
                maxChance = chance;
            }
        }
    }

    // Angle in reference to the field
    float realMaxAngle = maxX + (center - origin).angle();
    Line bestKickLine(origin, Point{cos(realMaxAngle), sin(realMaxAngle)});

    // Return point on target segment and chance
    return pair<Point, float>(target.nearestPoint(bestKickLine), maxChance);
}

tuple<float, float> KickEvaluator::eval_calculation(
    const float x, const float kmean, const float kstdev,
    const vector<float>& robotMeans, const vector<float>& robotStDevs,
    const vector<float>& robotVertScales, const float bLeft,
    const float bRight) {
    // 3 Main distribution sets
    // Set #1 : A set of each normal distribution for the obstacles
    // Set #2 : A band pass style distribution that represents a valid target
    // kick
    // Set #3 : A normal distribution representing a kick

    // Set #1 and #2 are combined. To keep the convolution simple, Set #2 is
    // represented using
    //      a Unit step function and just added/subtracted to/from Set #1
    // This will cause problems along the edges when a robot is near since it
    // will go negative
    // But it is not /super/ significant

    // The resulting F(X) represents the convolution of Set #12 and Set #3
    // All of this is calculated with Mathematica

    // We want the worst chance of success
    float minResults = 1.0f;
    int minIndex = 0;

    // Shortcuts for repeated operations
    float kstdev2 = kstdev * kstdev;

    const float sqrt2pi = 2.50662827f;        // sqrt(2*PI)
    const float sqrtpi_2 = 1.253314137f;      // sqrt(PI/2)
    float sqrt2_kstdev = (1.4142f * kstdev);  // sqrt(2) * kstdev
    float sqrt1_kstdev2 = 1.0f / sqrt(1.0f / kstdev2);

    float rmean;
    float rstdev;
    float rstdev2;
    float robotV;

    float kx = kmean - x;

    float fterm;  // First term,  Robot normal distribution
    float sterm;  // Second term, Left boundary
    float tterm;  // Third term,  Right Boundary

    float results;
    float derivative;

    sterm =
        sqrtpi_2 * (sqrt1_kstdev2 - kstdev * erf((kx + bLeft) / sqrt2_kstdev));

    tterm =
        sqrtpi_2 * (sqrt1_kstdev2 - kstdev * erf((kx + bRight) / sqrt2_kstdev));

    // For each robot distribution in Set #1
    for (int i = 0; i < robotMeans.size(); i++) {
        rmean = robotMeans[i];
        rstdev = robotStDevs[i];
        rstdev2 = rstdev * rstdev;
        robotV = robotVertScales[i];

        fterm = -1.0f * fast_exp(-0.5f * (kx + rmean) * (kx + rmean) /
                                 (kstdev2 + rstdev2)) *
                robotV * sqrt2pi;
        fterm = fterm / sqrt(1.0f / kstdev2 + 1.0f / rstdev2);

        results = 1.0f / (kstdev * sqrt2pi) * (fterm + sterm - tterm);

        if (results < minResults) {
            minResults = results;
            minIndex = i;
        }
    }

    // Calculate derivative of the convolution
    rmean = robotMeans[minIndex];
    rstdev = robotStDevs[minIndex];
    rstdev2 = rstdev * rstdev;
    robotV = robotVertScales[minIndex];

    fterm =
        fast_exp(-0.5f * (kx + rmean) * (kx + rmean) / (kstdev2 + rstdev2)) *
        robotV * sqrt2pi * (kx + rmean);
    fterm =
        fterm / (sqrt(1.0f / kstdev2 + 1.0f / rstdev2) * (kstdev2 + rstdev2));

    sterm = fast_exp(-0.5f * (kx + bLeft) * (kx + bLeft) / kstdev2);

    tterm = fast_exp(-0.5f * (kx + bRight) * (kx + bRight) / kstdev2);

    derivative = 1.0f / (kstdev * sqrt2pi) * (sterm - tterm - fterm);

    return make_tuple(minResults, derivative);
}

float KickEvaluator::get_target_angle(const Point origin,
                                      const Segment target) {
    Point left = target.pt[0] - origin;
    Point right = target.pt[1] - origin;

    return abs(left.angleBetween(right));
}

vector<Robot*> KickEvaluator::get_valid_robots() {
    vector<Robot*> bots(system->self.size() + system->opp.size());

    auto filter_predicate = [&](const Robot* bot) -> bool {
        return bot != nullptr && bot->visible &&
               find(excluded_robots.begin(), excluded_robots.end(), bot) ==
                   excluded_robots.end();
    };

    auto end_it = copy_if(system->self.begin(), system->self.end(),
                          bots.begin(), filter_predicate);

    end_it = copy_if(system->opp.begin(), system->opp.end(), end_it,
                     filter_predicate);

    bots.resize(distance(bots.begin(), end_it));

    return bots;
}

tuple<float, float> KickEvaluator::rect_to_polar(const Point origin,
                                                 const Point target,
                                                 const Point obstacle) {
    Point obstacleDir = obstacle - origin;
    Point targetDir = target - origin;

    return make_tuple(obstacleDir.mag(),
                      fixAngleRadians(targetDir.angleBetween(obstacleDir)));
}

vector<tuple<float, float> > KickEvaluator::convert_robots_to_polar(
    const Point origin, const Point target) {
    vector<Robot*> bots = get_valid_robots();
    vector<tuple<float, float> > botLocations;
    botLocations.reserve(bots.size() + botLocations.size());

    // Convert each bot position to polar
    transform(bots.begin(), bots.end(), back_inserter(botLocations),
              [target, origin, this](Robot* bot) {
                  return rect_to_polar(origin, target, bot->pos);
              });

    // Convert imaginary obstacles to polar
    transform(hypothetical_robot_locations.begin(),
              hypothetical_robot_locations.end(), back_inserter(botLocations),
              [target, origin, this](Point obstacle) {
                  return rect_to_polar(origin, target, obstacle);
              });

    return botLocations;
}

void KickEvaluator::init_gradient_configs(
    ParallelGradient1DConfig& pConfig,
    function<tuple<float, float>(float)>& func, const vector<float>& robotMeans,
    const vector<float>& robotStDevs, const float boundaryLower,
    const float boundaryUpper) {
    pConfig.GA1DConfig.reserve(robotStDevs.size());

    // Standard Gradient Configs
    const float dxError = 0.05;
    float maxXMovement =
        *min_element(robotStDevs.begin(), robotStDevs.end()) * 2;
    const float temperatureDescent = 0.5;
    const float temperatureMin = 0.01;
    const int maxIterations = 20;
    const float maxValue = 1;
    const float maxThresh = 0.05;

    // <PrevStart, Start>
    vector<tuple<float, float> > xStarts;
    xStarts.reserve(robotStDevs.size());

    // Add left boundary
    float startX = boundaryLower + *start_x_offset * *kick_std_dev;
    xStarts.emplace_back(boundaryLower, startX);

    // Add right boundary
    startX = boundaryUpper - *start_x_offset * *kick_std_dev;
    xStarts.emplace_back(boundaryUpper, startX);

    // For each robot
    for (int i = 0; i < robotMeans.size(); i++) {
        // -1 or 1
        for (int side = -1; side <= 1; side += 2) {
            startX =
                robotMeans.at(i) + side * *start_x_offset * robotStDevs.at(i);

            xStarts.emplace_back(robotMeans.at(i), startX);
        }
    }

    // Force into ascending order to make things simpler later on
    sort(xStarts.begin(), xStarts.end(),
         [&](tuple<float, float> a, tuple<float, float> b) {
             return get<1>(a) < get<1>(b);
         });

    // Create list of configs
    for (tuple<float, float> xStart : xStarts) {
        pConfig.GA1DConfig.emplace_back(&func, get<1>(xStart), get<0>(xStart),
                                        dxError, maxXMovement,
                                        temperatureDescent, temperatureMin,
                                        maxIterations, maxValue, maxThresh);
    }

    pConfig.xCombineThresh =
        *min_element(robotStDevs.begin(), robotStDevs.end()) * *start_x_offset /
        2;
}<|endoftext|>


<commit_before>#include <utils/common_utils.h>
#include <utils/logger.h>
#ifdef OS_WIN32
#include <win32/net_win32.h>
#elif defined(OS_LINUX)
#include <linux/net_linux.h>
#endif // OS_WIN32

namespace meshy {
#ifdef OS_LINUX
	int32_t SetNonBlocking(int32_t sockfd) {
		int32_t opts = fcntl(sockfd, F_GETFL);
		if (opts < 0)
		{
			TRACE_ERROR("fcntl(F_GETFL)\n");
			return -1;
		}
		opts |= O_NONBLOCK;
		if (fcntl(sockfd, F_SETFL, opts) < 0)
		{
			TRACE_ERROR("fcntl(F_SETFL)");
			return -1;
		}
		return 0;
	}
}
#elif defined(OS_WIN32)
	int32_t SetNonBlocking(int32_t sockfd) {
		u_long ul = 1;
		if (NO_ERROR != ioctlsocket(sockfd, FIONBIO, &ul)) {
			TRACE_ERROR("ioctlsocket");
			return -1;
		}
		return 0;
	}
#endif // OS_LINUX

}<commit_msg>modify common_utils.cpp<commit_after>#include <utils/common_utils.h>
#include <utils/logger.h>
#ifdef OS_WIN32
#include <win32/net_win32.h>
#elif defined(OS_LINUX)
#include <linux/net_linux.h>
#endif // OS_WIN32

namespace meshy {
#ifdef OS_LINUX
	int32_t SetNonBlocking(int32_t sockfd) {
		int32_t opts = fcntl(sockfd, F_GETFL);
		if (opts < 0)
		{
			TRACE_ERROR("fcntl(F_GETFL)\n");
			return -1;
		}
		opts |= O_NONBLOCK;
		if (fcntl(sockfd, F_SETFL, opts) < 0)
		{
			TRACE_ERROR("fcntl(F_SETFL)");
			return -1;
		}
		return 0;
	}
#elif defined(OS_WIN32)
	int32_t SetNonBlocking(int32_t sockfd) {
		u_long ul = 1;
		if (NO_ERROR != ioctlsocket(sockfd, FIONBIO, &ul)) {
			TRACE_ERROR("ioctlsocket");
			return -1;
		}
		return 0;
	}
#endif // OS_LINUX

}
<|endoftext|>