<commit_before>// testSimbodyEngine.cpp
// Author:  Frank C. Anderson

//==============================================================================
//==============================================================================
#include <iostream>
#include <OpenSim/Common/IO.h>
#include <OpenSim/Simulation/Model/ActuatorSet.h>
#include <OpenSim/Simulation/Model/ContactForceSet.h>
#include <OpenSim/Simulation/Model/AnalysisSet.h>
#include <OpenSim/Simulation/Control/ControlLinear.h>
#include <OpenSim/Simulation/Control/ControlSet.h>
#include <OpenSim/Simulation/Manager/Manager.h>
#include <OpenSim/Analyses/Kinematics.h>
#include <OpenSim/Simulation/Model/Model.h>
#include <OpenSim/Simulation/Model/GeneralizedForce.h>
#include <OpenSim/DynamicsEngines/SimbodyEngine/SimbodyEngine.h>

using namespace OpenSim;
using namespace SimTK;
using namespace std;

//______________________________________________________________________________
/**
 * Run a simulation of a pendulum with Simbody as the underlying dynamics
 * engine.
 */
int main()
{
	// STEP 1
	// Set output precision
	//IO::SetPrecision(8);
	//IO::SetDigitsPad(-1);

	// STEP 2
	// Construct the actuator set, contact set, and control set.
	//ActuatorSet actuatorSet("fallingBlock_actuators.xml");
	//ContactForceSet contactSet("fallingBlock_contacts.xml");
	//ControlSet controlSet("fallingBlock_controls.xml");

	// STEP 3
	// Construct the model and print out some information
	// about the model.  The model is build as a dynamically linked library
	// (rdBlock.dll on Windows).
	SimbodyEngine *pendulum = new SimbodyEngine();
	Model *model = new Model;
	model->setDynamicsEngine(*pendulum);
	model->setup();
	model->printDetailedInfo(cout);

	// ADD GENERALIZED FORCE(S)
	int index = 0;
	// 1
	GeneralizedForce *gf = new GeneralizedForce(model->getDynamicsEngine().getCoordinateSet()->get(index)->getName());
	gf->setName("one");
	gf->setModel(model);
	gf->setOptimalForce(100);
	model->getActuatorSet()->append(gf);
	// 2
	gf = new GeneralizedForce(model->getDynamicsEngine().getCoordinateSet()->get(index)->getName());
	gf->setName("two");
	gf->setModel(model);
	gf->setOptimalForce(100);
	model->getActuatorSet()->append(gf);
	// Setup model
	model->setup();

	// STEP 4
	// Alter the initial states if desired.
	// Initial states would normally be specified in a file
	OpenSim::Array<double> yi(0.0,model->getNumStates());
	model->getInitialStates(&yi[0]);
	yi[0] = 0.1;	// Initial angle of pendulum from vertical
	model->setInitialStates(&yi[0]);

	// STEP 5
	// Set the acceleration due to gravity.
	double g[] = { 0.0, 0.0, 0.0 };
	model->setGravity(g);

	// STEP 6
	// Add analyses to the model->
	// These analyses will gather information during a simulation
	// without altering the simulation.
	// stepInterval specifies how frequently analyses will record info,
	// every four integration steps in this case.
	int stepInterval = 1;
	// Kinematics
	Kinematics *kin = new Kinematics(model);
	kin->setStepInterval(stepInterval);
	model->addAnalysis(kin);
	// Actuation
	//Actuation *actuation = new Actuation(&model);
	//actuation->setStepInterval(stepInterval);
	//model->addAnalysis(actuation);
	// Contact
	//Contact *contact = new Contact(&model);
	//contact->setStepInterval(stepInterval);
	//model->addAnalysis(contact);

	// STEP 7
	// Construct the integrand and the manager.
	// The model integrand is what is integrated during the simulation.
	// The manager takes care of a variety of low-level initializations.
	ModelIntegrand *integrand = new ModelIntegrand(model);
	//integrand->setControlSet(controlSet);
	int nx = integrand->getControlSet()->getSize();
	cout<<"NumControls = "<<nx<<endl;
	for(int i=0;i<nx;i++) {
		Control *x = integrand->getControlSet()->get(i);
		if(x) x->setControlValue(0,1.0);
	}
	Manager manager(integrand);

	// STEP 8
	// Specify the initial and final times of the simulation.
	// In this case, the initial and final times are set based on
	// the range of times over which the controls are available.
	//Control *control;
	double ti=0.0,tf=4.0;
	//control = controlSet.get("ti");
	//if(control!=NULL) ti = control->getControlValue();
	//control = controlSet.get("tf");
	//if(control!=NULL) tf = control->getControlValue();
	manager.setInitialTime(ti);
	manager.setFinalTime(tf);

	// STEP 9
	// Set up the numerical integrator.
	int maxSteps = 20000;
	IntegRKF *integ = manager.getIntegrator();
	integ->setMaximumNumberOfSteps(maxSteps);
	integ->setMaxDT(1.0e-1);
	integ->setTolerance(1.0e-7);
	integ->setFineTolerance(5.0e-9);

	// STEP 10
	// Integrate
	cout<<"\n\nIntegrating from "<<ti<<" to "<<tf<<endl;
	manager.integrate();

	// STEP 11
	// Print the analysis results.
	model->getAnalysisSet()->printResults("SimbodyPendulum","./");

	// DELETE MODEL
	delete model;

	return 0;
}
<commit_msg>Added a Force actuator.<commit_after>// testSimbodyEngine.cpp
// Author:  Frank C. Anderson

//==============================================================================
//==============================================================================
#include <iostream>
#include <OpenSim/Common/IO.h>
#include <OpenSim/Simulation/Model/ActuatorSet.h>
#include <OpenSim/Simulation/Model/ContactForceSet.h>
#include <OpenSim/Simulation/Model/AnalysisSet.h>
#include <OpenSim/Simulation/Model/BodySet.h>
#include <OpenSim/Simulation/Control/ControlLinear.h>
#include <OpenSim/Simulation/Control/ControlSet.h>
#include <OpenSim/Simulation/Manager/Manager.h>
#include <OpenSim/Analyses/Kinematics.h>
#include <OpenSim/Simulation/Model/Model.h>
#include <OpenSim/Simulation/Model/GeneralizedForce.h>
#include <OpenSim/Simulation/Model/Force.h>
#include <OpenSim/DynamicsEngines/SimbodyEngine/SimbodyEngine.h>

using namespace OpenSim;
using namespace SimTK;
using namespace std;

//______________________________________________________________________________
/**
 * Run a simulation of a pendulum with Simbody as the underlying dynamics
 * engine.
 */
int main()
{
	// STEP 1
	// Set output precision
	//IO::SetPrecision(8);
	//IO::SetDigitsPad(-1);

	// STEP 2
	// Construct the actuator set, contact set, and control set.
	//ActuatorSet actuatorSet("fallingBlock_actuators.xml");
	//ContactForceSet contactSet("fallingBlock_contacts.xml");
	//ControlSet controlSet("fallingBlock_controls.xml");

	// STEP 3
	// Construct the model and print out some information
	// about the model.  The model is build as a dynamically linked library
	// (rdBlock.dll on Windows).
	SimbodyEngine *pendulum = new SimbodyEngine();
	Model *model = new Model;
	model->setDynamicsEngine(*pendulum);
	model->setup();

	// ADD FORCE(S)
	int index = 0;
	// Gen. Force 1
	GeneralizedForce *gf1 = new GeneralizedForce(model->getDynamicsEngine().getCoordinateSet()->get(index)->getName());
	gf1->setName("gf2");
	gf1->setModel(model);
	gf1->setOptimalForce(15);
	// Gen. Force 2
	GeneralizedForce *gf2 = new GeneralizedForce(model->getDynamicsEngine().getCoordinateSet()->get(index)->getName());
	gf2->setName("gf2");
	gf2->setModel(model);
	gf2->setOptimalForce(20);
	// Force 3
	Force *f1 = new Force("ground","pendulum");
	OpenSim::Array<double> down(0.0,3);  down[1] = 1.0;
	f1->setName("f1");
	f1->setForceDirectionA(&down[0]);
	OpenSim::Array<double> massCenter(0.0,3);
	model->getDynamicsEngine().getBodySet()->get("pendulum")->getMassCenter(&massCenter[0]);
	cout<<"mass center = "<<massCenter<<endl;
	f1->setPointB(&massCenter[0]);
	f1->setOptimalForce(20);
	f1->setModel(model);
	// Add to model
	model->getActuatorSet()->append(gf1);
	//model->getActuatorSet()->append(gf2);
	model->getActuatorSet()->append(f1);

	// Setup model
	model->setup();
	OpenSim::Array<double> inertia(0.0,9);
	model->getDynamicsEngine().getBodySet()->get("ground")->setInertia(inertia);
	model->printDetailedInfo(cout);

	// STEP 4
	// Alter the initial states if desired.
	// Initial states would normally be specified in a file
	OpenSim::Array<double> yi(0.0,model->getNumStates());
	model->getInitialStates(&yi[0]);
	yi[0] = 0.1;	// Initial angle of pendulum from vertical
	model->setInitialStates(&yi[0]);

	// STEP 5
	// Set the acceleration due to gravity.
	double g[] = { 0.0, 0.0, 0.0 };
	model->setGravity(g);

	// STEP 6
	// Add analyses to the model->
	// These analyses will gather information during a simulation
	// without altering the simulation.
	// stepInterval specifies how frequently analyses will record info,
	// every four integration steps in this case.
	int stepInterval = 1;
	// Kinematics
	Kinematics *kin = new Kinematics(model);
	kin->setStepInterval(stepInterval);
	model->addAnalysis(kin);
	// Actuation
	//Actuation *actuation = new Actuation(&model);
	//actuation->setStepInterval(stepInterval);
	//model->addAnalysis(actuation);
	// Contact
	//Contact *contact = new Contact(&model);
	//contact->setStepInterval(stepInterval);
	//model->addAnalysis(contact);

	// STEP 7
	// Construct the integrand and the manager.
	// The model integrand is what is integrated during the simulation.
	// The manager takes care of a variety of low-level initializations.
	ModelIntegrand *integrand = new ModelIntegrand(model);
	//integrand->setControlSet(controlSet);
	int nx = integrand->getControlSet()->getSize();
	cout<<"NumControls = "<<nx<<endl;
	for(int i=0;i<nx;i++) {
		Control *x = integrand->getControlSet()->get(i);
		if(x) x->setControlValue(0,1.0);
	}
	Manager manager(integrand);

	// STEP 8
	// Specify the initial and final times of the simulation.
	// In this case, the initial and final times are set based on
	// the range of times over which the controls are available.
	//Control *control;
	double ti=0.0,tf=4.0;
	//control = controlSet.get("ti");
	//if(control!=NULL) ti = control->getControlValue();
	//control = controlSet.get("tf");
	//if(control!=NULL) tf = control->getControlValue();
	manager.setInitialTime(ti);
	manager.setFinalTime(tf);

	// STEP 9
	// Set up the numerical integrator.
	int maxSteps = 20000;
	IntegRKF *integ = manager.getIntegrator();
	integ->setMaximumNumberOfSteps(maxSteps);
	integ->setMaxDT(1.0e-1);
	integ->setTolerance(1.0e-7);
	integ->setFineTolerance(5.0e-9);

	// STEP 10
	// Integrate
	cout<<"\n\nIntegrating from "<<ti<<" to "<<tf<<endl;
	manager.integrate();

	// STEP 11
	// Print the analysis results.
	model->getAnalysisSet()->printResults("SimbodyPendulum","./");

	// DELETE MODEL
	delete model;

	return 0;
}
<|endoftext|>


