<commit_before>#include "ws2812.h"
#include "Arduino.h"

bool isBackpack = false;

WS2812 strips[MAX_STRIPS];

uint8_t no_strips = 0; // how many strips have we configured.
uint16_t strip_lengths[MAX_STRIPS]; // now long each strip is.

void ws2812_initialise() {
    // initialises the strip defaults.

    for (uint8_t i = 0; i < MAX_STRIPS; i++) {
        strip_lengths[i] = 0;
    }
}

void ws2812_initialise(bool backpack) {
    // if backpack is true then set the strips up a little differently

    isBackpack = backpack;
    ws2812_initialise();

}

void process_command(byte argc, byte *argv){
    // this takes a pixel command that has been determined and then
    // processes it appropriately.

    // get the strip value off the command first

    uint8_t command = 0xF & argv[0];

    // now process the command.
    switch (command) {
        case PIXEL_SHOW: {
            // FIXME update this to use strips and iterate over it.
            for (uint8_t i = 0; i< MAX_STRIPS; i++) {
                if (strips[i].get_length() > 0) {
                    strips[i].sync();
                }
            }
            break;
        }
        case PIXEL_SET_STRIP: {
            // sets the entirety of the strip to one colour
            // FIXME this needs to operate over all the strips as well.
            uint32_t strip_colour = (uint32_t)argv[1] + ((uint32_t)argv[2]<<7) + ((uint32_t)argv[3]<<14) + ((uint32_t)argv[4] << 21);
            for (uint8_t i = 0; i < MAX_STRIPS; i++) {
                if (strips[i].get_length() > 0) {
            // TODO put detection in for colour off and then do a memset on it.
                    for (uint16_t j = 0; j<strips[i].get_length(); j++) {
                        strips[i].set_rgb_at(j, strip_colour);
                    }
                }
            }
            break;
        }
        case PIXEL_SET_PIXEL: {
            // sets the pixel given by the index to the given colour
            uint16_t index = (uint16_t)argv[1] + ((uint16_t)argv[2]<<7);
            uint32_t colour = (uint32_t)argv[3] + ((uint32_t)argv[4]<<7) + ((uint32_t)argv[5]<<14) + ((uint32_t)argv[6] << 21);
            strips[0].set_rgb_at(index, colour);
            strips[1].set_rgb_at(index, colour);
            // FIXME this needs to figure out which strip to use and set it.
            break;
        }
        case PIXEL_CONFIG_FIRMATA: {
            // Sets the pin that the neopixel strip is on as well as it's length

            // check to ensure we have at least 3 arg bytes (1 for pin & 2 for len)
            if (argc >= 3) {
                // loop over each group of 3 bytes and pull out the details
                // around the pin and strand length.
                for (uint8_t i = 0; i < (argc / 3); i ++) {
                    // calc the argv offset as x3 for each group & +1 due to the
                    // PIXEL_CONFIG command at argv[0]
                    uint8_t argv_offset = i * 3;

                    uint8_t pin = (uint8_t)argv[argv_offset+1] & 0x1F;
                    strips[i].setOutput(pin);

                    // get the top two bits for the colour order type.
                    uint8_t colour_type = (uint8_t)argv[argv_offset+1]>>5;
                    switch (colour_type) {
                        case PIXEL_COLOUR_GRB:
                            strips[i].setColorOrderGRB();
                            break;
                        case PIXEL_COLOUR_RGB:
                            strips[i].setColorOrderRGB();
                            break;
                        case PIXEL_COLOUR_BRG:
                            strips[i].setColorOrderBRG();
                            break;
                    }

                    // now get the strand length
                    strips[i].set_length((uint16_t)(argv[argv_offset+2]+(argv[argv_offset+3]<<7)));
                    uint16_t prev_strip_length = 0;
                    if (i > 0) {
                        prev_strip_length = strip_lengths[i-1];
                    }
                    strip_lengths[i] = strips[i].get_length() + prev_strip_length;
                }
            }

            break;
        }
        case PIXEL_CONFIG: {
            // Sets the pin and length of the specific strip
            Serial.print("ArgC: ");
            Serial.println(argc);
            break;

        }
        case PIXEL_CONFIG_BACKPACK: {
            // Sets the pin and length of the specific strip

            break;

        }
    }
}

<commit_msg>set pixel initial multi strip detection in place<commit_after>#include "ws2812.h"
#include "Arduino.h"

bool isBackpack = false;

WS2812 strips[MAX_STRIPS];

uint8_t no_strips = 0; // how many strips have we configured.
uint16_t strip_lengths[MAX_STRIPS]; // now long each strip is.
bool strip_changed[MAX_STRIPS]; // used to optimise strip writes.

void ws2812_initialise() {
    // initialises the strip defaults.

    for (uint8_t i = 0; i < MAX_STRIPS; i++) {
        strip_lengths[i] = 0;
        strip_changed[i] = false;
    }
}

void ws2812_initialise(bool backpack) {
    // if backpack is true then set the strips up a little differently

    isBackpack = backpack;
    ws2812_initialise();

}

void process_command(byte argc, byte *argv){
    // this takes a pixel command that has been determined and then
    // processes it appropriately.

    // get the strip value off the command first

    uint8_t command = 0xF & argv[0];

    // now process the command.
    switch (command) {
        case PIXEL_SHOW: {
            // FIXME update this to use strips and iterate over it.
            for (uint8_t i = 0; i< MAX_STRIPS; i++) {
                if (strips[i].get_length() > 0 && strip_changed[i]) {
                    strips[i].sync();
                }
                strip_changed[i] = false;
            }
            break;
        }
        case PIXEL_SET_STRIP: {
            // sets the entirety of the strip to one colour
            // FIXME this needs to operate over all the strips as well.
            uint32_t strip_colour = (uint32_t)argv[1] + ((uint32_t)argv[2]<<7) + ((uint32_t)argv[3]<<14) + ((uint32_t)argv[4] << 21);
            for (uint8_t i = 0; i < MAX_STRIPS; i++) {
                if (strips[i].get_length() > 0) {
                    // TODO put detection in for colour off and then do a memset on it.
                    for (uint16_t j = 0; j<strips[i].get_length(); j++) {
                        strips[i].set_rgb_at(j, strip_colour);
                    }
                    strip_changed[i] = true;
                }
            }
            break;
        }
        case PIXEL_SET_PIXEL: {
            // sets the pixel given by the index to the given colour
            uint16_t index = (uint16_t)argv[1] + ((uint16_t)argv[2]<<7);
            uint32_t colour = (uint32_t)argv[3] + ((uint32_t)argv[4]<<7) + ((uint32_t)argv[5]<<14) + ((uint32_t)argv[6] << 21);

            int8_t strip = 0;
            for (uint8_t i = 0; i < MAX_STRIPS; i++) {
                if (strip_lengths[i] == 0) {
                    // we are outside of the number of pixels we have so break
                    break;
                }
                if (index < strip_lengths[i]) {
                    strip = i;
                    break;
                }
            }

            if (strip >= 0) {
                strips[strip].set_rgb_at(index, colour);
                strip_changed[strip] = true;
            }
            //strips[1].set_rgb_at(index, colour);
            //strip_changed[1] = false;
            // FIXME this needs to figure out which strip to use and set it.
            break;
        }
        case PIXEL_CONFIG_FIRMATA: {
            // Sets the pin that the neopixel strip is on as well as it's length

            // check to ensure we have at least 3 arg bytes (1 for pin & 2 for len)
            if (argc >= 3) {
                // loop over each group of 3 bytes and pull out the details
                // around the pin and strand length.
                for (uint8_t i = 0; i < (argc / 3); i ++) {
                    // calc the argv offset as x3 for each group & +1 due to the
                    // PIXEL_CONFIG command at argv[0]
                    uint8_t argv_offset = i * 3;

                    uint8_t pin = (uint8_t)argv[argv_offset+1] & 0x1F;
                    strips[i].setOutput(pin);

                    // get the top two bits for the colour order type.
                    uint8_t colour_type = (uint8_t)argv[argv_offset+1]>>5;
                    switch (colour_type) {
                        case PIXEL_COLOUR_GRB:
                            strips[i].setColorOrderGRB();
                            break;
                        case PIXEL_COLOUR_RGB:
                            strips[i].setColorOrderRGB();
                            break;
                        case PIXEL_COLOUR_BRG:
                            strips[i].setColorOrderBRG();
                            break;
                    }

                    // now get the strand length
                    strips[i].set_length((uint16_t)(argv[argv_offset+2]+(argv[argv_offset+3]<<7)));
                    uint16_t prev_strip_length = 0;
                    if (i > 0) {
                        prev_strip_length = strip_lengths[i-1];
                    }
                    strip_lengths[i] = strips[i].get_length() + prev_strip_length;
                }
            }

            break;
        }
        case PIXEL_CONFIG: {
            // Sets the pin and length of the specific strip
            Serial.print("ArgC: ");
            Serial.println(argc);
            break;

        }
        case PIXEL_CONFIG_BACKPACK: {
            // Sets the pin and length of the specific strip

            break;

        }
    }
}

<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2004 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

// bzflag common header
#include "common.h"

// interface header
#include "Address.h"

// system headers
#include <string.h>
#include <string>
#include <sys/types.h>
#if !defined(_WIN32)
#include <unistd.h>
#include <setjmp.h>
#else
#include <winsock2.h>
#include <ws2tcpip.h>
#endif

// common implementation headers
#include "bzsignal.h"
#include "ErrorHandler.h"

// local implementation headers
#include "Pack.h"

#if defined(sun)
  // Solaris...
  extern "C" int inet_aton(const char *, struct in_addr *);
#endif

//
// Address
//

#if !defined( GUSI_20 ) && !defined( WIN32 )
  Address			Address::localAddress("");
#endif

Address::Address()
{
  InAddr tempAddr;

  memset(&tempAddr, 0, sizeof(tempAddr));
  tempAddr.s_addr = htonl(INADDR_ANY);
  addr.push_back(tempAddr);
}

Address::Address(const std::string& name)
{
  Address a = getHostAddress(name);
  addr.push_back(a.addr[0]);
}

Address::Address(const Address& address) : addr(address.addr)
{
  // do nothing
}

Address::Address(const InAddr& _addr)
{
  addr.push_back(_addr);
}

Address::Address(const struct sockaddr_in& _addr)
{
  addr.push_back(_addr.sin_addr);
}

Address::~Address()
{
  // do nothing
}

Address&		Address::operator=(const Address& address)
{
  addr.clear();
  addr.push_back(address.addr[0]);
  return *this;
}

Address::operator InAddr() const
{
  return addr[0];
}

bool			Address::operator==(const Address& address) const
{
  return addr[0].s_addr == address.addr[0].s_addr;
}

bool			Address::operator!=(const Address& address) const
{
  return addr[0].s_addr != address.addr[0].s_addr;
}

bool			Address::isAny() const
{
  return addr[0].s_addr == htonl(INADDR_ANY);
}

std::string		Address::getDotNotation() const
{
  return std::string(inet_ntoa(addr[0]));
}

uint8_t		        Address::getIPVersion() const {
  return 4;
}

#if !defined(_WIN32)
static jmp_buf alarmEnv;
static void		onAlarm(int)
{
  // jump back to setjmp.  this handles the race condition where we
  // set the alarm but gethostbyname() wouldn't have been called
  // until after the alarm goes off (resulting in an indeterminate
  // wait).
  longjmp(alarmEnv, 1);
}
#endif

