<commit_before>
#include "JournalingObjectStore.h"

#include "config.h"

#define DOUT_SUBSYS journal
#undef dout_prefix
#define dout_prefix *_dout << dbeginl << "journal "

void JournalingObjectStore::journal_start()
{
  dout(10) << "journal_start" << dendl;
  finisher.start();
}

void JournalingObjectStore::journal_stop()
{
  dout(10) << "journal_stop" << dendl;
  finisher.stop();
  if (journal) {
    journal->close();
    delete journal;
    journal = 0;
  }
}

int JournalingObjectStore::journal_replay(uint64_t fs_op_seq)
{
  dout(10) << "journal_replay fs op_seq " << fs_op_seq << dendl;
  op_seq = fs_op_seq;

  if (!journal)
    return 0;

  int err = journal->open(op_seq+1);
  if (err < 0) {
    char buf[80];
    dout(3) << "journal_replay open failed with "
	    << strerror_r(-err, buf, sizeof(buf)) << dendl;
    delete journal;
    journal = 0;
    return err;
  }

  int count = 0;
  while (1) {
    bufferlist bl;
    uint64_t seq = op_seq + 1;
    if (!journal->read_entry(bl, seq)) {
      dout(3) << "journal_replay: end of journal, done." << dendl;
      break;
    }

    if (seq <= op_seq) {
      dout(3) << "journal_replay: skipping old op seq " << seq << " <= " << op_seq << dendl;
      continue;
    }
    assert(op_seq == seq-1);

    dout(3) << "journal_replay: applying op seq " << seq << " (op_seq " << op_seq << ")" << dendl;
    bufferlist::iterator p = bl.begin();
    list<Transaction*> tls;
    while (!p.end()) {
      Transaction *t = new Transaction(p);
      tls.push_back(t);
    }
    int r = apply_transactions(tls);
    while (!tls.empty()) {
      delete tls.front();
      tls.pop_front();
    }

    dout(3) << "journal_replay: r = " << r << ", op now seq " << op_seq << dendl;
    assert(op_seq == seq);
    seq++;  // we expect the next op
  }

  committed_seq = op_seq;

  // done reading, make writeable.
  journal->make_writeable();

  return count;
}

// ------------------------------------

uint64_t JournalingObjectStore::op_apply_start(uint64_t op)
{
  lock.Lock();
  while (blocked) {
    dout(10) << "op_apply_start blocked" << dendl;
    cond.Wait(lock);
  }
  open_ops++;

  if (!op)
    op = ++op_seq;
  dout(10) << "op_apply_start " << op << dendl;

  lock.Unlock();
  return op;
}

void JournalingObjectStore::op_apply_finish(uint64_t op)
{
  dout(10) << "op_apply_finish" << dendl;
  lock.Lock();
  if (--open_ops == 0)
    cond.Signal();

  // there can be multiple applies in flight; track the max value we
  // note.  note that we can't _read_ this value and learn anything
  // meaningful unless/until we've quiesced all in-flight applies.
  if (op > applied_seq)
    applied_seq = op;

  lock.Unlock();
}

uint64_t JournalingObjectStore::op_journal_start(uint64_t op)
{
  journal_lock.Lock();
  if (!op) {
    lock.Lock();
    op = ++op_seq;
    lock.Unlock();
  }
  return op;
}

void JournalingObjectStore::op_journal_finish()
{
  journal_lock.Unlock();
}

// ------------------------------------------

bool JournalingObjectStore::commit_start()
{
  // suspend new ops...
  Mutex::Locker l(lock);

  dout(10) << "commit_start" << dendl;
  blocked = true;
  while (open_ops > 0) {
    dout(10) << "commit_start blocked, waiting for " << open_ops << " open ops" << dendl;
    cond.Wait(lock);
  }

  if (op_seq == committed_seq) {
    dout(10) << "commit_start nothing to do" << dendl;
    blocked = false;
    cond.Signal();
    assert(commit_waiters.empty());
    return false;
  }

  // we can _only_ read applied_seq here because open_ops == 0 (we've
  // quiesced all in-flight applies).
  committing_seq = applied_seq;

  dout(10) << "commit_start committing " << committing_seq << ", still blocked" << dendl;
  return true;
}

void JournalingObjectStore::commit_started()
{
  Mutex::Locker l(lock);
  // allow new ops. (underlying fs should now be committing all prior ops)
  dout(10) << "commit_started committing " << committing_seq << ", unblocking" << dendl;
  blocked = false;
  cond.Signal();
}

void JournalingObjectStore::commit_finish()
{
  Mutex::Locker l(lock);
  dout(10) << "commit_finish thru " << committing_seq << dendl;

  if (journal)
    journal->committed_thru(committing_seq);
  committed_seq = committing_seq;

  map<version_t, vector<Context*> >::iterator p = commit_waiters.begin();
  while (p != commit_waiters.end() &&
	 p->first <= committing_seq) {
    finisher.queue(p->second);
    commit_waiters.erase(p++);
  }
}

void JournalingObjectStore::journal_transaction(ObjectStore::Transaction& t, uint64_t op,
						Context *onjournal)
{
  Mutex::Locker l(lock);
  dout(10) << "journal_transaction " << op << dendl;
  if (journal && journal->is_writeable()) {
    bufferlist tbl;
    t.encode(tbl);

    int alignment = -1;
    if ((int)t.get_data_length() >= g_conf.journal_align_min_size)
      alignment = t.get_data_alignment();

    journal->submit_entry(op, tbl, alignment, onjournal);
  } else if (onjournal)
    commit_waiters[op].push_back(onjournal);
}

void JournalingObjectStore::journal_transactions(list<ObjectStore::Transaction*>& tls, uint64_t op,
						 Context *onjournal)
{
  Mutex::Locker l(lock);
  dout(10) << "journal_transactions " << op << dendl;

  if (journal && journal->is_writeable()) {
    bufferlist tbl;
    unsigned data_len = 0, data_align = 0;
    for (list<ObjectStore::Transaction*>::iterator p = tls.begin(); p != tls.end(); p++) {
      ObjectStore::Transaction *t = *p;
      if (t->get_data_length() > data_len &&
	  (int)t->get_data_length() >= g_conf.journal_align_min_size) {
	data_len = t->get_data_length();
	data_align = (t->get_data_alignment() - tbl.length()) & ~PAGE_MASK;
      }
      t->encode(tbl);
    }
    journal->submit_entry(op, tbl, data_align, onjournal);
  } else if (onjournal)
    commit_waiters[op].push_back(onjournal);
}
<commit_msg>journal: initialize applied_seq during journal replay<commit_after>
#include "JournalingObjectStore.h"

#include "config.h"

#define DOUT_SUBSYS journal
#undef dout_prefix
#define dout_prefix *_dout << dbeginl << "journal "

void JournalingObjectStore::journal_start()
{
  dout(10) << "journal_start" << dendl;
  finisher.start();
}

void JournalingObjectStore::journal_stop()
{
  dout(10) << "journal_stop" << dendl;
  finisher.stop();
  if (journal) {
    journal->close();
    delete journal;
    journal = 0;
  }
}

int JournalingObjectStore::journal_replay(uint64_t fs_op_seq)
{
  dout(10) << "journal_replay fs op_seq " << fs_op_seq << dendl;
  op_seq = fs_op_seq;
  committed_seq = op_seq;
  applied_seq = fs_op_seq;

  if (!journal)
    return 0;

  int err = journal->open(op_seq+1);
  if (err < 0) {
    char buf[80];
    dout(3) << "journal_replay open failed with "
	    << strerror_r(-err, buf, sizeof(buf)) << dendl;
    delete journal;
    journal = 0;
    return err;
  }

  int count = 0;
  while (1) {
    bufferlist bl;
    uint64_t seq = op_seq + 1;
    if (!journal->read_entry(bl, seq)) {
      dout(3) << "journal_replay: end of journal, done." << dendl;
      break;
    }

    if (seq <= op_seq) {
      dout(3) << "journal_replay: skipping old op seq " << seq << " <= " << op_seq << dendl;
      continue;
    }
    assert(op_seq == seq-1);

    dout(3) << "journal_replay: applying op seq " << seq << " (op_seq " << op_seq << ")" << dendl;
    bufferlist::iterator p = bl.begin();
    list<Transaction*> tls;
    while (!p.end()) {
      Transaction *t = new Transaction(p);
      tls.push_back(t);
    }
    int r = apply_transactions(tls);
    while (!tls.empty()) {
      delete tls.front();
      tls.pop_front();
    }

    dout(3) << "journal_replay: r = " << r << ", op now seq " << op_seq << dendl;
    assert(op_seq == seq);
    seq++;  // we expect the next op
  }

  committed_seq = op_seq;
  applied_seq = op_seq;

  // done reading, make writeable.
  journal->make_writeable();

  return count;
}

// ------------------------------------

uint64_t JournalingObjectStore::op_apply_start(uint64_t op)
{
  lock.Lock();
  while (blocked) {
    dout(10) << "op_apply_start blocked" << dendl;
    cond.Wait(lock);
  }
  open_ops++;

  if (!op)
    op = ++op_seq;
  dout(10) << "op_apply_start " << op << dendl;

  lock.Unlock();
  return op;
}

void JournalingObjectStore::op_apply_finish(uint64_t op)
{
  dout(10) << "op_apply_finish" << dendl;
  lock.Lock();
  if (--open_ops == 0)
    cond.Signal();

  // there can be multiple applies in flight; track the max value we
  // note.  note that we can't _read_ this value and learn anything
  // meaningful unless/until we've quiesced all in-flight applies.
  if (op > applied_seq)
    applied_seq = op;

  lock.Unlock();
}

uint64_t JournalingObjectStore::op_journal_start(uint64_t op)
{
  journal_lock.Lock();
  if (!op) {
    lock.Lock();
    op = ++op_seq;
    lock.Unlock();
  }
  return op;
}

void JournalingObjectStore::op_journal_finish()
{
  journal_lock.Unlock();
}

// ------------------------------------------

bool JournalingObjectStore::commit_start()
{
  // suspend new ops...
  Mutex::Locker l(lock);

  dout(10) << "commit_start" << dendl;
  blocked = true;
  while (open_ops > 0) {
    dout(10) << "commit_start blocked, waiting for " << open_ops << " open ops" << dendl;
    cond.Wait(lock);
  }

  if (op_seq == committed_seq) {
    dout(10) << "commit_start nothing to do" << dendl;
    blocked = false;
    cond.Signal();
    assert(commit_waiters.empty());
    return false;
  }

  // we can _only_ read applied_seq here because open_ops == 0 (we've
  // quiesced all in-flight applies).
  committing_seq = applied_seq;

  dout(10) << "commit_start committing " << committing_seq << ", still blocked" << dendl;
  return true;
}

void JournalingObjectStore::commit_started()
{
  Mutex::Locker l(lock);
  // allow new ops. (underlying fs should now be committing all prior ops)
  dout(10) << "commit_started committing " << committing_seq << ", unblocking" << dendl;
  blocked = false;
  cond.Signal();
}

void JournalingObjectStore::commit_finish()
{
  Mutex::Locker l(lock);
  dout(10) << "commit_finish thru " << committing_seq << dendl;

  if (journal)
    journal->committed_thru(committing_seq);
  committed_seq = committing_seq;

  map<version_t, vector<Context*> >::iterator p = commit_waiters.begin();
  while (p != commit_waiters.end() &&
	 p->first <= committing_seq) {
    finisher.queue(p->second);
    commit_waiters.erase(p++);
  }
}

void JournalingObjectStore::journal_transaction(ObjectStore::Transaction& t, uint64_t op,
						Context *onjournal)
{
  Mutex::Locker l(lock);
  dout(10) << "journal_transaction " << op << dendl;
  if (journal && journal->is_writeable()) {
    bufferlist tbl;
    t.encode(tbl);

    int alignment = -1;
    if ((int)t.get_data_length() >= g_conf.journal_align_min_size)
      alignment = t.get_data_alignment();

    journal->submit_entry(op, tbl, alignment, onjournal);
  } else if (onjournal)
    commit_waiters[op].push_back(onjournal);
}

void JournalingObjectStore::journal_transactions(list<ObjectStore::Transaction*>& tls, uint64_t op,
						 Context *onjournal)
{
  Mutex::Locker l(lock);
  dout(10) << "journal_transactions " << op << dendl;

  if (journal && journal->is_writeable()) {
    bufferlist tbl;
    unsigned data_len = 0, data_align = 0;
    for (list<ObjectStore::Transaction*>::iterator p = tls.begin(); p != tls.end(); p++) {
      ObjectStore::Transaction *t = *p;
      if (t->get_data_length() > data_len &&
	  (int)t->get_data_length() >= g_conf.journal_align_min_size) {
	data_len = t->get_data_length();
	data_align = (t->get_data_alignment() - tbl.length()) & ~PAGE_MASK;
      }
      t->encode(tbl);
    }
    journal->submit_entry(op, tbl, data_align, onjournal);
  } else if (onjournal)
    commit_waiters[op].push_back(onjournal);
}
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the  "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Class header file.

// Base include file.  Must be first.
#include <xalanc/PlatformSupport/PlatformSupportDefinitions.hpp>

#include <xalanc/PlatformSupport/DOMStringHelper.hpp>
#include <xalanc/PlatformSupport/XalanMessageLoader.hpp>

#include <xalanc/Utils/XalanMsgLib/XalanMsgLib.hpp>

#include <xercesc/util/XMLString.hpp>

#if defined (XALAN_INMEM_MSG_LOADER)
#include <xalanc/PlatformSupport/XalanInMemoryMessageLoader.hpp>
#elif defined (XALAN_ICU_MSG_LOADER)
#include <xalanc/PlatformSupport/XalanICUMessageLoader.hpp>
#elif defined (XALAN_NLS_MSG_LOADER)
#include <xalanc/PlatformSupport/XalanNLSMessageLoader.hpp>
#else
#error You must provide a message loader
#endif