<commit_before>#include "yebash.hpp"
#include "History.hpp"

#include "catch.hpp"
#include <algorithm>
#include <sstream>

using namespace yb;
using namespace std;

TEST_CASE( "No suggestions when history is empty", "[basic.empty_history]"  ) {

    auto testCharacter = [] (char const c) {
        std::stringstream ss;
        std::stringstream output;
        History history;
        history.read(ss);
        HistorySuggestion suggestion(history);
        Printer printer(output);

        auto result = yebash(suggestion, printer, c);

        REQUIRE(result == c);
        REQUIRE(output.str() == "");
    };

    string domain = "abcdefghijklmnopqrstuvwxyz01234567890-_";
    for_each(begin(domain), end(domain), testCharacter);
}

<commit_msg>added history-preserve-order test<commit_after>#include "yebash.hpp"
#include "History.hpp"

#include "catch.hpp"
#include <iostream>
#include <algorithm>
#include <sstream>

using namespace yb;
using namespace std;

TEST_CASE( "No suggestions when history is empty", "[basic.empty_history]"  ) {

    auto testCharacter = [] (char const c) {
        std::stringstream ss;
        std::stringstream output;
        History history;
        history.read(ss);
        HistorySuggestion suggestion(history);
        Printer printer(output);

        auto result = yebash(suggestion, printer, c);

        REQUIRE(result == c);
        REQUIRE(output.str() == "");
    };

    string domain = "abcdefghijklmnopqrstuvwxyz01234567890-_";
    for_each(begin(domain), end(domain), testCharacter);
}

TEST_CASE( "Order of commands from history is preserved", "[basic.history_order_preserved]"  ) {

    std::stringstream ss;
    ss << "abc1" << std::endl;
    ss << "abc2" << std::endl;

    std::stringstream output;
    History history;
    history.read(ss);
    HistorySuggestion suggestion(history);
    Printer printer(output);

    auto character = 'a';
    auto result = yebash(suggestion, printer, character);

    REQUIRE(result == character);
    REQUIRE(output.str() == "abc2");
}

<|endoftext|>


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

#ifndef SD_SLIDESORTER_PAGE_ENUMERATION_HXX
#define SD_SLIDESORTER_PAGE_ENUMERATION_HXX

#include "pres.hxx"

#include "memory"

#include "model/SlsEnumeration.hxx"
#include "model/SlsSharedPageDescriptor.hxx"

namespace sd { namespace slidesorter { namespace model {

class SlideSorterModel;

/** Public class of page enumerations that delegates its calls to an
    implementation object that can filter pages by using one of several
    predicates.
*/
class PageEnumeration
    : public Enumeration<SharedPageDescriptor>
{
public:
    /** The type of the predicate that is used to filter pages from the set
        of all pages provided by the slide sorter model:
            PET_ALL enumerates all pages.
            PET_SELECTED gives access to only the selected pages.
            PET_VISIBLE gives access to only the visible pages.
    */
    enum PageEnumerationType { PET_ALL, PET_SELECTED, PET_VISIBLE };

    /** Create a new page enumeration that enumerates a subset of the pages
        of the given model.
        @param rModel
            The new page enumeration enumerates the pages of this model.
        @param eType
            This value determines which predicate/filter to use.  See the
            PageEnumerationType enum above for a description of the
            available values.
    */
    static PageEnumeration Create (
        const SlideSorterModel& rModel,
        PageEnumerationType eType);

    /** This constructor expects an implementation object that implements
        the predicate that filters the pages.  If you do not know where to
        get such an object from you may want to use the static Create()
        factory method for creating a page enumeration.  Otherwise you may
        want to use that method as well.
    */
    PageEnumeration (::std::auto_ptr<Enumeration<SharedPageDescriptor> > pImpl);

    /** This copy constructor creates a copy of the given enumeration.  This
        new enumeration points to the same element as the given one.
    */
    PageEnumeration (const PageEnumeration& rEnumeration);

    /** Create a new enumeration object.  The ownership of the
        implementation object goes to the new object.  Use this copy
        constructor only when you know what you are doing.  When in doubt,
        use the one argument version.
        @param bCloneImpl
            When <TRUE/> is given this constructor behaves exactly like its
            one argument version.  When <FALSE/> is given then the
            implementation object is not copied but moved from the given
            enumeration to the newly created one.  The given enumeration
            thus becomes empty.
    */
    PageEnumeration (PageEnumeration& rEnumeration, bool bCloneImpl);

    /** Create and return an exact copy of the called object.
    */
    virtual ::std::auto_ptr<Enumeration<SharedPageDescriptor> > Clone (void);

    PageEnumeration& operator= (const PageEnumeration& rEnumeration);

    /** Return <TRUE/> when the enumeration has more elements, i.e. it is
        save to call GetNextElement() at least one more time.
    */
    virtual bool HasMoreElements (void) const;

    /** Return the next element of the enumeration.  Call the
        HasMoreElements() before to make sure that there exists at least one
        more element.  Calling this method with HasMoreElements() returning
        <FALSE/> is an error.
    */
    virtual SharedPageDescriptor GetNextElement (void);

    /** Rewind the enumeration so that the next call to GetNextElement()
        will return its first element.
    */
    virtual void Rewind (void);

private:
    /// Implementation object.
    ::std::auto_ptr<Enumeration<SharedPageDescriptor> > mpImpl;

    // Default constructor not implemented.
    PageEnumeration (void);
};

} } } // end of namespace ::sd::slidesorter::model

#endif
<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.4.160); FILE MERGED 2006/11/27 13:48:11 cl 1.4.160.1: #i69285# warning free code changes for sd project<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SlsPageEnumeration.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-12 18:35:20 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SD_SLIDESORTER_PAGE_ENUMERATION_HXX
#define SD_SLIDESORTER_PAGE_ENUMERATION_HXX

#include "pres.hxx"

#include "memory"

#include "model/SlsEnumeration.hxx"
#include "model/SlsSharedPageDescriptor.hxx"

namespace sd { namespace slidesorter { namespace model {

class SlideSorterModel;

/** Public class of page enumerations that delegates its calls to an
    implementation object that can filter pages by using one of several
    predicates.
*/
class PageEnumeration
    : public Enumeration<SharedPageDescriptor>
{
public:
    /** The type of the predicate that is used to filter pages from the set
        of all pages provided by the slide sorter model:
            PET_ALL enumerates all pages.
            PET_SELECTED gives access to only the selected pages.
            PET_VISIBLE gives access to only the visible pages.
    */
    enum PageEnumerationType { PET_ALL, PET_SELECTED, PET_VISIBLE };

    /** Create a new page enumeration that enumerates a subset of the pages
        of the given model.
        @param rModel
            The new page enumeration enumerates the pages of this model.
        @param eType
            This value determines which predicate/filter to use.  See the
            PageEnumerationType enum above for a description of the
            available values.
    */
    static PageEnumeration Create (
        const SlideSorterModel& rModel,
        PageEnumerationType eType);

    /** This constructor expects an implementation object that implements
        the predicate that filters the pages.  If you do not know where to
        get such an object from you may want to use the static Create()
        factory method for creating a page enumeration.  Otherwise you may
        want to use that method as well.
    */
    PageEnumeration (::std::auto_ptr<Enumeration<SharedPageDescriptor> > pImpl);

    /** This copy constructor creates a copy of the given enumeration.  This
        new enumeration points to the same element as the given one.
    */
    PageEnumeration (const PageEnumeration& rEnumeration);

    /**
    */
    virtual ~PageEnumeration();

    /** Create a new enumeration object.  The ownership of the
        implementation object goes to the new object.  Use this copy
        constructor only when you know what you are doing.  When in doubt,
        use the one argument version.
        @param bCloneImpl
            When <TRUE/> is given this constructor behaves exactly like its
            one argument version.  When <FALSE/> is given then the
            implementation object is not copied but moved from the given
            enumeration to the newly created one.  The given enumeration
            thus becomes empty.
    */
    PageEnumeration (PageEnumeration& rEnumeration, bool bCloneImpl);

    /** Create and return an exact copy of the called object.
    */
    virtual ::std::auto_ptr<Enumeration<SharedPageDescriptor> > Clone (void);

    PageEnumeration& operator= (const PageEnumeration& rEnumeration);

    /** Return <TRUE/> when the enumeration has more elements, i.e. it is
        save to call GetNextElement() at least one more time.
    */
    virtual bool HasMoreElements (void) const;

    /** Return the next element of the enumeration.  Call the
        HasMoreElements() before to make sure that there exists at least one
        more element.  Calling this method with HasMoreElements() returning
        <FALSE/> is an error.
    */
    virtual SharedPageDescriptor GetNextElement (void);

    /** Rewind the enumeration so that the next call to GetNextElement()
        will return its first element.
    */
    virtual void Rewind (void);

private:
    /// Implementation object.
    ::std::auto_ptr<Enumeration<SharedPageDescriptor> > mpImpl;

    // Default constructor not implemented.
    PageEnumeration (void);
};

} } } // end of namespace ::sd::slidesorter::model

#endif
<|endoftext|>


<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2017.  All rights reserved
*/
#ifndef _Stroika_Foundation_Math_LinearAlgebra_Matrix_inl_
#define _Stroika_Foundation_Math_LinearAlgebra_Matrix_inl_ 1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
#include <vector>

#include "../../Characters/StringBuilder.h"
#include "../../Characters/ToString.h"

namespace Stroika {
    namespace Foundation {
        namespace Math {
            namespace LinearAlgebra {
                /*
                 ********************************************************************************
                 ******************************** Matrix<T>::IRep_ ******************************
                 ********************************************************************************
                 */
                template <typename T>
                class Matrix<T>::IRep_ {
                public:
                    DimensionType           fDimensions;
                    Containers::Sequence<T> fData; // row*nCols + col is addressing scheme

                    T GetAt (size_t row, size_t col)
                    {
                        Require (row < fDimensions.fRows);
                        Require (col < fDimensions.fColumns);
                        return fData[row * fDimensions.fColumns + col];
                    }
                };

