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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_configmgr.hxx"

#ifndef CONFIGMGR_BACKENDHELPER_BACKENDLAYERHELPER_HXX_
#include "backendlayerhelper.hxx"
#endif //CONFIGMGR_BACKENDHELPER_BACKENDLAYERHELPER_HXX_

#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _CPPUHELPER_IMPLEMENTATIONENTRY_HXX_
#include <cppuhelper/implementationentry.hxx>
#endif // _CPPUHELPER_IMPLEMENTATIONENTRY_HXX_

using namespace configmgr::backendhelper ;

//==============================================================================

static uno::Reference<uno::XInterface> SAL_CALL createBackendLayerHelper(
                   const uno::Reference<uno::XComponentContext>& aContext) {
    return * new BackendLayerHelper(aContext) ;
}
//==============================================================================

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

static const cppu::ImplementationEntry kImplementations_entries[] =
{
    {
        createBackendLayerHelper,
        BackendLayerHelper::getBackendLayerHelperName,
        BackendLayerHelper::getBackendLayerHelperServiceNames,
        cppu::createSingleComponentFactory,
        NULL,
        0
    },
    { NULL, NULL, NULL, NULL, NULL, 0 }
} ;
//------------------------------------------------------------------------------

extern "C" void SAL_CALL component_getImplementationEnvironment(
                const sal_Char  **ppEnvTypeName,
                uno_Environment ** /* ppEnv */
            )
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ;
}
//------------------------------------------------------------------------------

extern "C" sal_Bool SAL_CALL component_writeInfo(void *aServiceManager,
                                                 void *aRegistryKey) {
    return cppu::component_writeInfoHelper(aServiceManager,
                                           aRegistryKey,
                                           kImplementations_entries) ;
}
//------------------------------------------------------------------------------

extern "C" void *component_getFactory(const sal_Char *aImplementationName,
                                      void *aServiceManager,
                                      void *aRegistryKey) {
    return cppu::component_getFactoryHelper(aImplementationName,
                                            aServiceManager,
                                            aRegistryKey,
                                            kImplementations_entries) ;
}
//------------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS changefileheader (1.5.72); FILE MERGED 2008/04/01 12:27:20 thb 1.5.72.2: #i85898# Stripping all external header guards 2008/03/31 12:22:41 rt 1.5.72.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: componentdf.cxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_configmgr.hxx"
#include "backendlayerhelper.hxx"
#include <com/sun/star/registry/XRegistryKey.hpp>
#ifndef _CPPUHELPER_IMPLEMENTATIONENTRY_HXX_
#include <cppuhelper/implementationentry.hxx>
#endif // _CPPUHELPER_IMPLEMENTATIONENTRY_HXX_

using namespace configmgr::backendhelper ;

//==============================================================================

static uno::Reference<uno::XInterface> SAL_CALL createBackendLayerHelper(
                   const uno::Reference<uno::XComponentContext>& aContext) {
    return * new BackendLayerHelper(aContext) ;
}
//==============================================================================

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

static const cppu::ImplementationEntry kImplementations_entries[] =
{
    {
        createBackendLayerHelper,
        BackendLayerHelper::getBackendLayerHelperName,
        BackendLayerHelper::getBackendLayerHelperServiceNames,
        cppu::createSingleComponentFactory,
        NULL,
        0
    },
    { NULL, NULL, NULL, NULL, NULL, 0 }
} ;
//------------------------------------------------------------------------------

extern "C" void SAL_CALL component_getImplementationEnvironment(
                const sal_Char  **ppEnvTypeName,
                uno_Environment ** /* ppEnv */
            )
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ;
}
//------------------------------------------------------------------------------

extern "C" sal_Bool SAL_CALL component_writeInfo(void *aServiceManager,
                                                 void *aRegistryKey) {
    return cppu::component_writeInfoHelper(aServiceManager,
                                           aRegistryKey,
                                           kImplementations_entries) ;
}
//------------------------------------------------------------------------------

extern "C" void *component_getFactory(const sal_Char *aImplementationName,
                                      void *aServiceManager,
                                      void *aRegistryKey) {
    return cppu::component_getFactoryHelper(aImplementationName,
                                            aServiceManager,
                                            aRegistryKey,
                                            kImplementations_entries) ;
}
//------------------------------------------------------------------------------
<|endoftext|>


<commit_before>#include <gtsplibinstance.h>
#include <typeinfo>
#include <parser/exceptions/exceptions.h>
#include <sstream>

using namespace TSPLIB;

GTSPInstance::GTSPInstance(Instance &instance, TSP::TYPE type)
    : BaseInstance(instance, type)
{
    try {
        GTSPInstance &other = dynamic_cast<GTSPInstance&>(instance);
        // Copy the information from the other GTSP
        // TODO
    } catch(std::bad_cast) {
        // ignore
    }
}

bool GTSPInstance::set_gtsp_cluster_amount(int size)
{
    return true;
}

/**
 * Converts a string of integers to the cluster definitions
 * as follows:
 * add the nodes to the current cluster in case it is not a boundary token (-1)
 * otherwise, add the node to the current cluster
 *
 * Empties the incoming vector
 *
 * @param cluster_definition
 * @return
 */
bool GTSPInstance::set_gtsp_clusters(std::vector<int> cluster_definition)
{
    // TODO: double check for malformed input; does this method always terminate?

    auto begin = cluster_definition.begin();
    auto cluster = 0;
    while(begin != cluster_definition.end()) {
        auto end = begin;
        while(end != cluster_definition.end() && *end != -1) {
            ++end;
        }

        // ASSUMPTION: the cluster numbers are always incremented by 1, starting from 1
        begin++; // skip the cluster index

        clusters.resize(cluster + 1); // potentially expensive

        std::vector<unsigned int> cluster_list;
        for(auto it = begin; it != end; ++it) {
            clusters[cluster].push_back((*it) -1);
        }

        cluster++;
        begin = ++end;
    }

    return true;
}

std::vector<std::vector<unsigned int>> GTSPInstance::get_clusters() const
{
    return clusters;
}
<commit_msg>Remove the unsigned restriction from the definition of clusters...<commit_after>#include <gtsplibinstance.h>
#include <typeinfo>
#include <parser/exceptions/exceptions.h>
#include <sstream>

using namespace TSPLIB;

GTSPInstance::GTSPInstance(Instance &instance, TSP::TYPE type)
    : BaseInstance(instance, type)
{
    try {
        GTSPInstance &other = dynamic_cast<GTSPInstance&>(instance);
        // Copy the information from the other GTSP
        // TODO
    } catch(std::bad_cast) {
        // ignore
    }
}

bool GTSPInstance::set_gtsp_cluster_amount(int size)
{
    return true;
}

/**
 * Converts a string of integers to the cluster definitions
 * as follows:
 * add the nodes to the current cluster in case it is not a boundary token (-1)
 * otherwise, add the node to the current cluster
 *
 * @param cluster_definition
 * @return
 */
bool GTSPInstance::set_gtsp_clusters(std::vector<int> cluster_definition)
{
    unsigned int cluster = 0; // convert to internal 0-based indexing
    for(int node : cluster_definition) {
        if(node == -1) {
            cluster++;
        } else if(0 >= node || node > dimension) {
            std::ostringstream err;
            err << "Node value " << node << " is out of range! Dimension of the problem is " << dimension;
            throw TSP::PARSER::Inconsistent_definition_exception(err.str());
        } else {
            if(clusters.size() < cluster + 1) {
                clusters.resize(cluster + 1);
            }
            clusters[cluster].push_back(node-1); // convert to internal 0-based indexing
        }
    }
    return true;
}

<|endoftext|>


<commit_before>// Copyright (C) 2012-2014 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "AutoPacketFactoryTest.hpp"
#include <autowiring/CoreThread.h>

TEST_F(AutoPacketFactoryTest, VerifyNoIssueWhileNotStarted) {
  AutoRequired<AutoPacketFactory> factory;
  ASSERT_THROW(factory->NewPacket(), autowiring_error) << "Issuing a packet in a context that has not yet been started should throw an exception";
}

TEST_F(AutoPacketFactoryTest, StopReallyStops) {
  AutoCurrentContext()->SignalShutdown();

  AutoRequired<AutoPacketFactory> factory;
  ASSERT_TRUE(factory->ShouldStop()) << "Expected that an attempt to insert a packet factory to an already-stopped context would stop the packet factory";
}

TEST_F(AutoPacketFactoryTest, VerifyNoIssueWhileStopped) {
  AutoCurrentContext()->SignalShutdown();

  AutoRequired<AutoPacketFactory> factory;
  ASSERT_THROW(factory->NewPacket(), autowiring_error) << "Issuing a packet in a context that has already been stopped should throw an exception";
}

class IssuesPacketWaitsThenQuits:
  public CoreThread
{
public:
  IssuesPacketWaitsThenQuits(void) :
    m_hasQuit(false)
  {
    // Note:  Don't do this in practice.  This only works because we only inject this type
    // into a context that's already running; normally, creating a packet from our ctor can
    // cause an exception if we are being injected before Initiate is called.
    AutoRequired<AutoPacketFactory> factory;
    m_packet = factory->NewPacket();
  }

  bool m_hasQuit;
  std::shared_ptr<AutoPacket> m_packet;

  void Run(void) override {
    // Move shared pointer locally:
    std::shared_ptr<AutoPacket> packet;
    std::swap(packet, m_packet);

    // Just wait a bit, then return, just like we said we would
    this->ThreadSleep(std::chrono::milliseconds(50));

    // Update our variable and then return out:
    m_hasQuit = true;
  }
};

TEST_F(AutoPacketFactoryTest, WaitRunsDownAllPackets) {
  AutoCurrentContext()->Initiate();

  // Create a factory in our context, factory had better be started:
  AutoRequired<AutoPacketFactory> factory;
  ASSERT_TRUE(factory->IsRunning()) << "Factory was not started even though it was a member of an initiated context";

  // Make the thread create and hold a packet, and then return
  AutoRequired<IssuesPacketWaitsThenQuits> ipwtq;

  // Shutdown context
  AutoCurrentContext()->SignalShutdown();

  // Now we're going to try to run down the factory:
  factory->Wait();

  // Verify that the thread has quit:
  ASSERT_TRUE(ipwtq->m_hasQuit) << "AutoPacketFactory::Wait returned prematurely";
}

class HoldsAutoPacketFactoryReference {
public:
  HoldsAutoPacketFactoryReference(void):
    m_value(0)
  {}

  AutoRequired<AutoPacketFactory> m_factory;
  int m_value;

  // Just a dummy AutoFilter method so that this class is recognized as an AutoFilter
  void AutoFilter(int value) {
    m_value = value;
  }
};