XALAN_CPP_NAMESPACE_BEGIN

#define MAX_MESSAGE_LEN 1024

XalanMessageLoader*     XalanMessageLoader::s_msgLoader = 0;

static MemoryManager*      s_initManager;

XalanMessageLoader::~XalanMessageLoader()
{
}

void
XalanMessageLoader::initialize(MemoryManager&      theManager)
{
#if defined (XALAN_INMEM_MSG_LOADER)
        typedef XalanMessageLoader::XalanMessageLoaderCreateFunct <XalanInMemoryMessageLoader> LoaderCreatorType;
#elif defined (XALAN_ICU_MSG_LOADER)
        typedef XalanMessageLoader::XalanMessageLoaderCreateFunct <XalanICUMessageLoader> LoaderCreatorType;
#elif defined (XALAN_NLS_MSG_LOADER)
        typedef XalanMessageLoader::XalanMessageLoaderCreateFunct <XalanNLSMessageLoader> LoaderCreatorType;
#else
#error You must provide a message loader
#endif

    if (s_msgLoader == 0)
    {
        s_initManager = &theManager;

        s_msgLoader = LoaderCreatorType()(theManager);
    }

    assert(s_msgLoader != 0);
}

void
XalanMessageLoader::terminate()
{

    typedef XalanMessageLoader::XalanMessageLoaderDestructFunct LoaderDestructType;

    assert(s_initManager != 0);

    LoaderDestructType()(*s_initManager, s_msgLoader);

    s_msgLoader = 0;
}

XalanDOMString&
XalanMessageLoader::getMessage(
            XalanDOMString&         theResultMessage,
            XalanMessages::Codes    msgToLoad,
            const XalanDOMString&   repText1 )
{
    assert(s_msgLoader != 0);

    XalanDOMChar    sBuffer[MAX_MESSAGE_LEN];

    s_msgLoader->load(
        msgToLoad,
        theResultMessage.getMemoryManager(),
        sBuffer,
        MAX_MESSAGE_LEN,
        repText1.c_str());

    theResultMessage.assign(sBuffer);

    return theResultMessage;
}

XalanDOMString&
XalanMessageLoader::getMessage(
            XalanDOMString&         theResultMessage,
            XalanMessages::Codes    msgToLoad,
            const XalanDOMString&   repText1,
            const XalanDOMString&   repText2)
{
    assert(s_msgLoader != 0);

    XalanDOMChar    sBuffer[MAX_MESSAGE_LEN];

    s_msgLoader->load(
        msgToLoad,
        theResultMessage.getMemoryManager(),
        sBuffer,
        MAX_MESSAGE_LEN,
        repText1.c_str(),
        repText2.c_str());

    theResultMessage.assign(sBuffer);

    return theResultMessage;
}

XalanDOMString&
XalanMessageLoader::getMessage(
            XalanDOMString&         theResultMessage,
            XalanMessages::Codes    msgToLoad,
            const XalanDOMString&   repText1 ,
            const XalanDOMString&   repText2 ,
            const XalanDOMString&   repText3)
{
    assert(s_msgLoader != 0);

    XalanDOMChar    sBuffer[MAX_MESSAGE_LEN];

    s_msgLoader->load(
        msgToLoad,
        theResultMessage.getMemoryManager(),
        sBuffer,
        MAX_MESSAGE_LEN,
        repText1.c_str(),
        repText2.c_str(),
        repText3.c_str());

    theResultMessage.assign(sBuffer);

    return theResultMessage;
}

XalanDOMString&
XalanMessageLoader::getMessage(
            XalanDOMString&         theResultMessage,
            XalanMessages::Codes    msgToLoad)

{
    assert(s_msgLoader != 0);

    XalanDOMChar    sBuffer[MAX_MESSAGE_LEN];

    s_msgLoader->loadMsg(msgToLoad,
                            sBuffer,
                            MAX_MESSAGE_LEN) ;

    theResultMessage.assign(sBuffer);

    return theResultMessage;
}

bool
XalanMessageLoader::load(
            XalanMessages::Codes    msgToLoad,
            MemoryManager&          theMemoryManager,
            XalanDOMChar*           toFill,
            XalanSize_t             maxChars,
            const XalanDOMChar*     repText1,
            const XalanDOMChar*     repText2,
            const XalanDOMChar*     repText3,
            const XalanDOMChar*     repText4)
{
    // Call the other version to load up the message
    if (!loadMsg(msgToLoad, toFill, maxChars))
        return false;

    XALAN_USING_XERCES(XMLString)

    // And do the token replacement
    XMLString::replaceTokens(
        toFill,
        maxChars,
        repText1,
        repText2,
        repText3,
        repText4,
        &theMemoryManager);

    return true;
}

XalanDOMString&
XalanMessageLoader::getMessage(
            XalanDOMString&         theResultMessage,
            XalanMessages::Codes    msgToLoad,
            const char*             repText1,
            const char*             repText2,
            const char*             repText3,
            const char*             repText4)
{
    XalanDOMChar    sBuffer[MAX_MESSAGE_LEN];

    s_msgLoader->load(
        msgToLoad,
        theResultMessage.getMemoryManager(),
        sBuffer,
        MAX_MESSAGE_LEN,
        repText1,
        repText2,
        repText3,
        repText4);

    theResultMessage.assign(sBuffer);

    return theResultMessage;
}

XalanDOMString&
XalanMessageLoader::getMessage(
            XalanDOMString&         theResultMessage,
            XalanMessages::Codes    msgToLoad,
            const XalanDOMChar*     repText1,
            const XalanDOMChar*     repText2,
            const XalanDOMChar*     repText3,
            const XalanDOMChar*     repText4)
{
    XalanDOMChar    sBuffer[MAX_MESSAGE_LEN];

    s_msgLoader->load(
        msgToLoad,
        theResultMessage.getMemoryManager(),
        sBuffer,
        MAX_MESSAGE_LEN,
        repText1,
        repText2,
        repText3,
        repText4);

    theResultMessage.assign(sBuffer);

    return theResultMessage;
}

bool
XalanMessageLoader::load(
            XalanMessages::Codes    msgToLoad,
            MemoryManager&      theManager,
            XalanDOMChar*           toFill,
            XalanSize_t             maxChars,
            const char*             repText1,
            const char*             repText2,
            const char*             repText3,
            const char*             repText4)
{
    XalanDOMString theFirstParam(theManager);
    if (repText1 != 0)
    {
        theFirstParam.assign(repText1);
    }

    XalanDOMString theSecParam(theManager);
    if (repText2 != 0)
    {
        theSecParam.assign(repText2);
    }

    XalanDOMString theThirdParam(theManager);
    if( repText3 != 0)
    {
        theThirdParam.assign(repText3);
    }

    XalanDOMString theForthParam(theManager);
    if (repText4 != 0)
    {
        theForthParam.assign(repText4);
    }

    return load(
                msgToLoad,
                theManager,
                toFill,
                maxChars,
                theFirstParam.c_str(),
                theSecParam.c_str(),
                theThirdParam.c_str(),
                theForthParam.c_str());
}

XALAN_CPP_NAMESPACE_END
<commit_msg>Fixed buffer overflow problem with XMLString::replaceTokens. See XALANC-698.<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the  "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Class header file.

// Base include file.  Must be first.
#include <xalanc/PlatformSupport/PlatformSupportDefinitions.hpp>

#include <xalanc/PlatformSupport/DOMStringHelper.hpp>
#include <xalanc/PlatformSupport/XalanMessageLoader.hpp>

#include <xalanc/Utils/XalanMsgLib/XalanMsgLib.hpp>

#include <xercesc/util/XMLString.hpp>

#if defined (XALAN_INMEM_MSG_LOADER)
#include <xalanc/PlatformSupport/XalanInMemoryMessageLoader.hpp>
#elif defined (XALAN_ICU_MSG_LOADER)
#include <xalanc/PlatformSupport/XalanICUMessageLoader.hpp>
#elif defined (XALAN_NLS_MSG_LOADER)
#include <xalanc/PlatformSupport/XalanNLSMessageLoader.hpp>
#else
#error You must provide a message loader
#endif

XALAN_CPP_NAMESPACE_BEGIN

static const size_t kMaxMessageLength = 1024;

XalanMessageLoader*     XalanMessageLoader::s_msgLoader = 0;

static MemoryManager*      s_initManager;

XalanMessageLoader::~XalanMessageLoader()
{
}

void
XalanMessageLoader::initialize(MemoryManager&      theManager)
{
#if defined (XALAN_INMEM_MSG_LOADER)
        typedef XalanMessageLoader::XalanMessageLoaderCreateFunct <XalanInMemoryMessageLoader> LoaderCreatorType;
#elif defined (XALAN_ICU_MSG_LOADER)
        typedef XalanMessageLoader::XalanMessageLoaderCreateFunct <XalanICUMessageLoader> LoaderCreatorType;
#elif defined (XALAN_NLS_MSG_LOADER)
        typedef XalanMessageLoader::XalanMessageLoaderCreateFunct <XalanNLSMessageLoader> LoaderCreatorType;
#else
#error You must provide a message loader
#endif

    if (s_msgLoader == 0)
    {
        s_initManager = &theManager;

        s_msgLoader = LoaderCreatorType()(theManager);
    }

    assert(s_msgLoader != 0);
}

void
XalanMessageLoader::terminate()
{

    typedef XalanMessageLoader::XalanMessageLoaderDestructFunct LoaderDestructType;

    assert(s_initManager != 0);

    LoaderDestructType()(*s_initManager, s_msgLoader);

    s_msgLoader = 0;
}

XalanDOMString&
XalanMessageLoader::getMessage(
            XalanDOMString&         theResultMessage,
            XalanMessages::Codes    msgToLoad,
            const XalanDOMString&   repText1 )
{
    assert(s_msgLoader != 0);

    XalanDOMChar    sBuffer[kMaxMessageLength + 1];

    s_msgLoader->load(
        msgToLoad,
        theResultMessage.getMemoryManager(),
        sBuffer,
        kMaxMessageLength,
        repText1.c_str());

    theResultMessage.assign(sBuffer);

    return theResultMessage;
}

XalanDOMString&
XalanMessageLoader::getMessage(
            XalanDOMString&         theResultMessage,
            XalanMessages::Codes    msgToLoad,
            const XalanDOMString&   repText1,
            const XalanDOMString&   repText2)
{
    assert(s_msgLoader != 0);

    XalanDOMChar    sBuffer[kMaxMessageLength + 1];

    s_msgLoader->load(
        msgToLoad,
        theResultMessage.getMemoryManager(),
        sBuffer,
        kMaxMessageLength,
        repText1.c_str(),
        repText2.c_str());

    theResultMessage.assign(sBuffer);

    return theResultMessage;
}

XalanDOMString&
XalanMessageLoader::getMessage(
            XalanDOMString&         theResultMessage,
            XalanMessages::Codes    msgToLoad,
            const XalanDOMString&   repText1 ,
            const XalanDOMString&   repText2 ,
            const XalanDOMString&   repText3)
{
    assert(s_msgLoader != 0);

    XalanDOMChar    sBuffer[kMaxMessageLength + 1];

    s_msgLoader->load(
        msgToLoad,
        theResultMessage.getMemoryManager(),
        sBuffer,
        kMaxMessageLength,
        repText1.c_str(),
        repText2.c_str(),
        repText3.c_str());

    theResultMessage.assign(sBuffer);

    return theResultMessage;
}

XalanDOMString&
XalanMessageLoader::getMessage(
            XalanDOMString&         theResultMessage,
            XalanMessages::Codes    msgToLoad)

{
    assert(s_msgLoader != 0);

    XalanDOMChar    sBuffer[kMaxMessageLength + 1];

    s_msgLoader->loadMsg(msgToLoad,
                            sBuffer,
                            kMaxMessageLength) ;

    theResultMessage.assign(sBuffer);

    return theResultMessage;
}

bool
XalanMessageLoader::load(
            XalanMessages::Codes    msgToLoad,
            MemoryManager&          theMemoryManager,
            XalanDOMChar*           toFill,
            XalanSize_t             maxChars,
            const XalanDOMChar*     repText1,
            const XalanDOMChar*     repText2,
            const XalanDOMChar*     repText3,
            const XalanDOMChar*     repText4)
{
    // Call the other version to load up the message
    if (!loadMsg(msgToLoad, toFill, maxChars))
        return false;

    XALAN_USING_XERCES(XMLString)

    // And do the token replacement
    XMLString::replaceTokens(
        toFill,
        maxChars,
        repText1,
        repText2,
        repText3,
        repText4,
        &theMemoryManager);

    return true;
}

XalanDOMString&
XalanMessageLoader::getMessage(
            XalanDOMString&         theResultMessage,
            XalanMessages::Codes    msgToLoad,
            const char*             repText1,
            const char*             repText2,
            const char*             repText3,
            const char*             repText4)
{
    XalanDOMChar    sBuffer[kMaxMessageLength + 1];

    s_msgLoader->load(
        msgToLoad,
        theResultMessage.getMemoryManager(),
        sBuffer,
        kMaxMessageLength,
        repText1,
        repText2,
        repText3,
        repText4);

    theResultMessage.assign(sBuffer);

    return theResultMessage;
}

XalanDOMString&
XalanMessageLoader::getMessage(
            XalanDOMString&         theResultMessage,
            XalanMessages::Codes    msgToLoad,
            const XalanDOMChar*     repText1,
            const XalanDOMChar*     repText2,
            const XalanDOMChar*     repText3,
            const XalanDOMChar*     repText4)
{
    XalanDOMChar    sBuffer[kMaxMessageLength + 1];

    s_msgLoader->load(
        msgToLoad,
        theResultMessage.getMemoryManager(),
        sBuffer,
        kMaxMessageLength,
        repText1,
        repText2,
        repText3,
        repText4);

    theResultMessage.assign(sBuffer);

    return theResultMessage;
}