                /*
                 ********************************************************************************
                 ********************************** Matrix<T> ***********************************
                 ********************************************************************************
                 */
                template <typename T>
                inline Matrix<T>::Matrix (const DimensionType& dimensions)
                    : Matrix (dimensions, 0)
                {
                }
                template <typename T>
                Matrix<T>::Matrix (const DimensionType& dimensions, Configuration::ArgByValueType<T> fillValue)
                    : fRep_ (make_shared<IRep_> (dimensions))
                {
                    for (size_t r = 0; r < dimension.fRows; ++r) {
                        for (size_t c = 0; c < dimension.fColumns; ++c) {
                            fRep_->get ()->Append (fillValue);
                        }
                    }
                }
                template <typename T>
                Matrix<T>::Matrix (const DimensionType& dimensions, const function<T ()>& filler)
                    : fRep_ (make_shared<IRep_> (dimensions))
                {
                    for (size_t r = 0; r < dimension.fRows; ++r) {
                        for (size_t c = 0; c < dimension.fColumns; ++c) {
                            fRep_->get ()->Append (filler ());
                        }
                    }
                }
                template <typename T>
                Matrix<T> Matrix<T>::Identity (const DimensionType& dimensions)
                {
                    size_t row = 0;
                    size_t col = 0;
                    return Matrix{dimensions, [&]() { T result = (row == col) ? 1 : 0; ++col; if (col > dimensions.fColumns) { col = 0; row++; } }};
                }
                template <typename T>
                inline auto Matrix<T>::GetDimensions () const -> DimensionType
                {
                    return fRep_->cget ()->fDimensions;
                }
                template <typename T>
                Containers::Sequence<Vector<T>> Matrix<T>::GetRows () const
                {
                    Containers::Sequence<Vector<T>> result;
                    DimensionType                   dim = GetDimensions ();
                    for (size_t r = 0; r < dim.fRows; ++r) {
                        vector<T> row;
                        for (size_t c = 0; c < dim.fColumns; ++c) {
                            row.push_back (fRep_->cget ()->GetAt (r, c));
                        }
                        result += Vector<T>{row};
                    }
                    return result;
                }
                template <typename T>
                Containers::Sequence<Vector<T>> Matrix<T>::GetColumns () const
                {
                    Containers::Sequence<Vector<T>> result;
                    DimensionType                   dim = GetDimensions ();
                    for (size_t c = 0; c < dim.fColumns; ++c) {
                        vector<T> col;
                        for (size_t r = 0; r < dim.fRows; ++r) {
                            col.push_back (fRep_->cget ()->GetAt (r, c));
                        }
                        result += Vector<T>{col};
                    }
                    return result;
                }
                template <typename T>
                inline T Matrix<T>::GetAt (size_t r, size_t c) const
                {
                    return fRep_->cget ()->GetAt (r, c);
                }
                template <typename T>
                inline typename Matrix<T>::TemporaryRowReference_ Matrix<T>::operator[] (size_t row) const
                {
                    return TMP_{*this, row};
                }
                template <typename T>
                Characters::String Matrix<T>::ToString () const
                {
                    Characters::StringBuilder sb;
                    sb += L"[";
                    for (size_t row = 0; row < GetDimensions ().fRows; ++row) {
                        sb += L"[";
                        for (size_t col = 0; col < GetDimensions ().fColumns; ++col) {
                            sb += Characters::ToString (GetAt (row, col)) + L", ";
                        }
                        sb += L"],";
                    }
                    sb += L"]";
                    return sb.str ();
                }
            }
        }
    }
}
#endif /*_Stroika_Foundation_Math_LinearAlgebra_Matrix_inl_*/
<commit_msg>fix some typos with new linearalgebra code<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2017.  All rights reserved
*/
#ifndef _Stroika_Foundation_Math_LinearAlgebra_Matrix_inl_
#define _Stroika_Foundation_Math_LinearAlgebra_Matrix_inl_ 1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
#include <vector>

#include "../../Characters/StringBuilder.h"
#include "../../Characters/ToString.h"

namespace Stroika {
    namespace Foundation {
        namespace Math {
            namespace LinearAlgebra {
                /*
                 ********************************************************************************
                 ******************************** Matrix<T>::IRep_ ******************************
                 ********************************************************************************
                 */
                template <typename T>
                class Matrix<T>::IRep_ {
                public:
                    DimensionType           fDimensions;
                    Containers::Sequence<T> fData; // row*nCols + col is addressing scheme

                    T GetAt (size_t row, size_t col)
                    {
                        Require (row < fDimensions.fRows);
                        Require (col < fDimensions.fColumns);
                        return fData[row * fDimensions.fColumns + col];
                    }
                };

                /*
                 ********************************************************************************
                 ********************************** Matrix<T> ***********************************
                 ********************************************************************************
                 */
                template <typename T>
                inline Matrix<T>::Matrix (const DimensionType& dimensions)
                    : Matrix (dimensions, 0)
                {
                }
                template <typename T>
                Matrix<T>::Matrix (const DimensionType& dimensions, Configuration::ArgByValueType<T> fillValue)
                    : fRep_ (make_shared<IRep_> (dimensions))
                {
                    for (size_t r = 0; r < dimensions.fRows; ++r) {
                        for (size_t c = 0; c < dimensions.fColumns; ++c) {
                            fRep_->get ()->Append (fillValue);
                        }
                    }
                }
                template <typename T>
                Matrix<T>::Matrix (const DimensionType& dimensions, const function<T ()>& filler)
                    : fRep_ (make_shared<IRep_> (dimensions))
                {
                    for (size_t r = 0; r < dimensions.fRows; ++r) {
                        for (size_t c = 0; c < dimensions.fColumns; ++c) {
                            fRep_->get ()->Append (filler ());
                        }
                    }
                }
                template <typename T>
                Matrix<T> Matrix<T>::Identity (const DimensionType& dimensions)
                {
                    size_t row = 0;
                    size_t col = 0;
                    return Matrix{dimensions, [&]() { T result = (row == col) ? 1 : 0; ++col; if (col > dimensions.fColumns) { col = 0; row++; } }};
                }
                template <typename T>
                inline auto Matrix<T>::GetDimensions () const -> DimensionType
                {
                    return fRep_->cget ()->fDimensions;
                }
                template <typename T>
                Containers::Sequence<Vector<T>> Matrix<T>::GetRows () const
                {
                    Containers::Sequence<Vector<T>> result;
                    DimensionType                   dim = GetDimensions ();
                    for (size_t r = 0; r < dim.fRows; ++r) {
                        vector<T> row;
                        for (size_t c = 0; c < dim.fColumns; ++c) {
                            row.push_back (fRep_->cget ()->GetAt (r, c));
                        }
                        result += Vector<T>{row};
                    }
                    return result;
                }
                template <typename T>
                Containers::Sequence<Vector<T>> Matrix<T>::GetColumns () const
                {
                    Containers::Sequence<Vector<T>> result;
                    DimensionType                   dim = GetDimensions ();
                    for (size_t c = 0; c < dim.fColumns; ++c) {
                        vector<T> col;
                        for (size_t r = 0; r < dim.fRows; ++r) {
                            col.push_back (fRep_->cget ()->GetAt (r, c));
                        }
                        result += Vector<T>{col};
                    }
                    return result;
                }
                template <typename T>
                inline T Matrix<T>::GetAt (size_t r, size_t c) const
                {
                    return fRep_->cget ()->GetAt (r, c);
                }
                template <typename T>
                inline typename Matrix<T>::TemporaryRowReference_ Matrix<T>::operator[] (size_t row) const
                {
                    return TemporaryRowReference_{*this, row};
                }
                template <typename T>
                Characters::String Matrix<T>::ToString () const
                {
                    Characters::StringBuilder sb;
                    sb += L"[";
                    for (size_t row = 0; row < GetDimensions ().fRows; ++row) {
                        sb += L"[";
                        for (size_t col = 0; col < GetDimensions ().fColumns; ++col) {
                            sb += Characters::ToString (GetAt (row, col)) + L", ";
                        }
                        sb += L"],";
                    }
                    sb += L"]";
                    return sb.str ();
                }
            }
        }
    }
}
#endif /*_Stroika_Foundation_Math_LinearAlgebra_Matrix_inl_*/
<|endoftext|>


<commit_before>//
//  AnimatedMultiSinus.cpp
//  LaserAnimTool
//
//  Created by pach on 07/08/14.
//  Copyright (c) 2014 __MyCompanyName__. All rights reserved.
//

#include "AnimatedMultiSinus.h"

AnimatedMultiSinus::AnimatedMultiSinus(){

}

AnimatedMultiSinus::~AnimatedMultiSinus(){
    AnimatedStuff::~AnimatedStuff();
}

void AnimatedMultiSinus::setup(string name) {
    AnimatedStuff::setup(name);

    type = "AnimatedMultiSinus";

    gui->addSpacer();
    gui->addIntSlider("/nbPoint", 10, 1000, &nbPoint);
    gui->addSlider("/posY", -1., 1., &posY);
    gui->addSpacer();
    gui->addSlider("/1/freq", 0., 500., &sin1.freq);
    gui->addSlider("/1/speed", 0., 50., &sin1.speed);
    gui->addSlider("/1/height", 0., 1., &sin1.height);
    gui->addSpacer();
    gui->addSlider("/2/freq", 0., 500., &sin2.freq);
    gui->addSlider("/2/speed", 0., 50., &sin2.speed);
    gui->addSlider("/2/height", 0., 1., &sin2.height);
    gui->addSpacer();
    gui->addSlider("/3/freq", 0., 500., &sin3.freq);
    gui->addSlider("/3/speed", 0., 50., &sin3.speed);
    gui->addSlider("/3/height", 0., 1., &sin3.height);
    ofPolyline p;
    polylines.push_back(p);

    load();

}

void AnimatedMultiSinus::update() {
    polylines[0].clear();

    for (int i=0 ; i<nbPoint ; i++){
        float y1 = sin((float)i/sin1.freq+ofGetElapsedTimef()*sin1.speed)*sin1.height;
        float y2 = sin((float)i/sin2.freq+ofGetElapsedTimef()*sin2.speed)*sin2.height;
        float y3 = sin((float)i/sin3.freq+ofGetElapsedTimef()*sin3.speed)*sin3.height;
        polylines[0].addVertex((float)i/(float)nbPoint, y1+y2+y3-posY);
    }
}