TEST_F(AutoPacketFactoryTest, AutoPacketFactoryCycle) {
  std::weak_ptr<CoreContext> ctxtWeak;
  std::weak_ptr<HoldsAutoPacketFactoryReference> hapfrWeak;
  std::shared_ptr<AutoPacket> packet;

  {
    // Create a context, fill it up, kick it off:
    AutoCreateContext ctxt;
    CurrentContextPusher pshr(ctxt);
    AutoRequired<HoldsAutoPacketFactoryReference> hapfr(ctxt);
    ctxt->Initiate();

    // A weak pointer is used to detect object destruction
    ctxtWeak = ctxt;
    hapfrWeak = hapfr;

    // Trivial validation-of-reciept:
    AutoRequired<AutoPacketFactory> factory;
    {
      auto trivial = factory->NewPacket();
      trivial->Decorate((int) 54);
      ASSERT_EQ(54, hapfr->m_value) << "A simple packet was not received as expected by an AutoFilter";
    }

    // Create a packet which will force in a back-reference:
    packet = factory->NewPacket();

    // Terminate the context:
    ctxt->SignalShutdown();

    // Verify that we can still decorate the packet and also that the packet is delivered to the factory:
    packet->Decorate((int) 55);

    // Relock, verify the value was received by the hapfr:
    ASSERT_EQ(55, hapfr->m_value) << "AutoFilter did not receive a packet as expected";
  }

  // Verify that the context went out of scope as expected
  ASSERT_TRUE(ctxtWeak.expired()) << "AutoPacketFactory incorrectly held a cyclic reference even after the context was shut down";

  // Now we can release the packet and verify that everything gets cleaned up:
  packet.reset();
  ASSERT_TRUE(hapfrWeak.expired()) << "The last packet from a factory was released; this should have resulted in teardown, but it did not";
}<commit_msg>Fixing incorrect unit test<commit_after>// Copyright (C) 2012-2014 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "AutoPacketFactoryTest.hpp"
#include <autowiring/CoreThread.h>

TEST_F(AutoPacketFactoryTest, VerifyNoIssueWhileNotStarted) {
  AutoRequired<AutoPacketFactory> factory;
  ASSERT_THROW(factory->NewPacket(), autowiring_error) << "Issuing a packet in a context that has not yet been started should throw an exception";
}

TEST_F(AutoPacketFactoryTest, StopReallyStops) {
  AutoCurrentContext()->SignalShutdown();

  AutoRequired<AutoPacketFactory> factory;
  ASSERT_TRUE(factory->ShouldStop()) << "Expected that an attempt to insert a packet factory to an already-stopped context would stop the packet factory";
}

TEST_F(AutoPacketFactoryTest, VerifyNoIssueWhileStopped) {
  AutoCurrentContext()->SignalShutdown();

  AutoRequired<AutoPacketFactory> factory;
  ASSERT_THROW(factory->NewPacket(), autowiring_error) << "Issuing a packet in a context that has already been stopped should throw an exception";
}

class IssuesPacketWaitsThenQuits:
  public CoreThread
{
public:
  IssuesPacketWaitsThenQuits(void) :
    m_hasQuit(false)
  {
    // Note:  Don't do this in practice.  This only works because we only inject this type
    // into a context that's already running; normally, creating a packet from our ctor can
    // cause an exception if we are being injected before Initiate is called.
    AutoRequired<AutoPacketFactory> factory;
    m_packet = factory->NewPacket();
  }

  bool m_hasQuit;
  std::shared_ptr<AutoPacket> m_packet;

  void Run(void) override {
    // Move shared pointer locally:
    std::shared_ptr<AutoPacket> packet;
    std::swap(packet, m_packet);

    // Just wait a bit, then return, just like we said we would
    this->ThreadSleep(std::chrono::milliseconds(50));

    // Update our variable and then return out:
    m_hasQuit = true;
  }
};

TEST_F(AutoPacketFactoryTest, WaitRunsDownAllPackets) {
  AutoCurrentContext()->Initiate();

  // Create a factory in our context, factory had better be started:
  AutoRequired<AutoPacketFactory> factory;
  ASSERT_TRUE(factory->IsRunning()) << "Factory was not started even though it was a member of an initiated context";

  // Make the thread create and hold a packet, and then return
  AutoRequired<IssuesPacketWaitsThenQuits> ipwtq;

  // Shutdown context
  AutoCurrentContext()->SignalShutdown();

  // Now we're going to try to run down the factory:
  factory->Wait();

  // Verify that the thread has quit:
  ASSERT_TRUE(ipwtq->m_hasQuit) << "AutoPacketFactory::Wait returned prematurely";
}

class HoldsAutoPacketFactoryReference {
public:
  HoldsAutoPacketFactoryReference(void):
    m_value(0)
  {}

  AutoRequired<AutoPacketFactory> m_factory;
  int m_value;

  // Just a dummy AutoFilter method so that this class is recognized as an AutoFilter
  void AutoFilter(int value) {
    m_value = value;
  }
};

TEST_F(AutoPacketFactoryTest, AutoPacketFactoryCycle) {
  std::weak_ptr<CoreContext> ctxtWeak;
  std::weak_ptr<HoldsAutoPacketFactoryReference> hapfrWeak;
  std::shared_ptr<AutoPacket> packet;

  {
    // Create a context, fill it up, kick it off:
    AutoCreateContext ctxt;
    CurrentContextPusher pshr(ctxt);
    AutoRequired<HoldsAutoPacketFactoryReference> hapfr(ctxt);
    ctxt->Initiate();

    // A weak pointer is used to detect object destruction
    ctxtWeak = ctxt;
    hapfrWeak = hapfr;

    // Trivial validation-of-reciept:
    AutoRequired<AutoPacketFactory> factory;
    {
      auto trivial = factory->NewPacket();
      trivial->Decorate((int) 54);
      ASSERT_EQ(54, hapfr->m_value) << "A simple packet was not received as expected by an AutoFilter";
    }

    // Create a packet which will force in a back-reference:
    packet = factory->NewPacket();

    // Terminate the context:
    ctxt->SignalShutdown();

    // Verify that we can still decorate the packet and also that the packet is delivered to the factory:
    packet->Decorate((int) 55);

    // Relock, verify the value was received by the hapfr:
    ASSERT_EQ(55, hapfr->m_value) << "AutoFilter did not receive a packet as expected";
  }

  // The context cannot go out of socpe until all packets in the context are out of scope
  ASSERT_FALSE(ctxtWeak.expired()) << "Context went out of scope before all packets were finished being processed";

  // Now we can release the packet and verify that everything gets cleaned up:
  packet.reset();
  ASSERT_TRUE(ctxtWeak.expired()) << "AutoPacketFactory incorrectly held a cyclic reference even after the context was shut down";
  ASSERT_TRUE(hapfrWeak.expired()) << "The last packet from a factory was released; this should have resulted in teardown, but it did not";
}<|endoftext|>


<commit_before>#include "simulator.h"
#include "log.h"
#include "lcp.h"
#include "mcp.h"
#include "core.h"
#include "core_manager.h"
#include "thread_manager.h"
#include "sim_thread_manager.h"

Simulator *Simulator::m_singleton;
config::Config *Simulator::m_config_file;

void Simulator::allocate()
{
   assert(m_singleton == NULL);
   m_singleton = new Simulator();
}

void Simulator::setConfig(config::Config *cfg)
{
   m_config_file = cfg;
}

void Simulator::release()
{
   delete m_singleton;
   m_singleton = NULL;
}

Simulator* Simulator::getSingleton()
{
   return m_singleton;
}

Simulator::Simulator()
   : m_mcp(NULL)
   , m_mcp_thread(NULL)
   , m_lcp(NULL)
   , m_lcp_thread(NULL)
   , m_config()
   , m_log(m_config.getTotalCores())
   , m_transport(NULL)
   , m_core_manager(NULL)
   , m_thread_manager(NULL)
   , m_sim_thread_manager(NULL)
   , m_finished(false)
{
}

void Simulator::start()
{
   LOG_PRINT("In Simulator ctor.");

   m_config.logCoreMap();

   m_transport = Transport::create();
   m_core_manager = new CoreManager();
   m_thread_manager = new ThreadManager(m_core_manager);
   m_sim_thread_manager = new SimThreadManager();

   startMCP();

   m_sim_thread_manager->spawnSimThreads();

   m_lcp = new LCP();
   m_lcp_thread = Thread::create(m_lcp);
   m_lcp_thread->run();
}

Simulator::~Simulator()
{
   LOG_PRINT("Simulator dtor starting...");

   broadcastFinish();

   endMCP();

   m_sim_thread_manager->quitSimThreads();

   m_transport->barrier();

   m_lcp->finish();

   m_core_manager->outputSummary();

   delete m_lcp_thread;
   delete m_mcp_thread;
   delete m_lcp;
   delete m_mcp;
   delete m_sim_thread_manager;
   delete m_thread_manager;
   delete m_core_manager;
   delete m_transport;

   LOG_PRINT("Simulator dtor finished.");
}

void Simulator::broadcastFinish()
{
   if (Config::getSingleton()->getCurrentProcessNum() != 0)
      return;

   m_num_procs_finished = 1;

   // let the rest of the simulator know its time to exit
   Transport::Node *globalNode = Transport::getSingleton()->getGlobalNode();

   SInt32 msg = LCP_MESSAGE_SIMULATOR_FINISHED;
   for (UInt32 i = 1; i < Config::getSingleton()->getProcessCount(); i++)
   {
      globalNode->globalSend(i, &msg, sizeof(msg));
   }

   while (m_num_procs_finished < Config::getSingleton()->getProcessCount())
   {
      sched_yield();
   }
}

void Simulator::handleFinish()
{
   LOG_ASSERT_ERROR(Config::getSingleton()->getCurrentProcessNum() != 0,
                    "LCP_MESSAGE_SIMULATOR_FINISHED received on master process.");

   Transport::Node *globalNode = Transport::getSingleton()->getGlobalNode();
   SInt32 msg = LCP_MESSAGE_SIMULATOR_FINISHED_ACK;
   globalNode->globalSend(0, &msg, sizeof(msg));

   m_finished = true;
}

void Simulator::deallocateProcess()
{
   LOG_ASSERT_ERROR(Config::getSingleton()->getCurrentProcessNum() == 0,
                    "LCP_MESSAGE_SIMULATOR_FINISHED_ACK received on slave process.");

   ++m_num_procs_finished;
}

void Simulator::startMCP()
{
   if (m_config.getCurrentProcessNum() != m_config.getProcessNumForCore(Config::getSingleton()->getMCPCoreNum()))
      return;

   LOG_PRINT("Creating new MCP object in process %i", m_config.getCurrentProcessNum());

   // FIXME: Can't the MCP look up its network itself in the
   // constructor?
   Core * mcp_core = m_core_manager->getCoreFromID(m_config.getMCPCoreNum());
   LOG_ASSERT_ERROR(mcp_core, "Could not find the MCP's core!");

   Network & mcp_network = *(mcp_core->getNetwork());
   m_mcp = new MCP(mcp_network);

   m_mcp_thread = Thread::create(m_mcp);
   m_mcp_thread->run();
}