bool
XalanMessageLoader::load(
            XalanMessages::Codes    msgToLoad,
            MemoryManager&      theManager,
            XalanDOMChar*           toFill,
            XalanSize_t             maxChars,
            const char*             repText1,
            const char*             repText2,
            const char*             repText3,
            const char*             repText4)
{
    XalanDOMString theFirstParam(theManager);
    if (repText1 != 0)
    {
        theFirstParam.assign(repText1);
    }

    XalanDOMString theSecParam(theManager);
    if (repText2 != 0)
    {
        theSecParam.assign(repText2);
    }

    XalanDOMString theThirdParam(theManager);
    if( repText3 != 0)
    {
        theThirdParam.assign(repText3);
    }

    XalanDOMString theForthParam(theManager);
    if (repText4 != 0)
    {
        theForthParam.assign(repText4);
    }

    return load(
                msgToLoad,
                theManager,
                toFill,
                maxChars,
                theFirstParam.c_str(),
                theSecParam.c_str(),
                theThirdParam.c_str(),
                theForthParam.c_str());
}

XALAN_CPP_NAMESPACE_END
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include <arrow-glib/buffer.hpp>
#include <arrow-glib/data-type.hpp>
#include <arrow-glib/tensor.hpp>
#include <arrow-glib/type.hpp>

G_BEGIN_DECLS

/**
 * SECTION: tensor
 * @short_description: Tensor class.
 * @include: arrow-glib/arrow-glib.h
 *
 * #GArrowTensor is a tensor class.
 *
 * Since: 0.3.0
 */

typedef struct GArrowTensorPrivate_ {
  std::shared_ptr<arrow::Tensor> tensor;
} GArrowTensorPrivate;

enum {
  PROP_0,
  PROP_TENSOR
};

G_DEFINE_TYPE_WITH_PRIVATE(GArrowTensor, garrow_tensor, G_TYPE_OBJECT)

#define GARROW_TENSOR_GET_PRIVATE(obj)                                   \
  (G_TYPE_INSTANCE_GET_PRIVATE((obj), GARROW_TYPE_TENSOR, GArrowTensorPrivate))

static void
garrow_tensor_finalize(GObject *object)
{
  auto priv = GARROW_TENSOR_GET_PRIVATE(object);

  priv->tensor = nullptr;

  G_OBJECT_CLASS(garrow_tensor_parent_class)->finalize(object);
}

static void
garrow_tensor_set_property(GObject *object,
                          guint prop_id,
                          const GValue *value,
                          GParamSpec *pspec)
{
  auto priv = GARROW_TENSOR_GET_PRIVATE(object);

  switch (prop_id) {
  case PROP_TENSOR:
    priv->tensor =
      *static_cast<std::shared_ptr<arrow::Tensor> *>(g_value_get_pointer(value));
    break;
  default:
    G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
    break;
  }
}

static void
garrow_tensor_get_property(GObject *object,
                          guint prop_id,
                          GValue *value,
                          GParamSpec *pspec)
{
  switch (prop_id) {
  default:
    G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
    break;
  }
}

static void
garrow_tensor_init(GArrowTensor *object)
{
}

static void
garrow_tensor_class_init(GArrowTensorClass *klass)
{
  GParamSpec *spec;

  auto gobject_class = G_OBJECT_CLASS(klass);

  gobject_class->finalize     = garrow_tensor_finalize;
  gobject_class->set_property = garrow_tensor_set_property;
  gobject_class->get_property = garrow_tensor_get_property;

  spec = g_param_spec_pointer("tensor",
                              "Tensor",
                              "The raw std::shared<arrow::Tensor> *",
                              static_cast<GParamFlags>(G_PARAM_WRITABLE |
                                                       G_PARAM_CONSTRUCT_ONLY));
  g_object_class_install_property(gobject_class, PROP_TENSOR, spec);
}

/**
 * garrow_tensor_new:
 * @data_type: A #GArrowDataType that indicates each element type
 *   in the tensor.
 * @data: A #GArrowBuffer that contains tensor data.
 * @shape: (array length=n_dimensions): A list of dimension sizes.
 * @n_dimensions: The number of dimensions.
 * @strides: (array length=n_strides) (nullable): A list of the number of
 *   bytes in each dimension.
 * @n_strides: The number of strides.
 * @dimention_names: (array length=n_dimention_names) (nullable): A list of
 *   dimension names.
 * @n_dimention_names: The number of dimension names
 *
 * Returns: The newly created #GArrowTensor.
 *
 * Since: 0.3.0
 */
GArrowTensor *
garrow_tensor_new(GArrowDataType *data_type,
                  GArrowBuffer *data,
                  gint64 *shape,
                  gsize n_dimensions,
                  gint64 *strides,
                  gsize n_strides,
                  gchar **dimension_names,
                  gsize n_dimension_names)
{
  auto arrow_data_type = garrow_data_type_get_raw(data_type);
  auto arrow_data = garrow_buffer_get_raw(data);
  std::vector<int64_t> arrow_shape;
  for (gsize i = 0; i < n_dimensions; ++i) {
    arrow_shape.push_back(shape[i]);
  }
  std::vector<int64_t> arrow_strides;
  for (gsize i = 0; i < n_strides; ++i) {
    arrow_strides.push_back(strides[i]);
  }
  std::vector<std::string> arrow_dimension_names;
  for (gsize i = 0; i < n_dimension_names; ++i) {
    arrow_dimension_names.push_back(dimension_names[i]);
  }
  auto arrow_tensor =
    std::make_shared<arrow::Tensor>(arrow_data_type,
                                    arrow_data,
                                    arrow_shape,
                                    arrow_strides,
                                    arrow_dimension_names);
  auto tensor = garrow_tensor_new_raw(&arrow_tensor);
  return tensor;
}

/**
 * garrow_tensor_get_value_data_type:
 * @tensor: A #GArrowTensor.
 *
 * Returns: (transfer full): The data type of each value in the tensor.
 *
 * Since: 0.3.0
 */
GArrowDataType *
garrow_tensor_get_value_data_type(GArrowTensor *tensor)
{
  auto arrow_tensor = garrow_tensor_get_raw(tensor);
  auto arrow_data_type = arrow_tensor->type();
  return garrow_data_type_new_raw(&arrow_data_type);
}

/**
 * garrow_tensor_get_value_type:
 * @tensor: A #GArrowTensor.
 *
 * Returns: The type of each value in the tensor.
 *
 * Since: 0.3.0
 */
GArrowType
garrow_tensor_get_value_type(GArrowTensor *tensor)
{
  auto arrow_tensor = garrow_tensor_get_raw(tensor);
  auto arrow_type = arrow_tensor->type_id();
  return garrow_type_from_raw(arrow_type);
}

/**
 * garrow_tensor_get_buffer:
 * @tensor: A #GArrowTensor.
 *
 * Returns: (transfer full): The data of the tensor.
 *
 * Since: 0.3.0
 */
GArrowBuffer *
garrow_tensor_get_buffer(GArrowTensor *tensor)
{
  auto arrow_tensor = garrow_tensor_get_raw(tensor);
  auto arrow_buffer = arrow_tensor->data();
  return garrow_buffer_new_raw(&arrow_buffer);
}

/**
 * garrow_tensor_get_shape:
 * @tensor: A #GArrowTensor.
 * @n_dimensions: (out): The number of dimensions.
 *
 * Returns: (array length=n_dimensions): The shape of the tensor.
 *   It should be freed with g_free() when no longer needed.
 *
 * Since: 0.3.0
 */
gint64 *
garrow_tensor_get_shape(GArrowTensor *tensor, gint *n_dimensions)
{
  auto arrow_tensor = garrow_tensor_get_raw(tensor);
  auto arrow_shape = arrow_tensor->shape();
  auto n_dimensions_raw = arrow_shape.size();
  auto shape =
    static_cast<gint64 *>(g_malloc_n(sizeof(gint64), n_dimensions_raw));
  for (gsize i = 0; i < n_dimensions_raw; ++i) {
    shape[i] = arrow_shape[i];
  }
  *n_dimensions = static_cast<gint>(n_dimensions_raw);
  return shape;
}

/**
 * garrow_tensor_get_strides:
 * @tensor: A #GArrowTensor.
 * @n_strides: (out): The number of strides.
 *
 * Returns: (array length=n_strides): The strides of the tensor.
 *   It should be freed with g_free() when no longer needed.
 *
 * Since: 0.3.0
 */
gint64 *
garrow_tensor_get_strides(GArrowTensor *tensor, gint *n_strides)
{
  auto arrow_tensor = garrow_tensor_get_raw(tensor);
  auto arrow_strides = arrow_tensor->strides();
  auto n_strides_raw = arrow_strides.size();
  auto strides =
    static_cast<gint64 *>(g_malloc_n(sizeof(gint64), n_strides_raw));
  for (gsize i = 0; i < n_strides_raw; ++i) {
    strides[i] = arrow_strides[i];
  }
  *n_strides = static_cast<gint>(n_strides_raw);
  return strides;
}

/**
 * garrow_tensor_get_n_dimensions:
 * @tensor: A #GArrowTensor.
 *
 * Returns: The number of dimensions of the tensor.
 *
 * Since: 0.3.0
 */
gint
garrow_tensor_get_n_dimensions(GArrowTensor *tensor)
{
  auto arrow_tensor = garrow_tensor_get_raw(tensor);
  return arrow_tensor->ndim();
}

/**
 * garrow_tensor_get_dimension_name:
 * @tensor: A #GArrowTensor.
 * @i: The index of the target dimension.
 *
 * Returns: The i-th dimension name of the tensor.
 *
 * Since: 0.3.0
 */
const gchar *
garrow_tensor_get_dimension_name(GArrowTensor *tensor, gint i)
{
  auto arrow_tensor = garrow_tensor_get_raw(tensor);
  auto arrow_dimension_name = arrow_tensor->dim_name(i);
  return arrow_dimension_name.c_str();
}

/**
 * garrow_tensor_get_size:
 * @tensor: A #GArrowTensor.
 *
 * Returns: The number of value cells in the tensor.
 *
 * Since: 0.3.0
 */
gint64
garrow_tensor_get_size(GArrowTensor *tensor)
{
  auto arrow_tensor = garrow_tensor_get_raw(tensor);
  return arrow_tensor->size();
}

/**
 * garrow_tensor_is_mutable:
 * @tensor: A #GArrowTensor.
 *
 * Returns: %TRUE if the tensor is mutable, %FALSE otherwise.
 *
 * Since: 0.3.0
 */
gboolean
garrow_tensor_is_mutable(GArrowTensor *tensor)
{
  auto arrow_tensor = garrow_tensor_get_raw(tensor);
  return arrow_tensor->is_mutable();
}

/**
 * garrow_tensor_is_contiguous:
 * @tensor: A #GArrowTensor.
 *
 * Returns: %TRUE if the tensor is contiguous, %FALSE otherwise.
 *
 * Since: 0.3.0
 */
gboolean
garrow_tensor_is_contiguous(GArrowTensor *tensor)
{
  auto arrow_tensor = garrow_tensor_get_raw(tensor);
  return arrow_tensor->is_contiguous();
}

/**
 * garrow_tensor_is_row_major:
 * @tensor: A #GArrowTensor.
 *
 * Returns: %TRUE if the tensor is row major a.k.a. C order,
 *   %FALSE otherwise.
 *
 * Since: 0.3.0
 */
gboolean
garrow_tensor_is_row_major(GArrowTensor *tensor)
{
  auto arrow_tensor = garrow_tensor_get_raw(tensor);
  return arrow_tensor->is_row_major();
}

/**
 * garrow_tensor_is_column_major:
 * @tensor: A #GArrowTensor.
 *
 * Returns: %TRUE if the tensor is column major a.k.a. Fortran order,
 *   %FALSE otherwise.
 *
 * Since: 0.3.0
 */
gboolean
garrow_tensor_is_column_major(GArrowTensor *tensor)
{
  auto arrow_tensor = garrow_tensor_get_raw(tensor);
  return arrow_tensor->is_column_major();
}

G_END_DECLS

GArrowTensor *
garrow_tensor_new_raw(std::shared_ptr<arrow::Tensor> *arrow_tensor)
{
  auto tensor = GARROW_TENSOR(g_object_new(GARROW_TYPE_TENSOR,
                                           "tensor", arrow_tensor,
                                           NULL));
  return tensor;
}

std::shared_ptr<arrow::Tensor>
garrow_tensor_get_raw(GArrowTensor *tensor)
{
  auto priv = GARROW_TENSOR_GET_PRIVATE(tensor);
  return priv->tensor;
}
<commit_msg>ARROW-903: [GLib] Remove a needless "."<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include <arrow-glib/buffer.hpp>
#include <arrow-glib/data-type.hpp>
#include <arrow-glib/tensor.hpp>
#include <arrow-glib/type.hpp>

G_BEGIN_DECLS

/**
 * SECTION: tensor
 * @short_description: Tensor class
 * @include: arrow-glib/arrow-glib.h
 *
 * #GArrowTensor is a tensor class.
 *
 * Since: 0.3.0
 */

typedef struct GArrowTensorPrivate_ {
  std::shared_ptr<arrow::Tensor> tensor;
} GArrowTensorPrivate;

enum {
  PROP_0,
  PROP_TENSOR
};

G_DEFINE_TYPE_WITH_PRIVATE(GArrowTensor, garrow_tensor, G_TYPE_OBJECT)

#define GARROW_TENSOR_GET_PRIVATE(obj)                                   \
  (G_TYPE_INSTANCE_GET_PRIVATE((obj), GARROW_TYPE_TENSOR, GArrowTensorPrivate))

static void
garrow_tensor_finalize(GObject *object)
{
  auto priv = GARROW_TENSOR_GET_PRIVATE(object);

  priv->tensor = nullptr;

  G_OBJECT_CLASS(garrow_tensor_parent_class)->finalize(object);
}