void AnimatedMultiSinus::parseOSC(ofxOscMessage &m){
//    string msg = m.getAddress();
//    string cmd ;
//
//    int ces = msg.find_first_of("/");
//
//    if (ces != -1) {
//        if (ces == 0){
//            msg = msg.substr(ces+1);
//            cmd = msg;
//            ces = msg.find_first_of("/");
//            if (ces != -1) {
//                cmd = msg.substr(0, ces);
//                msg = msg.substr(ces);
//            }
//        }
//        else{
//            cmd = msg.substr(0, ces);
//            msg = msg.substr(ces);
//        }
//    }

    vector<string> osc = getOSCcmd(m.getAddress());
    string cmd = osc[0];
    string msg = osc[1];

    if (cmd == "nbPoint"){
        nbPoint = m.getArgAsInt32(0);
    }
    else if (cmd == "posY"){
        posY = ofMap(m.getArgAsFloat(0), 0., 1., -1., 1.);
    }
    else if (cmd == "1"){
//        ces = msg.find_first_of("/");
//
//        if (ces != -1) {
//            if (ces == 0){
//                msg = msg.substr(ces+1);
//                cmd = msg;
//                ces = msg.find_first_of("/");
//                if (ces != -1) {
//                    cmd = msg.substr(0, ces);
//                    msg = msg.substr(ces);
//                }
//            }
//            else{
//                cmd = msg.substr(0, ces);
//                msg = msg.substr(ces);
//            }
//        }
        osc = getOSCcmd(msg);
        cmd = osc[0];
        msg = osc[1];

        if (cmd == "freq"){
            sin1.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
        }
        else if (cmd == "speed"){
            sin1.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
        }
        else if (cmd == "height"){
            sin1.height = m.getArgAsFloat(0);
        }
    }
    else if (cmd == "2"){
//        ces = msg.find_first_of("/");
//
//        if (ces != -1) {
//            if (ces == 0){
//                msg = msg.substr(ces+1);
//                cmd = msg;
//                ces = msg.find_first_of("/");
//                if (ces != -1) {
//                    cmd = msg.substr(0, ces);
//                    msg = msg.substr(ces);
//                }
//            }
//            else{
//                cmd = msg.substr(0, ces);
//                msg = msg.substr(ces);
//            }
//        }
        osc = getOSCcmd(msg);
        cmd = osc[0];
        msg = osc[1];

        if (cmd == "freq"){
            sin2.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
        }
        else if (cmd == "speed"){
            sin2.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
        }
        else if (cmd == "height"){
            sin2.height = m.getArgAsFloat(0);
        }
    }
    else if (cmd == "3"){
//        ces = msg.find_first_of("/");
//
//        if (ces != -1) {
//            if (ces == 0){
//                msg = msg.substr(ces+1);
//                cmd = msg;
//                ces = msg.find_first_of("/");
//                if (ces != -1) {
//                    cmd = msg.substr(0, ces);
//                    msg = msg.substr(ces);
//                }
//            }
//            else{
//                cmd = msg.substr(0, ces);
//                msg = msg.substr(ces);
//            }
//        }

        osc = getOSCcmd(msg);
        cmd = osc[0];
        msg = osc[1];

        if (cmd == "freq"){
            sin3.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
        }
        else if (cmd == "speed"){
            sin3.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
        }
        else if (cmd == "height"){
            sin3.height = m.getArgAsFloat(0);
        }
    }
//    else if (cmd == "1/freq"){
//        sin1.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
//    }
//    else if (cmd == "1/speed"){
//        sin1.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
//    }
//    else if (cmd == "1/height"){
//        sin1.height = m.getArgAsFloat(0);
//    }
//    else if (cmd == "2/freq"){
//        sin2.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
//    }
//    else if (cmd == "2/speed"){
//        sin2.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
//    }
//    else if (cmd == "2/height"){
//        sin2.height = m.getArgAsFloat(0);
//    }
//    else if (cmd == "3/freq"){
//        sin3.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
//    }
//    else if (cmd == "3/speed"){
//        sin3.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
//    }
//    else if (cmd == "3/height"){
//        sin3.height = m.getArgAsFloat(0);
//    }
}<commit_msg>change speed range.<commit_after>//
//  AnimatedMultiSinus.cpp
//  LaserAnimTool
//
//  Created by pach on 07/08/14.
//  Copyright (c) 2014 __MyCompanyName__. All rights reserved.
//

#include "AnimatedMultiSinus.h"

AnimatedMultiSinus::AnimatedMultiSinus(){

}

AnimatedMultiSinus::~AnimatedMultiSinus(){
    AnimatedStuff::~AnimatedStuff();
}

void AnimatedMultiSinus::setup(string name) {
    AnimatedStuff::setup(name);

    type = "AnimatedMultiSinus";

    gui->addSpacer();
    gui->addIntSlider("/nbPoint", 10, 1000, &nbPoint);
    gui->addSlider("/posY", -1., 1., &posY);
    gui->addSpacer();
    gui->addSlider("/1/freq", 0., 500., &sin1.freq);
    gui->addSlider("/1/speed", -10., 10., &sin1.speed);
    gui->addSlider("/1/height", 0., 1., &sin1.height);
    gui->addSpacer();
    gui->addSlider("/2/freq", 0., 500., &sin2.freq);
    gui->addSlider("/2/speed", -10., 10., &sin2.speed);
    gui->addSlider("/2/height", 0., 1., &sin2.height);
    gui->addSpacer();
    gui->addSlider("/3/freq", 0., 500., &sin3.freq);
    gui->addSlider("/3/speed", -10., 10., &sin3.speed);
    gui->addSlider("/3/height", 0., 1., &sin3.height);
    ofPolyline p;
    polylines.push_back(p);

    load();

}

void AnimatedMultiSinus::update() {
    polylines[0].clear();

    for (int i=0 ; i<nbPoint ; i++){
        float y1 = sin((float)i/sin1.freq+ofGetElapsedTimef()*sin1.speed)*sin1.height;
        float y2 = sin((float)i/sin2.freq+ofGetElapsedTimef()*sin2.speed)*sin2.height;
        float y3 = sin((float)i/sin3.freq+ofGetElapsedTimef()*sin3.speed)*sin3.height;
        polylines[0].addVertex((float)i/(float)nbPoint, y1+y2+y3-posY);
    }
}

void AnimatedMultiSinus::parseOSC(ofxOscMessage &m){
//    string msg = m.getAddress();
//    string cmd ;
//
//    int ces = msg.find_first_of("/");
//
//    if (ces != -1) {
//        if (ces == 0){
//            msg = msg.substr(ces+1);
//            cmd = msg;
//            ces = msg.find_first_of("/");
//            if (ces != -1) {
//                cmd = msg.substr(0, ces);
//                msg = msg.substr(ces);
//            }
//        }
//        else{
//            cmd = msg.substr(0, ces);
//            msg = msg.substr(ces);
//        }
//    }

    vector<string> osc = getOSCcmd(m.getAddress());
    string cmd = osc[0];
    string msg = osc[1];

    if (cmd == "nbPoint"){
        nbPoint = m.getArgAsInt32(0);
    }
    else if (cmd == "posY"){
        posY = ofMap(m.getArgAsFloat(0), 0., 1., -1., 1.);
    }
    else if (cmd == "1"){
//        ces = msg.find_first_of("/");
//
//        if (ces != -1) {
//            if (ces == 0){
//                msg = msg.substr(ces+1);
//                cmd = msg;
//                ces = msg.find_first_of("/");
//                if (ces != -1) {
//                    cmd = msg.substr(0, ces);
//                    msg = msg.substr(ces);
//                }
//            }
//            else{
//                cmd = msg.substr(0, ces);
//                msg = msg.substr(ces);
//            }
//        }
        osc = getOSCcmd(msg);
        cmd = osc[0];
        msg = osc[1];

        if (cmd == "freq"){
            sin1.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
        }
        else if (cmd == "speed"){
            sin1.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
        }
        else if (cmd == "height"){
            sin1.height = m.getArgAsFloat(0);
        }
    }
    else if (cmd == "2"){
//        ces = msg.find_first_of("/");
//
//        if (ces != -1) {
//            if (ces == 0){
//                msg = msg.substr(ces+1);
//                cmd = msg;
//                ces = msg.find_first_of("/");
//                if (ces != -1) {
//                    cmd = msg.substr(0, ces);
//                    msg = msg.substr(ces);
//                }
//            }
//            else{
//                cmd = msg.substr(0, ces);
//                msg = msg.substr(ces);
//            }
//        }
        osc = getOSCcmd(msg);
        cmd = osc[0];
        msg = osc[1];

        if (cmd == "freq"){
            sin2.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
        }
        else if (cmd == "speed"){
            sin2.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
        }
        else if (cmd == "height"){
            sin2.height = m.getArgAsFloat(0);
        }
    }
    else if (cmd == "3"){
//        ces = msg.find_first_of("/");
//
//        if (ces != -1) {
//            if (ces == 0){
//                msg = msg.substr(ces+1);
//                cmd = msg;
//                ces = msg.find_first_of("/");
//                if (ces != -1) {
//                    cmd = msg.substr(0, ces);
//                    msg = msg.substr(ces);
//                }
//            }
//            else{
//                cmd = msg.substr(0, ces);
//                msg = msg.substr(ces);
//            }
//        }

        osc = getOSCcmd(msg);
        cmd = osc[0];
        msg = osc[1];

        if (cmd == "freq"){
            sin3.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
        }
        else if (cmd == "speed"){
            sin3.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
        }
        else if (cmd == "height"){
            sin3.height = m.getArgAsFloat(0);
        }
    }
//    else if (cmd == "1/freq"){
//        sin1.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
//    }
//    else if (cmd == "1/speed"){
//        sin1.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
//    }
//    else if (cmd == "1/height"){
//        sin1.height = m.getArgAsFloat(0);
//    }
//    else if (cmd == "2/freq"){
//        sin2.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
//    }
//    else if (cmd == "2/speed"){
//        sin2.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
//    }
//    else if (cmd == "2/height"){
//        sin2.height = m.getArgAsFloat(0);
//    }
//    else if (cmd == "3/freq"){
//        sin3.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
//    }
//    else if (cmd == "3/speed"){
//        sin3.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
//    }
//    else if (cmd == "3/height"){
//        sin3.height = m.getArgAsFloat(0);
//    }
}<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (c) Jürgen Riegel          (juergen.riegel@web.de)          *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   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 Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
#endif

#include <Base/Writer.h>

#include "Document.h"
#include "DocumentObject.h"
#include "DocumentObjectPy.h"
#include "DocumentObjectGroup.h"
#include "PropertyLinks.h"
#include "PropertyExpressionEngine.h"
#include <boost/signals/connection.hpp>
#include <boost/bind.hpp>

using namespace App;

PROPERTY_SOURCE(App::DocumentObject, App::PropertyContainer)

DocumentObjectExecReturn *DocumentObject::StdReturn = 0;

//===========================================================================
// DocumentObject
//===========================================================================