void Simulator::endMCP()
{
   if (m_config.getCurrentProcessNum() == m_config.getProcessNumForCore(m_config.getMCPCoreNum()))
      m_mcp->finish();
}

bool Simulator::finished()
{
   return m_finished;
}
<commit_msg>[logs] Remove final log output from simulator.cc<commit_after>#include "simulator.h"
#include "log.h"
#include "lcp.h"
#include "mcp.h"
#include "core.h"
#include "core_manager.h"
#include "thread_manager.h"
#include "sim_thread_manager.h"

Simulator *Simulator::m_singleton;
config::Config *Simulator::m_config_file;

void Simulator::allocate()
{
   assert(m_singleton == NULL);
   m_singleton = new Simulator();
}

void Simulator::setConfig(config::Config *cfg)
{
   m_config_file = cfg;
}

void Simulator::release()
{
   delete m_singleton;
   m_singleton = NULL;
}

Simulator* Simulator::getSingleton()
{
   return m_singleton;
}

Simulator::Simulator()
   : m_mcp(NULL)
   , m_mcp_thread(NULL)
   , m_lcp(NULL)
   , m_lcp_thread(NULL)
   , m_config()
   , m_log(m_config.getTotalCores())
   , m_transport(NULL)
   , m_core_manager(NULL)
   , m_thread_manager(NULL)
   , m_sim_thread_manager(NULL)
   , m_finished(false)
{
}

void Simulator::start()
{
   LOG_PRINT("In Simulator ctor.");

   m_config.logCoreMap();

   m_transport = Transport::create();
   m_core_manager = new CoreManager();
   m_thread_manager = new ThreadManager(m_core_manager);
   m_sim_thread_manager = new SimThreadManager();

   startMCP();

   m_sim_thread_manager->spawnSimThreads();

   m_lcp = new LCP();
   m_lcp_thread = Thread::create(m_lcp);
   m_lcp_thread->run();
}

Simulator::~Simulator()
{
   LOG_PRINT("Simulator dtor starting...");

   broadcastFinish();

   endMCP();

   m_sim_thread_manager->quitSimThreads();

   m_transport->barrier();

   m_lcp->finish();

   m_core_manager->outputSummary();

   delete m_lcp_thread;
   delete m_mcp_thread;
   delete m_lcp;
   delete m_mcp;
   delete m_sim_thread_manager;
   delete m_thread_manager;
   delete m_core_manager;
   delete m_transport;
}

void Simulator::broadcastFinish()
{
   if (Config::getSingleton()->getCurrentProcessNum() != 0)
      return;

   m_num_procs_finished = 1;

   // let the rest of the simulator know its time to exit
   Transport::Node *globalNode = Transport::getSingleton()->getGlobalNode();

   SInt32 msg = LCP_MESSAGE_SIMULATOR_FINISHED;
   for (UInt32 i = 1; i < Config::getSingleton()->getProcessCount(); i++)
   {
      globalNode->globalSend(i, &msg, sizeof(msg));
   }

   while (m_num_procs_finished < Config::getSingleton()->getProcessCount())
   {
      sched_yield();
   }
}

void Simulator::handleFinish()
{
   LOG_ASSERT_ERROR(Config::getSingleton()->getCurrentProcessNum() != 0,
                    "LCP_MESSAGE_SIMULATOR_FINISHED received on master process.");

   Transport::Node *globalNode = Transport::getSingleton()->getGlobalNode();
   SInt32 msg = LCP_MESSAGE_SIMULATOR_FINISHED_ACK;
   globalNode->globalSend(0, &msg, sizeof(msg));

   m_finished = true;
}

void Simulator::deallocateProcess()
{
   LOG_ASSERT_ERROR(Config::getSingleton()->getCurrentProcessNum() == 0,
                    "LCP_MESSAGE_SIMULATOR_FINISHED_ACK received on slave process.");

   ++m_num_procs_finished;
}

void Simulator::startMCP()
{
   if (m_config.getCurrentProcessNum() != m_config.getProcessNumForCore(Config::getSingleton()->getMCPCoreNum()))
      return;

   LOG_PRINT("Creating new MCP object in process %i", m_config.getCurrentProcessNum());

   // FIXME: Can't the MCP look up its network itself in the
   // constructor?
   Core * mcp_core = m_core_manager->getCoreFromID(m_config.getMCPCoreNum());
   LOG_ASSERT_ERROR(mcp_core, "Could not find the MCP's core!");

   Network & mcp_network = *(mcp_core->getNetwork());
   m_mcp = new MCP(mcp_network);

   m_mcp_thread = Thread::create(m_mcp);
   m_mcp_thread->run();
}

void Simulator::endMCP()
{
   if (m_config.getCurrentProcessNum() == m_config.getProcessNumForCore(m_config.getMCPCoreNum()))
      m_mcp->finish();
}

bool Simulator::finished()
{
   return m_finished;
}
<|endoftext|>


<commit_before><commit_msg>fix texbox vertical alignment, it was regression introduced by f1a2b0cb<commit_after><|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "boost/python.hpp"

#include "maya/MPxNode.h"
#include "maya/MSelectionList.h"
#include "maya/MFnDependencyNode.h"

#include "IECore/Parameterised.h"

#include "IECoreMaya/IECoreMaya.h"
#include "IECoreMaya/bindings/ParameterisedHolderBinding.h"
#include "IECoreMaya/bindings/MayaPythonUtilBinding.h"
#include "IECoreMaya/bindings/MObjectBinding.h"
#include "IECoreMaya/bindings/NodeBinding.h"
#include "IECoreMaya/bindings/DagNodeBinding.h"
#include "IECoreMaya/bindings/ConverterBinding.h"
#include "IECoreMaya/bindings/FromMayaConverterBinding.h"
#include "IECoreMaya/bindings/FromMayaPlugConverterBinding.h"
#include "IECoreMaya/bindings/PlugBinding.h"
#include "IECoreMaya/bindings/FromMayaObjectConverterBinding.h"
#include "IECoreMaya/bindings/FromMayaCameraConverterBinding.h"
#include "IECoreMaya/bindings/FromMayaCameraConverterBinding.h"
#include "IECoreMaya/bindings/MayaMeshBuilderBinding.h"

using namespace IECore;
using namespace IECoreMaya;

using namespace boost::python;

/// Maya 8.5 is built with 2-byte Unicode characters, Maya 2008 with 4-byte characters.
/// So we need to ensure that we're doing the same so that all external symbols resolve
/// correctly at runtime.
#if ( MAYA_API_VERSION >= 2008 )
BOOST_STATIC_ASSERT(sizeof(Py_UNICODE) == 4);
#else
BOOST_STATIC_ASSERT(sizeof(Py_UNICODE) == 2);
#endif

BOOST_PYTHON_MODULE(_IECoreMaya)
{
	bindMayaPythonUtil();
	bindMObject();
	bindNode();
	bindDagNode();
	bindParameterisedHolder();
	bindConverter();
	bindFromMayaConverter();
	bindFromMayaPlugConverter();
	bindPlug();
	bindFromMayaObjectConverter();
	bindFromMayaCameraConverter();
	bindMayaMeshBuilder();

	def( "majorVersion", &IECoreMaya::majorVersion );
	def( "minorVersion", &IECoreMaya::minorVersion );
	def( "patchVersion", &IECoreMaya::patchVersion );
	def( "versionString", &IECoreMaya::versionString, return_value_policy<copy_const_reference>() );
}
<commit_msg>Fixed unicode assert for builds outside IE<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "boost/python.hpp"

#include "maya/MPxNode.h"
#include "maya/MSelectionList.h"
#include "maya/MFnDependencyNode.h"

#include "IECore/Parameterised.h"

#include "IECoreMaya/IECoreMaya.h"
#include "IECoreMaya/bindings/ParameterisedHolderBinding.h"
#include "IECoreMaya/bindings/MayaPythonUtilBinding.h"
#include "IECoreMaya/bindings/MObjectBinding.h"
#include "IECoreMaya/bindings/NodeBinding.h"
#include "IECoreMaya/bindings/DagNodeBinding.h"
#include "IECoreMaya/bindings/ConverterBinding.h"
#include "IECoreMaya/bindings/FromMayaConverterBinding.h"
#include "IECoreMaya/bindings/FromMayaPlugConverterBinding.h"
#include "IECoreMaya/bindings/PlugBinding.h"
#include "IECoreMaya/bindings/FromMayaObjectConverterBinding.h"
#include "IECoreMaya/bindings/FromMayaCameraConverterBinding.h"
#include "IECoreMaya/bindings/FromMayaCameraConverterBinding.h"
#include "IECoreMaya/bindings/MayaMeshBuilderBinding.h"

using namespace IECore;
using namespace IECoreMaya;

using namespace boost::python;

/// Maya is built with 4-byte Unicode characters, so we need to ensure that we're doing
/// the same so that all external symbols resolve correctly at runtime.
#if ( MAYA_API_VERSION >= 2008 )
/// \todo Assert for earlier versions too, once installations of Python 2.5 for gcc4.0.2
/// are built correctly
BOOST_STATIC_ASSERT(sizeof(Py_UNICODE) == 4);
#endif

BOOST_PYTHON_MODULE(_IECoreMaya)
{
	bindMayaPythonUtil();
	bindMObject();
	bindNode();
	bindDagNode();
	bindParameterisedHolder();
	bindConverter();
	bindFromMayaConverter();
	bindFromMayaPlugConverter();
	bindPlug();
	bindFromMayaObjectConverter();
	bindFromMayaCameraConverter();
	bindMayaMeshBuilder();

	def( "majorVersion", &IECoreMaya::majorVersion );
	def( "minorVersion", &IECoreMaya::minorVersion );
	def( "patchVersion", &IECoreMaya::patchVersion );
	def( "versionString", &IECoreMaya::versionString, return_value_policy<copy_const_reference>() );
}
<|endoftext|>


<commit_before>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  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.
 */
/*
 * Copyright 2015 Cloudius Systems
 */

#include "http/httpd.hh"
#include "http/handlers.hh"
#include "http/function_handlers.hh"
#include "http/file_handler.hh"
#include "apps/httpd/demo.json.hh"

namespace bpo = boost::program_options;

using namespace httpd;

class handl : public httpd::handler_base {
public:
    virtual future<std::unique_ptr<reply> > handle(const sstring& path,
            std::unique_ptr<request> req, std::unique_ptr<reply> rep) {
        rep->_content = "hello";
        rep->done("html");
        return make_ready_future<std::unique_ptr<reply>>(std::move(rep));
    }
};