static void
garrow_tensor_set_property(GObject *object,
                          guint prop_id,
                          const GValue *value,
                          GParamSpec *pspec)
{
  auto priv = GARROW_TENSOR_GET_PRIVATE(object);

  switch (prop_id) {
  case PROP_TENSOR:
    priv->tensor =
      *static_cast<std::shared_ptr<arrow::Tensor> *>(g_value_get_pointer(value));
    break;
  default:
    G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
    break;
  }
}

static void
garrow_tensor_get_property(GObject *object,
                          guint prop_id,
                          GValue *value,
                          GParamSpec *pspec)
{
  switch (prop_id) {
  default:
    G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
    break;
  }
}

static void
garrow_tensor_init(GArrowTensor *object)
{
}

static void
garrow_tensor_class_init(GArrowTensorClass *klass)
{
  GParamSpec *spec;

  auto gobject_class = G_OBJECT_CLASS(klass);

  gobject_class->finalize     = garrow_tensor_finalize;
  gobject_class->set_property = garrow_tensor_set_property;
  gobject_class->get_property = garrow_tensor_get_property;

  spec = g_param_spec_pointer("tensor",
                              "Tensor",
                              "The raw std::shared<arrow::Tensor> *",
                              static_cast<GParamFlags>(G_PARAM_WRITABLE |
                                                       G_PARAM_CONSTRUCT_ONLY));
  g_object_class_install_property(gobject_class, PROP_TENSOR, spec);
}

/**
 * garrow_tensor_new:
 * @data_type: A #GArrowDataType that indicates each element type
 *   in the tensor.
 * @data: A #GArrowBuffer that contains tensor data.
 * @shape: (array length=n_dimensions): A list of dimension sizes.
 * @n_dimensions: The number of dimensions.
 * @strides: (array length=n_strides) (nullable): A list of the number of
 *   bytes in each dimension.
 * @n_strides: The number of strides.
 * @dimention_names: (array length=n_dimention_names) (nullable): A list of
 *   dimension names.
 * @n_dimention_names: The number of dimension names
 *
 * Returns: The newly created #GArrowTensor.
 *
 * Since: 0.3.0
 */
GArrowTensor *
garrow_tensor_new(GArrowDataType *data_type,
                  GArrowBuffer *data,
                  gint64 *shape,
                  gsize n_dimensions,
                  gint64 *strides,
                  gsize n_strides,
                  gchar **dimension_names,
                  gsize n_dimension_names)
{
  auto arrow_data_type = garrow_data_type_get_raw(data_type);
  auto arrow_data = garrow_buffer_get_raw(data);
  std::vector<int64_t> arrow_shape;
  for (gsize i = 0; i < n_dimensions; ++i) {
    arrow_shape.push_back(shape[i]);
  }
  std::vector<int64_t> arrow_strides;
  for (gsize i = 0; i < n_strides; ++i) {
    arrow_strides.push_back(strides[i]);
  }
  std::vector<std::string> arrow_dimension_names;
  for (gsize i = 0; i < n_dimension_names; ++i) {
    arrow_dimension_names.push_back(dimension_names[i]);
  }
  auto arrow_tensor =
    std::make_shared<arrow::Tensor>(arrow_data_type,
                                    arrow_data,
                                    arrow_shape,
                                    arrow_strides,
                                    arrow_dimension_names);
  auto tensor = garrow_tensor_new_raw(&arrow_tensor);
  return tensor;
}

/**
 * garrow_tensor_get_value_data_type:
 * @tensor: A #GArrowTensor.
 *
 * Returns: (transfer full): The data type of each value in the tensor.
 *
 * Since: 0.3.0
 */
GArrowDataType *
garrow_tensor_get_value_data_type(GArrowTensor *tensor)
{
  auto arrow_tensor = garrow_tensor_get_raw(tensor);
  auto arrow_data_type = arrow_tensor->type();
  return garrow_data_type_new_raw(&arrow_data_type);
}

/**
 * garrow_tensor_get_value_type:
 * @tensor: A #GArrowTensor.
 *
 * Returns: The type of each value in the tensor.
 *
 * Since: 0.3.0
 */
GArrowType
garrow_tensor_get_value_type(GArrowTensor *tensor)
{
  auto arrow_tensor = garrow_tensor_get_raw(tensor);
  auto arrow_type = arrow_tensor->type_id();
  return garrow_type_from_raw(arrow_type);
}

/**
 * garrow_tensor_get_buffer:
 * @tensor: A #GArrowTensor.
 *
 * Returns: (transfer full): The data of the tensor.
 *
 * Since: 0.3.0
 */
GArrowBuffer *
garrow_tensor_get_buffer(GArrowTensor *tensor)
{
  auto arrow_tensor = garrow_tensor_get_raw(tensor);
  auto arrow_buffer = arrow_tensor->data();
  return garrow_buffer_new_raw(&arrow_buffer);
}

/**
 * garrow_tensor_get_shape:
 * @tensor: A #GArrowTensor.
 * @n_dimensions: (out): The number of dimensions.
 *
 * Returns: (array length=n_dimensions): The shape of the tensor.
 *   It should be freed with g_free() when no longer needed.
 *
 * Since: 0.3.0
 */
gint64 *
garrow_tensor_get_shape(GArrowTensor *tensor, gint *n_dimensions)
{
  auto arrow_tensor = garrow_tensor_get_raw(tensor);
  auto arrow_shape = arrow_tensor->shape();
  auto n_dimensions_raw = arrow_shape.size();
  auto shape =
    static_cast<gint64 *>(g_malloc_n(sizeof(gint64), n_dimensions_raw));
  for (gsize i = 0; i < n_dimensions_raw; ++i) {
    shape[i] = arrow_shape[i];
  }
  *n_dimensions = static_cast<gint>(n_dimensions_raw);
  return shape;
}

/**
 * garrow_tensor_get_strides:
 * @tensor: A #GArrowTensor.
 * @n_strides: (out): The number of strides.
 *
 * Returns: (array length=n_strides): The strides of the tensor.
 *   It should be freed with g_free() when no longer needed.
 *
 * Since: 0.3.0
 */
gint64 *
garrow_tensor_get_strides(GArrowTensor *tensor, gint *n_strides)
{
  auto arrow_tensor = garrow_tensor_get_raw(tensor);
  auto arrow_strides = arrow_tensor->strides();
  auto n_strides_raw = arrow_strides.size();
  auto strides =
    static_cast<gint64 *>(g_malloc_n(sizeof(gint64), n_strides_raw));
  for (gsize i = 0; i < n_strides_raw; ++i) {
    strides[i] = arrow_strides[i];
  }
  *n_strides = static_cast<gint>(n_strides_raw);
  return strides;
}

/**
 * garrow_tensor_get_n_dimensions:
 * @tensor: A #GArrowTensor.
 *
 * Returns: The number of dimensions of the tensor.
 *
 * Since: 0.3.0
 */
gint
garrow_tensor_get_n_dimensions(GArrowTensor *tensor)
{
  auto arrow_tensor = garrow_tensor_get_raw(tensor);
  return arrow_tensor->ndim();
}

/**
 * garrow_tensor_get_dimension_name:
 * @tensor: A #GArrowTensor.
 * @i: The index of the target dimension.
 *
 * Returns: The i-th dimension name of the tensor.
 *
 * Since: 0.3.0
 */
const gchar *
garrow_tensor_get_dimension_name(GArrowTensor *tensor, gint i)
{
  auto arrow_tensor = garrow_tensor_get_raw(tensor);
  auto arrow_dimension_name = arrow_tensor->dim_name(i);
  return arrow_dimension_name.c_str();
}

/**
 * garrow_tensor_get_size:
 * @tensor: A #GArrowTensor.
 *
 * Returns: The number of value cells in the tensor.
 *
 * Since: 0.3.0
 */
gint64
garrow_tensor_get_size(GArrowTensor *tensor)
{
  auto arrow_tensor = garrow_tensor_get_raw(tensor);
  return arrow_tensor->size();
}

/**
 * garrow_tensor_is_mutable:
 * @tensor: A #GArrowTensor.
 *
 * Returns: %TRUE if the tensor is mutable, %FALSE otherwise.
 *
 * Since: 0.3.0
 */
gboolean
garrow_tensor_is_mutable(GArrowTensor *tensor)
{
  auto arrow_tensor = garrow_tensor_get_raw(tensor);
  return arrow_tensor->is_mutable();
}

/**
 * garrow_tensor_is_contiguous:
 * @tensor: A #GArrowTensor.
 *
 * Returns: %TRUE if the tensor is contiguous, %FALSE otherwise.
 *
 * Since: 0.3.0
 */
gboolean
garrow_tensor_is_contiguous(GArrowTensor *tensor)
{
  auto arrow_tensor = garrow_tensor_get_raw(tensor);
  return arrow_tensor->is_contiguous();
}

/**
 * garrow_tensor_is_row_major:
 * @tensor: A #GArrowTensor.
 *
 * Returns: %TRUE if the tensor is row major a.k.a. C order,
 *   %FALSE otherwise.
 *
 * Since: 0.3.0
 */
gboolean
garrow_tensor_is_row_major(GArrowTensor *tensor)
{
  auto arrow_tensor = garrow_tensor_get_raw(tensor);
  return arrow_tensor->is_row_major();
}

/**
 * garrow_tensor_is_column_major:
 * @tensor: A #GArrowTensor.
 *
 * Returns: %TRUE if the tensor is column major a.k.a. Fortran order,
 *   %FALSE otherwise.
 *
 * Since: 0.3.0
 */
gboolean
garrow_tensor_is_column_major(GArrowTensor *tensor)
{
  auto arrow_tensor = garrow_tensor_get_raw(tensor);
  return arrow_tensor->is_column_major();
}

G_END_DECLS

GArrowTensor *
garrow_tensor_new_raw(std::shared_ptr<arrow::Tensor> *arrow_tensor)
{
  auto tensor = GARROW_TENSOR(g_object_new(GARROW_TYPE_TENSOR,
                                           "tensor", arrow_tensor,
                                           NULL));
  return tensor;
}

std::shared_ptr<arrow::Tensor>
garrow_tensor_get_raw(GArrowTensor *tensor)
{
  auto priv = GARROW_TENSOR_GET_PRIVATE(tensor);
  return priv->tensor;
}
<|endoftext|>


<commit_before>#include "HAL/HAL.hpp"

#include "Port.h"
#include "HAL/Errors.hpp"
#include "ChipObject.h"
#include "NetworkCommunication/FRCComm.h"
#include "NetworkCommunication/UsageReporting.h"
#include "NetworkCommunication/LoadOut.h"
#include "ChipObject/nInterfaceGlobals.h"
#include <fstream>
#include <iostream>
#include <unistd.h>
#include <signal.h> // linux for kill
const uint32_t solenoid_kNumDO7_0Elements = 8;
const uint32_t dio_kNumSystems = tDIO::kNumSystems;
const uint32_t interrupt_kNumSystems = tInterrupt::kNumSystems;
const uint32_t kSystemClockTicksPerMicrosecond = 40;

static tGlobal *global;

void* getPort(uint8_t pin)
{
	Port* port = new Port();
	port->pin = pin;
	port->module = 1;
	return port;
}

/**
 * @deprecated Uses module numbers
 */
void* getPortWithModule(uint8_t module, uint8_t pin)
{
	Port* port = new Port();
	port->pin = pin;
	port->module = module;
	return port;
}

const char* getHALErrorMessage(int32_t code)
{
	if (code == 0)
		return "";
	else if (code == SAMPLE_RATE_TOO_HIGH)
		return SAMPLE_RATE_TOO_HIGH_MESSAGE;
	else if (code == VOLTAGE_OUT_OF_RANGE)
		return VOLTAGE_OUT_OF_RANGE_MESSAGE;
	else if (code == LOOP_TIMING_ERROR)
		return LOOP_TIMING_ERROR_MESSAGE;
	else if (code == SPI_WRITE_NO_MOSI)
		return SPI_WRITE_NO_MOSI_MESSAGE;
	else if (code == SPI_READ_NO_MISO)
		return SPI_READ_NO_MISO_MESSAGE;
	else if (code == SPI_READ_NO_DATA)
		return SPI_READ_NO_DATA_MESSAGE;
	else if (code == INCOMPATIBLE_STATE)
		return INCOMPATIBLE_STATE_MESSAGE;
	else if (code == NO_AVAILABLE_RESOURCES)
		return NO_AVAILABLE_RESOURCES_MESSAGE;
	else if (code == NULL_PARAMETER)
		return NULL_PARAMETER_MESSAGE;
	else if (code == ANALOG_TRIGGER_LIMIT_ORDER_ERROR)
		return ANALOG_TRIGGER_LIMIT_ORDER_ERROR_MESSAGE;
	else if (code == ANALOG_TRIGGER_PULSE_OUTPUT_ERROR)
		return ANALOG_TRIGGER_PULSE_OUTPUT_ERROR_MESSAGE;
	else if (code == PARAMETER_OUT_OF_RANGE)
		return PARAMETER_OUT_OF_RANGE_MESSAGE;
	else
		return "";
}

/**
 * Return the FPGA Version number.
 * For now, expect this to be competition year.
 * @return FPGA Version number.
 */
uint16_t getFPGAVersion(int32_t *status)
{
	return global->readVersion(status);
}

/**
 * Return the FPGA Revision number.
 * The format of the revision is 3 numbers.
 * The 12 most significant bits are the Major Revision.
 * the next 8 bits are the Minor Revision.
 * The 12 least significant bits are the Build Number.
 * @return FPGA Revision number.
 */
uint32_t getFPGARevision(int32_t *status)
{
	return global->readRevision(status);
}

/**
 * Read the microsecond-resolution timer on the FPGA.
 *
 * @return The current time in microseconds according to the FPGA (since FPGA reset).
 */