Address			Address::getHostAddress(const std::string hname)
{
  Address a;
  InAddr tempAddr;
  int j;

  struct hostent* hent;
  if (hname == "") {				// local address
    char hostname[MAXHOSTNAMELEN+1];
    if (gethostname(hostname, sizeof(hostname)) >= 0)
      hent = gethostbyname(hostname);
    else
      return a;
  }
  else if (inet_aton(hname.c_str(), &tempAddr) != 0) {
    a.addr.clear();
    a.addr.push_back(tempAddr);
    return a;
  }
  else {				// non-local address
#if !defined(_WIN32)
    // set alarm to avoid waiting too long
    SIG_PF oldAlarm = bzSignal(SIGALRM, SIG_PF(onAlarm));
    if (oldAlarm != SIG_ERR) {
      if (setjmp(alarmEnv) != 0) {
	// alarm went off
	hent = NULL;
	printError("Looking up host name: timeout");
	return a;
      }

      // wait up to this many seconds
      alarm(8);
    }
#endif

    hent = gethostbyname(hname.c_str());

#if !defined(_WIN32)
    if (oldAlarm != SIG_ERR) {
      alarm(0);
      bzSignal(SIGALRM, oldAlarm);
    }
#endif
  }

  if (!hent) {
    herror("Looking up host name");
    return a;
  }

  a.addr.clear();
  for (j=0; hent->h_addr_list[j] != NULL; j++){
    ::memcpy(&tempAddr, hent->h_addr_list[j], sizeof(tempAddr));
    a.addr.push_back(tempAddr);
  }
  return a;
}

std::string		Address::getHostByAddress(InAddr addr)
{
#if !defined(_WIN32)
  // set alarm to avoid waiting too long
  SIG_PF oldAlarm = bzSignal(SIGALRM, SIG_PF(onAlarm));
  if (oldAlarm != SIG_ERR) {
    if (setjmp(alarmEnv) != 0) {
      // alarm went off
      return std::string(inet_ntoa(addr));
    }

    // wait up to this many seconds
    alarm(8);
  }
#endif

  int addrLen = sizeof(addr);
  struct hostent* hent = gethostbyaddr((char*)&addr, addrLen, AF_INET);

#if !defined(_WIN32)
  if (oldAlarm != SIG_ERR) {
    alarm(0);
    bzSignal(SIGALRM, oldAlarm);
  }
#endif

  if (!hent) {
    // can't lookup name -- return in standard dot notation
    return std::string(inet_ntoa(addr));
  }
  return std::string(hent->h_name);
}

const std::string Address::getHostName(const std::string hostname) // const
{
  char myname[MAXHOSTNAMELEN+1];
  std::string name = hostname;
  if (name.length() <= 0) {
    if (gethostname(myname, sizeof(myname)) >= 0)
      name = std::string(myname);
  }
  if (name.length() <= 0) {
    return std::string("");
  }
  struct hostent* hent = gethostbyname(name.c_str());
  if (!hent) {
    return std::string("");
  }
  return std::string(hent->h_name);
}

void*			Address::pack(void* _buf) const
{
  unsigned char* buf = (unsigned char*)_buf;
  buf = (unsigned char*)nboPackUByte(_buf, 4);
  // everything in InAddr  is already in network byte order
  int32_t hostaddr = int32_t(addr[0].s_addr);
  ::memcpy(buf, &hostaddr, sizeof(int32_t));	buf += sizeof(int32_t);
  return (void*)buf;
}

void*			Address::unpack(void* _buf)
{
  unsigned char* buf = (unsigned char*)_buf;
  InAddr tempAddr;
  // FIXME - should actually parse the first byte to see if it's IPv4 or
  // IPv6
  ++buf;
  // everything in InAddr should be stored in network byte order
  int32_t hostaddr;
  ::memcpy(&hostaddr, buf, sizeof(int32_t));	buf += sizeof(int32_t);
  tempAddr.s_addr = u_long(hostaddr);
  addr.clear();
  addr.push_back(tempAddr);
  return (void*)buf;
}

//
// ServerId
//

void*			ServerId::pack(void* _buf) const
{
  // everything in PlayerId is already in network byte order
  unsigned char* buf = (unsigned char*)_buf;
  int32_t hostaddr = int32_t(serverHost.s_addr);
  ::memcpy(buf, &hostaddr, sizeof(int32_t));	buf += sizeof(int32_t);
  ::memcpy(buf, &port, sizeof(int16_t));	buf += sizeof(int16_t);
  ::memcpy(buf, &number, sizeof(int16_t));	buf += sizeof(int16_t);
  return (void*)buf;
}

void*			ServerId::unpack(void* _buf)
{
  // everything in ServerId should be stored in network byte order
  unsigned char* buf = (unsigned char*)_buf;
  int32_t hostaddr;
  ::memcpy(&hostaddr, buf, sizeof(int32_t));	buf += sizeof(int32_t);
  ::memcpy(&port, buf, sizeof(int16_t));	buf += sizeof(int16_t);
  ::memcpy(&number, buf, sizeof(int16_t));	buf += sizeof(int16_t);
  serverHost.s_addr = u_long(hostaddr);
  return (void*)buf;
}

bool			ServerId::operator==(const ServerId& id) const
{
  return serverHost.s_addr == id.serverHost.s_addr &&
			port == id.port && number == id.number;
}