void set_routes(routes& r) {
    function_handler* h1 = new function_handler([](const_req req) {
        return "hello";
    });
    function_handler* h2 = new function_handler([](std::unique_ptr<request> req) {
            return make_ready_future<json::json_return_type>("json-future");
    });
    r.add(operation_type::GET, url("/"), h1);
    r.add(operation_type::GET, url("/jf"), h2);
    r.add(operation_type::GET, url("/file").remainder("path"),
            new directory_handler("/"));
    demo_json::hello_world.set(r,
            [](const_req req) {
                demo_json::my_object obj;
                obj.var1 = req.param.at("var1");
                obj.var2 = req.param.at("var2");
                demo_json::ns_hello_world::query_enum v = demo_json::ns_hello_world::str2query_enum(req.query_parameters.at("query_enum"));
                // This demonstrate enum conversion
                obj.enum_var = v;
                return obj;
            });
}

int main(int ac, char** av) {
    app_template app;
    app.add_options()("port", bpo::value<uint16_t>()->default_value(10000),
            "HTTP Server port");
    return app.run(ac, av,
            [&] {
                auto&& config = app.configuration();
                uint16_t port = config["port"].as<uint16_t>();
                auto server = new distributed<http_server>;
                server->start().then([server = std::move(server), port] () mutable {
                            server->invoke_on_all([](http_server& server) {
                                set_routes(server._routes);
                            });
                            server->invoke_on_all(&http_server::listen, ipv4_addr {port});
                        }).then([port] {
                            std::cout << "Seastar HTTP server listening on port " << port << " ...\n";
                        });
            });
}
<commit_msg>httpd main using the http_server_control to start the server<commit_after>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  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.
 */
/*
 * Copyright 2015 Cloudius Systems
 */

#include "http/httpd.hh"
#include "http/handlers.hh"
#include "http/function_handlers.hh"
#include "http/file_handler.hh"
#include "apps/httpd/demo.json.hh"
#include "http/api_docs.hh"

namespace bpo = boost::program_options;

using namespace httpd;

class handl : public httpd::handler_base {
public:
    virtual future<std::unique_ptr<reply> > handle(const sstring& path,
            std::unique_ptr<request> req, std::unique_ptr<reply> rep) {
        rep->_content = "hello";
        rep->done("html");
        return make_ready_future<std::unique_ptr<reply>>(std::move(rep));
    }
};

void set_routes(routes& r) {
    function_handler* h1 = new function_handler([](const_req req) {
        return "hello";
    });
    function_handler* h2 = new function_handler([](std::unique_ptr<request> req) {
            return make_ready_future<json::json_return_type>("json-future");
    });
    r.add(operation_type::GET, url("/"), h1);
    r.add(operation_type::GET, url("/jf"), h2);
    r.add(operation_type::GET, url("/file").remainder("path"),
            new directory_handler("/"));
    demo_json::hello_world.set(r,
            [](const_req req) {
                demo_json::my_object obj;
                obj.var1 = req.param.at("var1");
                obj.var2 = req.param.at("var2");
                demo_json::ns_hello_world::query_enum v = demo_json::ns_hello_world::str2query_enum(req.query_parameters.at("query_enum"));
                // This demonstrate enum conversion
                obj.enum_var = v;
                return obj;
            });
}

int main(int ac, char** av) {
    app_template app;
    app.add_options()("port", bpo::value<uint16_t>()->default_value(10000),
            "HTTP Server port");
    return app.run(ac, av,
            [&] {
                auto&& config = app.configuration();
                uint16_t port = config["port"].as<uint16_t>();
                auto server = new http_server_control();
                auto rb= make_shared<api_registry_builder>("apps/httpd/");
                server->start().then([server] {
                    server->set_routes(set_routes);
                }).then([server, rb]{
                    server->set_routes(rb->set_api_doc());
                }).then([server, rb]{
                    server->set_routes(rb->register_function("demo", "hello world application"));
                }).then([server, port] {
                    server->listen(port);
                }).then([port] {
                    std::cout << "Seastar HTTP server listening on port " << port << " ...\n";
                });

            });
}
<|endoftext|>


<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// Base class for a tire.
// A tire subsystem is a force element. It is passed position and velocity
// information of the wheel body and it produces ground reaction forces and
// moments to be applied to the wheel body.
//
// =============================================================================

#include <cmath>

#include "chrono/physics/ChSystem.h"
#include "chrono_vehicle/wheeled_vehicle/ChTire.h"

namespace chrono {
namespace vehicle {

ChTire::ChTire(const std::string& name)
    : ChPart(name), m_stepsize(1e-3), m_slip_angle(0), m_longitudinal_slip(0), m_camber_angle(0) {}

// -----------------------------------------------------------------------------
// Base class implementation of the initialization function.
// -----------------------------------------------------------------------------
void ChTire::Initialize(std::shared_ptr<ChBody> wheel, VehicleSide side) {
    m_wheel = wheel;
    m_side = side;

    // Increment mass and inertia of the wheel body.
    wheel->SetMass(wheel->GetMass() + GetMass());
    wheel->SetInertiaXX(wheel->GetInertiaXX() + GetInertia());
}

// -----------------------------------------------------------------------------
// Default implementation of ReportMass simply returns the value from GetMass.
// However, concrete tire models which need to return 0 from GetMass (so that
// the mass of the tire is not double counted) will override this function.
// -----------------------------------------------------------------------------
double ChTire::ReportMass() const {
    return GetMass();
}

// -----------------------------------------------------------------------------
// Calculate kinematics quantities (slip angle, longitudinal slip, camber angle,
// and toe-in angle using the current state of the associated wheel body.
// -----------------------------------------------------------------------------
void ChTire::CalculateKinematics(double time, const WheelState& state, const ChTerrain& terrain) {
    // Wheel normal (expressed in global frame)
    ChVector<> wheel_normal = state.rot.GetYaxis();

    // Terrain normal at wheel location (expressed in global frame)
    ChVector<> Z_dir = terrain.GetNormal(state.pos.x(), state.pos.y());

    // Longitudinal (heading) and lateral directions, in the terrain plane
    ChVector<> X_dir = Vcross(wheel_normal, Z_dir);
    X_dir.Normalize();
    ChVector<> Y_dir = Vcross(Z_dir, X_dir);

    // Tire reference coordinate system
    ChMatrix33<> rot;
    rot.Set_A_axis(X_dir, Y_dir, Z_dir);
    ChCoordsys<> tire_csys(state.pos, rot.Get_A_quaternion());

    // Express wheel linear velocity in tire frame
    ChVector<> V = tire_csys.TransformDirectionParentToLocal(state.lin_vel);
    // Express wheel normal in tire frame
    ChVector<> n = tire_csys.TransformDirectionParentToLocal(wheel_normal);

    // Slip angle
    double abs_Vx = std::abs(V.x());
    double zero_Vx = 1e-4;
    m_slip_angle = (abs_Vx > zero_Vx) ? std::atan(V.y() / abs_Vx) : 0;

    // Longitudinal slip
    m_longitudinal_slip = (abs_Vx > zero_Vx) ? -(V.x() - state.omega * GetRadius()) / abs_Vx : 0;

    // Camber angle
    m_camber_angle = std::atan2(n.z(), n.y());
}

// -----------------------------------------------------------------------------
// Utility function for characterizing the geometric contact between a disc with
// specified center location, normal direction, and radius and the terrain,
// assumed to be specified as a height field (over the x-y domain).
// This function returns false if no contact occurs. Otherwise, it sets the
// contact points on the disc (ptD) and on the terrain (ptT), the normal contact
// direction, and the resulting penetration depth (a positive value).
// -----------------------------------------------------------------------------
bool ChTire::disc_terrain_contact(const ChTerrain& terrain,
                                  const ChVector<>& disc_center,
                                  const ChVector<>& disc_normal,
                                  double disc_radius,
                                  ChCoordsys<>& contact,
                                  double& depth) {
    // Find terrain height below disc center. There is no contact if the disc
    // center is below the terrain or farther away by more than its radius.
    double hc = terrain.GetHeight(disc_center.x(), disc_center.y());
    if (disc_center.z() <= hc || disc_center.z() >= hc + disc_radius)
        return false;

    // Find the lowest point on the disc. There is no contact if the disc is
    // (almost) horizontal.
    ChVector<> dir1 = Vcross(disc_normal, ChVector<>(0, 0, 1));
    double sinTilt2 = dir1.Length2();

    if (sinTilt2 < 1e-3)
        return false;

    // Contact point (lowest point on disc).
    ChVector<> ptD = disc_center + disc_radius * Vcross(disc_normal, dir1 / sqrt(sinTilt2));

    // Find terrain height at lowest point. No contact if lowest point is above
    // the terrain.
    double hp = terrain.GetHeight(ptD.x(), ptD.y());

    if (ptD.z() > hp)
        return false;

    // Approximate the terrain with a plane. Define the projection of the lowest
    // point onto this plane as the contact point on the terrain.
    ChVector<> normal = terrain.GetNormal(ptD.x(), ptD.y());
    ChVector<> longitudinal = Vcross(disc_normal, normal);
    longitudinal.Normalize();
    ChVector<> lateral = Vcross(normal, longitudinal);
    ChMatrix33<> rot;
    rot.Set_A_axis(longitudinal, lateral, normal);

    contact.pos = ptD;
    contact.rot = rot.Get_A_quaternion();

    depth = Vdot(ChVector<>(0, 0, hp - ptD.z()), normal);
    assert(depth > 0);

    return true;
}

// -----------------------------------------------------------------------------
// Estimate the tire moments of inertia, given the tire specification and mass.
// The tire is assumed to be composed of simple geometric shapes:
// - The sidewalls are treated as discs with an inner diameter equal to the
//   wheel diameter, and an outer diameter equal to the static diameter of the
//   tire.
// - The tread face is treated as a band with a diameter equal to the static
//   radius of the tire.
// A rubber material is assumed, using a density of 1050 kg/m^3.
// -----------------------------------------------------------------------------
double VolumeCyl(double r_outer, double r_inner, double cyl_height) {
    return CH_C_PI * cyl_height * (r_outer * r_outer - r_inner * r_inner);
}

double InertiaRotCyl(double mass, double r_outer, double r_inner) {
    return mass * (r_outer * r_outer + r_inner * r_inner) / 2.0;
}

double InertiaTipCyl(double mass, double r_outer, double r_inner, double cyl_height) {
    return mass * (3.0 * (r_outer * r_outer + r_inner * r_inner) + cyl_height * cyl_height) / 12.0;
}

ChVector<> ChTire::EstimateInertia(double tire_width,    // tire width [mm]
                                   double aspect_ratio,  // aspect ratio: height to width [percentage]
                                   double rim_diameter,  // rim diameter [in]
                                   double tire_mass,     // mass of the tire [kg]
                                   double t_factor       // tread to sidewall thickness factor
) {
    double rho = 1050.0;  // rubber density in kg/m^3

    double width = tire_width / 1000;             // tire width in meters
    double secth = (aspect_ratio / 100) * width;  // tire height in meters
    double r_rim = (rim_diameter / 2) * 0.0254;   // rim radius in meters
    double r_tire = r_rim + secth;                // tire radius in meters

    // Estimate sidewall thickness.
    double t = 0;
    double m_test = 0;
    while (tire_mass - m_test > 0.0) {
        t += 1e-6;
        m_test = rho * (VolumeCyl(r_tire, r_tire - t_factor * t, width - 2 * t) + 2 * VolumeCyl(r_tire - t, r_rim, t));
    }

    // Lateral sidewall offset.
    double r_steiner = (width - t) / 2.0;

    // Calculate mass and moments of inertia of tread section and sidewall, separately.
    double m_tread = rho * VolumeCyl(r_tire, r_tire - t_factor * t, width - 2 * t);
    double Irot_tread = InertiaRotCyl(m_tread, r_tire, r_tire - 2 * t);
    double Itip_tread = InertiaTipCyl(m_tread, r_tire, r_tire - t_factor * t, width - 2 * t);

    double m_sidewall = rho * VolumeCyl(r_tire - t, r_rim, t);
    double Irot_sidewall = InertiaRotCyl(m_sidewall, r_tire - t, r_rim);
    double Itip_sidewall = InertiaTipCyl(m_sidewall, r_tire - t, r_rim, t) + m_sidewall * pow(r_steiner, 2.0);

    // Return composite tire inertia.
    return ChVector<>(Itip_tread + 2 * Itip_sidewall, Irot_tread + 2 * Irot_sidewall, Itip_tread + 2 * Itip_sidewall);
}

}  // end namespace vehicle
}  // end namespace chrono
<commit_msg>Modified contact point calculation to improve handling of (constant) terrain slopes.<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// Base class for a tire.
// A tire subsystem is a force element. It is passed position and velocity
// information of the wheel body and it produces ground reaction forces and
// moments to be applied to the wheel body.
//
// =============================================================================