uint32_t getFPGATime(int32_t *status)
{
	return global->readLocalTime(status);
}

/**
 * Set the state of the FPGA status LED on the cRIO.
 */
void setFPGALED(uint32_t state, int32_t *status)
{
	// XXX: Not supported?
	// global->writeFPGA_LED(state, status);
}

/**
 * Get the current state of the FPGA status LED on the cRIO.
 * @return The curent state of the FPGA LED.
 */
int32_t getFPGALED(int32_t *status)
{
	// XXX: Not supported?
	// bool ledValue = global->readFPGA_LED(status);
	// return ledValue;
	return 0; // XXX: Dummy value
}

int HALSetErrorData(const char *errors, int errorsLength, int wait_ms)
{
	return setErrorData(errors, errorsLength, wait_ms);
}

int HALSetUserDsLcdData(const char *userDsLcdData, int userDsLcdDataLength,
		int wait_ms)
{
	return setUserDsLcdData(userDsLcdData, userDsLcdDataLength, wait_ms);
}

int HALOverrideIOConfig(const char *ioConfig, int wait_ms)
{
	return overrideIOConfig(ioConfig, wait_ms);
}

int HALGetDynamicControlData(uint8_t type, char *dynamicData, int32_t maxLength,
		int wait_ms)
{
	return getDynamicControlData(type, dynamicData, maxLength, wait_ms);
}

int HALGetCommonControlData(HALCommonControlData *data, int wait_ms)
{
	return getRecentCommonControlData((FRCCommonControlData*) data, wait_ms);
}

void HALSetNewDataSem(pthread_mutex_t * param)
{
	setNewDataSem(param);
}

int HALSetStatusData(float battery, uint8_t dsDigitalOut, uint8_t updateNumber,
		const char *userDataHigh, int userDataHighLength,
		const char *userDataLow, int userDataLowLength, int wait_ms)
{
	return setStatusData(battery, dsDigitalOut, updateNumber, userDataHigh,
			userDataHighLength, userDataLow, userDataLowLength, wait_ms);
}

/**
 * Call this to start up HAL. This is required for robot programs.
 */
int HALInitialize(int mode)
{
	// image 4; Fixes errors caused by multiple processes. Talk to NI about this
	nFPGA::nRoboRIO_FPGANamespace::g_currentTargetClass =
			nLoadOut::kTargetClass_RoboRIO;

	global = tGlobal::create(&status);

	// Kill any previous robot programs
	std::fstream fs;
	// By making this both in/out, it won't give us an error if it doesnt exist
	fs.open("/var/lock/frc.pid", std::fstream::in | std::fstream::out);
	if (fs.bad())
		return 0;

	pid_t pid = 0;
	if (!fs.eof() && !fs.fail())
	{
		fs >> pid;
		//see if the pid is around, but we don't want to mess with init id=1, or ourselves
		if (pid >= 2 && kill(pid, 0) == 0 && pid != getpid())
		{
			std::cout << "Killing previously running FRC program..."
					<< std::endl;
			kill(pid, SIGTERM); // try to kill it
			delayMillis(100);
			if (kill(pid, 0) == 0)
			{
				// still not successfull
				if (mode == 0)
				{
					std::cout << "FRC pid " << pid
							<< " did not die within 110ms. Aborting"
							<< std::endl;
					return 0; // just fail
				}
				else if (mode == 1) // kill -9 it
					kill(pid, SIGKILL);
				else
				{
					std::cout << "WARNING: FRC pid " << pid
							<< " did not die within 110ms." << std::endl;
				}
			}

		}
	}
	fs.close();
	// we will re-open it write only to truncate the file
	fs.open("/var/lock/frc.pid", std::fstream::out | std::fstream::trunc);
	fs.seekp(0);
	pid = getpid();
	fs << pid << std::endl;
	fs.close();
	return 1;
}

void HALNetworkCommunicationObserveUserProgramStarting(void)
{
	FRC_NetworkCommunication_observeUserProgramStarting();
}

void HALNetworkCommunicationObserveUserProgramDisabled(void)
{
	FRC_NetworkCommunication_observeUserProgramDisabled();
}

void HALNetworkCommunicationObserveUserProgramAutonomous(void)
{
	FRC_NetworkCommunication_observeUserProgramAutonomous();
}

void HALNetworkCommunicationObserveUserProgramTeleop(void)
{
	FRC_NetworkCommunication_observeUserProgramTeleop();
}

void HALNetworkCommunicationObserveUserProgramTest(void)
{
	FRC_NetworkCommunication_observeUserProgramTest();
}

uint32_t HALReport(uint8_t resource, uint8_t instanceNumber, uint8_t context,
		const char *feature)
{
	//return FRC_NetworkCommunication_nUsageReporting_report( resource, instanceNumber, context, feature);
	return 0;
}

// TODO: HACKS
void NumericArrayResize()
{
}
void RTSetCleanupProc()
{
}
void EDVR_CreateReference()
{
}
void Occur()
{
}

void imaqGetErrorText()
{
}
void imaqGetLastError()
{
}
void niTimestamp64()
{
}

#include "NetworkCommunication/LoadOut.h"
namespace nLoadOut
{
bool getModulePresence(tModuleType moduleType, uint8_t moduleNumber)
{
	return true;
}
}
<commit_msg>Fixed a typo with the tGlobal commit<commit_after>#include "HAL/HAL.hpp"

#include "Port.h"
#include "HAL/Errors.hpp"
#include "ChipObject.h"
#include "NetworkCommunication/FRCComm.h"
#include "NetworkCommunication/UsageReporting.h"
#include "NetworkCommunication/LoadOut.h"
#include "ChipObject/nInterfaceGlobals.h"
#include <fstream>
#include <iostream>
#include <unistd.h>
#include <signal.h> // linux for kill
const uint32_t solenoid_kNumDO7_0Elements = 8;
const uint32_t dio_kNumSystems = tDIO::kNumSystems;
const uint32_t interrupt_kNumSystems = tInterrupt::kNumSystems;
const uint32_t kSystemClockTicksPerMicrosecond = 40;

static tGlobal *global;

void* getPort(uint8_t pin)
{
	Port* port = new Port();
	port->pin = pin;
	port->module = 1;
	return port;
}

/**
 * @deprecated Uses module numbers
 */
void* getPortWithModule(uint8_t module, uint8_t pin)
{
	Port* port = new Port();
	port->pin = pin;
	port->module = module;
	return port;
}

const char* getHALErrorMessage(int32_t code)
{
	if (code == 0)
		return "";
	else if (code == SAMPLE_RATE_TOO_HIGH)
		return SAMPLE_RATE_TOO_HIGH_MESSAGE;
	else if (code == VOLTAGE_OUT_OF_RANGE)
		return VOLTAGE_OUT_OF_RANGE_MESSAGE;
	else if (code == LOOP_TIMING_ERROR)
		return LOOP_TIMING_ERROR_MESSAGE;
	else if (code == SPI_WRITE_NO_MOSI)
		return SPI_WRITE_NO_MOSI_MESSAGE;
	else if (code == SPI_READ_NO_MISO)
		return SPI_READ_NO_MISO_MESSAGE;
	else if (code == SPI_READ_NO_DATA)
		return SPI_READ_NO_DATA_MESSAGE;
	else if (code == INCOMPATIBLE_STATE)
		return INCOMPATIBLE_STATE_MESSAGE;
	else if (code == NO_AVAILABLE_RESOURCES)
		return NO_AVAILABLE_RESOURCES_MESSAGE;
	else if (code == NULL_PARAMETER)
		return NULL_PARAMETER_MESSAGE;
	else if (code == ANALOG_TRIGGER_LIMIT_ORDER_ERROR)
		return ANALOG_TRIGGER_LIMIT_ORDER_ERROR_MESSAGE;
	else if (code == ANALOG_TRIGGER_PULSE_OUTPUT_ERROR)
		return ANALOG_TRIGGER_PULSE_OUTPUT_ERROR_MESSAGE;
	else if (code == PARAMETER_OUT_OF_RANGE)
		return PARAMETER_OUT_OF_RANGE_MESSAGE;
	else
		return "";
}

/**
 * Return the FPGA Version number.
 * For now, expect this to be competition year.
 * @return FPGA Version number.
 */
uint16_t getFPGAVersion(int32_t *status)
{
	return global->readVersion(status);
}

/**
 * Return the FPGA Revision number.
 * The format of the revision is 3 numbers.
 * The 12 most significant bits are the Major Revision.
 * the next 8 bits are the Minor Revision.
 * The 12 least significant bits are the Build Number.
 * @return FPGA Revision number.
 */
uint32_t getFPGARevision(int32_t *status)
{
	return global->readRevision(status);
}

/**
 * Read the microsecond-resolution timer on the FPGA.
 *
 * @return The current time in microseconds according to the FPGA (since FPGA reset).
 */
uint32_t getFPGATime(int32_t *status)
{
	return global->readLocalTime(status);
}

/**
 * Set the state of the FPGA status LED on the cRIO.
 */
void setFPGALED(uint32_t state, int32_t *status)
{
	// XXX: Not supported?
	// global->writeFPGA_LED(state, status);
}

/**
 * Get the current state of the FPGA status LED on the cRIO.
 * @return The curent state of the FPGA LED.
 */
int32_t getFPGALED(int32_t *status)
{
	// XXX: Not supported?
	// bool ledValue = global->readFPGA_LED(status);
	// return ledValue;
	return 0; // XXX: Dummy value
}

int HALSetErrorData(const char *errors, int errorsLength, int wait_ms)
{
	return setErrorData(errors, errorsLength, wait_ms);
}

int HALSetUserDsLcdData(const char *userDsLcdData, int userDsLcdDataLength,
		int wait_ms)
{
	return setUserDsLcdData(userDsLcdData, userDsLcdDataLength, wait_ms);
}

int HALOverrideIOConfig(const char *ioConfig, int wait_ms)
{
	return overrideIOConfig(ioConfig, wait_ms);
}

int HALGetDynamicControlData(uint8_t type, char *dynamicData, int32_t maxLength,
		int wait_ms)
{
	return getDynamicControlData(type, dynamicData, maxLength, wait_ms);
}

int HALGetCommonControlData(HALCommonControlData *data, int wait_ms)
{
	return getRecentCommonControlData((FRCCommonControlData*) data, wait_ms);
}

void HALSetNewDataSem(pthread_mutex_t * param)
{
	setNewDataSem(param);
}

int HALSetStatusData(float battery, uint8_t dsDigitalOut, uint8_t updateNumber,
		const char *userDataHigh, int userDataHighLength,
		const char *userDataLow, int userDataLowLength, int wait_ms)
{
	return setStatusData(battery, dsDigitalOut, updateNumber, userDataHigh,
			userDataHighLength, userDataLow, userDataLowLength, wait_ms);
}

/**
 * Call this to start up HAL. This is required for robot programs.
 */
int HALInitialize(int mode)
{
	// image 4; Fixes errors caused by multiple processes. Talk to NI about this
	nFPGA::nRoboRIO_FPGANamespace::g_currentTargetClass =
			nLoadOut::kTargetClass_RoboRIO;

	int32_t status;
	global = tGlobal::create(&status);

	// Kill any previous robot programs
	std::fstream fs;
	// By making this both in/out, it won't give us an error if it doesnt exist
	fs.open("/var/lock/frc.pid", std::fstream::in | std::fstream::out);
	if (fs.bad())
		return 0;

	pid_t pid = 0;
	if (!fs.eof() && !fs.fail())
	{
		fs >> pid;
		//see if the pid is around, but we don't want to mess with init id=1, or ourselves
		if (pid >= 2 && kill(pid, 0) == 0 && pid != getpid())
		{
			std::cout << "Killing previously running FRC program..."
					<< std::endl;
			kill(pid, SIGTERM); // try to kill it
			delayMillis(100);
			if (kill(pid, 0) == 0)
			{
				// still not successfull
				if (mode == 0)
				{
					std::cout << "FRC pid " << pid
							<< " did not die within 110ms. Aborting"
							<< std::endl;
					return 0; // just fail
				}
				else if (mode == 1) // kill -9 it
					kill(pid, SIGKILL);
				else
				{
					std::cout << "WARNING: FRC pid " << pid
							<< " did not die within 110ms." << std::endl;
				}
			}

		}
	}
	fs.close();
	// we will re-open it write only to truncate the file
	fs.open("/var/lock/frc.pid", std::fstream::out | std::fstream::trunc);
	fs.seekp(0);
	pid = getpid();
	fs << pid << std::endl;
	fs.close();
	return 1;
}

void HALNetworkCommunicationObserveUserProgramStarting(void)
{
	FRC_NetworkCommunication_observeUserProgramStarting();
}

void HALNetworkCommunicationObserveUserProgramDisabled(void)
{
	FRC_NetworkCommunication_observeUserProgramDisabled();
}

void HALNetworkCommunicationObserveUserProgramAutonomous(void)
{
	FRC_NetworkCommunication_observeUserProgramAutonomous();
}

void HALNetworkCommunicationObserveUserProgramTeleop(void)
{
	FRC_NetworkCommunication_observeUserProgramTeleop();
}

void HALNetworkCommunicationObserveUserProgramTest(void)
{
	FRC_NetworkCommunication_observeUserProgramTest();
}

uint32_t HALReport(uint8_t resource, uint8_t instanceNumber, uint8_t context,
		const char *feature)
{
	//return FRC_NetworkCommunication_nUsageReporting_report( resource, instanceNumber, context, feature);
	return 0;
}

// TODO: HACKS
void NumericArrayResize()
{
}
void RTSetCleanupProc()
{
}
void EDVR_CreateReference()
{
}
void Occur()
{
}

void imaqGetErrorText()
{
}
void imaqGetLastError()
{
}
void niTimestamp64()
{
}