DocumentObject::DocumentObject(void)
    : ExpressionEngine(),_pDoc(0),pcNameInDocument(0)
{
    // define Label of type 'Output' to avoid being marked as touched after relabeling
    ADD_PROPERTY_TYPE(Label,("Unnamed"),"Base",Prop_Output,"User name of the object (UTF8)");
    ADD_PROPERTY_TYPE(ExpressionEngine,(),"Base",Prop_Hidden,"Property expressions");
}

DocumentObject::~DocumentObject(void)
{
    if (!PythonObject.is(Py::_None())){
        // Remark: The API of Py::Object has been changed to set whether the wrapper owns the passed
        // Python object or not. In the constructor we forced the wrapper to own the object so we need
        // not to dec'ref the Python object any more.
        // But we must still invalidate the Python object because it need not to be
        // destructed right now because the interpreter can own several references to it.
        Base::PyObjectBase* obj = (Base::PyObjectBase*)PythonObject.ptr();
        // Call before decrementing the reference counter, otherwise a heap error can occur
        obj->setInvalid();
    }
}

namespace App {
class ObjectExecution
{
public:
    ObjectExecution(DocumentObject* o) : obj(o)
    { obj->StatusBits.set(3); }
    ~ObjectExecution()
    { obj->StatusBits.reset(3); }
private:
    DocumentObject* obj;
};
}

App::DocumentObjectExecReturn *DocumentObject::recompute(void)
{
    // set/unset the execution bit
    ObjectExecution exe(this);
    return this->execute();
}

DocumentObjectExecReturn *DocumentObject::execute(void)
{
    return StdReturn;
}

short DocumentObject::mustExecute(void) const
{
    return (isTouched() ? 1 : 0);
}

const char* DocumentObject::getStatusString(void) const
{
    if (isError()) {
        const char* text = getDocument()->getErrorDescription(this);
        return text ? text : "Error";
    }
    else if (isTouched())
        return "Touched";
    else
        return "Valid";
}

const char *DocumentObject::getNameInDocument(void) const
{
    // Note: It can happen that we query the internal name of an object even if it is not
    // part of a document (anymore). This is the case e.g. if we have a reference in Python
    // to an object that has been removed from the document. In this case we should rather
    // return 0.
    //assert(pcNameInDocument);
    if (!pcNameInDocument) return 0;
    return pcNameInDocument->c_str();
}

std::vector<DocumentObject*> DocumentObject::getOutList(void) const
{
    std::vector<Property*> List;
    std::vector<DocumentObject*> ret;
    getPropertyList(List);
    for (std::vector<Property*>::const_iterator It = List.begin();It != List.end(); ++It) {
        if ((*It)->isDerivedFrom(PropertyLinkList::getClassTypeId())) {
            const std::vector<DocumentObject*> &OutList = static_cast<PropertyLinkList*>(*It)->getValues();
            for (std::vector<DocumentObject*>::const_iterator It2 = OutList.begin();It2 != OutList.end(); ++It2) {
                if (*It2)
                    ret.push_back(*It2);
            }
        }
        else if ((*It)->isDerivedFrom(PropertyLinkSubList::getClassTypeId())) {
            const std::vector<DocumentObject*> &OutList = static_cast<PropertyLinkSubList*>(*It)->getValues();
            for (std::vector<DocumentObject*>::const_iterator It2 = OutList.begin();It2 != OutList.end(); ++It2) {
                if (*It2)
                    ret.push_back(*It2);
            }
        }
        else if ((*It)->isDerivedFrom(PropertyLink::getClassTypeId())) {
            if (static_cast<PropertyLink*>(*It)->getValue())
                ret.push_back(static_cast<PropertyLink*>(*It)->getValue());
        }
        else if ((*It)->isDerivedFrom(PropertyLinkSub::getClassTypeId())) {
            if (static_cast<PropertyLinkSub*>(*It)->getValue())
                ret.push_back(static_cast<PropertyLinkSub*>(*It)->getValue());
        }
    }

    // Get document objects that this document object relies on
    ExpressionEngine.getDocumentObjectDeps(ret);

    return ret;
}

std::vector<App::DocumentObject*> DocumentObject::getInList(void) const
{
    if (_pDoc)
        return _pDoc->getInList(this);
    else
        return std::vector<App::DocumentObject*>();
}

DocumentObjectGroup* DocumentObject::getGroup() const
{
    return DocumentObjectGroup::getGroupOfObject(this);
}

void DocumentObject::onLostLinkToObject(DocumentObject*)
{

}

App::Document *DocumentObject::getDocument(void) const
{
    return _pDoc;
}

void DocumentObject::setDocument(App::Document* doc)
{
    _pDoc=doc;
    onSettingDocument();
}

void DocumentObject::onBeforeChange(const Property* prop)
{

    // Store current name in oldLabel, to be able to easily retrieve old name of document object later
    // when renaming expressions.
    if (prop == &Label)
        oldLabel = Label.getStrValue();

    if (_pDoc)
        _pDoc->onBeforeChangeProperty(this,prop);
}

/// get called by the container when a Property was changed
void DocumentObject::onChanged(const Property* prop)
{
    if (_pDoc)
        _pDoc->onChangedProperty(this,prop);

    if (prop == &Label && _pDoc)
        _pDoc->signalRelabelObject(*this);

    if (prop->getType() & Prop_Output)
        return;
    // set object touched
    StatusBits.set(0);
}

PyObject *DocumentObject::getPyObject(void)
{
    if (PythonObject.is(Py::_None())) {
        // ref counter is set to 1
        PythonObject = Py::Object(new DocumentObjectPy(this),true);
    }
    return Py::new_reference_to(PythonObject);
}

std::vector<PyObject *> DocumentObject::getPySubObjects(const std::vector<std::string>&) const
{
    // default implementation returns nothing
    return std::vector<PyObject *>();
}

void DocumentObject::touch(void)
{
    StatusBits.set(0);
}

/**
 * @brief Check whether the document object is touched or not.
 * @return true if document object is touched, false if not.
 */

bool DocumentObject::isTouched() const
{
    return ExpressionEngine.isTouched() || StatusBits.test(0);
}

void DocumentObject::Save (Base::Writer &writer) const
{
    writer.ObjectName = this->getNameInDocument();
    App::PropertyContainer::Save(writer);
}

/**
 * @brief Associate the expression \expr with the object identifier \a path in this document object.
 * @param path Target object identifier for the result of the expression
 * @param expr Expression tree
 * @param comment Optional comment describing the expression
 */

void DocumentObject::setExpression(const ObjectIdentifier &path, boost::shared_ptr<Expression> expr, const char * comment)
{
    ExpressionEngine.setValue(path, expr, comment);
    connectRelabelSignals();
}

/**
 * @brief Get expression information associated with \a path.
 * @param path Object identifier
 * @return Expression info, containing expression and optional comment.
 */

const PropertyExpressionEngine::ExpressionInfo DocumentObject::getExpression(const ObjectIdentifier &path) const
{
    boost::any value = ExpressionEngine.getPathValue(path);

    if (value.type() == typeid(PropertyExpressionEngine::ExpressionInfo))
        return boost::any_cast<PropertyExpressionEngine::ExpressionInfo>(value);
    else
        return PropertyExpressionEngine::ExpressionInfo();
}

/**
 * @brief Invoke ExpressionEngine's renameObjectIdentifier, to possibly rewrite expressions using
 * the \a paths map with current and new identifiers.
 *
 * @param paths
 */

void DocumentObject::renameObjectIdentifiers(const std::map<ObjectIdentifier, ObjectIdentifier> &paths)
{
    ExpressionEngine.renameObjectIdentifiers(paths);
}

/**
 * @brief Helper function that sets up a signal to track document object renames.
 */