#include <cmath>

#include "chrono/physics/ChSystem.h"
#include "chrono_vehicle/wheeled_vehicle/ChTire.h"

namespace chrono {
namespace vehicle {

ChTire::ChTire(const std::string& name)
    : ChPart(name), m_stepsize(1e-3), m_slip_angle(0), m_longitudinal_slip(0), m_camber_angle(0) {}

// -----------------------------------------------------------------------------
// Base class implementation of the initialization function.
// -----------------------------------------------------------------------------
void ChTire::Initialize(std::shared_ptr<ChBody> wheel, VehicleSide side) {
    m_wheel = wheel;
    m_side = side;

    // Increment mass and inertia of the wheel body.
    wheel->SetMass(wheel->GetMass() + GetMass());
    wheel->SetInertiaXX(wheel->GetInertiaXX() + GetInertia());
}

// -----------------------------------------------------------------------------
// Default implementation of ReportMass simply returns the value from GetMass.
// However, concrete tire models which need to return 0 from GetMass (so that
// the mass of the tire is not double counted) will override this function.
// -----------------------------------------------------------------------------
double ChTire::ReportMass() const {
    return GetMass();
}

// -----------------------------------------------------------------------------
// Calculate kinematics quantities (slip angle, longitudinal slip, camber angle,
// and toe-in angle using the current state of the associated wheel body.
// -----------------------------------------------------------------------------
void ChTire::CalculateKinematics(double time, const WheelState& state, const ChTerrain& terrain) {
    // Wheel normal (expressed in global frame)
    ChVector<> wheel_normal = state.rot.GetYaxis();

    // Terrain normal at wheel location (expressed in global frame)
    ChVector<> Z_dir = terrain.GetNormal(state.pos.x(), state.pos.y());

    // Longitudinal (heading) and lateral directions, in the terrain plane
    ChVector<> X_dir = Vcross(wheel_normal, Z_dir);
    X_dir.Normalize();
    ChVector<> Y_dir = Vcross(Z_dir, X_dir);

    // Tire reference coordinate system
    ChMatrix33<> rot;
    rot.Set_A_axis(X_dir, Y_dir, Z_dir);
    ChCoordsys<> tire_csys(state.pos, rot.Get_A_quaternion());

    // Express wheel linear velocity in tire frame
    ChVector<> V = tire_csys.TransformDirectionParentToLocal(state.lin_vel);
    // Express wheel normal in tire frame
    ChVector<> n = tire_csys.TransformDirectionParentToLocal(wheel_normal);

    // Slip angle
    double abs_Vx = std::abs(V.x());
    double zero_Vx = 1e-4;
    m_slip_angle = (abs_Vx > zero_Vx) ? std::atan(V.y() / abs_Vx) : 0;

    // Longitudinal slip
    m_longitudinal_slip = (abs_Vx > zero_Vx) ? -(V.x() - state.omega * GetRadius()) / abs_Vx : 0;

    // Camber angle
    m_camber_angle = std::atan2(n.z(), n.y());
}

// -----------------------------------------------------------------------------
// Utility function for characterizing the geometric contact between a disc with
// specified center location, normal direction, and radius and the terrain,
// assumed to be specified as a height field (over the x-y domain).
// This function returns false if no contact occurs. Otherwise, it sets the
// contact points on the disc (ptD) and on the terrain (ptT), the normal contact
// direction, and the resulting penetration depth (a positive value).
//
// NOTE: uses terrain normal at disc center for approximative calculation.
// Hence only valid for terrains with constant slope. A completely accurate
// solution would require an iterative calculation of the contact point.
// -----------------------------------------------------------------------------
bool ChTire::disc_terrain_contact(const ChTerrain& terrain,
                                  const ChVector<>& disc_center,
                                  const ChVector<>& disc_normal,
                                  double disc_radius,
                                  ChCoordsys<>& contact,
                                  double& depth) {
    // Find terrain height below disc center. There is no contact if the disc
    // center is below the terrain or farther away by more than its radius.
    double hc = terrain.GetHeight(disc_center.x(), disc_center.y());
    if (disc_center.z() <= hc || disc_center.z() >= hc + disc_radius)
        return false;

    // Find the lowest point on the disc. There is no contact if the disc is
    // (almost) horizontal.
	ChVector<> nhelp = terrain.GetNormal(disc_center.x(), disc_center.y());
    ChVector<> dir1 = Vcross(disc_normal, nhelp);
    double sinTilt2 = dir1.Length2();

    if (sinTilt2 < 1e-3)
        return false;

    // Contact point (lowest point on disc).
    ChVector<> ptD = disc_center + disc_radius * Vcross(disc_normal, dir1 / sqrt(sinTilt2));

    // Find terrain height at lowest point. No contact if lowest point is above
    // the terrain.
    double hp = terrain.GetHeight(ptD.x(), ptD.y());

    if (ptD.z() > hp)
        return false;

    // Approximate the terrain with a plane. Define the projection of the lowest
    // point onto this plane as the contact point on the terrain.
    ChVector<> normal = terrain.GetNormal(ptD.x(), ptD.y());
    ChVector<> longitudinal = Vcross(disc_normal, normal);
    longitudinal.Normalize();
    ChVector<> lateral = Vcross(normal, longitudinal);
    ChMatrix33<> rot;
    rot.Set_A_axis(longitudinal, lateral, normal);

    contact.pos = ptD;
    contact.rot = rot.Get_A_quaternion();

    depth = Vdot(ChVector<>(0, 0, hp - ptD.z()), normal);
    assert(depth > 0);

    return true;
}

// -----------------------------------------------------------------------------
// Estimate the tire moments of inertia, given the tire specification and mass.
// The tire is assumed to be composed of simple geometric shapes:
// - The sidewalls are treated as discs with an inner diameter equal to the
//   wheel diameter, and an outer diameter equal to the static diameter of the
//   tire.
// - The tread face is treated as a band with a diameter equal to the static
//   radius of the tire.
// A rubber material is assumed, using a density of 1050 kg/m^3.
// -----------------------------------------------------------------------------
double VolumeCyl(double r_outer, double r_inner, double cyl_height) {
    return CH_C_PI * cyl_height * (r_outer * r_outer - r_inner * r_inner);
}

double InertiaRotCyl(double mass, double r_outer, double r_inner) {
    return mass * (r_outer * r_outer + r_inner * r_inner) / 2.0;
}

double InertiaTipCyl(double mass, double r_outer, double r_inner, double cyl_height) {
    return mass * (3.0 * (r_outer * r_outer + r_inner * r_inner) + cyl_height * cyl_height) / 12.0;
}

ChVector<> ChTire::EstimateInertia(double tire_width,    // tire width [mm]
                                   double aspect_ratio,  // aspect ratio: height to width [percentage]
                                   double rim_diameter,  // rim diameter [in]
                                   double tire_mass,     // mass of the tire [kg]
                                   double t_factor       // tread to sidewall thickness factor
) {
    double rho = 1050.0;  // rubber density in kg/m^3

    double width = tire_width / 1000;             // tire width in meters
    double secth = (aspect_ratio / 100) * width;  // tire height in meters
    double r_rim = (rim_diameter / 2) * 0.0254;   // rim radius in meters
    double r_tire = r_rim + secth;                // tire radius in meters

    // Estimate sidewall thickness.
    double t = 0;
    double m_test = 0;
    while (tire_mass - m_test > 0.0) {
        t += 1e-6;
        m_test = rho * (VolumeCyl(r_tire, r_tire - t_factor * t, width - 2 * t) + 2 * VolumeCyl(r_tire - t, r_rim, t));
    }

    // Lateral sidewall offset.
    double r_steiner = (width - t) / 2.0;

    // Calculate mass and moments of inertia of tread section and sidewall, separately.
    double m_tread = rho * VolumeCyl(r_tire, r_tire - t_factor * t, width - 2 * t);
    double Irot_tread = InertiaRotCyl(m_tread, r_tire, r_tire - 2 * t);
    double Itip_tread = InertiaTipCyl(m_tread, r_tire, r_tire - t_factor * t, width - 2 * t);

    double m_sidewall = rho * VolumeCyl(r_tire - t, r_rim, t);
    double Irot_sidewall = InertiaRotCyl(m_sidewall, r_tire - t, r_rim);
    double Itip_sidewall = InertiaTipCyl(m_sidewall, r_tire - t, r_rim, t) + m_sidewall * pow(r_steiner, 2.0);

    // Return composite tire inertia.
    return ChVector<>(Itip_tread + 2 * Itip_sidewall, Irot_tread + 2 * Irot_sidewall, Itip_tread + 2 * Itip_sidewall);
}

}  // end namespace vehicle
}  // end namespace chrono
<|endoftext|>


<commit_before>/**
 * Copyright (C) 2015 Dato, Inc.
 * All rights reserved.
 *
 * This software may be modified and distributed under the terms
 * of the BSD license. See the LICENSE file for details.
 */
#include <parallel/pthread_tools.hpp>
#include <parallel/lambda_omp.hpp>
#include <unity/lib/toolkit_function_macros.hpp>
#include <unity/extensions/cumulative_aggregates.hpp>