#include "NetworkCommunication/LoadOut.h"
namespace nLoadOut
{
bool getModulePresence(tModuleType moduleType, uint8_t moduleNumber)
{
	return true;
}
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/focus_cycler.h"

#include "ash/launcher/launcher.h"
#include "ash/shell.h"
#include "ash/shell_window_ids.h"
#include "ash/wm/window_util.h"
#include "ash/test/ash_test_base.h"
#include "ash/shell_factory.h"
#include "ui/aura/test/test_windows.h"
#include "ui/aura/window.h"
#include "ui/views/controls/button/menu_button.h"
#include "ui/views/widget/widget.h"

namespace ash {
namespace test {

using aura::test::CreateTestWindowWithId;
using aura::Window;
using internal::FocusCycler;

typedef AshTestBase FocusCyclerTest;

TEST_F(FocusCyclerTest, CycleFocusBrowserOnly) {
  scoped_ptr<FocusCycler> focus_cycler(new FocusCycler());

  // Create a single test window.
  Window* default_container =
      ash::Shell::GetInstance()->GetContainer(
          internal::kShellWindowId_DefaultContainer);
  scoped_ptr<Window> window0(CreateTestWindowWithId(0, default_container));
  ActivateWindow(window0.get());
  EXPECT_TRUE(IsActiveWindow(window0.get()));

  // Cycle the window
  focus_cycler->RotateFocus(FocusCycler::FORWARD);
  EXPECT_TRUE(IsActiveWindow(window0.get()));
}

TEST_F(FocusCyclerTest, CycleFocusForward) {
  scoped_ptr<FocusCycler> focus_cycler(new FocusCycler());

  // Add the Status area
  views::Widget* status_widget = internal::CreateStatusArea();
  ASSERT_TRUE(status_widget);
  focus_cycler->AddWidget(status_widget);

  // Add a mock button to the status area.
  status_widget->GetContentsView()->AddChildView(
      new views::MenuButton(NULL, string16(), NULL, false));

  // Add the launcher
  Launcher* launcher = Shell::GetInstance()->launcher();
  ASSERT_TRUE(launcher);
  views::Widget* launcher_widget = launcher->widget();
  ASSERT_TRUE(launcher_widget);
  focus_cycler->AddWidget(launcher_widget);
  launcher->SetFocusCycler(focus_cycler.get());

  // Create a single test window.
  Window* default_container =
      ash::Shell::GetInstance()->GetContainer(
          internal::kShellWindowId_DefaultContainer);
  scoped_ptr<Window> window0(CreateTestWindowWithId(0, default_container));
  ActivateWindow(window0.get());
  EXPECT_TRUE(IsActiveWindow(window0.get()));

  // Cycle focus to the status area
  focus_cycler->RotateFocus(FocusCycler::FORWARD);
  EXPECT_TRUE(status_widget->IsActive());

  // Cycle focus to the launcher
  focus_cycler->RotateFocus(FocusCycler::FORWARD);
  EXPECT_TRUE(launcher_widget->IsActive());

  // Cycle focus to the browser
  focus_cycler->RotateFocus(FocusCycler::FORWARD);
  EXPECT_TRUE(IsActiveWindow(window0.get()));
}

TEST_F(FocusCyclerTest, CycleFocusBackward) {
  scoped_ptr<FocusCycler> focus_cycler(new FocusCycler());

  // Add the Status area
  views::Widget* status_widget = internal::CreateStatusArea();
  ASSERT_TRUE(status_widget);
  focus_cycler->AddWidget(status_widget);

  // Add a mock button to the status area.
  status_widget->GetContentsView()->AddChildView(
      new views::MenuButton(NULL, string16(), NULL, false));

  // Add the launcher
  Launcher* launcher = Shell::GetInstance()->launcher();
  ASSERT_TRUE(launcher);
  views::Widget* launcher_widget = launcher->widget();
  ASSERT_TRUE(launcher_widget);
  focus_cycler->AddWidget(launcher_widget);
  launcher->SetFocusCycler(focus_cycler.get());

  // Create a single test window.
  Window* default_container =
      ash::Shell::GetInstance()->GetContainer(
          internal::kShellWindowId_DefaultContainer);
  scoped_ptr<Window> window0(CreateTestWindowWithId(0, default_container));
  ActivateWindow(window0.get());
  EXPECT_TRUE(IsActiveWindow(window0.get()));

  // Cycle focus to the launcher
  focus_cycler->RotateFocus(FocusCycler::BACKWARD);
  EXPECT_TRUE(launcher_widget->IsActive());

  // Cycle focus to the status area
  focus_cycler->RotateFocus(FocusCycler::BACKWARD);
  EXPECT_TRUE(status_widget->IsActive());

  // Cycle focus to the browser
  focus_cycler->RotateFocus(FocusCycler::BACKWARD);
  EXPECT_TRUE(IsActiveWindow(window0.get()));
}

}  // namespace test
}  // namespace ash
<commit_msg>ash: Fix chromeos build by adding missing wm:: for focus_cycler_unittest.cc<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/focus_cycler.h"

#include "ash/launcher/launcher.h"
#include "ash/shell.h"
#include "ash/shell_window_ids.h"
#include "ash/wm/window_util.h"
#include "ash/test/ash_test_base.h"
#include "ash/shell_factory.h"
#include "ui/aura/test/test_windows.h"
#include "ui/aura/window.h"
#include "ui/views/controls/button/menu_button.h"
#include "ui/views/widget/widget.h"

namespace ash {
namespace test {

using aura::test::CreateTestWindowWithId;
using aura::Window;
using internal::FocusCycler;

typedef AshTestBase FocusCyclerTest;

TEST_F(FocusCyclerTest, CycleFocusBrowserOnly) {
  scoped_ptr<FocusCycler> focus_cycler(new FocusCycler());

  // Create a single test window.
  Window* default_container =
      ash::Shell::GetInstance()->GetContainer(
          internal::kShellWindowId_DefaultContainer);
  scoped_ptr<Window> window0(CreateTestWindowWithId(0, default_container));
  wm::ActivateWindow(window0.get());
  EXPECT_TRUE(wm::IsActiveWindow(window0.get()));

  // Cycle the window
  focus_cycler->RotateFocus(FocusCycler::FORWARD);
  EXPECT_TRUE(wm::IsActiveWindow(window0.get()));
}

TEST_F(FocusCyclerTest, CycleFocusForward) {
  scoped_ptr<FocusCycler> focus_cycler(new FocusCycler());

  // Add the Status area
  views::Widget* status_widget = internal::CreateStatusArea();
  ASSERT_TRUE(status_widget);
  focus_cycler->AddWidget(status_widget);

  // Add a mock button to the status area.
  status_widget->GetContentsView()->AddChildView(
      new views::MenuButton(NULL, string16(), NULL, false));

  // Add the launcher
  Launcher* launcher = Shell::GetInstance()->launcher();
  ASSERT_TRUE(launcher);
  views::Widget* launcher_widget = launcher->widget();
  ASSERT_TRUE(launcher_widget);
  focus_cycler->AddWidget(launcher_widget);
  launcher->SetFocusCycler(focus_cycler.get());

  // Create a single test window.
  Window* default_container =
      ash::Shell::GetInstance()->GetContainer(
          internal::kShellWindowId_DefaultContainer);
  scoped_ptr<Window> window0(CreateTestWindowWithId(0, default_container));
  wm::ActivateWindow(window0.get());
  EXPECT_TRUE(wm::IsActiveWindow(window0.get()));

  // Cycle focus to the status area
  focus_cycler->RotateFocus(FocusCycler::FORWARD);
  EXPECT_TRUE(status_widget->IsActive());

  // Cycle focus to the launcher
  focus_cycler->RotateFocus(FocusCycler::FORWARD);
  EXPECT_TRUE(launcher_widget->IsActive());

  // Cycle focus to the browser
  focus_cycler->RotateFocus(FocusCycler::FORWARD);
  EXPECT_TRUE(wm::IsActiveWindow(window0.get()));
}

TEST_F(FocusCyclerTest, CycleFocusBackward) {
  scoped_ptr<FocusCycler> focus_cycler(new FocusCycler());

  // Add the Status area
  views::Widget* status_widget = internal::CreateStatusArea();
  ASSERT_TRUE(status_widget);
  focus_cycler->AddWidget(status_widget);

  // Add a mock button to the status area.
  status_widget->GetContentsView()->AddChildView(
      new views::MenuButton(NULL, string16(), NULL, false));

  // Add the launcher
  Launcher* launcher = Shell::GetInstance()->launcher();
  ASSERT_TRUE(launcher);
  views::Widget* launcher_widget = launcher->widget();
  ASSERT_TRUE(launcher_widget);
  focus_cycler->AddWidget(launcher_widget);
  launcher->SetFocusCycler(focus_cycler.get());

  // Create a single test window.
  Window* default_container =
      ash::Shell::GetInstance()->GetContainer(
          internal::kShellWindowId_DefaultContainer);
  scoped_ptr<Window> window0(CreateTestWindowWithId(0, default_container));
  wm::ActivateWindow(window0.get());
  EXPECT_TRUE(wm::IsActiveWindow(window0.get()));

  // Cycle focus to the launcher
  focus_cycler->RotateFocus(FocusCycler::BACKWARD);
  EXPECT_TRUE(launcher_widget->IsActive());

  // Cycle focus to the status area
  focus_cycler->RotateFocus(FocusCycler::BACKWARD);
  EXPECT_TRUE(status_widget->IsActive());

  // Cycle focus to the browser
  focus_cycler->RotateFocus(FocusCycler::BACKWARD);
  EXPECT_TRUE(wm::IsActiveWindow(window0.get()));
}

}  // namespace test
}  // namespace ash
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <fstream>
using namespace std;

template<typename T>
struct Node
{
	T x;
	Node<T> * left;
	Node<T> * right;
	Node(T const& value) : x{ value }, left{ nullptr }, right{ nullptr } {}
};

template<typename T>
class Tree
{
private:
	Node<T> * root;
public:
	Tree()
	{
		root  = nullptr;
	}

	~Tree()
	{
		deleteNode(root);
	}

	void deleteNode(Node<T> * node)
	{
		if (node == nullptr) return;
		deleteNode(node->left);
		deleteNode(node->right);
		delete node;
	}

	T x_() const
	{
		return root->x;
	}

	Node<T> * left_() const
	{
		return root->left;
	}

	Node<T> * right_() const
	{
		return root->right;
	}

	Node<T> * root_() const
	{
		return root;
	}

	void insert(const T& value)
	{
		insert(root, value);
	}

	void insert(Node<T>* & node, const T& value)
	{
		if (node)
		{
			if (value < node->x)
				insert(node->left, value);
			else if (value > node->x)
				insert(node->right, value);
			else return;
		}
		else node = new Node<T>(value);
	}

	Node<T> * search(const T& x)const
	{
		Node<T> * curEl = root;
		while (curEl != nullptr)
		{
			if (curEl->x == x)
				break;
			else
			{
				if (x > curEl->x)
					curEl = curEl->right;
				else curEl = curEl->left;
			}
		}
		return curEl;
	}

	bool check_search(const T& x)
	{
		Node<T> * node;
		node = search(x);
		if (node != nullptr)
			return true;
		else return false;
	}

	void fIn(const string filename)
	{
		ifstream fin;
		unsigned int k;
		fin.open(filename);
		if (!fin.is_open())
			cout << "The file isn't find" << endl;
		else
		{
			deleteNode(root);
			if (fin.eof()) return;
			else
			{
				fin >> k;
				T newEl;
				for (unsigned int i = 0; i < k; ++i)
				{
					fin >> newEl;
					insert(newEl);
				}
			}
			fin.close();
		}
	}

	unsigned int size(Node<T> * node)const
	{
		unsigned int size_ = 0;
		if (node != nullptr)
			size_ = size(node->left) + 1 + size(node->right);
		return size_;
	}

	void out_to_file(const string filename)const
	{
		ofstream fout;
		fout.open(filename);
		if (!fout.is_open())
			cout << "The file isn't find" << endl;
		else
		{
			unsigned int size_ = size(root);
			if (size_ == 0)
				return;
			fout << size_ << "\t";
			fOut(root, fout);
			fout.close();
		}
	}

	void fOut(Node<T> * node, ostream&stream)const
	{
		if (node != nullptr)
		{
			fOut(node->left, stream);
			stream << node->x << " ";
			fOut(node->right, stream);
		}
	}

	void out(ostream & stream)const
	{
		Out(root, stream, 0);
	}

	void Out(Node<T> * node, ostream&stream, size_t level)const
	{
		Node<T> * curEl = node;
		if (curEl != nullptr)
		{
			Out(curEl->right, stream, level + 1);
			for (unsigned int i = 0; i < level; ++i)
				stream << '-';
			stream << curEl->x << endl;
			Out(curEl->left, stream, level + 1);
		}
	}

	Node<T> * prev_(const T& x)
	{
		return prev(root, x);
	}

	Node<T> * prev_(Node<T> * & node, const T& x)
	{
		if (check_search(x))
		{
			Node<T> * prev = nullptr;
			Node<T> * cur = nullptr;
			while (node->x != x)
			{
				if (x < node->x)
				{
					prev = node;
					cur = node->left;
					prev(cur, x);
				}
				else if (x > node->x)
				{
					prev = node;
					cur = node->right;
					prev(cur, x);
				}
			}
			return prev;
		}
		else return;
	}