bool			ServerId::operator!=(const ServerId& id) const
{
  return serverHost.s_addr != id.serverHost.s_addr ||
			port != id.port || number != id.number;
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8

<commit_msg>try to fix winsock debaucle<commit_after>/* bzflag
 * Copyright (c) 1993 - 2004 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

// bzflag common header
#include "common.h"

// interface header
#include "Address.h"

// system headers
#include <string.h>
#include <string>
#include <sys/types.h>
#if !defined(_WIN32)
#include <unistd.h>
#include <setjmp.h>
#endif

// common implementation headers
#include "bzsignal.h"
#include "ErrorHandler.h"

// local implementation headers
#include "Pack.h"

#if defined(sun)
  // Solaris...
  extern "C" int inet_aton(const char *, struct in_addr *);
#endif

//
// Address
//

#if !defined( GUSI_20 ) && !defined( WIN32 )
  Address			Address::localAddress("");
#endif

Address::Address()
{
  InAddr tempAddr;

  memset(&tempAddr, 0, sizeof(tempAddr));
  tempAddr.s_addr = htonl(INADDR_ANY);
  addr.push_back(tempAddr);
}

Address::Address(const std::string& name)
{
  Address a = getHostAddress(name);
  addr.push_back(a.addr[0]);
}

Address::Address(const Address& address) : addr(address.addr)
{
  // do nothing
}

Address::Address(const InAddr& _addr)
{
  addr.push_back(_addr);
}

Address::Address(const struct sockaddr_in& _addr)
{
  addr.push_back(_addr.sin_addr);
}

Address::~Address()
{
  // do nothing
}

Address&		Address::operator=(const Address& address)
{
  addr.clear();
  addr.push_back(address.addr[0]);
  return *this;
}

Address::operator InAddr() const
{
  return addr[0];
}

bool			Address::operator==(const Address& address) const
{
  return addr[0].s_addr == address.addr[0].s_addr;
}

bool			Address::operator!=(const Address& address) const
{
  return addr[0].s_addr != address.addr[0].s_addr;
}

bool			Address::isAny() const
{
  return addr[0].s_addr == htonl(INADDR_ANY);
}

std::string		Address::getDotNotation() const
{
  return std::string(inet_ntoa(addr[0]));
}

uint8_t		        Address::getIPVersion() const {
  return 4;
}

#if !defined(_WIN32)
static jmp_buf alarmEnv;
static void		onAlarm(int)
{
  // jump back to setjmp.  this handles the race condition where we
  // set the alarm but gethostbyname() wouldn't have been called
  // until after the alarm goes off (resulting in an indeterminate
  // wait).
  longjmp(alarmEnv, 1);
}
#endif

Address			Address::getHostAddress(const std::string hname)
{
  Address a;
  InAddr tempAddr;
  int j;

  struct hostent* hent;
  if (hname == "") {				// local address
    char hostname[MAXHOSTNAMELEN+1];
    if (gethostname(hostname, sizeof(hostname)) >= 0)
      hent = gethostbyname(hostname);
    else
      return a;
  }
  else if (inet_aton(hname.c_str(), &tempAddr) != 0) {
    a.addr.clear();
    a.addr.push_back(tempAddr);
    return a;
  }
  else {				// non-local address
#if !defined(_WIN32)
    // set alarm to avoid waiting too long
    SIG_PF oldAlarm = bzSignal(SIGALRM, SIG_PF(onAlarm));
    if (oldAlarm != SIG_ERR) {
      if (setjmp(alarmEnv) != 0) {
	// alarm went off
	hent = NULL;
	printError("Looking up host name: timeout");
	return a;
      }

      // wait up to this many seconds
      alarm(8);
    }
#endif

    hent = gethostbyname(hname.c_str());

#if !defined(_WIN32)
    if (oldAlarm != SIG_ERR) {
      alarm(0);
      bzSignal(SIGALRM, oldAlarm);
    }
#endif
  }

  if (!hent) {
    herror("Looking up host name");
    return a;
  }

  a.addr.clear();
  for (j=0; hent->h_addr_list[j] != NULL; j++){
    ::memcpy(&tempAddr, hent->h_addr_list[j], sizeof(tempAddr));
    a.addr.push_back(tempAddr);
  }
  return a;
}

std::string		Address::getHostByAddress(InAddr addr)
{
#if !defined(_WIN32)
  // set alarm to avoid waiting too long
  SIG_PF oldAlarm = bzSignal(SIGALRM, SIG_PF(onAlarm));
  if (oldAlarm != SIG_ERR) {
    if (setjmp(alarmEnv) != 0) {
      // alarm went off
      return std::string(inet_ntoa(addr));
    }

    // wait up to this many seconds
    alarm(8);
  }
#endif

  int addrLen = sizeof(addr);
  struct hostent* hent = gethostbyaddr((char*)&addr, addrLen, AF_INET);

#if !defined(_WIN32)
  if (oldAlarm != SIG_ERR) {
    alarm(0);
    bzSignal(SIGALRM, oldAlarm);
  }
#endif

  if (!hent) {
    // can't lookup name -- return in standard dot notation
    return std::string(inet_ntoa(addr));
  }
  return std::string(hent->h_name);
}

const std::string Address::getHostName(const std::string hostname) // const
{
  char myname[MAXHOSTNAMELEN+1];
  std::string name = hostname;
  if (name.length() <= 0) {
    if (gethostname(myname, sizeof(myname)) >= 0)
      name = std::string(myname);
  }
  if (name.length() <= 0) {
    return std::string("");
  }
  struct hostent* hent = gethostbyname(name.c_str());
  if (!hent) {
    return std::string("");
  }
  return std::string(hent->h_name);
}

void*			Address::pack(void* _buf) const
{
  unsigned char* buf = (unsigned char*)_buf;
  buf = (unsigned char*)nboPackUByte(_buf, 4);
  // everything in InAddr  is already in network byte order
  int32_t hostaddr = int32_t(addr[0].s_addr);
  ::memcpy(buf, &hostaddr, sizeof(int32_t));	buf += sizeof(int32_t);
  return (void*)buf;
}

void*			Address::unpack(void* _buf)
{
  unsigned char* buf = (unsigned char*)_buf;
  InAddr tempAddr;
  // FIXME - should actually parse the first byte to see if it's IPv4 or
  // IPv6
  ++buf;
  // everything in InAddr should be stored in network byte order
  int32_t hostaddr;
  ::memcpy(&hostaddr, buf, sizeof(int32_t));	buf += sizeof(int32_t);
  tempAddr.s_addr = u_long(hostaddr);
  addr.clear();
  addr.push_back(tempAddr);
  return (void*)buf;
}

//
// ServerId
//

void*			ServerId::pack(void* _buf) const
{
  // everything in PlayerId is already in network byte order
  unsigned char* buf = (unsigned char*)_buf;
  int32_t hostaddr = int32_t(serverHost.s_addr);
  ::memcpy(buf, &hostaddr, sizeof(int32_t));	buf += sizeof(int32_t);
  ::memcpy(buf, &port, sizeof(int16_t));	buf += sizeof(int16_t);
  ::memcpy(buf, &number, sizeof(int16_t));	buf += sizeof(int16_t);
  return (void*)buf;
}

void*			ServerId::unpack(void* _buf)
{
  // everything in ServerId should be stored in network byte order
  unsigned char* buf = (unsigned char*)_buf;
  int32_t hostaddr;
  ::memcpy(&hostaddr, buf, sizeof(int32_t));	buf += sizeof(int32_t);
  ::memcpy(&port, buf, sizeof(int16_t));	buf += sizeof(int16_t);
  ::memcpy(&number, buf, sizeof(int16_t));	buf += sizeof(int16_t);
  serverHost.s_addr = u_long(hostaddr);
  return (void*)buf;
}

bool			ServerId::operator==(const ServerId& id) const
{
  return serverHost.s_addr == id.serverHost.s_addr &&
			port == id.port && number == id.number;
}

bool			ServerId::operator!=(const ServerId& id) const
{
  return serverHost.s_addr != id.serverHost.s_addr ||
			port != id.port || number != id.number;
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8

<|endoftext|>


<commit_before>#include <nan.h>
#include "Curl.h"

NAN_MODULE_INIT( Initialize ) {

    Curl::Initialize( target );
}

NODE_MODULE( node_libcurl, Initialize );
<commit_msg>renamed Initialize function to Init.<commit_after>#include <nan.h>
#include "Curl.h"

NAN_MODULE_INIT( Init ) {

    Curl::Initialize( target );
}

NODE_MODULE( node_libcurl, Init );
<|endoftext|>


<commit_before>#ifndef SRC_ONLINE_AROW_HPP_
#define SRC_ONLINE_AROW_HPP_

#include <Eigen/Dense>
#include <cstdbool>
#include "utility.hpp"

class AROW {
private :
  const int kDim;
  const double kR;

private :
  Eigen::VectorXd _covariances;
  Eigen::VectorXd _means;

public :
  AROW(const int dim, const double r)
    : kDim(dim),
      kR(r),
      _covariances(Eigen::VectorXd::Ones(kDim)),
      _means(Eigen::VectorXd::Zero(kDim)) {

    static_assert(std::numeric_limits<decltype(dim)>::max() > 0, "Dimension Error. (Dimension > 0)");
    static_assert(std::numeric_limits<decltype(r)>::max() > 0, "Hyper Parameter Error. (r > 0)");

  }

  virtual ~AROW() { }

  double suffer_loss(const double margin, const int label) const {
    return margin * label;
  }

  double calculate_margin(const Eigen::VectorXd& x) const {
    return _means.dot(x);
  }

  double calculate_confidence(const Eigen::VectorXd& f) const {
    auto confidence = 0.0;
    utility::enumerate(f.data(), f.data() + f.size(), 0,
                       [&](const int index, const double value) {
                         confidence += _covariances[index] * value * value;
                       });
    return confidence;
  }

  bool update(const Eigen::VectorXd& feature, const int label) {
    const auto margin = calculate_margin(feature);
    const auto confidence = calculate_confidence(feature);
    const auto beta = 1.0 / (confidence + kR);
    const auto alpha = std::max(0.0, 1.0 - label * margin) * beta;

    if (suffer_loss(margin, label) >= 1.0) { return false; }

    utility::enumerate(feature.data(), feature.data() + feature.size(), 0,
                       [&](const int index, const double value) {
                         const auto v = _covariances[index] * value;
                         _means[index] += alpha * label * v;
                         _covariances[index] -= beta * v * v;
                       });
    return true;
  }

  int predict(Eigen::VectorXd& x) const {
    return calculate_margin(x) > 0.0 ? 1 : -1;
  }

};

#endif //SRC_ONLINE_AROW_HPP_
<commit_msg>kDimの型をstd::size_tに変更<commit_after>#ifndef SRC_ONLINE_AROW_HPP_
#define SRC_ONLINE_AROW_HPP_

#include <Eigen/Dense>
#include <cstdbool>
#include "utility.hpp"

class AROW {
private :
  const std::size_t kDim;
  const double kR;

private :
  Eigen::VectorXd _covariances;
  Eigen::VectorXd _means;

public :
  AROW(const std::size_t dim, const double r)
    : kDim(dim),
      kR(r),
      _covariances(Eigen::VectorXd::Ones(kDim)),
      _means(Eigen::VectorXd::Zero(kDim)) {

    static_assert(std::numeric_limits<decltype(dim)>::max() > 0, "Dimension Error. (Dimension > 0)");
    static_assert(std::numeric_limits<decltype(r)>::max() > 0, "Hyper Parameter Error. (r > 0)");

  }

  virtual ~AROW() { }

  double suffer_loss(const double margin, const int label) const {
    return margin * label;
  }

  double calculate_margin(const Eigen::VectorXd& x) const {
    return _means.dot(x);
  }

  double calculate_confidence(const Eigen::VectorXd& f) {
    auto confidence = 0.0;
    utility::enumerate(f.data(), f.data() + f.size(), 0,
                       [&](const int index, const double value) {
                         confidence += _covariances[index] * value * value;
                       });
    return confidence;
  }

  bool update(const Eigen::VectorXd& feature, const int label) {
    const auto margin = calculate_margin(feature);
    const auto confidence = calculate_confidence(feature);
    const auto beta = 1.0 / (confidence + kR);
    const auto alpha = std::max(0.0, 1.0 - label * margin) * beta;

    if (suffer_loss(margin, label) >= 1.0) { return false; }

    utility::enumerate(feature.data(), feature.data() + feature.size(), 0,
                       [&](const int index, const double value) {
                         const auto v = _covariances[index] * value;
                         _means[index] += alpha * label * v;
                         _covariances[index] -= beta * v * v;
                       });
    return true;
  }

  int predict(Eigen::VectorXd& x) const {
    return calculate_margin(x) > 0.0 ? 1 : -1;
  }

};

#endif //SRC_ONLINE_AROW_HPP_
<|endoftext|>


<commit_before>#ifndef OPERATOR_MAP_HPP
#define OPERATOR_MAP_HPP

#include <string>
#include <vector>
#include <unordered_map>
#include <functional>

#include "util.hpp"
#include "object.hpp"
#include "operator.hpp"

typedef std::vector<std::string> OperandTypeList; // The types of the operands
typedef std::vector<Object::Link> OperandList; // The list of actual operands
typedef std::function<Object::Link(OperandList)> OperatorFunction; // The code that runs for a specific operand list
typedef std::unordered_map<OperandTypeList, OperatorFunction, VectorHash<std::string>> Operations; // Maps specific operand types to their respective code

#define OPERATION [](OperandList operands) -> Object::Link
#define CAST(what, type) PtrUtil<type>::dynPtrCast(what)

/*
  Example result for integer addition:
  {{"Integer", "Integer"}, OPERATION {
    return PtrUtil<Integer>::make(CAST(operands[0], Integer)->getValue() + CAST(operands[1], Integer)->getValue());
  }}
*/
#define BINARY_ARITHMETIC_OP(type1, type2, resultType, op) \
{{#type1, #type2}, OPERATION {\
  return PtrUtil<resultType>::make(CAST(operands[0], type1)->getValue() op CAST(operands[1], type2)->getValue());\
}}

#define BINARY_ARITHMETIC_SET(op) \
BINARY_ARITHMETIC_OP(Integer, Integer, Integer, op),\
BINARY_ARITHMETIC_OP(Integer, Float, Float, op),\
BINARY_ARITHMETIC_OP(Float, Integer, Float, op),\
BINARY_ARITHMETIC_OP(Float, Float, Float, op)

// Maps an operator name to the operations that use it
std::unordered_map<std::string, Operations> operatorMap {
  {"Add", {
    BINARY_ARITHMETIC_SET(+),
  }},
  {"Substract", {
    BINARY_ARITHMETIC_SET(-),
  }},
  {"Multiply", {
    BINARY_ARITHMETIC_SET(*),
  }},
  {"Divide", {
    BINARY_ARITHMETIC_SET(/),
  }}
};

#undef BINARY_ARITHMETIC_SET
#undef BINARY_ARITHMETIC_OP
#undef CAST
#undef OPERATION

OperandTypeList typeListFrom(OperandList list) {
  OperandTypeList t {};
  t.resize(list.size());
  std::transform(ALL(list), t.begin(), [](const Object::Link& operand) {
    return operand->getTypeName();
  });
  return t;
}

Object::Link executeOperator(OperatorName opName, OperandList list) {
  OperandTypeList tl = typeListFrom(list);
  OperatorFunction func = operatorMap[opName][tl];
  return func(list);
}

#endif
<commit_msg>Handle references in operators<commit_after>#ifndef OPERATOR_MAP_HPP
#define OPERATOR_MAP_HPP

#include <string>
#include <vector>
#include <unordered_map>
#include <functional>

#include "util.hpp"
#include "object.hpp"
#include "operator.hpp"

typedef std::vector<std::string> OperandTypeList; // The types of the operands
typedef std::vector<Object::Link> OperandList; // The list of actual operands
typedef std::function<Object::Link(OperandList)> OperatorFunction; // The code that runs for a specific operand list
typedef std::unordered_map<OperandTypeList, OperatorFunction, VectorHash<std::string>> Operations; // Maps specific operand types to their respective code

/*
  Dereference all PtrUtil<Reference> in the operand list, by replacing them with the value they reference.
  Use if the operator does not mutate the referenced thing.
*/
void dereferenceAll(OperandList& list) {
  std::for_each(ALL(list), [](Object::Link& element) {
    if (element->getTypeName() == "Reference") {
      element = PtrUtil<Reference>::dynPtrCast(element)->getValue();
    }
  });
}

#define OPERATION [](OperandList operands) -> Object::Link
#define CAST(what, type) PtrUtil<type>::dynPtrCast(what)

/*
  Example result for integer addition:
  {{"Integer", "Integer"}, OPERATION {
    return PtrUtil<Integer>::make(CAST(operands[0], Integer)->getValue() + CAST(operands[1], Integer)->getValue());
  }}
*/
#define BINARY_ARITHMETIC_OP(type1, type2, resultType, op) \
{{#type1, #type2}, OPERATION {\
  dereferenceAll(operands);\
  return PtrUtil<resultType>::make(CAST(operands[0], type1)->getValue() op CAST(operands[1], type2)->getValue());\
}}

#define BINARY_ARITHMETIC_SET(op) \
BINARY_ARITHMETIC_OP(Integer, Integer, Integer, op),\
BINARY_ARITHMETIC_OP(Integer, Float, Float, op),\
BINARY_ARITHMETIC_OP(Float, Integer, Float, op),\
BINARY_ARITHMETIC_OP(Float, Float, Float, op)

// Maps an operator name to the operations that use it
std::unordered_map<std::string, Operations> operatorMap {
  {"Add", {
    BINARY_ARITHMETIC_SET(+),
  }},
  {"Substract", {
    BINARY_ARITHMETIC_SET(-),
  }},
  {"Multiply", {
    BINARY_ARITHMETIC_SET(*),
  }},
  {"Divide", {
    BINARY_ARITHMETIC_SET(/),
  }}
};

#undef BINARY_ARITHMETIC_SET
#undef BINARY_ARITHMETIC_OP
#undef CAST
#undef OPERATION

OperandTypeList typeListFrom(OperandList list) {
  OperandTypeList t {};
  t.resize(list.size());
  std::transform(ALL(list), t.begin(), [](const Object::Link& operand) {
    return operand->getTypeName();
  });
  return t;
}

Object::Link executeOperator(OperatorName opName, OperandList list) {
  OperandTypeList tl = typeListFrom(list);
  OperatorFunction func = operatorMap[opName][tl];
  return func(list);
}

#endif
<|endoftext|>


<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * 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
 * OpenSceneGraph Public License for more details.
*/
#include <string.h>
#include <osgDB/Field>

using namespace osgDB;
using namespace std;

Field::Field()
{
    _init();
}

Field::Field(const Field& ic)
{
    _copy(ic);
}

Field::~Field()
{
    _free();
}

Field& Field::operator = (const Field& ic)
{
    if (this==&ic) return *this;
    _free();
    _copy(ic);
    return *this;
}

void Field::_free()
{
    // free all data
    if (_fieldCache) delete [] _fieldCache;

    _init();

}

void Field::_init()
{

    _fieldCacheCapacity = 256;
    _fieldCacheSize = 0;
    _fieldCache = NULL;

    _fieldType = UNINITIALISED;

    _withinQuotes = false;

    _noNestedBrackets = 0;

}

void Field::_copy(const Field& ic)
{

    // copy string cache.
    if (ic._fieldCache)
    {
        _fieldCacheCapacity = ic._fieldCacheCapacity;
        _fieldCacheSize = ic._fieldCacheSize;
        _fieldCache = new char [_fieldCacheCapacity];
        strncpy(_fieldCache,ic._fieldCache,_fieldCacheCapacity);
    }
    else
    {
        _fieldCacheCapacity = 0;
        _fieldCacheSize = 0;
        _fieldCache = NULL;
    }

    _fieldType = ic._fieldType;

    _withinQuotes = ic._withinQuotes;

    _noNestedBrackets = ic._noNestedBrackets;
}

void Field::setWithinQuotes(bool withinQuotes)
{
    _withinQuotes=withinQuotes;
    _fieldType = UNINITIALISED;
}

bool Field::getWithinQuotes()
{
    return _withinQuotes;
}

void Field::setNoNestedBrackets(int no)
{
    _noNestedBrackets=no;
}

int Field::getNoNestedBrackets()
{
    return _noNestedBrackets;
}

const char* Field::getStr() const
{
    if (_fieldCacheSize!=0) return _fieldCache;
    else return NULL;
}

char* Field::takeStr()
{
    char* field = _fieldCache;

    _fieldCache = NULL;
    _fieldCacheSize = 0;

    _fieldType = UNINITIALISED;
    _withinQuotes = false;

    return field;
}

void Field::reset()
{
    _fieldCacheSize = 0;
    if (_fieldCache)
    {
        _fieldCache[_fieldCacheSize] = 0;
    }

    _withinQuotes = false;
    _noNestedBrackets = 0;
}

void Field::addChar(char c)
{
    if (_fieldCache==NULL)
    {
        if (_fieldCacheCapacity<MIN_CACHE_SIZE) _fieldCacheCapacity=MIN_CACHE_SIZE;
        _fieldCache = new char[_fieldCacheCapacity];
        memset(_fieldCache,0,_fieldCacheCapacity);
        _fieldCacheSize = 0;
    }
    else if (_fieldCacheSize>=_fieldCacheCapacity-1)
    {
        if (_fieldCacheCapacity<MIN_CACHE_SIZE) _fieldCacheCapacity=MIN_CACHE_SIZE;
        while (_fieldCacheSize>=_fieldCacheCapacity-1) _fieldCacheCapacity *= 2;
        char* tmp_str = _fieldCache;
        _fieldCache = new char[_fieldCacheCapacity];
        memset(_fieldCache,0,_fieldCacheCapacity);
        strncpy(_fieldCache,tmp_str,_fieldCacheSize);
        delete [] tmp_str;

    }
    _fieldCache[_fieldCacheSize++] = c;
    _fieldCache[_fieldCacheSize] = 0;
    _fieldType = UNINITIALISED;
}

Field::FieldType Field::getFieldType() const
{
    if (_fieldType==UNINITIALISED && _fieldCache)
    {
        _fieldType = calculateFieldType(_fieldCache,_withinQuotes);
    }
    return _fieldType;
}

bool Field::isValid() const
{
    if (_fieldCacheSize>0  && !_withinQuotes) return true;
    else return false;
}

bool Field::isOpenBracket() const
{
    if (_fieldCacheSize==1) return _fieldCache[0]=='{';
    else return false;
}

bool Field::isCloseBracket() const
{
    if (_fieldCacheSize==1) return _fieldCache[0]=='}';
    else return false;
}

bool Field::isWord() const
{
    getFieldType();
    return (_fieldType==WORD);
}

bool Field::matchWord(const char* str) const
{
    getFieldType();
    return _fieldType==WORD && strcmp(_fieldCache,str)==0;
}

bool Field::matchWord(const char* str,int noCharacters) const
{
    getFieldType();
    return _fieldType==WORD && strncmp(_fieldCache,str,noCharacters)==0;
}

bool Field::isString() const
{
    return getNoCharacters()!=0;
}

bool Field::matchString(const char* str) const
{
    return strcmp(_fieldCache,str)==0;
}

bool Field::matchString(const char* str,int noCharacters) const
{
    return strncmp(_fieldCache,str,noCharacters)==0;
}

bool Field::isQuotedString() const
{
    return _withinQuotes;
}

bool Field::isInt() const
{
    getFieldType();
    return _fieldType==INTEGER;
}

bool Field::matchInt(int i) const
{
    getFieldType();
    if (_fieldType==INTEGER)
    {
        return strtol(_fieldCache,NULL,0)==i;
    }
    else
    {
        return false;
    }
}

bool Field::getInt(int& i) const
{
    getFieldType();
    if (_fieldType==INTEGER)
    {
        i = strtol(_fieldCache,NULL,0);
        return true;
    }
    else
    {
        return false;
    }
}

bool Field::isUInt() const
{
    getFieldType();
    return _fieldType==INTEGER;
}

bool Field::matchUInt(unsigned int i) const
{
    getFieldType();
    if (_fieldType==INTEGER)
    {
        return (unsigned int) strtoul(_fieldCache,NULL,0)==i;
    }
    else
    {
        return false;
    }
}

bool Field::getUInt(unsigned int& i) const
{
    getFieldType();
    if (_fieldType==INTEGER)
    {
        i = strtoul(_fieldCache,NULL,0);
        return true;
    }
    else
    {
        return false;
    }
}

bool Field::isFloat() const
{
    getFieldType();
    return _fieldType==REAL || _fieldType==INTEGER;
}

bool Field::matchFloat(float f) const
{
    getFieldType();
    if (_fieldType==REAL || _fieldType==INTEGER)
    {
        return (float)atof(_fieldCache)==f;
    }
    else
    {
        return false;
    }
}

bool Field::getFloat(float& f) const
{
    getFieldType();
    if (_fieldType==REAL || _fieldType==INTEGER)
    {
        f = (float)atof(_fieldCache);
        return true;
    }
    else
    {
        return false;
    }
}

bool Field::getFloat(double& f) const
{
    getFieldType();
    if (_fieldType==REAL || _fieldType==INTEGER)
    {
        f = atof(_fieldCache);
        return true;
    }
    else
    {
        return false;
    }
}

Field::FieldType Field::calculateFieldType(const char* str,bool withinQuotes)
{
    if (str==NULL) return BLANK;
    if (*str==0) return BLANK;

    if (withinQuotes) return STRING;

    bool hadPlusMinus = false;
    bool hadDecimalPlace = false;
    bool hadExponent = false;
    bool couldBeInt = true;
    bool couldBeFloat = true;
    int noZeroToNine = 0;

    const char* ptr = str;

    // check if could be a hex number.
    if (strncmp(ptr,"0x",2)==0)
    {
        // skip over leading 0x, and then go through rest of string
        // checking to make sure all values are 0...9 or a..f.
        ptr+=2;
        while (
               *ptr!=0 &&
               ((*ptr>='0' && *ptr<='9') ||
                (*ptr>='a' && *ptr<='f') ||
                (*ptr>='A' && *ptr<='F'))
              )
        {
            ++ptr;
        }

        // got to end of string without failure, therefore must be a hex integer.
        if (*ptr==0) return INTEGER;
    }

    ptr = str;
    // check if a float or an int.
    while (*ptr!=0 && couldBeFloat)
    {
        if (*ptr=='+' || *ptr=='-')
        {
            if (hadPlusMinus)
            {
                couldBeInt = false;
                couldBeFloat = false;
            } else hadPlusMinus = true;
        }
        else if (*ptr>='0' && *ptr<='9')
        {
            noZeroToNine++;
        }
        else if (*ptr=='.')
        {
            if (hadDecimalPlace)
            {
                couldBeInt = false;
                couldBeFloat = false;
            }
            else
            {
                hadDecimalPlace = true;
                couldBeInt = false;
            }
        }
        else if (*ptr=='e' || *ptr=='E')
        {
            if (hadExponent || noZeroToNine==0)
            {
                couldBeInt = false;
                couldBeFloat = false;
            }
            else
            {
                hadExponent = true;
                couldBeInt = false;
                hadDecimalPlace = false;
                hadPlusMinus = false;
                noZeroToNine=0;
            }
        }
        else
        {
            couldBeInt = false;
            couldBeFloat = false;
        }
        ++ptr;
    }

    if (couldBeInt && noZeroToNine>0) return INTEGER;
    if (couldBeFloat && noZeroToNine>0) return REAL;
    if (str[0]=='{') return OPEN_BRACKET;
    if (str[0]=='}') return CLOSE_BRACKET;
    return WORD;
}
<commit_msg>Introduce a custom atof function that always assumes data comes in form 10.10 with the full stop used as a decimal place.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * 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
 * OpenSceneGraph Public License for more details.
*/
#include <string.h>
#include <math.h>
#include <osg/Notify>
#include <osgDB/Field>

using namespace osgDB;
using namespace std;

double osg_atof(const char* str)
{
    const char* ptr = str;

    // check if could be a hex number.
    if (strncmp(ptr,"0x",2)==0)
    {

        double value = 0.0;

        // skip over leading 0x, and then go through rest of string
        // checking to make sure all values are 0...9 or a..f.
        ptr+=2;
        while (
               *ptr!=0 &&
               ((*ptr>='0' && *ptr<='9') ||
                (*ptr>='a' && *ptr<='f') ||
                (*ptr>='A' && *ptr<='F'))
              )
        {
            if (*ptr>='0' && *ptr<='9') value = value*16.0 + double(*ptr-'0');
            else if (*ptr>='a' && *ptr<='f') value = value*16.0 + double(*ptr-'a'+10);
            else if (*ptr>='A' && *ptr<='F') value = value*16.0 + double(*ptr-'A'+10);
            ++ptr;
        }

        // osg::notify(osg::NOTICE)<<"Read "<<str<<" result = "<<value<<std::endl;
        return value;
    }

    ptr = str;

    bool    hadDecimal[2];
    double  value[2];
    double  sign[2];
    double  decimalMultiplier[2];

    hadDecimal[0] = hadDecimal[1] = false;
    sign[0] = sign[1] = 1.0;
    value[0] = value[1] = 0.0;
    decimalMultiplier[0] = decimalMultiplier[1] = 0.1;
    int pos = 0;

    // compute mantissa and exponent parts
    while (*ptr!=0 && pos<2)
    {
        if (*ptr=='+')
        {
            sign[pos] = 1.0;
        }
        else if (*ptr=='-')
        {
            sign[pos] = -1.0;
        }
        else if (*ptr>='0' && *ptr<='9')
        {
            if (!hadDecimal[pos])
            {
                value[pos] = value[pos]*10.0 + double(*ptr-'0');
            }
            else
            {
                value[pos] = value[pos] + decimalMultiplier[pos] * double(*ptr-'0');
                decimalMultiplier[pos] *= 0.1;
            }
        }
        else if (*ptr=='.')
        {
            hadDecimal[pos] = true;
        }
        else if (*ptr=='e' || *ptr=='E')
        {
            if (pos==1) break;

            pos = 1;
        }
        else
        {
            break;
        }
        ++ptr;
    }

    if (pos==0)
    {
        // osg::notify(osg::NOTICE)<<"Read "<<str<<" result = "<<value[0]*sign[0]<<std::endl;
        return value[0]*sign[0];
    }
    else
    {
        double mantissa = value[0]*sign[0];
        double exponent = value[1]*sign[1];
        //osg::notify(osg::NOTICE)<<"Read "<<str<<" mantissa = "<<mantissa<<" exponent="<<exponent<<" result = "<<mantissa*pow(10.0,exponent)<<std::endl;
        return mantissa*pow(10.0,exponent);
    }
}

Field::Field()
{
    _init();
}

Field::Field(const Field& ic)
{
    _copy(ic);
}

Field::~Field()
{
    _free();
}

Field& Field::operator = (const Field& ic)
{
    if (this==&ic) return *this;
    _free();
    _copy(ic);
    return *this;
}

void Field::_free()
{
    // free all data
    if (_fieldCache) delete [] _fieldCache;

    _init();

}

void Field::_init()
{

    _fieldCacheCapacity = 256;
    _fieldCacheSize = 0;
    _fieldCache = NULL;

    _fieldType = UNINITIALISED;

    _withinQuotes = false;

    _noNestedBrackets = 0;

}

void Field::_copy(const Field& ic)
{

    // copy string cache.
    if (ic._fieldCache)
    {
        _fieldCacheCapacity = ic._fieldCacheCapacity;
        _fieldCacheSize = ic._fieldCacheSize;
        _fieldCache = new char [_fieldCacheCapacity];
        strncpy(_fieldCache,ic._fieldCache,_fieldCacheCapacity);
    }
    else
    {
        _fieldCacheCapacity = 0;
        _fieldCacheSize = 0;
        _fieldCache = NULL;
    }

    _fieldType = ic._fieldType;

    _withinQuotes = ic._withinQuotes;

    _noNestedBrackets = ic._noNestedBrackets;
}

void Field::setWithinQuotes(bool withinQuotes)
{
    _withinQuotes=withinQuotes;
    _fieldType = UNINITIALISED;
}

bool Field::getWithinQuotes()
{
    return _withinQuotes;
}

void Field::setNoNestedBrackets(int no)
{
    _noNestedBrackets=no;
}

int Field::getNoNestedBrackets()
{
    return _noNestedBrackets;
}

const char* Field::getStr() const
{
    if (_fieldCacheSize!=0) return _fieldCache;
    else return NULL;
}

char* Field::takeStr()
{
    char* field = _fieldCache;

    _fieldCache = NULL;
    _fieldCacheSize = 0;

    _fieldType = UNINITIALISED;
    _withinQuotes = false;

    return field;
}

void Field::reset()
{
    _fieldCacheSize = 0;
    if (_fieldCache)
    {
        _fieldCache[_fieldCacheSize] = 0;
    }

    _withinQuotes = false;
    _noNestedBrackets = 0;
}

void Field::addChar(char c)
{
    if (_fieldCache==NULL)
    {
        if (_fieldCacheCapacity<MIN_CACHE_SIZE) _fieldCacheCapacity=MIN_CACHE_SIZE;
        _fieldCache = new char[_fieldCacheCapacity];
        memset(_fieldCache,0,_fieldCacheCapacity);
        _fieldCacheSize = 0;
    }
    else if (_fieldCacheSize>=_fieldCacheCapacity-1)
    {
        if (_fieldCacheCapacity<MIN_CACHE_SIZE) _fieldCacheCapacity=MIN_CACHE_SIZE;
        while (_fieldCacheSize>=_fieldCacheCapacity-1) _fieldCacheCapacity *= 2;
        char* tmp_str = _fieldCache;
        _fieldCache = new char[_fieldCacheCapacity];
        memset(_fieldCache,0,_fieldCacheCapacity);
        strncpy(_fieldCache,tmp_str,_fieldCacheSize);
        delete [] tmp_str;

    }
    _fieldCache[_fieldCacheSize++] = c;
    _fieldCache[_fieldCacheSize] = 0;
    _fieldType = UNINITIALISED;
}

Field::FieldType Field::getFieldType() const
{
    if (_fieldType==UNINITIALISED && _fieldCache)
    {
        _fieldType = calculateFieldType(_fieldCache,_withinQuotes);
    }
    return _fieldType;
}

bool Field::isValid() const
{
    if (_fieldCacheSize>0  && !_withinQuotes) return true;
    else return false;
}

bool Field::isOpenBracket() const
{
    if (_fieldCacheSize==1) return _fieldCache[0]=='{';
    else return false;
}

bool Field::isCloseBracket() const
{
    if (_fieldCacheSize==1) return _fieldCache[0]=='}';
    else return false;
}

bool Field::isWord() const
{
    getFieldType();
    return (_fieldType==WORD);
}

bool Field::matchWord(const char* str) const
{
    getFieldType();
    return _fieldType==WORD && strcmp(_fieldCache,str)==0;
}

bool Field::matchWord(const char* str,int noCharacters) const
{
    getFieldType();
    return _fieldType==WORD && strncmp(_fieldCache,str,noCharacters)==0;
}

bool Field::isString() const
{
    return getNoCharacters()!=0;
}

bool Field::matchString(const char* str) const
{
    return strcmp(_fieldCache,str)==0;
}

bool Field::matchString(const char* str,int noCharacters) const
{
    return strncmp(_fieldCache,str,noCharacters)==0;
}

bool Field::isQuotedString() const
{
    return _withinQuotes;
}

bool Field::isInt() const
{
    getFieldType();
    return _fieldType==INTEGER;
}

bool Field::matchInt(int i) const
{
    getFieldType();
    if (_fieldType==INTEGER)
    {
        return strtol(_fieldCache,NULL,0)==i;
    }
    else
    {
        return false;
    }
}

bool Field::getInt(int& i) const
{
    getFieldType();
    if (_fieldType==INTEGER)
    {
        i = strtol(_fieldCache,NULL,0);
        return true;
    }
    else
    {
        return false;
    }
}

bool Field::isUInt() const
{
    getFieldType();
    return _fieldType==INTEGER;
}

bool Field::matchUInt(unsigned int i) const
{
    getFieldType();
    if (_fieldType==INTEGER)
    {
        return (unsigned int) strtoul(_fieldCache,NULL,0)==i;
    }
    else
    {
        return false;
    }
}

bool Field::getUInt(unsigned int& i) const
{
    getFieldType();
    if (_fieldType==INTEGER)
    {
        i = strtoul(_fieldCache,NULL,0);
        return true;
    }
    else
    {
        return false;
    }
}

bool Field::isFloat() const
{
    getFieldType();
    return _fieldType==REAL || _fieldType==INTEGER;
}

bool Field::matchFloat(float f) const
{
    getFieldType();
    if (_fieldType==REAL || _fieldType==INTEGER)
    {
        return (float)osg_atof(_fieldCache)==f;
    }
    else
    {
        return false;
    }
}

bool Field::getFloat(float& f) const
{
    getFieldType();
    if (_fieldType==REAL || _fieldType==INTEGER)
    {
        f = (float)osg_atof(_fieldCache);
        return true;
    }
    else
    {
        return false;
    }
}

bool Field::getFloat(double& f) const
{
    getFieldType();
    if (_fieldType==REAL || _fieldType==INTEGER)
    {
        f = osg_atof(_fieldCache);
        return true;
    }
    else
    {
        return false;
    }
}

Field::FieldType Field::calculateFieldType(const char* str,bool withinQuotes)
{
    if (str==NULL) return BLANK;
    if (*str==0) return BLANK;

    if (withinQuotes) return STRING;

    bool hadPlusMinus = false;
    bool hadDecimalPlace = false;
    bool hadExponent = false;
    bool couldBeInt = true;
    bool couldBeFloat = true;
    int noZeroToNine = 0;

    const char* ptr = str;

    // check if could be a hex number.
    if (strncmp(ptr,"0x",2)==0)
    {
        // skip over leading 0x, and then go through rest of string
        // checking to make sure all values are 0...9 or a..f.
        ptr+=2;
        while (
               *ptr!=0 &&
               ((*ptr>='0' && *ptr<='9') ||
                (*ptr>='a' && *ptr<='f') ||
                (*ptr>='A' && *ptr<='F'))
              )
        {
            ++ptr;
        }

        // got to end of string without failure, therefore must be a hex integer.
        if (*ptr==0) return INTEGER;
    }

    ptr = str;
    // check if a float or an int.
    while (*ptr!=0 && couldBeFloat)
    {
        if (*ptr=='+' || *ptr=='-')
        {
            if (hadPlusMinus)
            {
                couldBeInt = false;
                couldBeFloat = false;
            } else hadPlusMinus = true;
        }
        else if (*ptr>='0' && *ptr<='9')
        {
            noZeroToNine++;
        }
        else if (*ptr=='.')
        {
            if (hadDecimalPlace)
            {
                couldBeInt = false;
                couldBeFloat = false;
            }
            else
            {
                hadDecimalPlace = true;
                couldBeInt = false;
            }
        }
        else if (*ptr=='e' || *ptr=='E')
        {
            if (hadExponent || noZeroToNine==0)
            {
                couldBeInt = false;
                couldBeFloat = false;
            }
            else
            {
                hadExponent = true;
                couldBeInt = false;
                hadDecimalPlace = false;
                hadPlusMinus = false;
                noZeroToNine=0;
            }
        }
        else
        {
            couldBeInt = false;
            couldBeFloat = false;
        }
        ++ptr;
    }

    if (couldBeInt && noZeroToNine>0) return INTEGER;
    if (couldBeFloat && noZeroToNine>0) return REAL;
    if (str[0]=='{') return OPEN_BRACKET;
    if (str[0]=='}') return CLOSE_BRACKET;
    return WORD;
}
<|endoftext|>


<commit_before>#include <routingkit/osm_profile.h>

namespace RoutingKit{

namespace{
	bool str_eq(const char*l, const char*r){
		return !strcmp(l, r);
	}

	bool str_wild_char_eq(const char*l, const char*r){
		while(*l != '\0' && *r != '\0'){
			if(*l != '?' && *r != '?' && *l != *r)
				return false;
			++l;
			++r;
		}
		return *l == '\0' && *r == '\0';
	}

	bool starts_with(const char*prefix, const char*str){
		while(*prefix != '\0' && *str == *prefix){
			++prefix;
			++str;
		}
		return *prefix == '\0';
	}

	void copy_str_and_make_lower_case(const char*in, char*out, unsigned out_size){
		char*out_end = out + out_size-1;
		while(*in && out != out_end){
			if('A' <= *in && *in <= 'Z')
				*out = *in - 'A' + 'a';
			else
				*out = *in;
			++in;
			++out;
		}
		*out = '\0';
	}

	// Splits the string at some separators such as ; and calls f(str) for each part.
	// The ; is replaced by a '\0'. Leading spaces are removed
	template<class F>
	void split_str_at_osm_value_separators(char*in, const F&f){
		while(*in == ' ')
			++in;
		const char*value_begin = in;
		for(;;){
			while(*in != '\0' && *in != ';')
				++in;
			if(*in == '\0'){
				f(value_begin);
				return;
			}else{
				*in = '\0';
				f(value_begin);
				++in;
				while(*in == ' ')
					++in;
				value_begin = in;
			}
		}
	}
}

bool is_osm_way_used_by_cars(uint64_t osm_way_id, const TagMap&tags, std::function<void(const std::string&)>log_message){
	const char* junction = tags["junction"];
	if(junction != nullptr)
		return true;

	const char* highway = tags["highway"];
	if(highway == nullptr)
		return false;

	const char*motor_vehicle = tags["motor_vehicle"];
	if(motor_vehicle && str_eq(motor_vehicle, "no"))
		return false;

	const char*access = tags["access"];
	if(access){
		if(!(str_eq(access, "yes") || str_eq(access, "permissive") || str_eq(access, "delivery")|| str_eq(access, "designated") || str_eq(access, "destination")))
			return false;
	}

	if(
		str_eq(highway, "motorway") ||
		str_eq(highway, "trunk") ||
		str_eq(highway, "primary") ||
		str_eq(highway, "secondary") ||
		str_eq(highway, "tertiary") ||
		str_eq(highway, "unclassified") ||
		str_eq(highway, "residential") ||
		str_eq(highway, "service") ||
		str_eq(highway, "motorway_link") ||
		str_eq(highway, "trunk_link") ||
		str_eq(highway, "primary_link") ||
		str_eq(highway, "secondary_link") ||
		str_eq(highway, "motorway_junction") ||
		str_eq(highway, "living_street") ||
		str_eq(highway, "residential") ||
		str_eq(highway, "ferry")
	)
		return true;

	if(str_eq(highway, "bicycle_road")){
		auto motorcar = tags["motorcar"];
		if(motorcar != nullptr)
			if(str_eq(motorcar, "yes"))
				return true;
		return false;
	}

	if(
		str_eq(highway, "construction") ||
		str_eq(highway, "path") ||
		str_eq(highway, "footway") ||
		str_eq(highway, "cycleway") ||
		str_eq(highway, "bridleway") ||
		str_eq(highway, "pedestrian") ||
		str_eq(highway, "bus_guideway") ||
		str_eq(highway, "raceway") ||
		str_eq(highway, "escape") ||
		str_eq(highway, "steps") ||
		str_eq(highway, "conveying")
	)
		return false;

	const char* oneway = tags["oneway"];
	if(oneway != nullptr){
		if(str_eq(oneway, "reversible")) {
			return false;
		}
	}

	const char* maxspeed = tags["maxspeed"];
	if(maxspeed != nullptr)
		return true;

	return false;
}

OSMWayDirectionCategory get_osm_car_direction_category(uint64_t osm_way_id, const TagMap&tags, std::function<void(const std::string&)>log_message){
	const char
		*oneway = tags["oneway"],
		*junction = tags["junction"],
		*highway = tags["highway"]
	;
	if(oneway != nullptr){
		if(str_eq(oneway, "-1") || str_eq(oneway, "reverse") || str_eq(oneway, "backward")) {
			return OSMWayDirectionCategory::only_open_backwards;
		} else if(str_eq(oneway, "yes") || str_eq(oneway, "true") || str_eq(oneway, "1")) {
			return OSMWayDirectionCategory::only_open_forwards;
		} else if(str_eq(oneway, "no") || str_eq(oneway, "false") || str_eq(oneway, "0")) {
			return OSMWayDirectionCategory::open_in_both;
		} else if(str_eq(oneway, "reversible")) {
			return OSMWayDirectionCategory::closed;
		} else {
			log_message("Warning: OSM way "+std::to_string(osm_way_id)+" has unknown oneway tag value \""+oneway+"\" for \"oneway\". Way is closed.");
		}
	} else if(junction != nullptr && str_eq(junction, "roundabout")) {
		return OSMWayDirectionCategory::only_open_forwards;
	} else if(highway != nullptr && (str_eq(highway, "motorway") || str_eq(highway, "motorway_link"))) {
		return OSMWayDirectionCategory::only_open_forwards;
	}
	return OSMWayDirectionCategory::open_in_both;
}

namespace{
	unsigned parse_maxspeed_value(uint64_t osm_way_id, const char*maxspeed, std::function<void(const std::string&)>log_message){
		if(str_eq(maxspeed, "signals") || str_eq(maxspeed, "variable"))
			return inf_weight;

		if(str_eq(maxspeed, "none") || str_eq(maxspeed, "unlimited"))
			return 130;

		if(str_eq(maxspeed, "walk") || str_eq(maxspeed, "foot") || str_wild_char_eq(maxspeed, "??:walk"))
			return 5;

		if(str_wild_char_eq(maxspeed, "??:urban") || str_eq(maxspeed, "urban"))
			return 40;

		if(str_wild_char_eq(maxspeed, "??:living_street") || str_eq(maxspeed, "living_street"))
			return 10;

		if(str_eq(maxspeed, "de:rural") || str_eq(maxspeed, "at:rural") || str_eq(maxspeed, "ro:rural") || str_eq(maxspeed, "rural"))
			return 100;
		if(str_eq(maxspeed, "ru:rural") || str_eq(maxspeed, "fr:rural") || str_eq(maxspeed, "ua:rural"))
			return 90;

		if(str_eq(maxspeed, "ru:motorway"))
			return 110;
		if(str_eq(maxspeed, "at:motorway") || str_eq(maxspeed, "ro:motorway"))
			return 130;

		if(str_eq(maxspeed, "national"))
			return 100;

		if(str_eq(maxspeed, "ro:trunk"))
			return 100;
		if(str_eq(maxspeed, "dk:rural") || str_eq(maxspeed, "ch:rural"))
			return 80;
		if(str_eq(maxspeed, "it:rural") || str_eq(maxspeed, "hu:rural"))
			return 90;
		if(str_eq(maxspeed, "de:zone:30"))
			return 30;

		if('0' <= *maxspeed && *maxspeed <= '9'){
			unsigned speed = 0;
			while('0' <= *maxspeed && *maxspeed <= '9'){
				speed *= 10;
				speed += *maxspeed - '0';
				++maxspeed;
			}
			while(*maxspeed == ' ')
				++maxspeed;
			if(*maxspeed == '\0' || str_eq(maxspeed, "km/h") || str_eq(maxspeed, "kmh") || str_eq(maxspeed, "kph")){
				return speed;
			}else if(str_eq(maxspeed, "mph")){
				return speed * 1609 / 1000;
			}else if(str_eq(maxspeed, "knots")){
				return speed * 1852 / 1000;
			}else{
				log_message("Warning: OSM way "+std::to_string(osm_way_id) +" has an unknown unit \""+maxspeed+"\" for its \"maxspeed\" tag -> assuming \"km/h\".");
				return speed;
			}
		}else{
			log_message("Warning: OSM way "+std::to_string(osm_way_id) +" has an unrecognized value of \""+maxspeed+"\" for its \"maxspeed\" tag.");
		}

		return inf_weight;
	}
}

unsigned get_osm_way_speed(uint64_t osm_way_id, const TagMap&tags, std::function<void(const std::string&)>log_message){
	auto maxspeed = tags["maxspeed"];
	if(maxspeed != nullptr){
		char lower_case_maxspeed[1024];
		copy_str_and_make_lower_case(maxspeed, lower_case_maxspeed, sizeof(lower_case_maxspeed)-1);

		unsigned speed = inf_weight;

		split_str_at_osm_value_separators(
			lower_case_maxspeed,
			 [&](const char*maxspeed){
				min_to(speed, parse_maxspeed_value(osm_way_id, maxspeed, log_message));
			}
		);

		if(speed == 0){
			speed = 1;
			log_message("Warning: OSM way "+std::to_string(osm_way_id)+" has speed 0 km/h, setting it to 1 km/h");
		}

		if(speed != inf_weight)
			return speed;

	}

	auto junction = tags["junction"];
	if(junction){
		return 20;
	}

	auto highway = tags["highway"];
	if(highway){
		if(str_eq(highway, "motorway"))
			return 90;
		if(str_eq(highway, "motorway_link"))
			return 45;
		if(str_eq(highway, "trunk"))
			return 85;
		if(str_eq(highway, "trunk_link"))
			return 40;
		if(str_eq(highway, "primary"))
			return 65;
		if(str_eq(highway, "primary_link"))
			return 30;
		if(str_eq(highway, "secondary"))
			return 55;
		if(str_eq(highway, "secondary_link"))
			return 25;
		if(str_eq(highway, "tertiary"))
			return 40;
		if(str_eq(highway, "tertiary_link"))
			return 20;
		if(str_eq(highway, "unclassified"))
			return 25;
		if(str_eq(highway, "residential"))
			return 25;
		if(str_eq(highway, "living_street"))
			return 10;
		if(str_eq(highway, "service"))
			return 1;
		if(str_eq(highway, "ferry"))
			return 5;
	}

	if(maxspeed && highway)
		log_message("Warning: OSM way "+std::to_string(osm_way_id) +" has an unrecognized \"maxspeed\" tag of \""+maxspeed+"\" and an unrecognized \"highway\" tag of \""+highway+"\" and an no junction tag -> assuming 50km/h.");
	if(!maxspeed && highway)
		log_message("Warning: OSM way "+std::to_string(osm_way_id) +" has no \"maxspeed\" and an unrecognized \"highway\" tag of \""+highway+"\" and an no junction tag -> assuming 50km/h.");
	if(!maxspeed && !highway)
		log_message("Warning: OSM way "+std::to_string(osm_way_id) +" has no \"maxspeed\" and no \"highway\" tag of \""+highway+"\" and an no junction tag -> assuming 50km/h.");
	if(maxspeed && !highway)
		log_message("Warning: OSM way "+std::to_string(osm_way_id) +" has an unrecognized \"maxspeed\" tag of \""+maxspeed+"\" and no \"highway\" tag and an no junction tag -> assuming 50km/h.");
	return 50;
}

std::string get_osm_way_name(uint64_t osm_way_id, const TagMap&tags, std::function<void(const std::string&)>log_message){
	auto
		name = tags["name"],
		ref = tags["ref"];

	if(name != nullptr && ref != nullptr)
		return std::string(name) + ";"+ref;
	else if(name != nullptr)
		return std::string(name);
	else if(ref != nullptr)
		return std::string(ref);
	else
		return std::string();
}

} // RoutingKit
<commit_msg>Fix white space<commit_after>#include <routingkit/osm_profile.h>

namespace RoutingKit{

namespace{
	bool str_eq(const char*l, const char*r){
		return !strcmp(l, r);
	}

	bool str_wild_char_eq(const char*l, const char*r){
		while(*l != '\0' && *r != '\0'){
			if(*l != '?' && *r != '?' && *l != *r)
				return false;
			++l;
			++r;
		}
		return *l == '\0' && *r == '\0';
	}

	bool starts_with(const char*prefix, const char*str){
		while(*prefix != '\0' && *str == *prefix){
			++prefix;
			++str;
		}
		return *prefix == '\0';
	}

	void copy_str_and_make_lower_case(const char*in, char*out, unsigned out_size){
		char*out_end = out + out_size-1;
		while(*in && out != out_end){
			if('A' <= *in && *in <= 'Z')
				*out = *in - 'A' + 'a';
			else
				*out = *in;
			++in;
			++out;
		}
		*out = '\0';
	}

	// Splits the string at some separators such as ; and calls f(str) for each part.
	// The ; is replaced by a '\0'. Leading spaces are removed
	template<class F>
	void split_str_at_osm_value_separators(char*in, const F&f){
		while(*in == ' ')
			++in;
		const char*value_begin = in;
		for(;;){
			while(*in != '\0' && *in != ';')
				++in;
			if(*in == '\0'){
				f(value_begin);
				return;
			}else{
				*in = '\0';
				f(value_begin);
				++in;
				while(*in == ' ')
					++in;
				value_begin = in;
			}
		}
	}
}

bool is_osm_way_used_by_cars(uint64_t osm_way_id, const TagMap&tags, std::function<void(const std::string&)>log_message){
	const char* junction = tags["junction"];
	if(junction != nullptr)
		return true;

	const char* highway = tags["highway"];
	if(highway == nullptr)
		return false;

	const char*motor_vehicle = tags["motor_vehicle"];
	if(motor_vehicle && str_eq(motor_vehicle, "no"))
		return false;

	const char*access = tags["access"];
	if(access){
		if(!(str_eq(access, "yes") || str_eq(access, "permissive") || str_eq(access, "delivery")|| str_eq(access, "designated") || str_eq(access, "destination")))
			return false;
	}

	if(
		str_eq(highway, "motorway") ||
		str_eq(highway, "trunk") ||
		str_eq(highway, "primary") ||
		str_eq(highway, "secondary") ||
		str_eq(highway, "tertiary") ||
		str_eq(highway, "unclassified") ||
		str_eq(highway, "residential") ||
		str_eq(highway, "service") ||
		str_eq(highway, "motorway_link") ||
		str_eq(highway, "trunk_link") ||
		str_eq(highway, "primary_link") ||
		str_eq(highway, "secondary_link") ||
		str_eq(highway, "motorway_junction") ||
		str_eq(highway, "living_street") ||
		str_eq(highway, "residential") ||
		str_eq(highway, "ferry")
	)
		return true;

	if(str_eq(highway, "bicycle_road")){
		auto motorcar = tags["motorcar"];
		if(motorcar != nullptr)
			if(str_eq(motorcar, "yes"))
				return true;
		return false;
	}

	if(
		str_eq(highway, "construction") ||
		str_eq(highway, "path") ||
		str_eq(highway, "footway") ||
		str_eq(highway, "cycleway") ||
		str_eq(highway, "bridleway") ||
		str_eq(highway, "pedestrian") ||
		str_eq(highway, "bus_guideway") ||
		str_eq(highway, "raceway") ||
		str_eq(highway, "escape") ||
		str_eq(highway, "steps") ||
		str_eq(highway, "conveying")
	)
		return false;

	const char* oneway = tags["oneway"];
	if(oneway != nullptr){
		if(str_eq(oneway, "reversible")) {
			return false;
		}
	}

	const char* maxspeed = tags["maxspeed"];
	if(maxspeed != nullptr)
		return true;

	return false;
}

OSMWayDirectionCategory get_osm_car_direction_category(uint64_t osm_way_id, const TagMap&tags, std::function<void(const std::string&)>log_message){
	const char
		*oneway = tags["oneway"],
		*junction = tags["junction"],
		*highway = tags["highway"]
	;
	if(oneway != nullptr){
		if(str_eq(oneway, "-1") || str_eq(oneway, "reverse") || str_eq(oneway, "backward")) {
			return OSMWayDirectionCategory::only_open_backwards;
		} else if(str_eq(oneway, "yes") || str_eq(oneway, "true") || str_eq(oneway, "1")) {
			return OSMWayDirectionCategory::only_open_forwards;
		} else if(str_eq(oneway, "no") || str_eq(oneway, "false") || str_eq(oneway, "0")) {
			return OSMWayDirectionCategory::open_in_both;
		} else if(str_eq(oneway, "reversible")) {
			return OSMWayDirectionCategory::closed;
		} else {
			log_message("Warning: OSM way "+std::to_string(osm_way_id)+" has unknown oneway tag value \""+oneway+"\" for \"oneway\". Way is closed.");
		}
	} else if(junction != nullptr && str_eq(junction, "roundabout")) {
		return OSMWayDirectionCategory::only_open_forwards;
	} else if(highway != nullptr && (str_eq(highway, "motorway") || str_eq(highway, "motorway_link"))) {
		return OSMWayDirectionCategory::only_open_forwards;
	}
	return OSMWayDirectionCategory::open_in_both;
}

namespace{
	unsigned parse_maxspeed_value(uint64_t osm_way_id, const char*maxspeed, std::function<void(const std::string&)>log_message){
		if(str_eq(maxspeed, "signals") || str_eq(maxspeed, "variable"))
			return inf_weight;

		if(str_eq(maxspeed, "none") || str_eq(maxspeed, "unlimited"))
			return 130;

		if(str_eq(maxspeed, "walk") || str_eq(maxspeed, "foot") || str_wild_char_eq(maxspeed, "??:walk"))
			return 5;

		if(str_wild_char_eq(maxspeed, "??:urban") || str_eq(maxspeed, "urban"))
			return 40;

		if(str_wild_char_eq(maxspeed, "??:living_street") || str_eq(maxspeed, "living_street"))
			return 10;

		if(str_eq(maxspeed, "de:rural") || str_eq(maxspeed, "at:rural") || str_eq(maxspeed, "ro:rural") || str_eq(maxspeed, "rural"))
			return 100;
		if(str_eq(maxspeed, "ru:rural") || str_eq(maxspeed, "fr:rural") || str_eq(maxspeed, "ua:rural"))
			return 90;

		if(str_eq(maxspeed, "ru:motorway"))
			return 110;
		if(str_eq(maxspeed, "at:motorway") || str_eq(maxspeed, "ro:motorway"))
			return 130;

		if(str_eq(maxspeed, "national"))
			return 100;

		if(str_eq(maxspeed, "ro:trunk"))
			return 100;
		if(str_eq(maxspeed, "dk:rural") || str_eq(maxspeed, "ch:rural"))
			return 80;
		if(str_eq(maxspeed, "it:rural") || str_eq(maxspeed, "hu:rural"))
			return 90;
		if(str_eq(maxspeed, "de:zone:30"))
			return 30;

		if('0' <= *maxspeed && *maxspeed <= '9'){
			unsigned speed = 0;
			while('0' <= *maxspeed && *maxspeed <= '9'){
				speed *= 10;
				speed += *maxspeed - '0';
				++maxspeed;
			}
			while(*maxspeed == ' ')
				++maxspeed;
			if(*maxspeed == '\0' || str_eq(maxspeed, "km/h") || str_eq(maxspeed, "kmh") || str_eq(maxspeed, "kph")){
				return speed;
			}else if(str_eq(maxspeed, "mph")){
				return speed * 1609 / 1000;
			}else if(str_eq(maxspeed, "knots")){
				return speed * 1852 / 1000;
			}else{
				log_message("Warning: OSM way "+std::to_string(osm_way_id) +" has an unknown unit \""+maxspeed+"\" for its \"maxspeed\" tag -> assuming \"km/h\".");
				return speed;
			}
		}else{
			log_message("Warning: OSM way "+std::to_string(osm_way_id) +" has an unrecognized value of \""+maxspeed+"\" for its \"maxspeed\" tag.");
		}

		return inf_weight;
	}
}

unsigned get_osm_way_speed(uint64_t osm_way_id, const TagMap&tags, std::function<void(const std::string&)>log_message){
	auto maxspeed = tags["maxspeed"];
	if(maxspeed != nullptr){
		char lower_case_maxspeed[1024];
		copy_str_and_make_lower_case(maxspeed, lower_case_maxspeed, sizeof(lower_case_maxspeed)-1);

		unsigned speed = inf_weight;

		split_str_at_osm_value_separators(
			lower_case_maxspeed,
			 [&](const char*maxspeed){
				min_to(speed, parse_maxspeed_value(osm_way_id, maxspeed, log_message));
			}
		);

		if(speed == 0){
			speed = 1;
			log_message("Warning: OSM way "+std::to_string(osm_way_id)+" has speed 0 km/h, setting it to 1 km/h");
		}

		if(speed != inf_weight)
			return speed;

	}

	auto junction = tags["junction"];
	if(junction){
		return 20;
	}

	auto highway = tags["highway"];
	if(highway){
		if(str_eq(highway, "motorway"))
			return 90;
		if(str_eq(highway, "motorway_link"))
			return 45;
		if(str_eq(highway, "trunk"))
			return 85;
		if(str_eq(highway, "trunk_link"))
			return 40;
		if(str_eq(highway, "primary"))
			return 65;
		if(str_eq(highway, "primary_link"))
			return 30;
		if(str_eq(highway, "secondary"))
			return 55;
		if(str_eq(highway, "secondary_link"))
			return 25;
		if(str_eq(highway, "tertiary"))
			return 40;
		if(str_eq(highway, "tertiary_link"))
			return 20;
		if(str_eq(highway, "unclassified"))
			return 25;
		if(str_eq(highway, "residential"))
			return 25;
		if(str_eq(highway, "living_street"))
			return 10;
		if(str_eq(highway, "service"))
			return 1;
		if(str_eq(highway, "ferry"))
			return 5;
	}

	if(maxspeed && highway)
		log_message("Warning: OSM way "+std::to_string(osm_way_id) +" has an unrecognized \"maxspeed\" tag of \""+maxspeed+"\" and an unrecognized \"highway\" tag of \""+highway+"\" and an no junction tag -> assuming 50km/h.");
	if(!maxspeed && highway)
		log_message("Warning: OSM way "+std::to_string(osm_way_id) +" has no \"maxspeed\" and an unrecognized \"highway\" tag of \""+highway+"\" and an no junction tag -> assuming 50km/h.");
	if(!maxspeed && !highway)
		log_message("Warning: OSM way "+std::to_string(osm_way_id) +" has no \"maxspeed\" and no \"highway\" tag of \""+highway+"\" and an no junction tag -> assuming 50km/h.");
	if(maxspeed && !highway)
		log_message("Warning: OSM way "+std::to_string(osm_way_id) +" has an unrecognized \"maxspeed\" tag of \""+maxspeed+"\" and no \"highway\" tag and an no junction tag -> assuming 50km/h.");
	return 50;
}

std::string get_osm_way_name(uint64_t osm_way_id, const TagMap&tags, std::function<void(const std::string&)>log_message){
	auto
		name = tags["name"],
		ref = tags["ref"];

	if(name != nullptr && ref != nullptr)
		return std::string(name) + ";"+ref;
	else if(name != nullptr)
		return std::string(name);
	else if(ref != nullptr)
		return std::string(ref);
	else
		return std::string();
}

} // RoutingKit
<|endoftext|>


<commit_before>#include <stdio.h>

#include <context.h>
#include <parser.h>

int parse_list(Context* context, vword_t addr, SNode* ast)
{
    // needed space
    size_t len = ast->subnodes->numOfElements() * sizeof(vword_t);
    vword_t lptr = addr;

    ListIterator<SNode*> it = ListIterator<SNode*>(ast->subnodes);
    while(! it.isLast())
    {
        SNode* sn = it.getCurrent();

        switch(sn->type)
        {
            case SYMBOL:
            case INTEGER:
                // direcly insert word
                parse(context, lptr, sn);
                break;

            case LIST:
            case STRING:
                // here we need pointers
                vword_t subaddr = addr + len;
                len += parse(context, subaddr, sn);

                context->write_word(lptr, subaddr);
                break;
        }

        lptr += sizeof(vword_t);
        it.next();
    }

    return len;
}

int parse_list_se(Context* context, vword_t addr, SNode* ast)
{
    // needed space
    size_t n = ast->subnodes->numOfElements();

	size_t len = 4*VWORD_SIZE;
	size_t j = 0;
	vword_t lptr = addr + len;

	len += 2 * n * VWORD_SIZE;

    ListIterator<SNode*> it = ListIterator<SNode*>(ast->subnodes);
    while(! it.isLast())
    {
        SNode* sn = it.getCurrent();
		vword_t subaddr;

        switch(sn->type)
        {
            case SYMBOL:
            case INTEGER:
                // direcly insert word
				context->write_word(lptr + (j++)*VWORD_SIZE, VWORD_SIZE);
                parse_se(context, lptr + (j++)*VWORD_SIZE, sn);
                break;

            case LIST:
				subaddr = addr+len;
				len += parse_se(context, subaddr, sn);

				context->write_word(lptr + (j++)*VWORD_SIZE, (vword_t)-1);
                context->write_word(lptr + (j++)*VWORD_SIZE, subaddr);
				break;

            case STRING:
/*                // here we need pointers
                vword_t subaddr = addr + len;
                len += parse(context, subaddr, sn);

                context->write_word(addr+len, subaddr);
				len += VWORD_SIZE;

				list[i++]
*/
                break;
        }

        it.next();
    }

	vword_t v[4];
	v[0] = 3 * VWORD_SIZE;
	v[1] = resolve_symbol("deval");
	v[2] = n;
	v[3] = lptr;

	context->write(addr, 4*VWORD_SIZE, (vbyte_t*) &v);

    return len;
}

<commit_msg>only pre evaluate 'arguments'<commit_after>#include <stdio.h>

#include <context.h>
#include <parser.h>

int parse_list(Context* context, vword_t addr, SNode* ast)
{
    // needed space
    size_t len = ast->subnodes->numOfElements() * sizeof(vword_t);
    vword_t lptr = addr;

    ListIterator<SNode*> it = ListIterator<SNode*>(ast->subnodes);
    while(! it.isLast())
    {
        SNode* sn = it.getCurrent();

        switch(sn->type)
        {
            case SYMBOL:
            case INTEGER:
                // direcly insert word
                parse(context, lptr, sn);
                break;

            case LIST:
            case STRING:
                // here we need pointers
                vword_t subaddr = addr + len;
                len += parse(context, subaddr, sn);

                context->write_word(lptr, subaddr);
                break;
        }

        lptr += sizeof(vword_t);
        it.next();
    }

    return len;
}

int parse_list_se(Context* context, vword_t addr, SNode* ast)
{
    // needed space
    size_t n = ast->subnodes->numOfElements();

    size_t len = 4*VWORD_SIZE;
    size_t j = 0;
    vword_t lptr = addr + len;

    len += 2 * n * VWORD_SIZE;

    ListIterator<SNode*> it = ListIterator<SNode*>(ast->subnodes);
    while(! it.isLast())
    {
        SNode* sn = it.getCurrent();
        vword_t subaddr;
        vword_t m;

        switch(sn->type)
        {
            case SYMBOL:
            case INTEGER:
                // direcly insert word
                context->write_word(lptr + (j++)*VWORD_SIZE, VWORD_SIZE);
                parse_se(context, lptr + (j++)*VWORD_SIZE, sn);
                break;

            case LIST:
            case STRING:
                subaddr = addr+len;
                len += parse_se(context, subaddr, sn);

                m = (j == 0 || sn->type == STRING) ? VWORD_SIZE : -1;

                context->write_word(lptr + (j++)*VWORD_SIZE, m);
                context->write_word(lptr + (j++)*VWORD_SIZE, subaddr);
                break;
        }

        it.next();
    }

    vword_t v[4];
    v[0] = 3 * VWORD_SIZE;
    v[1] = resolve_symbol("deval");
    v[2] = n;
    v[3] = lptr;

    context->write(addr, 4*VWORD_SIZE, (vbyte_t*) &v);

    return len;
}

<|endoftext|>


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

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

//_________________________________________________________________________________________________________________
//  includes of other projects
//_________________________________________________________________________________________________________________

#include <vcl/menu.hxx>

#define ADDONMENU_ITEMID_START    1500
#define ADDONMENU_ITEMID_END      2000

namespace framework
{

class AddonMenu : public PopupMenu
{
    public:
                        AddonMenu( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame );
                        ~AddonMenu();

    private:
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > m_xFrame;
};

class AddonMenuManager;
class AddonPopupMenu : public PopupMenu
{
    public:
                                ~AddonPopupMenu();

        // Check if command URL string has the unique prefix to identify addon popup menus
        static sal_Bool         IsCommandURLPrefix( const rtl::OUString& aCmdURL );

        void                    SetCommandURL( const rtl::OUString& aCmdURL ) { m_aCommandURL = aCmdURL; }
        const rtl::OUString&    GetCommandURL() const { return m_aCommandURL; }

    protected:
        void                    Initialize( const com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& rAddonPopupMenuDefinition );

    private:
                                AddonPopupMenu( const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame );

        rtl::OUString                                                     m_aCommandURL;
        ::com::sun::star::uno::Reference< com::sun::star::frame::XFrame > m_xFrame;

    friend class AddonMenuManager;
};

class AddonMenuManager
{
    public:
        enum MenuType
        {
            ADDON_MENU,
            ADDON_POPUPMENU
        };

        static sal_Bool   HasAddonMenuElements();
        static sal_Bool   HasAddonHelpMenuElements();

        static sal_Bool   IsAddonMenuId( USHORT nId ) { return (( nId >= ADDONMENU_ITEMID_START ) && ( nId < ADDONMENU_ITEMID_END )); }

        // Check if the context string matches the provided xModel context
        static sal_Bool   IsCorrectContext( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& rModel, const rtl::OUString& aContext );

        // Factory method to create different Add-On menu types
        static PopupMenu* CreatePopupMenuType( MenuType eMenuType, const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame );

        // Create the Add-Ons menu
        static AddonMenu* CreateAddonMenu( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame );

        // Merge the Add-Ons help menu items into the given menu bar at a defined pos
        static void       MergeAddonHelpMenu( const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame,
                                              MenuBar* pMergeMenuBar );

        // Merge the addon popup menus into the given menu bar at the provided pos.
        static void       MergeAddonPopupMenus( const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame,
                                                const com::sun::star::uno::Reference< com::sun::star::frame::XModel >& rModel,
                                                USHORT   nMergeAtPos,
                                                MenuBar* pMergeMenuBar );

        // Returns the next position to insert a menu item/sub menu
        static USHORT     GetNextPos( USHORT nPos );

        // Build up the menu item and sub menu into the provided pCurrentMenu. The sub menus should be of type nSubMenuType.
        static void       BuildMenu( PopupMenu*  pCurrentMenu,
                                     MenuType    nSubMenuType,
                                     USHORT      nInsPos,
                                     USHORT&     nUniqueMenuId,
                                     com::sun::star::uno::Sequence< com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > > aAddonMenuDefinition,
                                     const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame,
                                     const com::sun::star::uno::Reference< com::sun::star::frame::XModel >& rModel );

        // Retrieve the menu entry property values from a sequence
        static void       GetMenuEntry( const com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& rAddonMenuEntry,
                                        ::rtl::OUString& rTitle,
                                        ::rtl::OUString& rURL,
                                        ::rtl::OUString& rTarget,
                                        ::rtl::OUString& rImageId,
                                        ::rtl::OUString& rContext,
                                        com::sun::star::uno::Sequence< com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > >& rAddonSubMenu );
};

} // namespace framework

#endif // #ifndef __FRAMEWORK_CLASSES_ADDONMENU_HXX_
<commit_msg>INTEGRATION: CWS fwk66 (1.5.298); FILE MERGED 2007/06/05 06:31:37 pb 1.5.298.2: RESYNC: (1.5-1.6); FILE MERGED 2007/06/04 11:24:22 cd 1.5.298.1: #i78020# Support merging to menu and toolbar for add-ons<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: addonmenu.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: ihi $ $Date: 2007-07-10 15:05:16 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef __FRAMEWORK_CLASSES_ADDONMENU_HXX_
#define __FRAMEWORK_CLASSES_ADDONMENU_HXX_

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

//_________________________________________________________________________________________________________________
//  includes of other projects
//_________________________________________________________________________________________________________________

#include <vcl/menu.hxx>

#define ADDONMENU_ITEMID_START       2000
#define ADDONMENU_ITEMID_END         3000

namespace framework
{

class AddonMenu : public PopupMenu
{
    public:
                        AddonMenu( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame );
                        ~AddonMenu();

    private:
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > m_xFrame;
};

class AddonMenuManager;
class AddonPopupMenu : public PopupMenu
{
    public:
                                ~AddonPopupMenu();

        // Check if command URL string has the unique prefix to identify addon popup menus
        static sal_Bool         IsCommandURLPrefix( const rtl::OUString& aCmdURL );

        void                    SetCommandURL( const rtl::OUString& aCmdURL ) { m_aCommandURL = aCmdURL; }
        const rtl::OUString&    GetCommandURL() const { return m_aCommandURL; }

    protected:
        void                    Initialize( const com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& rAddonPopupMenuDefinition );

    private:
                                AddonPopupMenu( const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame );

        rtl::OUString                                                     m_aCommandURL;
        ::com::sun::star::uno::Reference< com::sun::star::frame::XFrame > m_xFrame;

    friend class AddonMenuManager;
};

class AddonMenuManager
{
    public:
        enum MenuType
        {
            ADDON_MENU,
            ADDON_POPUPMENU
        };

        static sal_Bool   HasAddonMenuElements();
        static sal_Bool   HasAddonHelpMenuElements();

        static sal_Bool   IsAddonMenuId( USHORT nId ) { return (( nId >= ADDONMENU_ITEMID_START ) && ( nId < ADDONMENU_ITEMID_END )); }

        // Check if the context string matches the provided xModel context
        static sal_Bool   IsCorrectContext( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& rModel, const rtl::OUString& aContext );

        // Factory method to create different Add-On menu types
        static PopupMenu* CreatePopupMenuType( MenuType eMenuType, const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame );

        // Create the Add-Ons menu
        static AddonMenu* CreateAddonMenu( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame );

        // Merge the Add-Ons help menu items into the given menu bar at a defined pos
        static void       MergeAddonHelpMenu( const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame,
                                              MenuBar* pMergeMenuBar );

        // Merge the addon popup menus into the given menu bar at the provided pos.
        static void       MergeAddonPopupMenus( const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame,
                                                const com::sun::star::uno::Reference< com::sun::star::frame::XModel >& rModel,
                                                USHORT   nMergeAtPos,
                                                MenuBar* pMergeMenuBar );

        // Returns the next position to insert a menu item/sub menu
        static USHORT     GetNextPos( USHORT nPos );

        // Build up the menu item and sub menu into the provided pCurrentMenu. The sub menus should be of type nSubMenuType.
        static void       BuildMenu( PopupMenu*  pCurrentMenu,
                                     MenuType    nSubMenuType,
                                     USHORT      nInsPos,
                                     USHORT&     nUniqueMenuId,
                                     com::sun::star::uno::Sequence< com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > > aAddonMenuDefinition,
                                     const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame,
                                     const com::sun::star::uno::Reference< com::sun::star::frame::XModel >& rModel );

        // Retrieve the menu entry property values from a sequence
        static void       GetMenuEntry( const com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& rAddonMenuEntry,
                                        ::rtl::OUString& rTitle,
                                        ::rtl::OUString& rURL,
                                        ::rtl::OUString& rTarget,
                                        ::rtl::OUString& rImageId,
                                        ::rtl::OUString& rContext,
                                        com::sun::star::uno::Sequence< com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > >& rAddonSubMenu );
};

} // namespace framework

#endif // #ifndef __FRAMEWORK_CLASSES_ADDONMENU_HXX_
<|endoftext|>