namespace graphlab {
namespace cumulative_aggregates {

/**
 * Throw an error if a vector is of unequal length.
 * \param[in] gl_sarray of type vector
 */
void check_vector_equal_size(const gl_sarray& in) {

  // Initialize.
  DASSERT_TRUE(in.dtype() == flex_type_enum::VECTOR);
  size_t n_threads = thread::cpu_count();
  n_threads = std::max(n_threads, 1);
  size_t m_size = in.size();

  // Throw the following error.
  auto throw_error = [] (size_t row_number, size_t expected, size_t current) {
    std::stringstream ss;
    ss << "Vectors must be of the same size. Row " << row_number
       << " contains a vector of size " << current << ". Expected a vector of"
       << " size " << expected << "." << std::endl;
    log_and_throw(ss.str());
  };

  // Within each block of the SArray, check that the vectors have the same size.
  std::vector<size_t> expected_sizes (n_threads, size_t(-1));
  in_parallel([&](size_t thread_idx, size_t n_threads) {
    size_t start_row = thread_idx * m_size / n_threads;
    size_t end_row = (thread_idx + 1) * m_size / n_threads;
    size_t expected_size = size_t(-1);
    size_t row_number = start_row;
    for (const auto& v: in.range_iterator(start_row, end_row)) {
      if (v != FLEX_UNDEFINED) {
        if (expected_size == size_t(-1)) {
          expected_size = v.size();
          expected_sizes[thread_idx] = expected_size;
        } else {
          DASSERT_TRUE(v.get_type() == flex_type_enum::VECTOR);
          if (expected_size != v.size()) {
            throw_error(row_number, expected_size, v.size());
          }
        }
      }
      row_number++;
    }
  });

  // Make sure sizes accross blocks are also the same.
  size_t vector_size = size_t(-1);
  for (size_t thread_idx = 0; thread_idx < n_threads; thread_idx++) {
    // If this block contains all None values, skip it.
    if (expected_sizes[thread_idx] != size_t(-1)) {

      if (vector_size == size_t(-1)) {
          vector_size = expected_sizes[thread_idx];
      } else {
         if (expected_sizes[thread_idx] != vector_size) {
           throw_error(thread_idx * m_size / n_threads,
                              vector_size, expected_sizes[thread_idx]);
         }
      }
    }
  }

}

gl_sarray _sarray_cumulative_built_in_aggregate(const gl_sarray& in,
                                                const std::string& name) {
  flex_type_enum input_type = in.dtype();
  std::shared_ptr<group_aggregate_value> aggregator;

  // Cumulative sum, and avg support vector types.
  if (name == "__builtin__cum_sum__") {
    switch(input_type) {
      case flex_type_enum::VECTOR: {
        check_vector_equal_size(in);
        aggregator = get_builtin_group_aggregator(std::string("__builtin__vector__sum__"));
        break;
      }
      default:
        aggregator = get_builtin_group_aggregator(std::string("__builtin__sum__"));
        break;
    }
  } else if (name == "__builtin__cum_avg__") {
    switch(input_type) {
      case flex_type_enum::VECTOR: {
        check_vector_equal_size(in);
        aggregator = get_builtin_group_aggregator(std::string("__builtin__vector__avg__"));
        break;
      }
      default:
        aggregator = get_builtin_group_aggregator(std::string("__builtin__avg__"));
        break;
    }
  } else if (name == "__builtin__cum_max__") {
      aggregator = get_builtin_group_aggregator(std::string("__builtin__max__"));
  } else if (name == "__builtin__cum_min__") {
      aggregator = get_builtin_group_aggregator(std::string("__builtin__min__"));
  } else if (name == "__builtin__cum_var__") {
      aggregator = get_builtin_group_aggregator(std::string("__builtin__var__"));
  } else if (name == "__builtin__cum_std__") {
      aggregator = get_builtin_group_aggregator(std::string("__builtin__stdv__"));
  } else {
    log_and_throw("Internal error. Unknown cumulative aggregator " + name);
  }
  return in.cumulative_aggregate(aggregator);
}

BEGIN_FUNCTION_REGISTRATION
REGISTER_FUNCTION(_sarray_cumulative_built_in_aggregate, "in", "name");
END_FUNCTION_REGISTRATION

}
}
<commit_msg>Fixed a small but with std::max.<commit_after>/**
 * Copyright (C) 2015 Dato, Inc.
 * All rights reserved.
 *
 * This software may be modified and distributed under the terms
 * of the BSD license. See the LICENSE file for details.
 */
#include <parallel/pthread_tools.hpp>
#include <parallel/lambda_omp.hpp>
#include <unity/lib/toolkit_function_macros.hpp>
#include <unity/extensions/cumulative_aggregates.hpp>

namespace graphlab {
namespace cumulative_aggregates {

/**
 * Throw an error if a vector is of unequal length.
 * \param[in] gl_sarray of type vector
 */
void check_vector_equal_size(const gl_sarray& in) {

  // Initialize.
  DASSERT_TRUE(in.dtype() == flex_type_enum::VECTOR);
  size_t n_threads = thread::cpu_count();
  n_threads = std::max(n_threads, size_t(1));
  size_t m_size = in.size();

  // Throw the following error.
  auto throw_error = [] (size_t row_number, size_t expected, size_t current) {
    std::stringstream ss;
    ss << "Vectors must be of the same size. Row " << row_number
       << " contains a vector of size " << current << ". Expected a vector of"
       << " size " << expected << "." << std::endl;
    log_and_throw(ss.str());
  };

  // Within each block of the SArray, check that the vectors have the same size.
  std::vector<size_t> expected_sizes (n_threads, size_t(-1));
  in_parallel([&](size_t thread_idx, size_t n_threads) {
    size_t start_row = thread_idx * m_size / n_threads;
    size_t end_row = (thread_idx + 1) * m_size / n_threads;
    size_t expected_size = size_t(-1);
    size_t row_number = start_row;
    for (const auto& v: in.range_iterator(start_row, end_row)) {
      if (v != FLEX_UNDEFINED) {
        if (expected_size == size_t(-1)) {
          expected_size = v.size();
          expected_sizes[thread_idx] = expected_size;
        } else {
          DASSERT_TRUE(v.get_type() == flex_type_enum::VECTOR);
          if (expected_size != v.size()) {
            throw_error(row_number, expected_size, v.size());
          }
        }
      }
      row_number++;
    }
  });

  // Make sure sizes accross blocks are also the same.
  size_t vector_size = size_t(-1);
  for (size_t thread_idx = 0; thread_idx < n_threads; thread_idx++) {
    // If this block contains all None values, skip it.
    if (expected_sizes[thread_idx] != size_t(-1)) {

      if (vector_size == size_t(-1)) {
          vector_size = expected_sizes[thread_idx];
      } else {
         if (expected_sizes[thread_idx] != vector_size) {
           throw_error(thread_idx * m_size / n_threads,
                              vector_size, expected_sizes[thread_idx]);
         }
      }
    }
  }

}

gl_sarray _sarray_cumulative_built_in_aggregate(const gl_sarray& in,
                                                const std::string& name) {
  flex_type_enum input_type = in.dtype();
  std::shared_ptr<group_aggregate_value> aggregator;

  // Cumulative sum, and avg support vector types.
  if (name == "__builtin__cum_sum__") {
    switch(input_type) {
      case flex_type_enum::VECTOR: {
        check_vector_equal_size(in);
        aggregator = get_builtin_group_aggregator(std::string("__builtin__vector__sum__"));
        break;
      }
      default:
        aggregator = get_builtin_group_aggregator(std::string("__builtin__sum__"));
        break;
    }
  } else if (name == "__builtin__cum_avg__") {
    switch(input_type) {
      case flex_type_enum::VECTOR: {
        check_vector_equal_size(in);
        aggregator = get_builtin_group_aggregator(std::string("__builtin__vector__avg__"));
        break;
      }
      default:
        aggregator = get_builtin_group_aggregator(std::string("__builtin__avg__"));
        break;
    }
  } else if (name == "__builtin__cum_max__") {
      aggregator = get_builtin_group_aggregator(std::string("__builtin__max__"));
  } else if (name == "__builtin__cum_min__") {
      aggregator = get_builtin_group_aggregator(std::string("__builtin__min__"));
  } else if (name == "__builtin__cum_var__") {
      aggregator = get_builtin_group_aggregator(std::string("__builtin__var__"));
  } else if (name == "__builtin__cum_std__") {
      aggregator = get_builtin_group_aggregator(std::string("__builtin__stdv__"));
  } else {
    log_and_throw("Internal error. Unknown cumulative aggregator " + name);
  }
  return in.cumulative_aggregate(aggregator);
}

BEGIN_FUNCTION_REGISTRATION
REGISTER_FUNCTION(_sarray_cumulative_built_in_aggregate, "in", "name");
END_FUNCTION_REGISTRATION

}
}
<|endoftext|>


<commit_before>// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,unix.Malloc -std=c++11 -fblocks -verify %s
// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks,unix.Malloc -std=c++11 -DLEAKS=1 -fblocks -verify %s
// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,unix.Malloc -std=c++11 -analyzer-config c++-allocator-inlining=true -DALLOCATOR_INLINING=1 -fblocks -verify %s
// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks,unix.Malloc -std=c++11 -analyzer-config c++-allocator-inlining=true -DLEAKS=1 -DALLOCATOR_INLINING=1 -fblocks -verify %s
#include "Inputs/system-header-simulator-cxx.h"

#if !LEAKS
// expected-no-diagnostics
#endif

void *allocator(std::size_t size);

void *operator new[](std::size_t size) throw() { return allocator(size); }
void *operator new(std::size_t size) throw() { return allocator(size); }
void *operator new(std::size_t size, const std::nothrow_t &nothrow) throw() { return allocator(size); }
void *operator new(std::size_t, double d);

class C {
public:
  void *operator new(std::size_t);
};

void testNewMethod() {
  void *p1 = C::operator new(0); // no warn

  C *p2 = new C; // no warn

  C *c3 = ::new C;
}
#if LEAKS && !ALLOCATOR_INLINING
// expected-warning@-2{{Potential leak of memory pointed to by 'c3'}}
#endif

void testOpNewArray() {
  void *p = operator new[](0); // call is inlined, no warn
}

void testNewExprArray() {
  int *p = new int[0];
}
#if LEAKS && !ALLOCATOR_INLINING
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif

//----- Custom non-placement operators
void testOpNew() {
  void *p = operator new(0); // call is inlined, no warn
}

void testNewExpr() {
  int *p = new int;
}
#if LEAKS && !ALLOCATOR_INLINING
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif

//----- Custom NoThrow placement operators
void testOpNewNoThrow() {
  void *p = operator new(0, std::nothrow); // call is inlined, no warn
}
#if LEAKS
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif

void testNewExprNoThrow() {
  int *p = new(std::nothrow) int;
}
#if LEAKS
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif

//----- Custom placement operators
void testOpNewPlacement() {
  void *p = operator new(0, 0.1); // no warn
}

void testNewExprPlacement() {
  int *p = new(0.1) int; // no warn
}
<commit_msg>[analyzer] NFC: operator new: Fix new(nothrow) definition in tests.<commit_after>// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,unix.Malloc -std=c++11 -fblocks -verify %s
// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks,unix.Malloc -std=c++11 -DLEAKS=1 -fblocks -verify %s
// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,unix.Malloc -std=c++11 -analyzer-config c++-allocator-inlining=true -DALLOCATOR_INLINING=1 -fblocks -verify %s
// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks,unix.Malloc -std=c++11 -analyzer-config c++-allocator-inlining=true -DLEAKS=1 -DALLOCATOR_INLINING=1 -fblocks -verify %s
#include "Inputs/system-header-simulator-cxx.h"

#if !(LEAKS && !ALLOCATOR_INLINING)
// expected-no-diagnostics
#endif

void *allocator(std::size_t size);

void *operator new[](std::size_t size) throw() { return allocator(size); }
void *operator new(std::size_t size) throw() { return allocator(size); }
void *operator new(std::size_t size, const std::nothrow_t &nothrow) throw() { return allocator(size); }
void *operator new(std::size_t, double d);

class C {
public:
  void *operator new(std::size_t);
};

void testNewMethod() {
  void *p1 = C::operator new(0); // no warn

  C *p2 = new C; // no warn

  C *c3 = ::new C;
}
#if LEAKS && !ALLOCATOR_INLINING
// expected-warning@-2{{Potential leak of memory pointed to by 'c3'}}
#endif

void testOpNewArray() {
  void *p = operator new[](0); // call is inlined, no warn
}

void testNewExprArray() {
  int *p = new int[0];
}
#if LEAKS && !ALLOCATOR_INLINING
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif

//----- Custom non-placement operators
void testOpNew() {
  void *p = operator new(0); // call is inlined, no warn
}

void testNewExpr() {
  int *p = new int;
}
#if LEAKS && !ALLOCATOR_INLINING
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif

//----- Custom NoThrow placement operators
void testOpNewNoThrow() {
  void *p = operator new(0, std::nothrow); // call is inlined, no warn
}

void testNewExprNoThrow() {
  int *p = new(std::nothrow) int;
}
#if LEAKS && !ALLOCATOR_INLINING
// expected-warning@-2{{Potential leak of memory pointed to by 'p'}}
#endif

//----- Custom placement operators
void testOpNewPlacement() {
  void *p = operator new(0, 0.1); // no warn
}

void testNewExprPlacement() {
  int *p = new(0.1) int; // no warn
}
<|endoftext|>


<commit_before>// Begin CVS Header
//   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/compareExpressions/CNormalItemPower.cpp,v $
//   $Revision: 1.12 $
//   $Name:  $
//   $Author: gauges $
//   $Date: 2008/08/02 14:09:17 $
// End CVS Header

// Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

// Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

#ifdef WIN32
# pragma warning (disable: 4786)
# pragma warning (disable: 4243)
// warning C4355: 'this' : used in base member initializer list
# pragma warning (disable: 4355)
#endif  // WIN32

#include <sstream>

#include "copasi.h"

#include "CNormalItem.h"
#include "CNormalItemPower.h"
#include "CNormalFunction.h"
#include "CNormalCall.h"
#include "CNormalGeneralPower.h"
#include "CNormalChoice.h"

/**
 * Default constructor
 */
CNormalItemPower::CNormalItemPower(): CNormalBase(), mpItem(NULL), mExp(1.0), mItemType(CNormalItemPower::INVALID)
{}

/**
 * Copy Constructor
 */
CNormalItemPower::CNormalItemPower(const CNormalItemPower& src): CNormalBase(src), mpItem(NULL), mExp(src.mExp), mItemType(src.mItemType)
{
  if (this->mItemType != CNormalItemPower::INVALID)
    {
      this->mpItem = src.mpItem->copy();
    }
}

CNormalItemPower::~CNormalItemPower()
{
  if (this->mpItem != NULL) delete this->mpItem;
}

/**
 * Assignment operator Constructor
 */
CNormalItemPower& CNormalItemPower::operator=(const CNormalItemPower& src)
{
  if (this->mpItem != NULL) delete this->mpItem;
  this->mItemType = src.mItemType;
  if (this->mItemType != CNormalItemPower::INVALID)
    {
      this->mpItem = src.mpItem->copy();
    }
  else
    {
      this->mpItem = NULL;
    }
  mExp = src.mExp;
  return *this;
}

/**
 * Data constructor
 */
CNormalItemPower::CNormalItemPower(const CNormalBase& item, const C_FLOAT64& exp)
    : mpItem(NULL), mExp(exp), mItemType(CNormalItemPower::INVALID)
{
  if (!this->setItem(item))
    {
      this->mExp = 1.0;
    }
}

/**
 * Set the base of this itempower.
 * @return true.
 */
bool CNormalItemPower::setItem(const CNormalBase& item)
{
  bool result = true;
  if (dynamic_cast<const CNormalItem*>(&item))
    {
      if (this->mpItem != NULL) delete this->mpItem;
      this->mItemType = CNormalItemPower::ITEM;
      this->mpItem = item.copy();
    }
  else if (dynamic_cast<const CNormalFunction*>(&item))
    {
      if (this->mpItem != NULL) delete this->mpItem;
      this->mItemType = CNormalItemPower::FUNCTION;
      this->mpItem = item.copy();
    }
  else if (dynamic_cast<const CNormalGeneralPower*>(&item))
    {
      if (this->mpItem != NULL) delete this->mpItem;
      this->mItemType = CNormalItemPower::POWER;
      this->mpItem = item.copy();
    }
  else if (dynamic_cast<const CNormalChoice*>(&item))
    {
      if (this->mpItem != NULL) delete this->mpItem;
      this->mItemType = CNormalItemPower::CHOICE;
      this->mpItem = item.copy();
    }
  else if (dynamic_cast<const CNormalCall*>(&item))
    {
      if (this->mpItem != NULL) delete this->mpItem;
      this->mItemType = CNormalItemPower::CALL;
      this->mpItem = item.copy();
    }
  else
    {
      result = false;
    }
  return result;
}

/**
 * Set the exponent of this power
 * @return true
 */
bool CNormalItemPower::setExp(const C_FLOAT64& number)
{
  if (mExp < 0.0)
    return false;
  mExp = number;
  return true;
}

/**
 * Retrieve the base of this power
 * @return mItem
 */
CNormalBase& CNormalItemPower::getItem()
{
  return *mpItem;
}

/**
 * Retrieve the base of this power
 * @return mItem
 */
const CNormalBase& CNormalItemPower::getItem() const
  {
    return *mpItem;
  }

/**
 * Retrieve the exponent of this power
 * @return mExp
 */
const C_FLOAT64& CNormalItemPower::getExp() const
  {
    return mExp;
  }

/**
 * Examine equality of two item powers.
 * @return bool.
 */
bool CNormalItemPower::operator==(const CNormalItemPower & rhs) const
  {
    bool result = (this->mItemType == rhs.mItemType);
    result &= (this->mExp == rhs.mExp);
    if (result == true)
      {
        switch (this->mItemType)
          {
          case CNormalItemPower::ITEM:
            result = (dynamic_cast<CNormalItem&>(*this->mpItem) == dynamic_cast<CNormalItem&>(*rhs.mpItem));
            break;
          case CNormalItemPower::FUNCTION:
            result = (dynamic_cast<CNormalFunction&>(*this->mpItem) == dynamic_cast<CNormalFunction&>(*rhs.mpItem));
            break;
          case CNormalItemPower::POWER:
            result = (dynamic_cast<CNormalGeneralPower&>(*this->mpItem) == dynamic_cast<CNormalGeneralPower&>(*rhs.mpItem));
            break;
          case CNormalItemPower::CHOICE:
            result = (dynamic_cast<CNormalChoice&>(*this->mpItem) == dynamic_cast<CNormalChoice&>(*rhs.mpItem));
          case CNormalItemPower::CALL:
            result = (dynamic_cast<CNormalCall&>(*this->mpItem) == dynamic_cast<CNormalCall&>(*rhs.mpItem));
          case CNormalItemPower::INVALID:
            result = true;
            break;
          }
      }
    return result;
  }

/**
 * Examine inequality of two item powers.
 * @return bool.
 */
bool CNormalItemPower::operator<(const CNormalItemPower & rhs) const
  {
    bool result = false;
    if (this->mItemType < rhs.mItemType)
      {
        result = true;
      }
    else if (this->mItemType == rhs.mItemType)
      {
        switch (this->mItemType)
          {
          case CNormalItemPower::ITEM:
            result = (dynamic_cast<CNormalItem&>(*this->mpItem) < dynamic_cast<CNormalItem&>(*rhs.mpItem));
            if(!result)
              {
                result = !(dynamic_cast<CNormalItem&>(*rhs.mpItem) < dynamic_cast<CNormalItem&>(*this->mpItem));
                if(result)
                  {
                    result = (rhs.mExp < this->mExp);
                  }
              }
            break;
          case CNormalItemPower::FUNCTION:
            result = (dynamic_cast<CNormalFunction&>(*this->mpItem) < dynamic_cast<CNormalFunction&>(*rhs.mpItem));
            if(!result)
              {
                result = !(dynamic_cast<CNormalFunction&>(*rhs.mpItem) < dynamic_cast<CNormalFunction&>(*this->mpItem));
                if(result)
                  {
                    result = (rhs.mExp < this->mExp);
                  }
              }
            break;
          case CNormalItemPower::POWER:
            result = (dynamic_cast<CNormalGeneralPower&>(*this->mpItem) < dynamic_cast<CNormalGeneralPower&>(*rhs.mpItem));
            if(!result)
              {
                result = !(dynamic_cast<CNormalGeneralPower&>(*rhs.mpItem) < dynamic_cast<CNormalGeneralPower&>(*this->mpItem));
                if(result)
                  {
                    result = (rhs.mExp < this->mExp);
                  }
              }
            break;
          case CNormalItemPower::CHOICE:
            result = (dynamic_cast<CNormalChoice&>(*this->mpItem) < dynamic_cast<CNormalChoice&>(*rhs.mpItem));
            if(!result)
              {
                result = !(dynamic_cast<CNormalChoice&>(*rhs.mpItem) < dynamic_cast<CNormalChoice&>(*this->mpItem));
                if(result)
                  {
                    result = (rhs.mExp < this->mExp);
                  }
              }
            break;
          case CNormalItemPower::CALL:
            result = (dynamic_cast<CNormalCall&>(*this->mpItem) < dynamic_cast<CNormalCall&>(*rhs.mpItem));
            if(!result)
              {
                result = !(dynamic_cast<CNormalCall&>(*rhs.mpItem) < dynamic_cast<CNormalCall&>(*this->mpItem));
                if(result)
                  {
                    result = (rhs.mExp < this->mExp);
                  }
              }
            break;
          case CNormalItemPower::INVALID:
            result = false;
            break;
          }
      }
    return result;
  }