	void deliteX(const T& x)
	{
		Node<T> * curEl = search(x);
		Node<T> * prev = nullptr;
		if (curEl != nullptr)
		{
			if (curEl->left == nullptr&&curEl->right == nullptr)
			{
				prev = prev_(x);
				if (x < prev->x)
					prev->left = nullptr;
				if (x > prev->x)
					prev->right = nullptr;
			}
			else
			{
				if (curEl->right != nullptr)
				{
					* left = curEl->left;
					* right = curEl->right;
					Node<T> * leftEl = curEl->right;
					while (leftEl->left||leftEl->right)
					{
						if (leftEl->left)
							leftEl = leftEl->left;
						else leftEl = leftEl->right;
					}
					prev = prev_(leftEl->x);
					if (x < prev->x)
						prev->left = nullptr;
					if (x > prev->x)
						prev->right = nullptr;
					leftEl->left = left;
					leftEl->right = right;
					curEl = leftEl;
				}
			}
		}
		else return;
	}
};
<commit_msg>Update BinaryTree.hpp<commit_after>#include <iostream>
#include <string>
#include <fstream>
using namespace std;

template<typename T>
struct Node
{
	T x;
	Node<T> * left;
	Node<T> * right;
	Node(T const& value) : x{ value }, left{ nullptr }, right{ nullptr } {}
};

template<typename T>
class Tree
{
private:
	Node<T> * root;
public:
	Tree()
	{
		root  = nullptr;
	}

	~Tree()
	{
		deleteNode(root);
	}

	void deleteNode(Node<T> * node)
	{
		if (node == nullptr) return;
		deleteNode(node->left);
		deleteNode(node->right);
		delete node;
	}

	T x_() const
	{
		return root->x;
	}

	Node<T> * left_() const
	{
		return root->left;
	}

	Node<T> * right_() const
	{
		return root->right;
	}

	Node<T> * root_() const
	{
		return root;
	}

	void insert(const T& value)
	{
		insert(root, value);
	}

	void insert(Node<T>* & node, const T& value)
	{
		if (node)
		{
			if (value < node->x)
				insert(node->left, value);
			else if (value > node->x)
				insert(node->right, value);
			else return;
		}
		else node = new Node<T>(value);
	}

	Node<T> * search(const T& x)const
	{
		Node<T> * curEl = root;
		while (curEl != nullptr)
		{
			if (curEl->x == x)
				break;
			else
			{
				if (x > curEl->x)
					curEl = curEl->right;
				else curEl = curEl->left;
			}
		}
		return curEl;
	}

	bool check_search(const T& x)
	{
		Node<T> * node;
		node = search(x);
		if (node != nullptr)
			return true;
		else return false;
	}

	void fIn(const string filename)
	{
		ifstream fin;
		unsigned int k;
		fin.open(filename);
		if (!fin.is_open())
			cout << "The file isn't find" << endl;
		else
		{
			deleteNode(root);
			if (fin.eof()) return;
			else
			{
				fin >> k;
				T newEl;
				for (unsigned int i = 0; i < k; ++i)
				{
					fin >> newEl;
					insert(newEl);
				}
			}
			fin.close();
		}
	}

	unsigned int size(Node<T> * node)const
	{
		unsigned int size_ = 0;
		if (node != nullptr)
			size_ = size(node->left) + 1 + size(node->right);
		return size_;
	}

	void out_to_file(const string filename)const
	{
		ofstream fout;
		fout.open(filename);
		if (!fout.is_open())
			cout << "The file isn't find" << endl;
		else
		{
			unsigned int size_ = size(root);
			if (size_ == 0)
				return;
			fout << size_ << "\t";
			fOut(root, fout);
			fout.close();
		}
	}

	void fOut(Node<T> * node, ostream&stream)const
	{
		if (node != nullptr)
		{
			fOut(node->left, stream);
			stream << node->x << " ";
			fOut(node->right, stream);
		}
	}

	void out(ostream & stream)const
	{
		Out(root, stream, 0);
	}

	void Out(Node<T> * node, ostream&stream, size_t level)const
	{
		Node<T> * curEl = node;
		if (curEl != nullptr)
		{
			Out(curEl->right, stream, level + 1);
			for (unsigned int i = 0; i < level; ++i)
				stream << '-';
			stream << curEl->x << endl;
			Out(curEl->left, stream, level + 1);
		}
	}

	Node<T> * prev_(const T& x)
	{
		return prev(root, x);
	}

	Node<T> * prev_(Node<T> * & node, const T& x)
	{
		if (check_search(x))
		{
			Node<T> * prev = nullptr;
			Node<T> * cur = nullptr;
			while (node->x != x)
			{
				if (x < node->x)
				{
					prev = node;
					cur = node->left;
					prev(cur, x);
				}
				else if (x > node->x)
				{
					prev = node;
					cur = node->right;
					prev(cur, x);
				}
			}
			return prev;
		}
		else return;
	}