void DocumentObject::connectRelabelSignals()
{
    // Only keep signal if the ExpressionEngine has at least one expression
    if (ExpressionEngine.numExpressions() > 0) {

        // Not already connected?
        if (!onRelabledObjectConnection.connected())
            onRelabledObjectConnection = getDocument()->signalRelabelObject.connect(boost::bind(&PropertyExpressionEngine::slotObjectRenamed, &ExpressionEngine, _1));

        try {
            // Crude method to resolve all expression dependencies
            ExpressionEngine.execute();
        }
        catch (...) {
            // Ignore any error
        }
    }
    else {
        // Disconnect signals; nothing to track now
        onRelabledObjectConnection.disconnect();
        onRelabledDocumentConnection.disconnect();
    }
}
<commit_msg>DocumentObject: Don't emit signal if Label hasn't actually changed.<commit_after>/***************************************************************************
 *   Copyright (c) Jürgen Riegel          (juergen.riegel@web.de)          *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   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 Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
#endif

#include <Base/Writer.h>

#include "Document.h"
#include "DocumentObject.h"
#include "DocumentObjectPy.h"
#include "DocumentObjectGroup.h"
#include "PropertyLinks.h"
#include "PropertyExpressionEngine.h"
#include <boost/signals/connection.hpp>
#include <boost/bind.hpp>

using namespace App;

PROPERTY_SOURCE(App::DocumentObject, App::PropertyContainer)

DocumentObjectExecReturn *DocumentObject::StdReturn = 0;

//===========================================================================
// DocumentObject
//===========================================================================

DocumentObject::DocumentObject(void)
    : ExpressionEngine(),_pDoc(0),pcNameInDocument(0)
{
    // define Label of type 'Output' to avoid being marked as touched after relabeling
    ADD_PROPERTY_TYPE(Label,("Unnamed"),"Base",Prop_Output,"User name of the object (UTF8)");
    ADD_PROPERTY_TYPE(ExpressionEngine,(),"Base",Prop_Hidden,"Property expressions");
}

DocumentObject::~DocumentObject(void)
{
    if (!PythonObject.is(Py::_None())){
        // Remark: The API of Py::Object has been changed to set whether the wrapper owns the passed
        // Python object or not. In the constructor we forced the wrapper to own the object so we need
        // not to dec'ref the Python object any more.
        // But we must still invalidate the Python object because it need not to be
        // destructed right now because the interpreter can own several references to it.
        Base::PyObjectBase* obj = (Base::PyObjectBase*)PythonObject.ptr();
        // Call before decrementing the reference counter, otherwise a heap error can occur
        obj->setInvalid();
    }
}

namespace App {
class ObjectExecution
{
public:
    ObjectExecution(DocumentObject* o) : obj(o)
    { obj->StatusBits.set(3); }
    ~ObjectExecution()
    { obj->StatusBits.reset(3); }
private:
    DocumentObject* obj;
};
}

App::DocumentObjectExecReturn *DocumentObject::recompute(void)
{
    // set/unset the execution bit
    ObjectExecution exe(this);
    return this->execute();
}

DocumentObjectExecReturn *DocumentObject::execute(void)
{
    return StdReturn;
}

short DocumentObject::mustExecute(void) const
{
    return (isTouched() ? 1 : 0);
}

const char* DocumentObject::getStatusString(void) const
{
    if (isError()) {
        const char* text = getDocument()->getErrorDescription(this);
        return text ? text : "Error";
    }
    else if (isTouched())
        return "Touched";
    else
        return "Valid";
}

const char *DocumentObject::getNameInDocument(void) const
{
    // Note: It can happen that we query the internal name of an object even if it is not
    // part of a document (anymore). This is the case e.g. if we have a reference in Python
    // to an object that has been removed from the document. In this case we should rather
    // return 0.
    //assert(pcNameInDocument);
    if (!pcNameInDocument) return 0;
    return pcNameInDocument->c_str();
}

std::vector<DocumentObject*> DocumentObject::getOutList(void) const
{
    std::vector<Property*> List;
    std::vector<DocumentObject*> ret;
    getPropertyList(List);
    for (std::vector<Property*>::const_iterator It = List.begin();It != List.end(); ++It) {
        if ((*It)->isDerivedFrom(PropertyLinkList::getClassTypeId())) {
            const std::vector<DocumentObject*> &OutList = static_cast<PropertyLinkList*>(*It)->getValues();
            for (std::vector<DocumentObject*>::const_iterator It2 = OutList.begin();It2 != OutList.end(); ++It2) {
                if (*It2)
                    ret.push_back(*It2);
            }
        }
        else if ((*It)->isDerivedFrom(PropertyLinkSubList::getClassTypeId())) {
            const std::vector<DocumentObject*> &OutList = static_cast<PropertyLinkSubList*>(*It)->getValues();
            for (std::vector<DocumentObject*>::const_iterator It2 = OutList.begin();It2 != OutList.end(); ++It2) {
                if (*It2)
                    ret.push_back(*It2);
            }
        }
        else if ((*It)->isDerivedFrom(PropertyLink::getClassTypeId())) {
            if (static_cast<PropertyLink*>(*It)->getValue())
                ret.push_back(static_cast<PropertyLink*>(*It)->getValue());
        }
        else if ((*It)->isDerivedFrom(PropertyLinkSub::getClassTypeId())) {
            if (static_cast<PropertyLinkSub*>(*It)->getValue())
                ret.push_back(static_cast<PropertyLinkSub*>(*It)->getValue());
        }
    }

    // Get document objects that this document object relies on
    ExpressionEngine.getDocumentObjectDeps(ret);

    return ret;
}

std::vector<App::DocumentObject*> DocumentObject::getInList(void) const
{
    if (_pDoc)
        return _pDoc->getInList(this);
    else
        return std::vector<App::DocumentObject*>();
}

DocumentObjectGroup* DocumentObject::getGroup() const
{
    return DocumentObjectGroup::getGroupOfObject(this);
}

void DocumentObject::onLostLinkToObject(DocumentObject*)
{

}

App::Document *DocumentObject::getDocument(void) const
{
    return _pDoc;
}

void DocumentObject::setDocument(App::Document* doc)
{
    _pDoc=doc;
    onSettingDocument();
}

void DocumentObject::onBeforeChange(const Property* prop)
{

    // Store current name in oldLabel, to be able to easily retrieve old name of document object later
    // when renaming expressions.
    if (prop == &Label)
        oldLabel = Label.getStrValue();

    if (_pDoc)
        _pDoc->onBeforeChangeProperty(this,prop);
}

/// get called by the container when a Property was changed
void DocumentObject::onChanged(const Property* prop)
{
    if (_pDoc)
        _pDoc->onChangedProperty(this,prop);

    if (prop == &Label && _pDoc && oldLabel != Label.getStrValue())
        _pDoc->signalRelabelObject(*this);

    if (prop->getType() & Prop_Output)
        return;
    // set object touched
    StatusBits.set(0);
}

PyObject *DocumentObject::getPyObject(void)
{
    if (PythonObject.is(Py::_None())) {
        // ref counter is set to 1
        PythonObject = Py::Object(new DocumentObjectPy(this),true);
    }
    return Py::new_reference_to(PythonObject);
}

std::vector<PyObject *> DocumentObject::getPySubObjects(const std::vector<std::string>&) const
{
    // default implementation returns nothing
    return std::vector<PyObject *>();
}

void DocumentObject::touch(void)
{
    StatusBits.set(0);
}

/**
 * @brief Check whether the document object is touched or not.
 * @return true if document object is touched, false if not.
 */

bool DocumentObject::isTouched() const
{
    return ExpressionEngine.isTouched() || StatusBits.test(0);
}

void DocumentObject::Save (Base::Writer &writer) const
{
    writer.ObjectName = this->getNameInDocument();
    App::PropertyContainer::Save(writer);
}

/**
 * @brief Associate the expression \expr with the object identifier \a path in this document object.
 * @param path Target object identifier for the result of the expression
 * @param expr Expression tree
 * @param comment Optional comment describing the expression
 */

void DocumentObject::setExpression(const ObjectIdentifier &path, boost::shared_ptr<Expression> expr, const char * comment)
{
    ExpressionEngine.setValue(path, expr, comment);
    connectRelabelSignals();
}

/**
 * @brief Get expression information associated with \a path.
 * @param path Object identifier
 * @return Expression info, containing expression and optional comment.
 */

const PropertyExpressionEngine::ExpressionInfo DocumentObject::getExpression(const ObjectIdentifier &path) const
{
    boost::any value = ExpressionEngine.getPathValue(path);

    if (value.type() == typeid(PropertyExpressionEngine::ExpressionInfo))
        return boost::any_cast<PropertyExpressionEngine::ExpressionInfo>(value);
    else
        return PropertyExpressionEngine::ExpressionInfo();
}

/**
 * @brief Invoke ExpressionEngine's renameObjectIdentifier, to possibly rewrite expressions using
 * the \a paths map with current and new identifiers.
 *
 * @param paths
 */

void DocumentObject::renameObjectIdentifiers(const std::map<ObjectIdentifier, ObjectIdentifier> &paths)
{
    ExpressionEngine.renameObjectIdentifiers(paths);
}

/**
 * @brief Helper function that sets up a signal to track document object renames.
 */