std::ostream & operator<< (std::ostream &os, const CNormalItemPower & d)
{
  os << d.toString();
  return os;
}

std::string CNormalItemPower::toString() const
  {
    std::ostringstream os;
    if (this->mItemType == CNormalItemPower::ITEM || this->mItemType == CNormalItemPower::FUNCTION || this->mItemType == CNormalItemPower::CALL || (this->mItemType == CNormalItemPower::POWER && this->mExp == 1.0))
      {
        os << this->mpItem->toString();
      }
    else
      {
        os << "(" << this->mpItem->toString() << ")";
      }
    if (this->mExp != 1.0)
      {
        os << "^" << this->mExp;
      }
    return os.str();
  }

CNormalBase * CNormalItemPower::copy() const
  {
    return new CNormalItemPower(*this);
  }

CNormalItemPower::ItemType CNormalItemPower::getItemType() const
  {
    return this->mItemType;
  }

bool CNormalItemPower::simplify()
{
  return this->mpItem->simplify();
}
<commit_msg>Added two missing break statements.<commit_after>// Begin CVS Header
//   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/compareExpressions/CNormalItemPower.cpp,v $
//   $Revision: 1.13 $
//   $Name:  $
//   $Author: gauges $
//   $Date: 2008/10/09 15:26:31 $
// End CVS Header

// Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

// Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

#ifdef WIN32
# pragma warning (disable: 4786)
# pragma warning (disable: 4243)
// warning C4355: 'this' : used in base member initializer list
# pragma warning (disable: 4355)
#endif  // WIN32

#include <sstream>

#include "copasi.h"

#include "CNormalItem.h"
#include "CNormalItemPower.h"
#include "CNormalFunction.h"
#include "CNormalCall.h"
#include "CNormalGeneralPower.h"
#include "CNormalChoice.h"

/**
 * Default constructor
 */
CNormalItemPower::CNormalItemPower(): CNormalBase(), mpItem(NULL), mExp(1.0), mItemType(CNormalItemPower::INVALID)
{}

/**
 * Copy Constructor
 */
CNormalItemPower::CNormalItemPower(const CNormalItemPower& src): CNormalBase(src), mpItem(NULL), mExp(src.mExp), mItemType(src.mItemType)
{
  if (this->mItemType != CNormalItemPower::INVALID)
    {
      this->mpItem = src.mpItem->copy();
    }
}

CNormalItemPower::~CNormalItemPower()
{
  if (this->mpItem != NULL) delete this->mpItem;
}

/**
 * Assignment operator Constructor
 */
CNormalItemPower& CNormalItemPower::operator=(const CNormalItemPower& src)
{
  if (this->mpItem != NULL) delete this->mpItem;
  this->mItemType = src.mItemType;
  if (this->mItemType != CNormalItemPower::INVALID)
    {
      this->mpItem = src.mpItem->copy();
    }
  else
    {
      this->mpItem = NULL;
    }
  mExp = src.mExp;
  return *this;
}

/**
 * Data constructor
 */
CNormalItemPower::CNormalItemPower(const CNormalBase& item, const C_FLOAT64& exp)
    : mpItem(NULL), mExp(exp), mItemType(CNormalItemPower::INVALID)
{
  if (!this->setItem(item))
    {
      this->mExp = 1.0;
    }
}

/**
 * Set the base of this itempower.
 * @return true.
 */
bool CNormalItemPower::setItem(const CNormalBase& item)
{
  bool result = true;
  if (dynamic_cast<const CNormalItem*>(&item))
    {
      if (this->mpItem != NULL) delete this->mpItem;
      this->mItemType = CNormalItemPower::ITEM;
      this->mpItem = item.copy();
    }
  else if (dynamic_cast<const CNormalFunction*>(&item))
    {
      if (this->mpItem != NULL) delete this->mpItem;
      this->mItemType = CNormalItemPower::FUNCTION;
      this->mpItem = item.copy();
    }
  else if (dynamic_cast<const CNormalGeneralPower*>(&item))
    {
      if (this->mpItem != NULL) delete this->mpItem;
      this->mItemType = CNormalItemPower::POWER;
      this->mpItem = item.copy();
    }
  else if (dynamic_cast<const CNormalChoice*>(&item))
    {
      if (this->mpItem != NULL) delete this->mpItem;
      this->mItemType = CNormalItemPower::CHOICE;
      this->mpItem = item.copy();
    }
  else if (dynamic_cast<const CNormalCall*>(&item))
    {
      if (this->mpItem != NULL) delete this->mpItem;
      this->mItemType = CNormalItemPower::CALL;
      this->mpItem = item.copy();
    }
  else
    {
      result = false;
    }
  return result;
}

/**
 * Set the exponent of this power
 * @return true
 */
bool CNormalItemPower::setExp(const C_FLOAT64& number)
{
  if (mExp < 0.0)
    return false;
  mExp = number;
  return true;
}

/**
 * Retrieve the base of this power
 * @return mItem
 */
CNormalBase& CNormalItemPower::getItem()
{
  return *mpItem;
}

/**
 * Retrieve the base of this power
 * @return mItem
 */
const CNormalBase& CNormalItemPower::getItem() const
  {
    return *mpItem;
  }

/**
 * Retrieve the exponent of this power
 * @return mExp
 */
const C_FLOAT64& CNormalItemPower::getExp() const
  {
    return mExp;
  }

/**
 * Examine equality of two item powers.
 * @return bool.
 */
bool CNormalItemPower::operator==(const CNormalItemPower & rhs) const
  {
    bool result = (this->mItemType == rhs.mItemType);
    result &= (this->mExp == rhs.mExp);
    if (result == true)
      {
        switch (this->mItemType)
          {
          case CNormalItemPower::ITEM:
            result = (dynamic_cast<CNormalItem&>(*this->mpItem) == dynamic_cast<CNormalItem&>(*rhs.mpItem));
            break;
          case CNormalItemPower::FUNCTION:
            result = (dynamic_cast<CNormalFunction&>(*this->mpItem) == dynamic_cast<CNormalFunction&>(*rhs.mpItem));
            break;
          case CNormalItemPower::POWER:
            result = (dynamic_cast<CNormalGeneralPower&>(*this->mpItem) == dynamic_cast<CNormalGeneralPower&>(*rhs.mpItem));
            break;
          case CNormalItemPower::CHOICE:
            result = (dynamic_cast<CNormalChoice&>(*this->mpItem) == dynamic_cast<CNormalChoice&>(*rhs.mpItem));
            break;
          case CNormalItemPower::CALL:
            result = (dynamic_cast<CNormalCall&>(*this->mpItem) == dynamic_cast<CNormalCall&>(*rhs.mpItem));
            break;
          case CNormalItemPower::INVALID:
            result = true;
            break;
          }
      }
    return result;
  }

/**
 * Examine inequality of two item powers.
 * @return bool.
 */
bool CNormalItemPower::operator<(const CNormalItemPower & rhs) const
  {
    bool result = false;
    if (this->mItemType < rhs.mItemType)
      {
        result = true;
      }
    else if (this->mItemType == rhs.mItemType)
      {
        switch (this->mItemType)
          {
          case CNormalItemPower::ITEM:
            result = (dynamic_cast<CNormalItem&>(*this->mpItem) < dynamic_cast<CNormalItem&>(*rhs.mpItem));
            if(!result)
              {
                result = !(dynamic_cast<CNormalItem&>(*rhs.mpItem) < dynamic_cast<CNormalItem&>(*this->mpItem));
                if(result)
                  {
                    result = (rhs.mExp < this->mExp);
                  }
              }
            break;
          case CNormalItemPower::FUNCTION:
            result = (dynamic_cast<CNormalFunction&>(*this->mpItem) < dynamic_cast<CNormalFunction&>(*rhs.mpItem));
            if(!result)
              {
                result = !(dynamic_cast<CNormalFunction&>(*rhs.mpItem) < dynamic_cast<CNormalFunction&>(*this->mpItem));
                if(result)
                  {
                    result = (rhs.mExp < this->mExp);
                  }
              }
            break;
          case CNormalItemPower::POWER:
            result = (dynamic_cast<CNormalGeneralPower&>(*this->mpItem) < dynamic_cast<CNormalGeneralPower&>(*rhs.mpItem));
            if(!result)
              {
                result = !(dynamic_cast<CNormalGeneralPower&>(*rhs.mpItem) < dynamic_cast<CNormalGeneralPower&>(*this->mpItem));
                if(result)
                  {
                    result = (rhs.mExp < this->mExp);
                  }
              }
            break;
          case CNormalItemPower::CHOICE:
            result = (dynamic_cast<CNormalChoice&>(*this->mpItem) < dynamic_cast<CNormalChoice&>(*rhs.mpItem));
            if(!result)
              {
                result = !(dynamic_cast<CNormalChoice&>(*rhs.mpItem) < dynamic_cast<CNormalChoice&>(*this->mpItem));
                if(result)
                  {
                    result = (rhs.mExp < this->mExp);
                  }
              }
            break;
          case CNormalItemPower::CALL:
            result = (dynamic_cast<CNormalCall&>(*this->mpItem) < dynamic_cast<CNormalCall&>(*rhs.mpItem));
            if(!result)
              {
                result = !(dynamic_cast<CNormalCall&>(*rhs.mpItem) < dynamic_cast<CNormalCall&>(*this->mpItem));
                if(result)
                  {
                    result = (rhs.mExp < this->mExp);
                  }
              }
            break;
          case CNormalItemPower::INVALID:
            result = false;
            break;
          }
      }
    return result;
  }

std::ostream & operator<< (std::ostream &os, const CNormalItemPower & d)
{
  os << d.toString();
  return os;
}

std::string CNormalItemPower::toString() const
  {
    std::ostringstream os;
    if (this->mItemType == CNormalItemPower::ITEM || this->mItemType == CNormalItemPower::FUNCTION || this->mItemType == CNormalItemPower::CALL || (this->mItemType == CNormalItemPower::POWER && this->mExp == 1.0))
      {
        os << this->mpItem->toString();
      }
    else
      {
        os << "(" << this->mpItem->toString() << ")";
      }
    if (this->mExp != 1.0)
      {
        os << "^" << this->mExp;
      }
    return os.str();
  }

CNormalBase * CNormalItemPower::copy() const
  {
    return new CNormalItemPower(*this);
  }

CNormalItemPower::ItemType CNormalItemPower::getItemType() const
  {
    return this->mItemType;
  }

bool CNormalItemPower::simplify()
{
  return this->mpItem->simplify();
}
<|endoftext|>