	void deliteX(const T& x)
	{
		Node<T> * curEl = search(x);
		Node<T> * prev = nullptr;
		if (curEl != nullptr)
		{
			if (curEl->left == nullptr&&curEl->right == nullptr)
			{
				prev = prev_(x);
				if (x < prev->x)
					prev->left = nullptr;
				if (x > prev->x)
					prev->right = nullptr;
			}
			else
			{
				if (curEl->right != nullptr)
				{
					Node<T> * left_ = curEl->left;
					Node<T> * right_ = curEl->right;
					Node<T> * leftEl = curEl->right;
					while (leftEl->left)
						leftEl = leftEl->left;
					prev = prev_(leftEl->x);
					if (x < prev->x)
						prev->left = nullptr;
					if (x > prev->x)
						prev->right = nullptr;
					leftEl->left = left_;
					leftEl->right = right_;
					curEl = leftEl;
				}
				if (curEl->left != nullptr&&curEl->right == nullptr)
				{
					prev = prev_(curEl->x);
					if (curEl->x < prev->x)
						prev->left = curEl->left;
					else prev->right = curEl->left;
				}
			}
		}
		else return;
	}
};
<|endoftext|>


<commit_before>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core  If not, see
// <http://www.gnu.org/licenses/>.

#define BOOST_TEST_MODULE gradient_based

#include <cmath>
#include <boost/test/included/unit_test.hpp>

#include <hpp/fcl/collision_object.h>
#include <hpp/fcl/math/transform.h>
#include <hpp/fcl/shape/geometric_shapes.h>

#include <hpp/model/device.hh>

#include <hpp/pinocchio/joint.hh>
#include <hpp/pinocchio/collision-object.hh>
#include <hpp/pinocchio/device.hh>

#include <hpp/core/steering-method-straight.hh>
#include <hpp/core/path-optimization/gradient-based.hh>
#include <hpp/core/path-vector.hh>
#include <hpp/core/problem.hh>
#include <pinocchio/multibody/joint/joint-variant.hpp>
#include <pinocchio/spatial/fcl-pinocchio-conversions.hpp>
#include <pinocchio/multibody/geometry.hpp>

#include "../tests/utils.hh"

using hpp::pinocchio::BodyPtr_t;
using hpp::pinocchio::Body;
using hpp::pinocchio::CollisionObject;
using hpp::pinocchio::CollisionObjectPtr_t;
using hpp::pinocchio::Configuration_t;
using hpp::pinocchio::Device;
using hpp::pinocchio::DevicePtr_t;
using hpp::pinocchio::Transform3f;
using hpp::pinocchio::JointPtr_t;
using hpp::pinocchio::value_type;
using fcl::Quaternion3f;
using fcl::Box;
using hpp::core::ConfigurationPtr_t;
using hpp::core::PathVector;
using hpp::core::PathVectorPtr_t;
using hpp::core::Problem;
using hpp::core::SteeringMethodPtr_t;
using hpp::core::SteeringMethodStraight;
using hpp::core::PathOptimizerPtr_t;
using hpp::core::pathOptimization::GradientBased;

using namespace hpp::core;
using namespace hpp::pinocchio;

using ::se3::JointModelPX;
using ::se3::JointModelPY;
using ::se3::JointModelPZ;
using ::se3::JointModelRUBZ;
using ::se3::JointIndex;
using ::se3::FrameIndex;

BOOST_AUTO_TEST_SUITE( test_hpp_core )

DevicePtr_t createRobot ()
{
  DevicePtr_t robot = Device::create ("test");
  const std::string& name = robot->name ();
  ModelPtr_t m = ModelPtr_t(new ::se3::Model());
  GeomModelPtr_t gm = GeomModelPtr_t(new ::se3::GeometryModel());
  robot->model(m);
  robot->geomModel(gm);
  Transform3f mat; mat.setIdentity ();
  std::string jointName = name + "_x";

  JointIndex idX = robot->model().addJoint(0,JointModelPX(), mat,jointName);

  std::string jointNameY = name + "_y";

  idX = robot->model().addJoint(idX,JointModelPY(), mat,jointNameY);

  idX = robot->model().addJoint(idX,JointModelRUBZ(), mat,"rot_z");

  fcl::Transform3f position; position.setIdentity ();

  boost::shared_ptr <Box> box (new Box (1,2,1));
  fcl::CollisionObject object(box, position);
  robot->model().appendBodyToJoint(idX,::se3::Inertia::Identity(), se3::SE3::Identity());
  robot->model().addBodyFrame("body", idX, se3::SE3::Identity());
  FrameIndex bodyId = robot->model().getFrameId("body");
  robot->geomModel().addGeometryObject(
      se3::GeometryObject("obstacle", bodyId, idX, object.collisionGeometry(), mat, "", hpp::pinocchio::vector3_t::Ones()),
      robot->model());

  robot->createData();
  robot->createGeomData();
  return robot;
  /*
  DevicePtr_t robot = Device::create ("planar-robot");
  Transform3f position; position.setIdentity ();
  ObjectFactory factory;

  // planar root joint
  JointPtr_t root = factory.createJointTranslation2 (position);
  robot->rootJoint (root);
  // Rotation around z
  position.setQuatRotation (Quaternion3f (sqrt (2)/2, 0, -sqrt (2)/2, 0));
  JointPtr_t joint = factory.createUnBoundedJointRotation (position);
  root->addChildJoint (joint);
  position.setIdentity ();
  boost::shared_ptr <Box> box (new Box (1,2,1));
  CollisionObjectPtr_t object = CollisionObject::create (box, position, "box");
  BodyPtr_t body = new Body ();
  joint->setLinkedBody (body);
  body->addInnerObject (object, true, true);

  return robot;*/
}

BOOST_AUTO_TEST_CASE (BFGS)
{
  DevicePtr_t robot = createRobot ();
  Configuration_t q0 (robot->configSize ());
  Configuration_t q1 (robot->configSize ());
  Configuration_t q2 (robot->configSize ());
  Configuration_t q3 (robot->configSize ());
  Configuration_t q4 (robot->configSize ());
  value_type s = sqrt (2)/2;
  q0 (0) = -1; q0 (1) = 0; q0 (2) = 1; q0 (3) = 0;
  q1 (0) = -s; q1 (1) = s; q1 (2) = s; q1 (3) = s;
  q2 (0) = 0; q2 (1) = 1; q2 (2) = 0; q2 (3) = 1;
  q3 (0) = s; q3 (1) = s; q3 (2) = s; q3 (3) = s;
  q4 (0) = 1; q4 (1) = 0; q4 (2) = 1; q4 (3) = 0;

  Problem problem (robot);
  SteeringMethodPtr_t sm = problem.steeringMethod ();
  PathVectorPtr_t path = PathVector::create (robot->configSize (),
					     robot->numberDof ());
  path->appendPath ((*sm) (q0, q1));
  path->appendPath ((*sm) (q1, q2));
  path->appendPath ((*sm) (q2, q3));
  path->appendPath ((*sm) (q3, q4));

  PathOptimizerPtr_t pathOptimizer (GradientBased::create (problem));
  pathOptimizer->optimize (path);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Fix creation of robot in test-gradient-based.cc<commit_after>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core  If not, see
// <http://www.gnu.org/licenses/>.

#define BOOST_TEST_MODULE gradient_based

#include <cmath>
#include <boost/test/included/unit_test.hpp>

#include <hpp/fcl/collision_object.h>
#include <hpp/fcl/math/transform.h>
#include <hpp/fcl/shape/geometric_shapes.h>

#include <hpp/model/device.hh>

#include <hpp/pinocchio/joint.hh>
#include <hpp/pinocchio/collision-object.hh>
#include <hpp/pinocchio/device.hh>

#include <hpp/core/steering-method-straight.hh>
#include <hpp/core/path-optimization/gradient-based.hh>
#include <hpp/core/path-vector.hh>
#include <hpp/core/problem.hh>
#include <pinocchio/multibody/joint/joint-variant.hpp>
#include <pinocchio/spatial/fcl-pinocchio-conversions.hpp>
#include <pinocchio/multibody/geometry.hpp>

#include "../tests/utils.hh"

using hpp::pinocchio::BodyPtr_t;
using hpp::pinocchio::Body;
using hpp::pinocchio::CollisionObject;
using hpp::pinocchio::CollisionObjectPtr_t;
using hpp::pinocchio::Configuration_t;
using hpp::pinocchio::Device;
using hpp::pinocchio::DevicePtr_t;
using hpp::pinocchio::Transform3f;
using hpp::pinocchio::JointPtr_t;
using hpp::pinocchio::value_type;
using fcl::Quaternion3f;
using fcl::Box;
using hpp::core::ConfigurationPtr_t;
using hpp::core::PathVector;
using hpp::core::PathVectorPtr_t;
using hpp::core::Problem;
using hpp::core::SteeringMethodPtr_t;
using hpp::core::SteeringMethodStraight;
using hpp::core::PathOptimizerPtr_t;
using hpp::core::pathOptimization::GradientBased;

using namespace hpp::core;
using namespace hpp::pinocchio;

using ::se3::JointModelPX;
using ::se3::JointModelPY;
using ::se3::JointModelPZ;
using ::se3::JointModelRUBZ;
using ::se3::JointIndex;
using ::se3::FrameIndex;

BOOST_AUTO_TEST_SUITE( test_hpp_core )

DevicePtr_t createRobot ()
{
  DevicePtr_t robot = Device::create ("test");
  const std::string& name = robot->name ();
  ModelPtr_t m = ModelPtr_t(new ::se3::Model());
  GeomModelPtr_t gm = GeomModelPtr_t(new ::se3::GeometryModel());
  robot->model(m);
  robot->geomModel(gm);
  Transform3f mat; mat.setIdentity ();
  std::string jointName = name + "_x";

  JointIndex idX = robot->model().addJoint(0,JointModelPX(), mat,jointName);
  robot->model().addJointFrame(idX);

  std::string jointNameY = name + "_y";

  idX = robot->model().addJoint(idX,JointModelPY(), mat,jointNameY);
  robot->model().addJointFrame(idX);

  idX = robot->model().addJoint(idX,JointModelRUBZ(), mat,"rot_z");
  robot->model().addJointFrame(idX);

  fcl::Transform3f position; position.setIdentity ();

  boost::shared_ptr <Box> box (new Box (1,2,1));
  fcl::CollisionObject object(box, position);
  robot->model().appendBodyToJoint(idX,::se3::Inertia::Identity(), se3::SE3::Identity());
  robot->model().addBodyFrame("body", idX, se3::SE3::Identity());
  FrameIndex bodyId = robot->model().getFrameId("body");
  robot->geomModel().addGeometryObject(
      se3::GeometryObject("obstacle", bodyId, idX, object.collisionGeometry(), mat, "", hpp::pinocchio::vector3_t::Ones()),
      robot->model());

  robot->createData();
  robot->createGeomData();
  return robot;
  /*
  DevicePtr_t robot = Device::create ("planar-robot");
  Transform3f position; position.setIdentity ();
  ObjectFactory factory;

  // planar root joint
  JointPtr_t root = factory.createJointTranslation2 (position);
  robot->rootJoint (root);
  // Rotation around z
  position.setQuatRotation (Quaternion3f (sqrt (2)/2, 0, -sqrt (2)/2, 0));
  JointPtr_t joint = factory.createUnBoundedJointRotation (position);
  root->addChildJoint (joint);
  position.setIdentity ();
  boost::shared_ptr <Box> box (new Box (1,2,1));
  CollisionObjectPtr_t object = CollisionObject::create (box, position, "box");
  BodyPtr_t body = new Body ();
  joint->setLinkedBody (body);
  body->addInnerObject (object, true, true);

  return robot;*/
}

BOOST_AUTO_TEST_CASE (BFGS)
{
  DevicePtr_t robot = createRobot ();
  Configuration_t q0 (robot->configSize ());
  Configuration_t q1 (robot->configSize ());
  Configuration_t q2 (robot->configSize ());
  Configuration_t q3 (robot->configSize ());
  Configuration_t q4 (robot->configSize ());
  value_type s = sqrt (2)/2;
  q0 (0) = -1; q0 (1) = 0; q0 (2) = 1; q0 (3) = 0;
  q1 (0) = -s; q1 (1) = s; q1 (2) = s; q1 (3) = s;
  q2 (0) = 0; q2 (1) = 1; q2 (2) = 0; q2 (3) = 1;
  q3 (0) = s; q3 (1) = s; q3 (2) = s; q3 (3) = s;
  q4 (0) = 1; q4 (1) = 0; q4 (2) = 1; q4 (3) = 0;

  Problem problem (robot);
  SteeringMethodPtr_t sm = problem.steeringMethod ();
  PathVectorPtr_t path = PathVector::create (robot->configSize (),
					     robot->numberDof ());
  path->appendPath ((*sm) (q0, q1));
  path->appendPath ((*sm) (q1, q2));
  path->appendPath ((*sm) (q2, q3));
  path->appendPath ((*sm) (q3, q4));

  PathOptimizerPtr_t pathOptimizer (GradientBased::create (problem));
  pathOptimizer->optimize (path);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>/*
 * StreamServerManager.cpp
 *
 *  Created on: Sep 10, 2015
 *      Author: alarrosa14
 */
#include <chrono>

#include "lz4.h"
#include "lz4frame.h"

#include "StreamServerManager.h"

#define PACKET_HEADER_SIZE 10

StreamServerManager::StreamServerManager(void) {
	waitForNewFrameMutex.lock();
}

StreamServerManager::~StreamServerManager(void) {}

void StreamServerManager::setEnabled(const bool &isEnabled) {
	this->enabled = isEnabled;
}

void StreamServerManager::setCompressionEnabled(const bool &compression) {
	this->compressionEnabled = compression;
}

void StreamServerManager::setAddress(const string &address) {
	this->address = address;
}

void StreamServerManager::setPixelQuantity(const int &pixelQty){
	this->pixelQuantity = pixelQty;
}

void StreamServerManager::setPort(const int &port){
	this->port = port;
}

bool StreamServerManager::getEnabled() {
	return this->enabled;
}

bool StreamServerManager::getCompressionEnabled() {
	return this->compressionEnabled;
}

string StreamServerManager::getAddress() {
	return this->address;
}

int StreamServerManager::getPixelQuantity() {
	return this->pixelQuantity;
}

int StreamServerManager::getPort(){
	return this->port;
}

void StreamServerManager::setupStreamingSender() {
	cout << "Server config: " << this->address << endl << this->port << endl;
	cout << "Compression enabled? " << (this->compressionEnabled ? "True" : "False") << endl;
	string url = "http://" + this->address + ":" + to_string(this->port);
	cout << "Setting up Streaming Server: " << url << endl;

	udpManager.Create();
	cout << this->address.c_str() << this->port << endl;
	if (!udpManager.Connect(this->address.c_str(), this->port));
		cout << endl << endl << "Error connecting socket!" << endl << endl;
	udpManager.SetNonBlocking(true);

}

void StreamServerManager::addFrameToSendBuffer(DTFrame* newFrame) {
	lock();
	this->sendBuffer.push_back(newFrame);
	unlock();
	waitForNewFrameMutex.unlock();
}

void convertToArrayOfBytes(void* data, int length, unsigned char *buffer) {
	char* ptr = (char*)data;
	for (int i = 0; i < length; i++)
		buffer[i] = *ptr++;
};

uint64_t htonll(uint64_t n) {
#if __BYTE_ORDER == __BIG_ENDIAN
    return n;
#else
    return (((uint64_t)htonl(n)) << 32) + htonl(n >> 32);
#endif
}

uint64_t ntohll(uint64_t n) {
	return htonll(n);
}

void StreamServerManager::threadedFunction() {

	uint8_t currentSeqNmb = 0;
	uint8_t flags = 0x00;

	const int frameSize = this->pixelQuantity*3;

	size_t compressedBufferMaxSize;
	unsigned char *compressedBuffer = NULL;
	if (compressionEnabled) {
		flags = 0x01;
		compressedBufferMaxSize = LZ4F_compressFrameBound(frameSize, NULL);
		compressedBuffer = new unsigned char[compressedBufferMaxSize];
	}

	const int bufferSize = PACKET_HEADER_SIZE + ((compressionEnabled && compressedBufferMaxSize > frameSize) ? compressedBufferMaxSize : frameSize);
	unsigned char *buffer = new unsigned char[bufferSize];
	buffer[sizeof(uint64_t) + 2*sizeof(uint8_t) - 1] = flags;

	using namespace std::chrono;
	while(isThreadRunning()) {

		waitForNewFrameMutex.lock();
		lock();
		if(this->sendBuffer.size()>0){
	        vector<DTFrame*>::iterator it = this->sendBuffer.begin();
	        this->sendBuffer.erase(it);
	        unlock();

	        uint8_t* raw_frame = (*it)->getRawFrameData();
			int raw_frame_length = (*it)->getPixelQuantity()*3;

			assert(raw_frame_length == this->pixelQuantity*3);

			uint64_t ms = htonll(duration_cast< milliseconds >(
			    system_clock::now().time_since_epoch()
			).count());

			convertToArrayOfBytes(&ms, sizeof(ms), buffer);
			convertToArrayOfBytes(&currentSeqNmb, sizeof(currentSeqNmb), buffer + sizeof(ms));

			if (compressionEnabled) {
				size_t compressedBufferSize = LZ4F_compressFrame(compressedBuffer, compressedBufferMaxSize, raw_frame, raw_frame_length, NULL);
				convertToArrayOfBytes(compressedBuffer, compressedBufferSize, buffer + PACKET_HEADER_SIZE);
				this->udpManager.Send((char*) buffer, PACKET_HEADER_SIZE + compressedBufferSize);
			} else {
				convertToArrayOfBytes(raw_frame, raw_frame_length, buffer + PACKET_HEADER_SIZE);
				this->udpManager.Send((char*) buffer, bufferSize);
			}

			currentSeqNmb = (currentSeqNmb + 1) % 256;

		} else {
	    	unlock();
	    }
	}
	this->udpManager.Close();
	delete[]buffer;
	delete[]compressedBuffer;
}
<commit_msg>Added some scalability oriented code<commit_after>/*
 * StreamServerManager.cpp
 *
 *  Created on: Sep 10, 2015
 *      Author: alarrosa14
 */
#include <chrono>

#include "lz4.h"
#include "lz4frame.h"

#include "StreamServerManager.h"

#define PACKET_HEADER_SIZE 10

#define FRAME_DATA_COMPRESSED_MASK 0x01

StreamServerManager::StreamServerManager(void) {
	waitForNewFrameMutex.lock();
}

StreamServerManager::~StreamServerManager(void) {}

void StreamServerManager::setEnabled(const bool &isEnabled) {
	this->enabled = isEnabled;
}

void StreamServerManager::setCompressionEnabled(const bool &compression) {
	this->compressionEnabled = compression;
}

void StreamServerManager::setAddress(const string &address) {
	this->address = address;
}

void StreamServerManager::setPixelQuantity(const int &pixelQty){
	this->pixelQuantity = pixelQty;
}

void StreamServerManager::setPort(const int &port){
	this->port = port;
}

bool StreamServerManager::getEnabled() {
	return this->enabled;
}

bool StreamServerManager::getCompressionEnabled() {
	return this->compressionEnabled;
}

string StreamServerManager::getAddress() {
	return this->address;
}

int StreamServerManager::getPixelQuantity() {
	return this->pixelQuantity;
}

int StreamServerManager::getPort(){
	return this->port;
}

void StreamServerManager::setupStreamingSender() {
	cout << "Server config: " << this->address << endl << this->port << endl;
	cout << "Compression enabled? " << (this->compressionEnabled ? "True" : "False") << endl;
	string url = "http://" + this->address + ":" + to_string(this->port);
	cout << "Setting up Streaming Server: " << url << endl;

	udpManager.Create();
	cout << this->address.c_str() << this->port << endl;
	if (!udpManager.Connect(this->address.c_str(), this->port));
		cout << endl << endl << "Error connecting socket!" << endl << endl;
	udpManager.SetNonBlocking(true);

}

void StreamServerManager::addFrameToSendBuffer(DTFrame* newFrame) {
	lock();
	this->sendBuffer.push_back(newFrame);
	unlock();
	waitForNewFrameMutex.unlock();
}

void convertToArrayOfBytes(void* data, int length, unsigned char *buffer) {
	char* ptr = (char*)data;
	for (int i = 0; i < length; i++)
		buffer[i] = *ptr++;
};

uint64_t htonll(uint64_t n) {
#if __BYTE_ORDER == __BIG_ENDIAN
    return n;
#else
    return (((uint64_t)htonl(n)) << 32) + htonl(n >> 32);
#endif
}

uint64_t ntohll(uint64_t n) {
	return htonll(n);
}

void StreamServerManager::threadedFunction() {

	uint8_t currentSeqNmb = 0;
	uint8_t flags = 0x00;

	const int frameSize = this->pixelQuantity*3;

	size_t compressedBufferMaxSize;
	unsigned char *compressedBuffer = NULL;
	if (compressionEnabled) {
		flags = flags | FRAME_DATA_COMPRESSED_MASK;
		compressedBufferMaxSize = LZ4F_compressFrameBound(frameSize, NULL);
		compressedBuffer = new unsigned char[compressedBufferMaxSize];
	}

	const int bufferSize = PACKET_HEADER_SIZE + ((compressionEnabled && compressedBufferMaxSize > frameSize) ? compressedBufferMaxSize : frameSize);
	unsigned char *buffer = new unsigned char[bufferSize];
	buffer[sizeof(uint64_t) + 2*sizeof(uint8_t) - 1] = flags;

	using namespace std::chrono;
	while(isThreadRunning()) {

		waitForNewFrameMutex.lock();
		lock();
		if(this->sendBuffer.size()>0){
	        vector<DTFrame*>::iterator it = this->sendBuffer.begin();
	        this->sendBuffer.erase(it);
	        unlock();

	        uint8_t* raw_frame = (*it)->getRawFrameData();
			int raw_frame_length = (*it)->getPixelQuantity()*3;

			assert(raw_frame_length == this->pixelQuantity*3);

			uint64_t ms = htonll(duration_cast< milliseconds >(
			    system_clock::now().time_since_epoch()
			).count());

			convertToArrayOfBytes(&ms, sizeof(ms), buffer);
			convertToArrayOfBytes(&currentSeqNmb, sizeof(currentSeqNmb), buffer + sizeof(ms));

			if (compressionEnabled) {
				size_t compressedBufferSize = LZ4F_compressFrame(compressedBuffer, compressedBufferMaxSize, raw_frame, raw_frame_length, NULL);
				convertToArrayOfBytes(compressedBuffer, compressedBufferSize, buffer + PACKET_HEADER_SIZE);
				this->udpManager.Send((char*) buffer, PACKET_HEADER_SIZE + compressedBufferSize);
			} else {
				convertToArrayOfBytes(raw_frame, raw_frame_length, buffer + PACKET_HEADER_SIZE);
				this->udpManager.Send((char*) buffer, bufferSize);
			}

			currentSeqNmb = (currentSeqNmb + 1) % 256;

		} else {
	    	unlock();
	    }
	}
	this->udpManager.Close();
	delete[]buffer;
	delete[]compressedBuffer;
}
<|endoftext|>