void DocumentObject::connectRelabelSignals()
{
    // Only keep signal if the ExpressionEngine has at least one expression
    if (ExpressionEngine.numExpressions() > 0) {

        // Not already connected?
        if (!onRelabledObjectConnection.connected())
            onRelabledObjectConnection = getDocument()->signalRelabelObject.connect(boost::bind(&PropertyExpressionEngine::slotObjectRenamed, &ExpressionEngine, _1));

        try {
            // Crude method to resolve all expression dependencies
            ExpressionEngine.execute();
        }
        catch (...) {
            // Ignore any error
        }
    }
    else {
        // Disconnect signals; nothing to track now
        onRelabledObjectConnection.disconnect();
        onRelabledDocumentConnection.disconnect();
    }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>

using namespace std;

template <class T>
struct Node
{
	T element;
	Node<T> *left, *right, *pparent;
};

template <class T>
class BST {
private:
	Node<T> *root;
	int count;
public:
	BST();
	~BST();
	void deleteTree(Node<T> *Tree);
	void show(ostream&cout, const Node<T> *Tree) const;
	void add(const T&) const;
	bool search(const T&, Node<T> *Tree) const;
	void input(const string& file) const;
	void output(const string& file) const;
	Node<T>* MinElement(Node<T>* min);
	Node<T>* getroot() const;
	int getcount() const;
	Node<T>* del(Node<T>* parent, Node<T>* current, const T& val);
	bool delVal(const T& val);

};

template <typename T> BST<T>::BST() {
	root = NULL;
	count = 0;
}

template <typename T> BST<T>::~BST() {
	deleteTree(root);
}

template <typename T>void BST<T>::deleteTree(Node<T> *Tree) {
	if (!Tree)
		return;
	if (Tree->left) {
		deleteTree(Tree->left);
		Tree->left = nullptr;
	}

	if (Tree->right) {
		deleteTree(Tree->right);
		Tree->right = nullptr;
	}
	delete Tree;
}

template <typename T> void BST<T>::show(ostream&cout, const Node<T> *Tree) const{
	if (Tree != NULL) {

		cout << Tree->element << endl;;
		show(cout, Tree->left);
		show(cout, Tree->right);

	}
}

template <typename T> void BST<T>::add(const T &x) const{
	Node<T>* daughter = new Node<T>;
	daughter->element = x;
	daughter->left = daughter->right = nullptr;
	Node<T>* parent = root;
	Node<T>* temp = root;

	while (temp)
	{
		parent = temp;
		if (x < temp->element)
			temp = temp->left;
		else temp = temp->right;
	}

	if (!parent)
		root = daughter;
	else {
		if (x < parent->element)
			parent->left = daughter;
		else
			parent->right = daughter;
	}
	count++;
}

template <typename T> Node<T>* BST<T>::getroot() const {
	return root;
}

template <typename T> int BST<T>::getcount() const {
	return count;
}

template <typename T> void BST<T>::input(const string& file) const {
	ifstream fin(file);
	try
	{
		int temp;
		while (!fin.eof()) throw 1;
		{

			fin >> temp;
			add(temp);

		}
		fin.close();
	}
	catch (int i)
	{
		cout << "This file don't find" << endl;
	}

}

template <typename T> void BST<T>::output(const string& file) const {
	ofstream fout(file);
	show(fout, root);
	fout.close();
}

template <typename T> bool BST<T>::search(const T&x, Node<T>* Tree) const {
	if (Tree == nullptr)
		return false;
	if (x == Tree->element) {
		return true;
	}
	else if (x < Tree->element) {
		search(x, Tree->left);
	}
	else search(x, Tree->right);
}

template <typename T> Node<T>* BST<T>::MinElement(Node<T>* min) {
	if (min->left == nullptr)
		return min;
	else
		return MinElement(min->left);

}

template <typename T>
Node<T>* BST<T>::del(Node<T>* parent, Node<T>* current, const T& val)
{
	if (!current) return false;

	if (current->element == val)
	{
		if (current->left == NULL || current->right == NULL)
		{
			Node<T>* temp = current->left;
			if (current->right) temp = current->right;
			if (parent)
			{
				if (parent->left == current)
				{
					parent->left = temp;
				}
				else
				{
					parent->right = temp;
				}
			}
			else
			{
				this->root = temp;
			}
		}

		else
		{
			Node<T>* validSubs = current->right;
			while (validSubs->left)
			{
				validSubs = validSubs->left;
			}
			T temp = current->element;
			current->element = validSubs->element;
			validSubs->element = temp;
			return del(current, current->right, temp);

		}
		delete current;
		count--;
		return true;
	}

	if (current->element > val)

		return del(current, current->left, val);

	else

		return del(current, current->right, val);
}

template <typename T>
bool BST<T>::delVal(const T& val) {
	return this->del(NULL, root, val);
}
<commit_msg>Create BST.hpp<commit_after>#include <iostream>
#include <fstream>

using namespace std;

template <class T>
struct Node
{
	T element;
	Node<T> *left, *right, *pparent;
};

template <class T>
class BST {
private:
	Node<T> *root;
	int count;
public:
	BST();
	~BST();
	void deleteTree(Node<T> *Tree);
	void show(ostream&cout, const Node<T> *Tree) const;
	void add(const T&);
	bool search(const T&, Node<T> *Tree) const;
	void input(const string& file) const;
	void output(const string& file) const;
	Node<T>* MinElement(Node<T>* min);
	Node<T>* getroot() const;
	int getcount() const;
	Node<T>* del(Node<T>* parent, Node<T>* current, const T& val);
	bool delVal(const T& val);

};

template <typename T> BST<T>::BST() {
	root = NULL;
	count = 0;
}

template <typename T> BST<T>::~BST() {
	deleteTree(root);
}

template <typename T>void BST<T>::deleteTree(Node<T> *Tree) {
	if (!Tree)
		return;
	if (Tree->left) {
		deleteTree(Tree->left);
		Tree->left = nullptr;
	}

	if (Tree->right) {
		deleteTree(Tree->right);
		Tree->right = nullptr;
	}
	delete Tree;
}

template <typename T> void BST<T>::show(ostream&cout, const Node<T> *Tree) const{
	if (Tree != NULL) {

		cout << Tree->element << endl;;
		show(cout, Tree->left);
		show(cout, Tree->right);

	}
}

template <typename T> void BST<T>::add(const T &x) {
	Node<T>* daughter = new Node<T>;
	daughter->element = x;
	daughter->left = daughter->right = nullptr;
	Node<T>* parent = root;
	Node<T>* temp = root;

	while (temp)
	{
		parent = temp;
		if (x < temp->element)
			temp = temp->left;
		else temp = temp->right;
	}

	if (!parent)
		root = daughter;
	else {
		if (x < parent->element)
			parent->left = daughter;
		else
			parent->right = daughter;
	}
	count++;
}

template <typename T> Node<T>* BST<T>::getroot() const {
	return root;
}

template <typename T> int BST<T>::getcount() const {
	return count;
}

template <typename T> void BST<T>::input(const string& file) const {
	ifstream fin(file);
	try
	{
		int temp;
		while (!fin.eof()) throw 1;
		{

			fin >> temp;
			add(temp);

		}
		fin.close();
	}
	catch (int i)
	{
		cout << "This file don't find" << endl;
	}

}

template <typename T> void BST<T>::output(const string& file) const {
	ofstream fout(file);
	show(fout, root);
	fout.close();
}

template <typename T> bool BST<T>::search(const T&x, Node<T>* Tree) const {
	if (Tree == nullptr)
		return false;
	if (x == Tree->element) {
		return true;
	}
	else if (x < Tree->element) {
		search(x, Tree->left);
	}
	else search(x, Tree->right);
}

template <typename T> Node<T>* BST<T>::MinElement(Node<T>* min) {
	if (min->left == nullptr)
		return min;
	else
		return MinElement(min->left);

}

template <typename T>
Node<T>* BST<T>::del(Node<T>* parent, Node<T>* current, const T& val)
{
	if (!current) return false;

	if (current->element == val)
	{
		if (current->left == NULL || current->right == NULL)
		{
			Node<T>* temp = current->left;
			if (current->right) temp = current->right;
			if (parent)
			{
				if (parent->left == current)
				{
					parent->left = temp;
				}
				else
				{
					parent->right = temp;
				}
			}
			else
			{
				this->root = temp;
			}
		}

		else
		{
			Node<T>* validSubs = current->right;
			while (validSubs->left)
			{
				validSubs = validSubs->left;
			}
			T temp = current->element;
			current->element = validSubs->element;
			validSubs->element = temp;
			return del(current, current->right, temp);

		}
		delete current;
		count--;
		return true;
	}

	if (current->element > val)

		return del(current, current->left, val);

	else

		return del(current, current->right, val);
}

template <typename T>
bool BST<T>::delVal(const T& val) {
	return this->del(NULL, root, val);
}
<|endoftext|>


<commit_before>#include "gmock/gmock.h"
#include "Base.hpp"
#include "Child1.hpp"
#include "Child2.hpp"

using testing::Eq;
using testing::Test;
using testing::Types;

template <typename T>
class ADerivedBase : public Test {
 public:
  T derivedBase;
};

typedef Types<Child1, Child2> DerivedBases;

TYPED_TEST_CASE(ADerivedBase, DerivedBases);

TYPED_TEST(ADerivedBase, ReturnsOneInDoSomething) {
  ASSERT_THAT(this->derivedBase.doSomething(), Eq(1));
}
<commit_msg>:see_no_evil: Stop including Base<commit_after>#include "gmock/gmock.h"
#include "Child1.hpp"
#include "Child2.hpp"

using testing::Eq;
using testing::Test;
using testing::Types;

template <typename T>
class ADerivedBase : public Test {
 public:
  T derivedBase;
};

typedef Types<Child1, Child2> DerivedBases;

TYPED_TEST_CASE(ADerivedBase, DerivedBases);

TYPED_TEST(ADerivedBase, ReturnsOneInDoSomething) {
  ASSERT_THAT(this->derivedBase.doSomething(), Eq(1));
}
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2010, Willow Garage, 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 Willow Garage, Inc. nor the names of its
 *     contributors 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.
 *
 * $Id$
 *
 */

#ifndef SENSOR_MSGS_POINT_CLOUD_CONVERSION_H
#define SENSOR_MSGS_POINT_CLOUD_CONVERSION_H

#include <sensor_msgs/PointCloud.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/point_field_conversion.h>

/**
  * \brief Convert between the old (sensor_msgs::PointCloud) and the new (sensor_msgs::PointCloud2) format.
  * \author Radu Bogdan Rusu
  */
namespace sensor_msgs
{
  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  /** \brief Get the index of a specified field (i.e., dimension/channel)
    * \param points the the point cloud message
    * \param field_name the string defining the field name
    */
static inline int getPointCloud2FieldIndex (const sensor_msgs::PointCloud2 &cloud, const std::string &field_name)
{
  // Get the index we need
  for (size_t d = 0; d < cloud.fields.size (); ++d)
    if (cloud.fields[d].name == field_name)
      return (d);
  return (-1);
}

  ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  /** \brief Convert a sensor_msgs::PointCloud message to a sensor_msgs::PointCloud2 message.
    * \param input the message in the sensor_msgs::PointCloud format
    * \param output the resultant message in the sensor_msgs::PointCloud2 format
    */
static inline bool convertPointCloudToPointCloud2 (const sensor_msgs::PointCloud &input, sensor_msgs::PointCloud2 &output)
{
  output.header = input.header;
  output.width  = input.points.size ();
  output.height = 1;
  output.fields.resize (3 + input.channels.size ());
  // Convert x/y/z to fields
  output.fields[0].name = "x"; output.fields[1].name = "y"; output.fields[2].name = "z";
  int offset = 0;
  // All offsets are *4, as all field data types are float32
  for (size_t d = 0; d < output.fields.size (); ++d, offset += 4)
  {
    output.fields[d].offset = offset;
    output.fields[d].datatype = sensor_msgs::PointField::FLOAT32;
    output.fields[d].count  = 1;
  }
  output.point_step = offset;
  output.row_step   = output.point_step * output.width;
  // Convert the remaining of the channels to fields
  for (size_t d = 0; d < input.channels.size (); ++d)
    output.fields[3 + d].name = input.channels[d].name;
  output.data.resize (input.points.size () * output.point_step);
  output.is_bigendian = false;  // @todo ?
  output.is_dense     = false;

  // Copy the data points
  for (size_t cp = 0; cp < input.points.size (); ++cp)
  {
    memcpy (&output.data[cp * output.point_step + output.fields[0].offset], &input.points[cp].x, sizeof (float));
    memcpy (&output.data[cp * output.point_step + output.fields[1].offset], &input.points[cp].y, sizeof (float));
    memcpy (&output.data[cp * output.point_step + output.fields[2].offset], &input.points[cp].z, sizeof (float));
    for (size_t d = 0; d < input.channels.size (); ++d)
    {
      if (input.channels[d].values.size() == input.points.size())
      {
        memcpy (&output.data[cp * output.point_step + output.fields[3 + d].offset], &input.channels[d].values[cp], sizeof (float));
      }
    }
  }
  return (true);
}

  ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  /** \brief Convert a sensor_msgs::PointCloud2 message to a sensor_msgs::PointCloud message.
    * \param input the message in the sensor_msgs::PointCloud2 format
    * \param output the resultant message in the sensor_msgs::PointCloud format
    */
static inline bool convertPointCloud2ToPointCloud (const sensor_msgs::PointCloud2 &input, sensor_msgs::PointCloud &output)
{

  output.header = input.header;
  output.points.resize (input.width * input.height);
  output.channels.resize (input.fields.size () - 3);
  // Get the x/y/z field offsets
  int x_idx = getPointCloud2FieldIndex (input, "x");
  int y_idx = getPointCloud2FieldIndex (input, "y");
  int z_idx = getPointCloud2FieldIndex (input, "z");
  if (x_idx == -1 || y_idx == -1 || z_idx == -1)
  {
    std::cerr << "x/y/z coordinates not found! Cannot convert to sensor_msgs::PointCloud!" << std::endl;
    return (false);
  }
  int x_offset = input.fields[x_idx].offset;
  int y_offset = input.fields[y_idx].offset;
  int z_offset = input.fields[z_idx].offset;
  uint8_t x_datatype = input.fields[x_idx].datatype;
  uint8_t y_datatype = input.fields[y_idx].datatype;
  uint8_t z_datatype = input.fields[z_idx].datatype;

  // Convert the fields to channels
  int cur_c = 0;
  for (size_t d = 0; d < input.fields.size (); ++d)
  {
    if ((int)input.fields[d].offset == x_offset || (int)input.fields[d].offset == y_offset || (int)input.fields[d].offset == z_offset)
      continue;
    output.channels[cur_c].name = input.fields[d].name;
    output.channels[cur_c].values.resize (output.points.size ());
    cur_c++;
  }

  // Copy the data points
  for (size_t cp = 0; cp < output.points.size (); ++cp)
  {
    // Copy x/y/z
    output.points[cp].x = sensor_msgs::readPointCloud2BufferValue<float>(&input.data[cp * input.point_step + x_offset], x_datatype);
    output.points[cp].y = sensor_msgs::readPointCloud2BufferValue<float>(&input.data[cp * input.point_step + y_offset], y_datatype);
    output.points[cp].z = sensor_msgs::readPointCloud2BufferValue<float>(&input.data[cp * input.point_step + z_offset], z_datatype);
    // Copy the rest of the data
    int cur_c = 0;
    for (size_t d = 0; d < input.fields.size (); ++d)
    {
      if ((int)input.fields[d].offset == x_offset || (int)input.fields[d].offset == y_offset || (int)input.fields[d].offset == z_offset)
        continue;
      output.channels[cur_c++].values[cp] = sensor_msgs::readPointCloud2BufferValue<float>(&input.data[cp * input.point_step + input.fields[d].offset], input.fields[d].datatype);
    }
  }
  return (true);
}
}
#endif// SENSOR_MSGS_POINT_CLOUD_CONVERSION_H
<commit_msg>Update copyright.<commit_after>// Copyright (c) 2010, Willow Garage
// All rights reserved.
//
// Software License Agreement (BSD License 2.0)
//
// 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 the copyright holder nor the names of its
//    contributors 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.

// this file is originally ported from ROS1:
// https://raw.githubusercontent.com/ros/common_msgs/ef18af000759bf15c7ea036356dbdce631c75577/sensor_msgs/include/sensor_msgs/point_cloud_conversion.h_
//
#ifndef SENSOR_MSGS__POINT_CLOUD_CONVERSION_HPP_
#define SENSOR_MSGS__POINT_CLOUD_CONVERSION_HPP_

#include <sensor_msgs/PointCloud.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/point_field_conversion.h>

/**
  * \brief Convert between the old (sensor_msgs::PointCloud) and the new (sensor_msgs::PointCloud2) format.
  * \author Radu Bogdan Rusu
  */
namespace sensor_msgs
{
  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  /** \brief Get the index of a specified field (i.e., dimension/channel)
    * \param points the the point cloud message
    * \param field_name the string defining the field name
    */
static inline int getPointCloud2FieldIndex (const sensor_msgs::PointCloud2 &cloud, const std::string &field_name)
{
  // Get the index we need
  for (size_t d = 0; d < cloud.fields.size (); ++d)
    if (cloud.fields[d].name == field_name)
      return (d);
  return (-1);
}

  ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  /** \brief Convert a sensor_msgs::PointCloud message to a sensor_msgs::PointCloud2 message.
    * \param input the message in the sensor_msgs::PointCloud format
    * \param output the resultant message in the sensor_msgs::PointCloud2 format
    */
static inline bool convertPointCloudToPointCloud2 (const sensor_msgs::PointCloud &input, sensor_msgs::PointCloud2 &output)
{
  output.header = input.header;
  output.width  = input.points.size ();
  output.height = 1;
  output.fields.resize (3 + input.channels.size ());
  // Convert x/y/z to fields
  output.fields[0].name = "x"; output.fields[1].name = "y"; output.fields[2].name = "z";
  int offset = 0;
  // All offsets are *4, as all field data types are float32
  for (size_t d = 0; d < output.fields.size (); ++d, offset += 4)
  {
    output.fields[d].offset = offset;
    output.fields[d].datatype = sensor_msgs::PointField::FLOAT32;
    output.fields[d].count  = 1;
  }
  output.point_step = offset;
  output.row_step   = output.point_step * output.width;
  // Convert the remaining of the channels to fields
  for (size_t d = 0; d < input.channels.size (); ++d)
    output.fields[3 + d].name = input.channels[d].name;
  output.data.resize (input.points.size () * output.point_step);
  output.is_bigendian = false;  // @todo ?
  output.is_dense     = false;

  // Copy the data points
  for (size_t cp = 0; cp < input.points.size (); ++cp)
  {
    memcpy (&output.data[cp * output.point_step + output.fields[0].offset], &input.points[cp].x, sizeof (float));
    memcpy (&output.data[cp * output.point_step + output.fields[1].offset], &input.points[cp].y, sizeof (float));
    memcpy (&output.data[cp * output.point_step + output.fields[2].offset], &input.points[cp].z, sizeof (float));
    for (size_t d = 0; d < input.channels.size (); ++d)
    {
      if (input.channels[d].values.size() == input.points.size())
      {
        memcpy (&output.data[cp * output.point_step + output.fields[3 + d].offset], &input.channels[d].values[cp], sizeof (float));
      }
    }
  }
  return (true);
}

  ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  /** \brief Convert a sensor_msgs::PointCloud2 message to a sensor_msgs::PointCloud message.
    * \param input the message in the sensor_msgs::PointCloud2 format
    * \param output the resultant message in the sensor_msgs::PointCloud format
    */
static inline bool convertPointCloud2ToPointCloud (const sensor_msgs::PointCloud2 &input, sensor_msgs::PointCloud &output)
{

  output.header = input.header;
  output.points.resize (input.width * input.height);
  output.channels.resize (input.fields.size () - 3);
  // Get the x/y/z field offsets
  int x_idx = getPointCloud2FieldIndex (input, "x");
  int y_idx = getPointCloud2FieldIndex (input, "y");
  int z_idx = getPointCloud2FieldIndex (input, "z");
  if (x_idx == -1 || y_idx == -1 || z_idx == -1)
  {
    std::cerr << "x/y/z coordinates not found! Cannot convert to sensor_msgs::PointCloud!" << std::endl;
    return (false);
  }
  int x_offset = input.fields[x_idx].offset;
  int y_offset = input.fields[y_idx].offset;
  int z_offset = input.fields[z_idx].offset;
  uint8_t x_datatype = input.fields[x_idx].datatype;
  uint8_t y_datatype = input.fields[y_idx].datatype;
  uint8_t z_datatype = input.fields[z_idx].datatype;

  // Convert the fields to channels
  int cur_c = 0;
  for (size_t d = 0; d < input.fields.size (); ++d)
  {
    if ((int)input.fields[d].offset == x_offset || (int)input.fields[d].offset == y_offset || (int)input.fields[d].offset == z_offset)
      continue;
    output.channels[cur_c].name = input.fields[d].name;
    output.channels[cur_c].values.resize (output.points.size ());
    cur_c++;
  }

  // Copy the data points
  for (size_t cp = 0; cp < output.points.size (); ++cp)
  {
    // Copy x/y/z
    output.points[cp].x = sensor_msgs::readPointCloud2BufferValue<float>(&input.data[cp * input.point_step + x_offset], x_datatype);
    output.points[cp].y = sensor_msgs::readPointCloud2BufferValue<float>(&input.data[cp * input.point_step + y_offset], y_datatype);
    output.points[cp].z = sensor_msgs::readPointCloud2BufferValue<float>(&input.data[cp * input.point_step + z_offset], z_datatype);
    // Copy the rest of the data
    int cur_c = 0;
    for (size_t d = 0; d < input.fields.size (); ++d)
    {
      if ((int)input.fields[d].offset == x_offset || (int)input.fields[d].offset == y_offset || (int)input.fields[d].offset == z_offset)
        continue;
      output.channels[cur_c++].values[cp] = sensor_msgs::readPointCloud2BufferValue<float>(&input.data[cp * input.point_step + input.fields[d].offset], input.fields[d].datatype);
    }
  }
  return (true);
}
}  // namespace sensor_msgs

#endif  // SENSOR_MSGS__POINT_CLOUD_CONVERSION_HPP_
<|endoftext|>


<commit_before>#include "io/PLY.hh"

#include "distances/Hausdorff.hh"
#include "distances/NearestNeighbour.hh"

#include "utilities/Timer.hh"

#include "persistentHomology/Calculation.hh"

#include "persistenceDiagrams/PersistenceDiagram.hh"
#include "persistenceDiagrams/Norms.hh"

#include <iostream>

using DataType   = double;
using VertexType = unsigned;

int main( int argc, char** argv )
{
  std::string filename;
  std::string property = "quality";

  if( argc == 1 )
    return -1;

  if( argc >= 2 )
    filename = argv[1];

  if( argc >= 3 )
    property = argv[2];

  auto K
    = aleph::io::loadPLY<DataType, VertexType>( filename, property );

  std::cerr << "* Loaded simplicial complex with " << K.size() << " simplices\n";

  aleph::utilities::Timer timer;

  auto diagrams
    = aleph::calculatePersistenceDiagrams( K );

  std::cerr << "* Calculated " << diagrams.size() << " persistence diagrams in " << timer.elapsed_s() << "s\n";

  for( auto&& D : diagrams )
    std::cout << D << "\n";

  for( auto&& D : diagrams )
  {
    std::cerr << "* Total degree-1 persistence: " << aleph::totalPersistence( D, 1.0 ) << "\n"
              << "* Total degree-2 persistence: " << aleph::totalPersistence( D, 2.0 ) << "\n"
              << "* 1-norm:                     " << aleph::pNorm( D, 1.0 ) << "\n"
              << "* 2-norm:                     " << aleph::pNorm( D, 2.0 ) << "\n";
  }

  // FIXME: Remove after debugging
  for( auto&& D1 : diagrams )
    for( auto&& D2 : diagrams )
      std::cerr << aleph::distances::nearestNeighbourDistance( D1, D2 ) << "\n";

  std::cerr << std::string( 80, '-' ) << "\n";

  for( auto&& D1 : diagrams )
    for( auto&& D2 : diagrams )
      std::cerr << aleph::distances::hausdorffDistance( D1, D2 ) << "\n";

}
<commit_msg>Some TODOs for PLY processing example<commit_after>#include "io/PLY.hh"

#include "distances/Hausdorff.hh"
#include "distances/NearestNeighbour.hh"

#include "persistenceDiagrams/PersistenceDiagram.hh"
#include "persistenceDiagrams/Norms.hh"

#include "persistentHomology/Calculation.hh"

#include "utilities/Timer.hh"

#include <iostream>

using DataType   = double;
using VertexType = unsigned;

int main( int argc, char** argv )
{
  std::string filename;
  std::string property = "quality";

  if( argc == 1 )
    return -1;

  if( argc >= 2 )
    filename = argv[1];

  if( argc >= 3 )
    property = argv[2];

  auto K
    = aleph::io::loadPLY<DataType, VertexType>( filename, property );

  // TODO:
  //   - Expansion (higher-dimensional simplices)
  //   - Different filtrations (superlevel, sublevel)

  std::cerr << "* Loaded simplicial complex with " << K.size() << " simplices\n";

  aleph::utilities::Timer timer;

  auto diagrams
    = aleph::calculatePersistenceDiagrams( K );

  std::cerr << "* Calculated " << diagrams.size() << " persistence diagrams in " << timer.elapsed_s() << "s\n";

  for( auto&& D : diagrams )
  {
    D.removeDiagonal();
    std::cout << D << "\n";
  }

  for( auto&& D : diagrams )
  {
    std::cerr << "* Total degree-1 persistence: " << aleph::totalPersistence( D, 1.0 ) << "\n"
              << "* Total degree-2 persistence: " << aleph::totalPersistence( D, 2.0 ) << "\n"
              << "* 1-norm:                     " << aleph::pNorm( D, 1.0 ) << "\n"
              << "* 2-norm:                     " << aleph::pNorm( D, 2.0 ) << "\n";
  }
}
<|endoftext|>