<commit_before>#include "kernel.h"
#include "raster.h"
#include "connectorinterface.h"
#include "symboltable.h"
#include "ilwisoperation.h"

using namespace Ilwis;

OperationHelper::OperationHelper()
{
}

Box3D<qint32> OperationHelper::initialize(const IGridCoverage &inputGC, IGridCoverage &outputGC, const Parameter& parm, quint64 what)
{
    Resource resource(itGRIDCOVERAGE);
    Size sz = inputGC->size();
    Box3D<qint32> box(sz);

    if ( what & itGRIDSIZE) {
        resource.addProperty("size", IVARIANT(sz));
    }
    if ( what & itENVELOPE) {
        if ( box.isNull() || !box.isValid()) {
            sz = inputGC->size();
            box  = Box3D<qint32>(sz);
        }
        Box2D<double> bounds = inputGC->georeference()->pixel2Coord(box);
        resource.addProperty("envelope", IVARIANT(bounds));
    }
    if ( what & itCOORDSYSTEM) {
        resource.addProperty("coordinatesystem", IVARIANT(inputGC->coordinateSystem()));
    }

    if ( what & itGEOREF) {
        if ( box.isNull() || !box.isValid()) {
            sz = inputGC->size();
            box  = Box3D<qint32>(sz);
        }
        if ( sz.xsize() == box.xlength() && sz.ysize() == box.ylength())
            resource.addProperty("georeference", IVARIANT(inputGC->georeference()));
    }
    if ( what & itDOMAIN) {
        resource.addProperty("domain", IVARIANT(inputGC->datadef().domain()));
    }
    resource.prepare();

    outputGC.prepare(resource);
    if ( what & itTABLE) {
        if ( inputGC->attributeTable(itGRIDCOVERAGE).isValid())    {
            if ( inputGC->datadef().domain() == outputGC->datadef().domain()) {
                if ( outputGC.isValid())
                    outputGC->attributeTable(itGRIDCOVERAGE,inputGC->attributeTable(itGRIDCOVERAGE));
            }
        }
    }

    return box;
}

IIlwisObject OperationHelper::initialize(const IIlwisObject &inputObject, IlwisTypes tp, const Parameter& parm, quint64 what)
{
    Resource resource(tp);
    if (inputObject->ilwisType() & itCOVERAGE) {
        ICoverage covInput = inputObject.get<Coverage>();
        if (inputObject->ilwisType() == itGRIDCOVERAGE) {
            IGridCoverage gcInput = inputObject.get<GridCoverage>();
            if ( what & itGRIDSIZE) {
                Size sz = gcInput->size();
                Box3D<qint32> box(sz);
                resource.addProperty("size", IVARIANT(box.size()));
            }
            if ( what & itGEOREF) {
                resource.addProperty("georeference", IVARIANT(gcInput->georeference()));
            }
        }
        if ( what & itENVELOPE) {
            Box2D<double> bounds = covInput->envelope();
            resource.addProperty("envelope", IVARIANT(bounds));
        }
        if ( what & itCOORDSYSTEM) {
            resource.addProperty("coordinatesystem", IVARIANT(covInput->coordinateSystem()));
        }
        if ( what & itDOMAIN) {
            resource.addProperty("domain", IVARIANT(covInput->datadef().domain()));
        }
    }

    resource.prepare();
    IIlwisObject obj;
    obj.prepare(resource);
    if (inputObject->ilwisType() & itCOVERAGE) {
        ICoverage covInput = inputObject.get<Coverage>();
        ICoverage covOutput = inputObject.get<Coverage>();
        if (inputObject->ilwisType() == itGRIDCOVERAGE) {
            //IGridCoverage gcInput = inputObject.get<GridCoverage>();
        }
        if ( what & itTABLE) {
            if ( covInput->attributeTable(itGRIDCOVERAGE).isValid())    {
                if ( covInput->datadef().domain() == covOutput->datadef().domain()) {
                    if ( covOutput.isValid())
                        covOutput->attributeTable(tp,covInput->attributeTable(tp));
                }
            }
        }

    }

    return obj;
}

int OperationHelper::subdivideTasks(ExecutionContext *ctx,const IGridCoverage& gcov, const Box3D<qint32> &bnds, std::vector<Box3D<qint32> > &boxes)
{
    if ( !gcov.isValid() || gcov->size().isNull() || gcov->size().ysize() == 0) {
        return ERROR1(ERR_NO_INITIALIZED_1, "Grid size");
        return iUNDEF;
    }

    int cores = std::min(QThread::idealThreadCount(),gcov->size().ysize());
    if (gcov->size().totalSize() < 10000)
        cores = 1;

    boxes.clear();
    boxes.resize(cores);
    Box3D<qint32> bounds = bnds;
    if ( bounds.isNull())
        bounds = Box3D<qint32>(gcov->size());
    int left = 0; //bounds.min_corner().x();
    int right = bounds.size().xsize();
    int top = bounds.size().ysize();
    int step = bounds.size().ysize() / cores;
    int currentY = 0;

    for(int i=0 ; i < cores; ++i){
        Box3D<qint32> smallBox(Pixel(left, currentY), Pixel(right - 1, std::min(top - 1,currentY + step)) );
        boxes[i] = smallBox;
        currentY = currentY + step  ;
    }
    return cores;
}

<commit_msg>support for disabling multithreading<commit_after>#include "kernel.h"
#include "raster.h"
#include "connectorinterface.h"
#include "symboltable.h"
#include "ilwisoperation.h"

using namespace Ilwis;

OperationHelper::OperationHelper()
{
}

Box3D<qint32> OperationHelper::initialize(const IGridCoverage &inputGC, IGridCoverage &outputGC, const Parameter& parm, quint64 what)
{
    Resource resource(itGRIDCOVERAGE);
    Size sz = inputGC->size();
    Box3D<qint32> box(sz);

    if ( what & itGRIDSIZE) {
        resource.addProperty("size", IVARIANT(sz));
    }
    if ( what & itENVELOPE) {
        if ( box.isNull() || !box.isValid()) {
            sz = inputGC->size();
            box  = Box3D<qint32>(sz);
        }
        Box2D<double> bounds = inputGC->georeference()->pixel2Coord(box);
        resource.addProperty("envelope", IVARIANT(bounds));
    }
    if ( what & itCOORDSYSTEM) {
        resource.addProperty("coordinatesystem", IVARIANT(inputGC->coordinateSystem()));
    }

    if ( what & itGEOREF) {
        if ( box.isNull() || !box.isValid()) {
            sz = inputGC->size();
            box  = Box3D<qint32>(sz);
        }
        if ( sz.xsize() == box.xlength() && sz.ysize() == box.ylength())
            resource.addProperty("georeference", IVARIANT(inputGC->georeference()));
    }
    if ( what & itDOMAIN) {
        resource.addProperty("domain", IVARIANT(inputGC->datadef().domain()));
    }
    resource.prepare();

    outputGC.prepare(resource);
    if ( what & itTABLE) {
        if ( inputGC->attributeTable(itGRIDCOVERAGE).isValid())    {
            if ( inputGC->datadef().domain() == outputGC->datadef().domain()) {
                if ( outputGC.isValid())
                    outputGC->attributeTable(itGRIDCOVERAGE,inputGC->attributeTable(itGRIDCOVERAGE));
            }
        }
    }

    return box;
}

IIlwisObject OperationHelper::initialize(const IIlwisObject &inputObject, IlwisTypes tp, const Parameter& parm, quint64 what)
{
    Resource resource(tp);
    if (inputObject->ilwisType() & itCOVERAGE) {
        ICoverage covInput = inputObject.get<Coverage>();
        if (inputObject->ilwisType() == itGRIDCOVERAGE) {
            IGridCoverage gcInput = inputObject.get<GridCoverage>();
            if ( what & itGRIDSIZE) {
                Size sz = gcInput->size();
                Box3D<qint32> box(sz);
                resource.addProperty("size", IVARIANT(box.size()));
            }
            if ( what & itGEOREF) {
                resource.addProperty("georeference", IVARIANT(gcInput->georeference()));
            }
        }
        if ( what & itENVELOPE) {
            Box2D<double> bounds = covInput->envelope();
            resource.addProperty("envelope", IVARIANT(bounds));
        }
        if ( what & itCOORDSYSTEM) {
            resource.addProperty("coordinatesystem", IVARIANT(covInput->coordinateSystem()));
        }
        if ( what & itDOMAIN) {
            resource.addProperty("domain", IVARIANT(covInput->datadef().domain()));
        }
    }

    resource.prepare();
    IIlwisObject obj;
    obj.prepare(resource);
    if (inputObject->ilwisType() & itCOVERAGE) {
        ICoverage covInput = inputObject.get<Coverage>();
        ICoverage covOutput = inputObject.get<Coverage>();
        if (inputObject->ilwisType() == itGRIDCOVERAGE) {
            //IGridCoverage gcInput = inputObject.get<GridCoverage>();
        }
        if ( what & itTABLE) {
            if ( covInput->attributeTable(itGRIDCOVERAGE).isValid())    {
                if ( covInput->datadef().domain() == covOutput->datadef().domain()) {
                    if ( covOutput.isValid())
                        covOutput->attributeTable(tp,covInput->attributeTable(tp));
                }
            }
        }

    }

    return obj;
}

int OperationHelper::subdivideTasks(ExecutionContext *ctx,const IGridCoverage& gcov, const Box3D<qint32> &bnds, std::vector<Box3D<qint32> > &boxes)
{
    if ( !gcov.isValid() || gcov->size().isNull() || gcov->size().ysize() == 0) {
        return ERROR1(ERR_NO_INITIALIZED_1, "Grid size");
        return iUNDEF;
    }

    int cores = std::min(QThread::idealThreadCount(),gcov->size().ysize());
    if (gcov->size().totalSize() < 10000 || ctx->_threaded == false)
        cores = 1;

    boxes.clear();
    boxes.resize(cores);
    Box3D<qint32> bounds = bnds;
    if ( bounds.isNull())
        bounds = Box3D<qint32>(gcov->size());
    int left = 0; //bounds.min_corner().x();
    int right = bounds.size().xsize();
    int top = bounds.size().ysize();
    int step = bounds.size().ysize() / cores;
    int currentY = 0;

    for(int i=0 ; i < cores; ++i){
        Box3D<qint32> smallBox(Pixel(left, currentY), Pixel(right - 1, std::min(top - 1,currentY + step)) );
        boxes[i] = smallBox;
        currentY = currentY + step  ;
    }
    return cores;
}

<|endoftext|>


<commit_before>// The MIT License (MIT)
//
// Copyright (c) 2016 Northeastern University
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

// This file tests the cpu_operations.cc DotProduct() function. First, it tests
// the functionality to ensure the dot product works properly by manually
// calculating the dot product and comparing it to the result of the function
// which calculated dot product with the Eigen built-in functionality. Then
// the two cases where incorrect function uses will result in fatal error are
// tested. This involves trying to calculate the dot product of two vectors of
// different size or trying to calculate the dot product of empty vectors.

#include <stdio.h>
#include <iostream>
#include "Eigen/Dense"
#include "gtest/gtest.h"
#include "include/cpu_operations.h"
#include "include/vector.h"

template<class T>
class DotProductTest : public ::testing::Test {
 public:
  Nice::Vector<T> vec1;
  Nice::Vector<T> vec2;
  T result;

  void DotProd() {
    result = Nice::CpuOperations<T>::DotProduct(this->vec1, this->vec2);
  }
};

typedef ::testing::Types<int, float, double> MyTypes;
TYPED_TEST_CASE(DotProductTest, MyTypes);

TYPED_TEST(DotProductTest, DotProductFunctionality) {
  int vec_size = 15;
  this->vec1.setRandom(vec_size);
  this->vec2.setRandom(vec_size);

  TypeParam correct = 0;
  for (int i = 0; i < vec_size; ++i)
    correct += (this->vec1[i]*this->vec2[i]);

  this->DotProd();

  EXPECT_EQ(this->result, correct);
}

TYPED_TEST(DotProductTest, DifferentSizeVectors) {
  this->vec1.setRandom(4);
  this->vec2.setRandom(2);
  ASSERT_DEATH(this->DotProd(), ".*");
}

TYPED_TEST(DotProductTest, EmptyVectors) {
  ASSERT_DEATH(this->DotProd(), ".*");
}
<commit_msg>delete this-> for class member method<commit_after>// The MIT License (MIT)
//
// Copyright (c) 2016 Northeastern University
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

// This file tests the cpu_operations.cc DotProduct() function. First, it tests
// the functionality to ensure the dot product works properly by manually
// calculating the dot product and comparing it to the result of the function
// which calculated dot product with the Eigen built-in functionality. Then
// the two cases where incorrect function uses will result in fatal error are
// tested. This involves trying to calculate the dot product of two vectors of
// different size or trying to calculate the dot product of empty vectors.

#include <stdio.h>
#include <iostream>
#include "Eigen/Dense"
#include "gtest/gtest.h"
#include "include/cpu_operations.h"
#include "include/vector.h"

template<class T>
class DotProductTest : public ::testing::Test {
 public:
  Nice::Vector<T> vec1;
  Nice::Vector<T> vec2;
  T result;

  void DotProd() {
    result = Nice::CpuOperations<T>::DotProduct(vec1, vec2);
  }
};

typedef ::testing::Types<int, float, double> MyTypes;
TYPED_TEST_CASE(DotProductTest, MyTypes);

TYPED_TEST(DotProductTest, DotProductFunctionality) {
  int vec_size = 15;
  this->vec1.setRandom(vec_size);
  this->vec2.setRandom(vec_size);

  TypeParam correct = 0;
  for (int i = 0; i < vec_size; ++i)
    correct += (this->vec1[i]*this->vec2[i]);

  this->DotProd();

  EXPECT_EQ(this->result, correct);
}

TYPED_TEST(DotProductTest, DifferentSizeVectors) {
  this->vec1.setRandom(4);
  this->vec2.setRandom(2);
  ASSERT_DEATH(this->DotProd(), ".*");
}

TYPED_TEST(DotProductTest, EmptyVectors) {
  ASSERT_DEATH(this->DotProd(), ".*");
}
<|endoftext|>


<commit_before>/// COMPONENT
#include <csapex/model/node.h>

/// COMPONENT
#include <csapex_vision/roi_message.h>
#include <csapex_vision/cv_mat_message.h>
#include <csapex_core_plugins/vector_message.h>

/// PROJECT
#include <utils_param/range_parameter.h>
#include <utils_param/parameter_factory.h>
#include <csapex/msg/io.h>
#include <csapex/model/node_modifier.h>
#include <csapex/utility/register_apex_plugin.h>

namespace csapex {

using namespace connection_types;

class GridArrangedRois : public csapex::Node
{
public:
    GridArrangedRois()
    {

    }

public:
    virtual void setup(csapex::NodeModifier& node_modifier) override
    {
        input_  = node_modifier.addInput<CvMatMessage>("Image");
        output_ = node_modifier.addOutput<VectorMessage, RoiMessage>("ROIs");
    }

    virtual void setupParameters(Parameterizable &parameters) override
    {
        parameters.addParameter(param::ParameterFactory::declareRange("dimension x", 1, 1000, 64, 1));
        parameters.addParameter(param::ParameterFactory::declareRange("dimension y", 1, 1000, 48, 1));
        parameters.addParameter(param::ParameterFactory::declareColorParameter("color", 255,0,0));
    }

    virtual void process() override
    {
        CvMatMessage::ConstPtr in = msg::getMessage<connection_types::CvMatMessage>(input_);
        VectorMessage::Ptr out(VectorMessage::make<RoiMessage>());

        int dim_x = readParameter<int>("dimension x");
        int dim_y = readParameter<int>("dimension y");
        int cell_height = in->value.rows / dim_y;
        int rest_height = in->value.rows % dim_y;
        int cell_width  = in->value.cols / dim_x;
        int rest_witdh  = in->value.cols % dim_x;

        const std::vector<int>& c = readParameter<std::vector<int> >("color");
        cv::Scalar color = cv::Scalar(c[2], c[1], c[0]);

        cv::Rect rect;
        for(int i = 0 ; i < dim_y ; ++i) {
            for(int j = 0 ; j < dim_x ; ++j) {
                RoiMessage::Ptr roi(new RoiMessage);
                rect.x = cell_width  * j;
                rect.y = cell_height * i;
                rect.width  = cell_width  + ((j == dim_x - 1) ? rest_witdh : 0);
                rect.height = cell_height + ((i == dim_y - 1) ? rest_height : 0);
                roi->value.setRect(rect);
                roi->value.setColor(color);
                out->value.push_back(roi);
            }
        }

        msg::publish(output_, out);
    }

private:
    Input*  input_;
    Output* output_;
};
}

CSAPEX_REGISTER_CLASS(csapex::GridArrangedRois, csapex::Node)
<commit_msg>grid arranged roi class<commit_after>/// COMPONENT
#include <csapex/model/node.h>

/// COMPONENT
#include <csapex_vision/roi_message.h>
#include <csapex_vision/cv_mat_message.h>
#include <csapex_core_plugins/vector_message.h>

/// PROJECT
#include <utils_param/range_parameter.h>
#include <utils_param/parameter_factory.h>
#include <csapex/msg/io.h>
#include <csapex/model/node_modifier.h>
#include <csapex/utility/register_apex_plugin.h>

namespace csapex {

using namespace connection_types;

class GridArrangedRois : public csapex::Node
{
public:
    GridArrangedRois()
    {

    }

public:
    virtual void setup(csapex::NodeModifier& node_modifier) override
    {
        input_  = node_modifier.addInput<CvMatMessage>("Image");
        output_ = node_modifier.addOutput<VectorMessage, RoiMessage>("ROIs");
    }

    virtual void setupParameters(Parameterizable &parameters) override
    {
        parameters.addParameter(param::ParameterFactory::declareRange("dimension x", 1, 1000, 64, 1));
        parameters.addParameter(param::ParameterFactory::declareRange("dimension y", 1, 1000, 48, 1));
        parameters.addParameter(param::ParameterFactory::declareRange("class id", -1, 255, -1, 1));
        parameters.addParameter(param::ParameterFactory::declareColorParameter("color", 255,0,0));
    }

    virtual void process() override
    {
        CvMatMessage::ConstPtr in = msg::getMessage<connection_types::CvMatMessage>(input_);
        VectorMessage::Ptr out(VectorMessage::make<RoiMessage>());

        int dim_x = readParameter<int>("dimension x");
        int dim_y = readParameter<int>("dimension y");
        int class_id = readParameter<int>("class id");
        const std::vector<int>& c = readParameter<std::vector<int> >("color");
        cv::Scalar color = cv::Scalar(c[2], c[1], c[0]);
        int cell_height = in->value.rows / dim_y;
        int rest_height = in->value.rows % dim_y;
        int cell_width  = in->value.cols / dim_x;
        int rest_witdh  = in->value.cols % dim_x;

        cv::Rect rect;
        for(int i = 0 ; i < dim_y ; ++i) {
            for(int j = 0 ; j < dim_x ; ++j) {
                RoiMessage::Ptr roi(new RoiMessage);
                rect.x = cell_width  * j;
                rect.y = cell_height * i;
                rect.width  = cell_width  + ((j == dim_x - 1) ? rest_witdh : 0);
                rect.height = cell_height + ((i == dim_y - 1) ? rest_height : 0);
                roi->value.setRect(rect);
                roi->value.setColor(color);
                roi->value.setClassification(class_id);
                out->value.push_back(roi);
            }
        }

        msg::publish(output_, out);
    }

private:
    Input*  input_;
    Output* output_;
};
}

CSAPEX_REGISTER_CLASS(csapex::GridArrangedRois, csapex::Node)
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// multibip32.cpp
//
// Copyright (c) 2014 Eric Lombrozo
//
// All Rights Reserved.
//

#include <CoinCore/hdkeys.h>
#include <CoinCore/Base58Check.h>
#include <CoinQ/CoinQ_script.h>
#include <stdutils/uchar_vector.h>

#include <iostream>
#include <sstream>
#include <stdexcept>

using namespace Coin;
using namespace CoinQ::Script;
using namespace std;

const unsigned char ADDRESS_VERSIONS[] = { 0x00, 0x05 };

int main(int argc, char* argv[])
{
    if (argc < 4 || argc % 2) // Parameter count must be even
    {
        cerr << "# Usage: " << argv[0] << " <minsigs> <master key 1> <path 1> ... [master key n] [path n]" << endl;
        return -1;
    }

    try
    {
        uint32_t minsigs = strtoul(argv[1], NULL, 10);
        vector<bytes_t> pubkeys;

        for (size_t i = 2; i < argc; i+=2)
        {
            bytes_t extkey;
            if (!fromBase58Check(string(argv[i]), extkey))
            {
                stringstream err;
                err << "Invalid master key base58: " << argv[i];
                throw runtime_error(err.str());
            }

            HDKeychain keychain(extkey);
            keychain = keychain.getChild(string(argv[i+1]));
            pubkeys.push_back(keychain.pubkey());
        }

        Script script(Script::PAY_TO_MULTISIG_SCRIPT_HASH, minsigs, pubkeys);
        uchar_vector txoutscript = script.txoutscript();
        cout << "TxOut script: " << txoutscript.getHex() << endl;
        cout << "Address:      " << getAddressForTxOutScript(txoutscript, ADDRESS_VERSIONS) << endl;
    }
    catch (const exception& e)
    {
        cerr << "Error: " << e.what() << endl;
        return -2;
    }

    return 0;
}
<commit_msg>Two usages for multibip32 tool - the first one just shows the address and pubkey for a single BIP32 master key child.<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// multibip32.cpp
//
// Copyright (c) 2014 Eric Lombrozo
//
// All Rights Reserved.
//

#include <CoinCore/hdkeys.h>
#include <CoinCore/Base58Check.h>
#include <CoinQ/CoinQ_script.h>
#include <stdutils/uchar_vector.h>

#include <iostream>
#include <sstream>
#include <stdexcept>

using namespace Coin;
using namespace CoinQ::Script;
using namespace std;

const unsigned char ADDRESS_VERSIONS[] = { 0x00, 0x05 };

void showUsage(char* argv[])
{
    cerr << "# Usage 1: " << argv[0] << " <master key> <path>" << endl;
    cerr << "# Usage 2: " << argv[0] << " <minsigs> <master key 1> <path 1> ... [master key n] [path n]" << endl;
}

int main(int argc, char* argv[])
{
    if (argc < 3)
    {
        showUsage(argv);
        return -1;
    }

    try
    {
        if (argc == 3)
        {
            bytes_t extkey;
            if (!fromBase58Check(string(argv[1]), extkey)) throw runtime_error("Invalid master key base58.");

            HDKeychain keychain(extkey);
            keychain = keychain.getChild(string(argv[2]));

            uchar_vector pubkey = keychain.pubkey();
            vector<bytes_t> pubkeys;
            pubkeys.push_back(pubkey);

            Script script(Script::PAY_TO_PUBKEY_HASH, 1, pubkeys);
            uchar_vector txoutscript = script.txoutscript();
            cout << "TxOut script: " << txoutscript.getHex() << endl;
            cout << "Address:      " << getAddressForTxOutScript(txoutscript, ADDRESS_VERSIONS) << endl;
            cout << "Public key:   " << pubkey.getHex() << endl;
            return 0;
        }

        if (argc % 2)
        {
            showUsage(argv);
            return -1;
        }

        uint32_t minsigs = strtoul(argv[1], NULL, 10);
        vector<bytes_t> pubkeys;

        for (size_t i = 2; i < argc; i+=2)
        {
            bytes_t extkey;
            if (!fromBase58Check(string(argv[i]), extkey))
            {
                stringstream err;
                err << "Invalid master key base58: " << argv[i];
                throw runtime_error(err.str());
            }

            HDKeychain keychain(extkey);
            keychain = keychain.getChild(string(argv[i+1]));
            pubkeys.push_back(keychain.pubkey());
        }

        //sort(pubkeys.begin(), pubkeys.end());

        Script script(Script::PAY_TO_MULTISIG_SCRIPT_HASH, minsigs, pubkeys);
        uchar_vector txoutscript = script.txoutscript();
        cout << "TxOut script: " << txoutscript.getHex() << endl;
        cout << "Address:      " << getAddressForTxOutScript(txoutscript, ADDRESS_VERSIONS) << endl;
    }
    catch (const exception& e)
    {
        cerr << "Error: " << e.what() << endl;
        return -2;
    }

    return 0;
}
<|endoftext|>


<commit_before>// This file is part of the dune-hdd project:
//   http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_DEFAULT_HH
#define DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_DEFAULT_HH

#ifndef DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BASE_DISABLE_CACHING
# define DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BASE_DISABLE_CACHING 0
#endif

#include <map>
#include <algorithm>

#include <dune/stuff/common/crtp.hh>
#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/la/solver.hh>
#include <dune/stuff/common/logging.hh>

#include <dune/pymor/operators/base.hh>
#include <dune/pymor/operators/affine.hh>
#include <dune/pymor/functionals/affine.hh>

#include <dune/gdt/discretefunction/default.hh>

#include "interfaces.hh"

namespace Dune {
namespace HDD {
namespace LinearElliptic {
namespace Discretizations {

// forward
template< class ImpTraits >
class ContainerBasedDefault;

namespace internal {

template< class MatrixImp, class VectorImp >
class ContainerBasedDefaultTraits
{
public:
  typedef MatrixImp MatrixType;
  typedef VectorImp VectorType;
  typedef Pymor::Operators::LinearAffinelyDecomposedContainerBased< MatrixType, VectorType > OperatorType;
  typedef OperatorType ProductType;
  typedef Pymor::Functionals::LinearAffinelyDecomposedVectorBased< VectorType > FunctionalType;
}; // class ContainerBasedDefaultTraits

} // namespace internal

template< class ImpTraits >
class CachedDefault
  : public DiscretizationInterface< ImpTraits >
{
  typedef DiscretizationInterface< ImpTraits >  BaseType;
  typedef CachedDefault< ImpTraits >            ThisType;
public:
  using typename BaseType::GridViewType;
  using typename BaseType::BoundaryInfoType;
  using typename BaseType::ProblemType;
  using typename BaseType::TestSpaceType;
  using typename BaseType::AnsatzSpaceType;
  using typename BaseType::VectorType;

private:
  typedef Stuff::Grid::BoundaryInfoProvider< typename GridViewType::Intersection > BoundaryInfoProvider;

public:
  static std::string static_id() { return "hdd.linearelliptic.discretizations.cached"; }

  CachedDefault(TestSpaceType test_spc,
                AnsatzSpaceType ansatz_spc,
                Stuff::Common::Configuration bnd_inf_cfg,
                const ProblemType& prb)
    : BaseType(prb)
    , test_space_(test_spc)
    , ansatz_space_(ansatz_spc)
    , boundary_info_cfg_(bnd_inf_cfg)
    , boundary_info_(BoundaryInfoProvider::create(boundary_info_cfg_.get< std::string >("type"), boundary_info_cfg_))
    , problem_(prb)
  {}

  CachedDefault(const ThisType& other) = default;

  ThisType& operator=(const ThisType& other) = delete;

  const TestSpaceType& test_space() const
  {
    return test_space_;
  }

  const AnsatzSpaceType& ansatz_space() const
  {
    return test_space_;
  }

  const GridViewType& grid_view() const
  {
    return test_space_.grid_view();
  }

  const Stuff::Common::Configuration& boundary_info_cfg() const
  {
    return boundary_info_cfg_;
  }

  const BoundaryInfoType& boundary_info() const
  {
    return *boundary_info_;
  }

  const ProblemType& problem() const
  {
    return problem_;
  }

  VectorType create_vector() const
  {
    return VectorType(ansatz_space_.mapper().size());
  }

  void visualize(const VectorType& vector,
                 const std::string filename,
                 const std::string name,
                 Pymor::Parameter mu = Pymor::Parameter()) const
  {
    VectorType tmp = vector.copy();
    const auto vectors = this->available_vectors();
    const auto result = std::find(vectors.begin(), vectors.end(), "dirichlet");
    if (result != vectors.end()) {
      const auto dirichlet_vector = this->get_vector("dirichlet");
      if (dirichlet_vector.parametric()) {
        const Pymor::Parameter mu_dirichlet = this->map_parameter(mu, "dirichlet");
        if (mu_dirichlet.type() != dirichlet_vector.parameter_type())
          DUNE_THROW(Pymor::Exceptions::wrong_parameter_type,
                     mu_dirichlet.type() << " vs. " << dirichlet_vector.parameter_type());
        tmp = dirichlet_vector.freeze_parameter(mu);
      } else
        tmp = *(dirichlet_vector.affine_part());
      tmp += vector;
    }
    const GDT::ConstDiscreteFunction< AnsatzSpaceType, VectorType >function(ansatz_space_, tmp, name);
    function.visualize(filename);
  } // ... visualize(...)

  using BaseType::solve;

  void solve(const DSC::Configuration options, VectorType& vector, const Pymor::Parameter mu = Pymor::Parameter()) const
  {
    auto logger = DSC::TimedLogger().get(static_id());
#if !DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BASE_DISABLE_CACHING
    const auto options_in_cache = cache_.find(options);
    bool exists = (options_in_cache != cache_.end());
    typename std::map< Pymor::Parameter, std::shared_ptr< VectorType > >::const_iterator options_and_mu_in_cache;
    if (exists) {
      options_and_mu_in_cache = options_in_cache->second.find(mu);
      exists = (options_and_mu_in_cache != options_in_cache->second.end());
    }
    if (!exists) {
#endif // !DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BASE_DISABLE_CACHING
      logger.info() << "solving";
      if (options.has_key("type"))
        logger.info() << " with '" << options.get< std::string >("type") << "'";
      if (!mu.empty())
        logger.info() << " for mu = " << mu;
      logger.info() << "... " << std::endl;
      uncached_solve(options, vector, mu);
#if !DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BASE_DISABLE_CACHING
      cache_[options][mu] = Stuff::Common::make_unique< VectorType >(vector.copy());
    } else {
      logger.info() << "retrieving solution ";
      if (!mu.empty())
        logger.info() << "for mu = " << mu << " ";
      logger.info() << "from cache... " << std::endl;
      const auto& result = *(options_and_mu_in_cache->second);
      vector = result;
    }
#endif // !DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BASE_DISABLE_CACHING
  } // ... solve(...)

  void uncached_solve(const DSC::Configuration options, VectorType& vector, const Pymor::Parameter mu) const
  {
    CHECK_AND_CALL_CRTP(this->as_imp().uncached_solve(options, vector, mu));
  }

protected:
  const TestSpaceType test_space_;
  const AnsatzSpaceType ansatz_space_;
  const Stuff::Common::Configuration boundary_info_cfg_;
  const std::shared_ptr< const BoundaryInfoType > boundary_info_;
  const ProblemType& problem_;

  mutable std::map< DSC::Configuration, std::map< Pymor::Parameter, std::shared_ptr< VectorType > > > cache_;
}; // class CachedDefault

template< class ImpTraits >
class ContainerBasedDefault
  : public CachedDefault< ImpTraits >
{
  typedef CachedDefault< ImpTraits >         BaseType;
  typedef ContainerBasedDefault< ImpTraits > ThisType;
public:
  typedef ImpTraits Traits;
  typedef typename Traits::MatrixType     MatrixType;
  typedef typename Traits::OperatorType   OperatorType;
  typedef typename Traits::ProductType    ProductType;
  typedef typename Traits::FunctionalType FunctionalType;

  using typename BaseType::GridViewType;
  using typename BaseType::BoundaryInfoType;
  using typename BaseType::ProblemType;
  using typename BaseType::TestSpaceType;
  using typename BaseType::AnsatzSpaceType;
  using typename BaseType::VectorType;
  typedef typename VectorType::ScalarType RangeFieldType;

protected:
  typedef Pymor::LA::AffinelyDecomposedContainer< MatrixType > AffinelyDecomposedMatrixType;
  typedef Pymor::LA::AffinelyDecomposedContainer< VectorType > AffinelyDecomposedVectorType;
  typedef Stuff::LA::Solver< MatrixType > SolverType;

public:
  static std::string static_id() { return "hdd.linearelliptic.discretizations.containerbased"; }

  ContainerBasedDefault(TestSpaceType test_spc,
                        AnsatzSpaceType ansatz_spc,
                        const Stuff::Common::Configuration& bnd_inf_cfg,
                        const ProblemType& prb)
    : BaseType(test_spc, ansatz_spc, bnd_inf_cfg, prb)
    , container_based_initialized_(false)
    , purely_neumann_(false)
    , matrix_(std::make_shared< AffinelyDecomposedMatrixType >())
    , rhs_(std::make_shared< AffinelyDecomposedVectorType >())
  {}

  ContainerBasedDefault(const ThisType& other) = default;

  ThisType& operator=(const ThisType& other) = delete;

  std::shared_ptr< AffinelyDecomposedMatrixType >& system_matrix()
  {
    return matrix_;
  }

  const std::shared_ptr< const AffinelyDecomposedMatrixType >& system_matrix() const
  {
    return matrix_;
  }

  std::shared_ptr< AffinelyDecomposedVectorType > rhs()
  {
    return rhs_;
  }

  const std::shared_ptr< const AffinelyDecomposedVectorType >& rhs() const
  {
    return rhs_;
  }

  OperatorType get_operator() const
  {
    assert_everything_is_ready();
    return OperatorType(*matrix_);
  }

  FunctionalType get_rhs() const
  {
    assert_everything_is_ready();
    return FunctionalType(*rhs_);
  }

  std::vector< std::string > available_products() const
  {
    if (products_.size() == 0)
      return std::vector< std::string >();
    std::vector< std::string > ret;
    for (const auto& pair : products_)
      ret.push_back(pair.first);
    return ret;
  } // ... available_products(...)

  ProductType get_product(const std::string id) const
  {
    if (products_.size() == 0)
      DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong,
                 "Do not call get_product() if available_products() is empty!");
    const auto result = products_.find(id);
    if (result == products_.end())
      DUNE_THROW(Stuff::Exceptions::wrong_input_given, id);
    return ProductType(*(result->second));
  } // ... get_product(...)

  std::vector< std::string > available_vectors() const
  {
    if (vectors_.size() == 0)
      return std::vector< std::string >();
    std::vector< std::string > ret;
    for (const auto& pair : vectors_)
      ret.push_back(pair.first);
    return ret;
  } // ... available_vectors(...)

  AffinelyDecomposedVectorType get_vector(const std::string id) const
  {
    if (vectors_.size() == 0)
      DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong,
                 "Do not call get_vector() if available_vectors() is empty!");
    const auto result = vectors_.find(id);
    if (result == vectors_.end())
      DUNE_THROW(Stuff::Exceptions::wrong_input_given, id);
    return *(result->second);
  } // ... get_vector(...)

  std::vector< std::string > solver_types() const
  {
    return SolverType::types();
  }

  DSC::Configuration solver_options(const std::string type = "") const
  {
    return SolverType::options(type);
  }

  /**
   * \brief solves for u_0
   */
  void uncached_solve(const DSC::Configuration options,
                      VectorType& vector,
                      const Pymor::Parameter mu = Pymor::Parameter()) const
  {
    auto logger = DSC::TimedLogger().get(static_id());
    assert_everything_is_ready();
    if (mu.type() != this->parameter_type())
      DUNE_THROW(Pymor::Exceptions::wrong_parameter_type, mu.type() << " vs. " << this->parameter_type());
    const auto& rhs = *(this->rhs_);
    const auto& matrix = *(this->matrix_);
    if (purely_neumann_) {
      VectorType tmp_rhs = rhs.parametric() ? rhs.freeze_parameter(this->map_parameter(mu, "rhs"))
                                            : *(rhs.affine_part());
      MatrixType tmp_system_matrix = matrix.parametric() ? matrix.freeze_parameter(this->map_parameter(mu, "lhs"))
                                                         : *(matrix.affine_part());
      tmp_system_matrix.unit_row(0);
      tmp_rhs.set_entry(0, 0.0);
      SolverType(tmp_system_matrix).apply(tmp_rhs, vector, options);
      vector -= vector.mean();
    } else {
      // compute right hand side vector
      logger.debug() << "computing right hand side..." << std::endl;
      std::shared_ptr< const VectorType > rhs_vector;
      if (!rhs.parametric())
        rhs_vector = rhs.affine_part();
      else {
        const Pymor::Parameter mu_rhs = this->map_parameter(mu, "rhs");
        rhs_vector = std::make_shared< const VectorType >(rhs.freeze_parameter(mu_rhs));
      }
      logger.debug() << "computing system matrix..." << std::endl;
      const OperatorType lhsOperator(matrix);
      if (lhsOperator.parametric()) {
        const Pymor::Parameter mu_lhs = this->map_parameter(mu, "lhs");
        const auto frozenOperator = lhsOperator.freeze_parameter(mu_lhs);
        frozenOperator.apply_inverse(*rhs_vector, vector, options);
      } else {
        const auto nonparametricOperator = lhsOperator.affine_part();
        nonparametricOperator.apply_inverse(*rhs_vector, vector, options);
      }
    }
  } // ... uncached_solve(...)

protected:
  void assert_everything_is_ready() const
  {
    if (!container_based_initialized_)
      DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong,
                 "The implemented discretization has to fill 'matrix_' and 'rhs_' during init() and set "
                 << "container_based_initialized_ to true!\n"
                 << "The user has to call init() before calling any other method!");
  } // ... assert_everything_is_ready()

  bool container_based_initialized_;
  bool purely_neumann_;
  std::shared_ptr< AffinelyDecomposedMatrixType > matrix_;
  std::shared_ptr< AffinelyDecomposedVectorType > rhs_;
  mutable std::map< std::string, std::shared_ptr< AffinelyDecomposedMatrixType > > products_;
  mutable std::map< std::string, std::shared_ptr< AffinelyDecomposedVectorType > > vectors_;
}; // class ContainerBasedDefault

} // namespace Discretizations
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune

#endif // DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_DEFAULT_HH
<commit_msg>[linearelliptic.discretizations] add finalize_init()<commit_after>// This file is part of the dune-hdd project:
//   http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_DEFAULT_HH
#define DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_DEFAULT_HH

#ifndef DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BASE_DISABLE_CACHING
# define DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BASE_DISABLE_CACHING 0
#endif

#include <map>
#include <algorithm>

#include <dune/stuff/common/crtp.hh>
#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/la/solver.hh>

#include <dune/pymor/operators/base.hh>
#include <dune/pymor/operators/affine.hh>
#include <dune/pymor/functionals/affine.hh>

#include <dune/gdt/discretefunction/default.hh>

#include "interfaces.hh"

namespace Dune {
namespace HDD {
namespace LinearElliptic {
namespace Discretizations {

// forward
template< class ImpTraits >
class ContainerBasedDefault;

namespace internal {

template< class MatrixImp, class VectorImp >
class ContainerBasedDefaultTraits
{
public:
  typedef MatrixImp MatrixType;
  typedef VectorImp VectorType;
  typedef Pymor::Operators::LinearAffinelyDecomposedContainerBased< MatrixType, VectorType > OperatorType;
  typedef OperatorType ProductType;
  typedef Pymor::Functionals::LinearAffinelyDecomposedVectorBased< VectorType > FunctionalType;
}; // class ContainerBasedDefaultTraits

} // namespace internal

template< class ImpTraits >
class CachedDefault
  : public DiscretizationInterface< ImpTraits >
{
  typedef DiscretizationInterface< ImpTraits >  BaseType;
  typedef CachedDefault< ImpTraits >            ThisType;
public:
  using typename BaseType::GridViewType;
  using typename BaseType::BoundaryInfoType;
  using typename BaseType::ProblemType;
  using typename BaseType::TestSpaceType;
  using typename BaseType::AnsatzSpaceType;
  using typename BaseType::VectorType;

private:
  typedef Stuff::Grid::BoundaryInfoProvider< typename GridViewType::Intersection > BoundaryInfoProvider;

public:
  static std::string static_id() { return "hdd.linearelliptic.discretizations.cached"; }

  CachedDefault(TestSpaceType test_spc,
                AnsatzSpaceType ansatz_spc,
                Stuff::Common::Configuration bnd_inf_cfg,
                const ProblemType& prb)
    : BaseType(prb)
    , test_space_(test_spc)
    , ansatz_space_(ansatz_spc)
    , boundary_info_cfg_(bnd_inf_cfg)
    , boundary_info_(BoundaryInfoProvider::create(boundary_info_cfg_.get< std::string >("type"), boundary_info_cfg_))
    , problem_(prb)
  {}

  CachedDefault(const ThisType& other) = default;

  ThisType& operator=(const ThisType& other) = delete;

  const TestSpaceType& test_space() const
  {
    return test_space_;
  }

  const AnsatzSpaceType& ansatz_space() const
  {
    return test_space_;
  }

  const GridViewType& grid_view() const
  {
    return test_space_.grid_view();
  }

  const Stuff::Common::Configuration& boundary_info_cfg() const
  {
    return boundary_info_cfg_;
  }

  const BoundaryInfoType& boundary_info() const
  {
    return *boundary_info_;
  }

  const ProblemType& problem() const
  {
    return problem_;
  }

  VectorType create_vector() const
  {
    return VectorType(ansatz_space_.mapper().size());
  }

  void visualize(const VectorType& vector,
                 const std::string filename,
                 const std::string name,
                 Pymor::Parameter mu = Pymor::Parameter()) const
  {
    VectorType tmp = vector.copy();
    const auto vectors = this->available_vectors();
    const auto result = std::find(vectors.begin(), vectors.end(), "dirichlet");
    if (result != vectors.end()) {
      const auto dirichlet_vector = this->get_vector("dirichlet");
      if (dirichlet_vector.parametric()) {
        const Pymor::Parameter mu_dirichlet = this->map_parameter(mu, "dirichlet");
        if (mu_dirichlet.type() != dirichlet_vector.parameter_type())
          DUNE_THROW(Pymor::Exceptions::wrong_parameter_type,
                     mu_dirichlet.type() << " vs. " << dirichlet_vector.parameter_type());
        tmp = dirichlet_vector.freeze_parameter(mu);
      } else
        tmp = *(dirichlet_vector.affine_part());
      tmp += vector;
    }
    const GDT::ConstDiscreteFunction< AnsatzSpaceType, VectorType >function(ansatz_space_, tmp, name);
    function.visualize(filename);
  } // ... visualize(...)

  using BaseType::solve;

  void solve(const DSC::Configuration options, VectorType& vector, const Pymor::Parameter mu = Pymor::Parameter()) const
  {
    auto logger = DSC::TimedLogger().get(static_id());
#if !DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BASE_DISABLE_CACHING
    const auto options_in_cache = cache_.find(options);
    bool exists = (options_in_cache != cache_.end());
    typename std::map< Pymor::Parameter, std::shared_ptr< VectorType > >::const_iterator options_and_mu_in_cache;
    if (exists) {
      options_and_mu_in_cache = options_in_cache->second.find(mu);
      exists = (options_and_mu_in_cache != options_in_cache->second.end());
    }
    if (!exists) {
#endif // !DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BASE_DISABLE_CACHING
      logger.info() << "solving";
      if (options.has_key("type"))
        logger.info() << " with '" << options.get< std::string >("type") << "'";
      if (!mu.empty())
        logger.info() << " for mu = " << mu;
      logger.info() << "... " << std::endl;
      uncached_solve(options, vector, mu);
#if !DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BASE_DISABLE_CACHING
      cache_[options][mu] = Stuff::Common::make_unique< VectorType >(vector.copy());
    } else {
      logger.info() << "retrieving solution ";
      if (!mu.empty())
        logger.info() << "for mu = " << mu << " ";
      logger.info() << "from cache... " << std::endl;
      const auto& result = *(options_and_mu_in_cache->second);
      vector = result;
    }
#endif // !DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BASE_DISABLE_CACHING
  } // ... solve(...)

  void uncached_solve(const DSC::Configuration options, VectorType& vector, const Pymor::Parameter mu) const
  {
    CHECK_AND_CALL_CRTP(this->as_imp().uncached_solve(options, vector, mu));
  }

protected:
  const TestSpaceType test_space_;
  const AnsatzSpaceType ansatz_space_;
  const Stuff::Common::Configuration boundary_info_cfg_;
  const std::shared_ptr< const BoundaryInfoType > boundary_info_;
  const ProblemType& problem_;

  mutable std::map< DSC::Configuration, std::map< Pymor::Parameter, std::shared_ptr< VectorType > > > cache_;
}; // class CachedDefault

template< class ImpTraits >
class ContainerBasedDefault
  : public CachedDefault< ImpTraits >
{
  typedef CachedDefault< ImpTraits >         BaseType;
  typedef ContainerBasedDefault< ImpTraits > ThisType;
public:
  typedef ImpTraits Traits;
  typedef typename Traits::MatrixType     MatrixType;
  typedef typename Traits::OperatorType   OperatorType;
  typedef typename Traits::ProductType    ProductType;
  typedef typename Traits::FunctionalType FunctionalType;

  using typename BaseType::GridViewType;
  using typename BaseType::BoundaryInfoType;
  using typename BaseType::ProblemType;
  using typename BaseType::TestSpaceType;
  using typename BaseType::AnsatzSpaceType;
  using typename BaseType::VectorType;
  typedef typename VectorType::ScalarType RangeFieldType;

protected:
  typedef Pymor::LA::AffinelyDecomposedContainer< MatrixType > AffinelyDecomposedMatrixType;
  typedef Pymor::LA::AffinelyDecomposedContainer< VectorType > AffinelyDecomposedVectorType;
  typedef Stuff::LA::Solver< MatrixType > SolverType;

public:
  static std::string static_id() { return "hdd.linearelliptic.discretizations.containerbased"; }

  ContainerBasedDefault(TestSpaceType test_spc,
                        AnsatzSpaceType ansatz_spc,
                        const Stuff::Common::Configuration& bnd_inf_cfg,
                        const ProblemType& prb)
    : BaseType(test_spc, ansatz_spc, bnd_inf_cfg, prb)
    , container_based_initialized_(false)
    , purely_neumann_(false)
    , matrix_(std::make_shared< AffinelyDecomposedMatrixType >())
    , rhs_(std::make_shared< AffinelyDecomposedVectorType >())
  {}

  ContainerBasedDefault(const ThisType& other) = default;

  ThisType& operator=(const ThisType& other) = delete;

  std::shared_ptr< AffinelyDecomposedMatrixType >& system_matrix()
  {
    return matrix_;
  }

  const std::shared_ptr< const AffinelyDecomposedMatrixType >& system_matrix() const
  {
    return matrix_;
  }

  std::shared_ptr< AffinelyDecomposedVectorType > rhs()
  {
    return rhs_;
  }

  const std::shared_ptr< const AffinelyDecomposedVectorType >& rhs() const
  {
    return rhs_;
  }

  OperatorType get_operator() const
  {
    assert_everything_is_ready();
    return OperatorType(*matrix_);
  }

  FunctionalType get_rhs() const
  {
    assert_everything_is_ready();
    return FunctionalType(*rhs_);
  }

  std::vector< std::string > available_products() const
  {
    if (products_.size() == 0)
      return std::vector< std::string >();
    std::vector< std::string > ret;
    for (const auto& pair : products_)
      ret.push_back(pair.first);
    return ret;
  } // ... available_products(...)

  ProductType get_product(const std::string id) const
  {
    if (products_.size() == 0)
      DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong,
                 "Do not call get_product() if available_products() is empty!");
    const auto result = products_.find(id);
    if (result == products_.end())
      DUNE_THROW(Stuff::Exceptions::wrong_input_given, id);
    return ProductType(*(result->second));
  } // ... get_product(...)

  std::vector< std::string > available_vectors() const
  {
    if (vectors_.size() == 0)
      return std::vector< std::string >();
    std::vector< std::string > ret;
    for (const auto& pair : vectors_)
      ret.push_back(pair.first);
    return ret;
  } // ... available_vectors(...)

  AffinelyDecomposedVectorType get_vector(const std::string id) const
  {
    if (vectors_.size() == 0)
      DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong,
                 "Do not call get_vector() if available_vectors() is empty!");
    const auto result = vectors_.find(id);
    if (result == vectors_.end())
      DUNE_THROW(Stuff::Exceptions::wrong_input_given, id);
    return *(result->second);
  } // ... get_vector(...)

  std::vector< std::string > solver_types() const
  {
    return SolverType::types();
  }

  DSC::Configuration solver_options(const std::string type = "") const
  {
    return SolverType::options(type);
  }

  /**
   * \brief solves for u_0
   */
  void uncached_solve(const DSC::Configuration options,
                      VectorType& vector,
                      const Pymor::Parameter mu = Pymor::Parameter()) const
  {
    auto logger = DSC::TimedLogger().get(static_id());
    assert_everything_is_ready();
    if (mu.type() != this->parameter_type())
      DUNE_THROW(Pymor::Exceptions::wrong_parameter_type, mu.type() << " vs. " << this->parameter_type());
    const auto& rhs = *(this->rhs_);
    const auto& matrix = *(this->matrix_);
    if (purely_neumann_) {
      VectorType tmp_rhs = rhs.parametric() ? rhs.freeze_parameter(this->map_parameter(mu, "rhs"))
                                            : *(rhs.affine_part());
      MatrixType tmp_system_matrix = matrix.parametric() ? matrix.freeze_parameter(this->map_parameter(mu, "lhs"))
                                                         : *(matrix.affine_part());
      tmp_system_matrix.unit_row(0);
      tmp_rhs.set_entry(0, 0.0);
      SolverType(tmp_system_matrix).apply(tmp_rhs, vector, options);
      vector -= vector.mean();
    } else {
      // compute right hand side vector
      logger.debug() << "computing right hand side..." << std::endl;
      std::shared_ptr< const VectorType > rhs_vector;
      if (!rhs.parametric())
        rhs_vector = rhs.affine_part();
      else {
        const Pymor::Parameter mu_rhs = this->map_parameter(mu, "rhs");
        rhs_vector = std::make_shared< const VectorType >(rhs.freeze_parameter(mu_rhs));
      }
      logger.debug() << "computing system matrix..." << std::endl;
      const OperatorType lhsOperator(matrix);
      if (lhsOperator.parametric()) {
        const Pymor::Parameter mu_lhs = this->map_parameter(mu, "lhs");
        const auto frozenOperator = lhsOperator.freeze_parameter(mu_lhs);
        frozenOperator.apply_inverse(*rhs_vector, vector, options);
      } else {
        const auto nonparametricOperator = lhsOperator.affine_part();
        nonparametricOperator.apply_inverse(*rhs_vector, vector, options);
      }
    }
  } // ... uncached_solve(...)

protected:
  void finalize_init()
  {
    if (!container_based_initialized_) {
      if (!matrix_->parametric())
        matrix_ = std::make_shared< AffinelyDecomposedMatrixType >(new MatrixType(matrix_->affine_part()->pruned()));
      for (auto& element : products_)
        if (!element.second->parametric())
          element.second = std::make_shared< AffinelyDecomposedMatrixType >(new MatrixType(element.second->affine_part()->pruned()));
      container_based_initialized_ = true;
    }
  } // ... finalize_init(...)

  void assert_everything_is_ready() const
  {
    if (!container_based_initialized_)
      DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong,
                 "The implemented discretization has to fill 'matrix_' and 'rhs_' during init() and set "
                 << "container_based_initialized_ to true!\n"
                 << "The user has to call init() before calling any other method!");
  } // ... assert_everything_is_ready()

  bool container_based_initialized_;
  bool purely_neumann_;
  std::shared_ptr< AffinelyDecomposedMatrixType > matrix_;
  std::shared_ptr< AffinelyDecomposedVectorType > rhs_;
  mutable std::map< std::string, std::shared_ptr< AffinelyDecomposedMatrixType > > products_;
  mutable std::map< std::string, std::shared_ptr< AffinelyDecomposedVectorType > > vectors_;
}; // class ContainerBasedDefault

} // namespace Discretizations
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune

#endif // DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_DEFAULT_HH
<|endoftext|>


<commit_before>#include "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkGradientShader.h"
#include "SkGraphics.h"
#include "SkImageDecoder.h"
#include "SkPath.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "SkXfermode.h"
#include "SkColorPriv.h"
#include "SkColorFilter.h"
#include "SkTime.h"
#include "SkRandom.h"

#include "SkLineClipper.h"
#include "SkEdgeClipper.h"

#define AUTO_ANIMATE    true

static int test0(SkPoint pts[], SkRect* clip) {
    pts[0].set(200000, 140);
    pts[1].set(-740000, 483);
    pts[2].set(1.00000102e-06f, 9.10000017e-05f);
    clip->set(0, 0, 640, 480);
    return 2;
}

///////////////////////////////////////////////////////////////////////////////

static void drawQuad(SkCanvas* canvas, const SkPoint pts[3], const SkPaint& p) {
    SkPath path;
    path.moveTo(pts[0]);
    path.quadTo(pts[1], pts[2]);
    canvas->drawPath(path, p);
}

static void drawCubic(SkCanvas* canvas, const SkPoint pts[4], const SkPaint& p) {
    SkPath path;
    path.moveTo(pts[0]);
    path.cubicTo(pts[1], pts[2], pts[3]);
    canvas->drawPath(path, p);
}

typedef void (*clipper_proc)(const SkPoint src[], const SkRect& clip,
                            SkCanvas*, const SkPaint&, const SkPaint&);

static void check_clipper(int count, const SkPoint pts[], const SkRect& clip) {
    for (int i = 0; i < count; i++) {
        SkASSERT(pts[i].fX >= clip.fLeft);
        SkASSERT(pts[i].fX <= clip.fRight);
        SkASSERT(pts[i].fY >= clip.fTop);
        SkASSERT(pts[i].fY <= clip.fBottom);
    }

    if (count > 1) {
        sk_assert_monotonic_y(pts, count);
    }
}

static void line_intersector(const SkPoint src[], const SkRect& clip,
                         SkCanvas* canvas, const SkPaint& p0, const SkPaint& p1) {
    canvas->drawPoints(SkCanvas::kLines_PointMode, 2, src, p1);

    SkPoint dst[2];
    if (SkLineClipper::IntersectLine(src, clip, dst)) {
        check_clipper(2, dst, clip);
        canvas->drawPoints(SkCanvas::kLines_PointMode, 2, dst, p0);
    }
}

static void line_clipper(const SkPoint src[], const SkRect& clip,
                         SkCanvas* canvas, const SkPaint& p0, const SkPaint& p1) {
    canvas->drawPoints(SkCanvas::kLines_PointMode, 2, src, p1);

    SkPoint dst[SkLineClipper::kMaxPoints];
    int count = SkLineClipper::ClipLine(src, clip, dst);
    for (int i = 0; i < count; i++) {
        check_clipper(2, &dst[i], clip);
        canvas->drawPoints(SkCanvas::kLines_PointMode, 2, &dst[i], p0);
    }
}

static void quad_clipper(const SkPoint src[], const SkRect& clip,
                         SkCanvas* canvas, const SkPaint& p0, const SkPaint& p1) {
    drawQuad(canvas, src, p1);

    SkEdgeClipper clipper;
    if (clipper.clipQuad(src, clip)) {
        SkPoint pts[4];
        SkPath::Verb verb;
        while ((verb = clipper.next(pts)) != SkPath::kDone_Verb) {
            switch (verb) {
                case SkPath::kLine_Verb:
                    check_clipper(2, pts, clip);
                    canvas->drawPoints(SkCanvas::kLines_PointMode, 2, pts, p0);
                    break;
                case SkPath::kQuad_Verb:
                    check_clipper(3, pts, clip);
                    drawQuad(canvas, pts, p0);
                    break;
                default:
                    SkASSERT(!"unexpected verb");
            }
        }
    }
}

static void cubic_clipper(const SkPoint src[], const SkRect& clip,
                       SkCanvas* canvas, const SkPaint& p0, const SkPaint& p1) {
    drawCubic(canvas, src, p1);

    SkEdgeClipper clipper;
    if (clipper.clipCubic(src, clip)) {
        SkPoint pts[4];
        SkPath::Verb verb;
        while ((verb = clipper.next(pts)) != SkPath::kDone_Verb) {
            switch (verb) {
                case SkPath::kLine_Verb:
                    check_clipper(2, pts, clip);
                    canvas->drawPoints(SkCanvas::kLines_PointMode, 2, pts, p0);
                    break;
                case SkPath::kCubic_Verb:
                 //   check_clipper(4, pts, clip);
                    drawCubic(canvas, pts, p0);
                    break;
                default:
                    SkASSERT(!"unexpected verb");
            }
        }
    }
}

static const clipper_proc gProcs[] = {
    line_intersector,
    line_clipper,
    quad_clipper,
    cubic_clipper
};

///////////////////////////////////////////////////////////////////////////////

enum {
    W = 640/3,
    H = 480/3
};

class LineClipperView : public SkView {
    SkMSec      fNow;
    int         fCounter;
    int         fProcIndex;
    SkRect      fClip;
    SkRandom    fRand;
    SkPoint     fPts[4];

    void randPts() {
        for (size_t i = 0; i < SK_ARRAY_COUNT(fPts); i++) {
            fPts[i].set(fRand.nextUScalar1() * 640,
                        fRand.nextUScalar1() * 480);
        }
        fCounter += 1;
    }

public:
	LineClipperView() {
        fProcIndex = 0;
        fCounter = 0;
        fNow = 0;

        int x = (640 - W)/2;
        int y = (480 - H)/2;
        fClip.set(SkIntToScalar(x), SkIntToScalar(y),
                  SkIntToScalar(x + W), SkIntToScalar(y + H));
        this->randPts();
    }

protected:
    // overrides from SkEventSink
    virtual bool onQuery(SkEvent* evt) {
        if (SampleCode::TitleQ(*evt)) {
            SampleCode::TitleR(evt, "LineClipper");
            return true;
        }
        return this->INHERITED::onQuery(evt);
    }

    void drawBG(SkCanvas* canvas) {
        canvas->drawColor(SK_ColorWHITE);
    }

    static void drawVLine(SkCanvas* canvas, SkScalar x, const SkPaint& paint) {
        canvas->drawLine(x, -999, x, 999, paint);
    }

    static void drawHLine(SkCanvas* canvas, SkScalar y, const SkPaint& paint) {
        canvas->drawLine(-999, y, 999, y, paint);
    }

    virtual void onDraw(SkCanvas* canvas) {
        this->drawBG(canvas);

        SkMSec now = SampleCode::GetAnimTime();
        if (fNow != now) {
            fNow = now;
            this->randPts();
            this->inval(NULL);
        }

     //   fProcIndex = test0(fPts, &fClip);

        SkPaint paint, paint1;

        drawVLine(canvas, fClip.fLeft + SK_ScalarHalf, paint);
        drawVLine(canvas, fClip.fRight - SK_ScalarHalf, paint);
        drawHLine(canvas, fClip.fTop + SK_ScalarHalf, paint);
        drawHLine(canvas, fClip.fBottom - SK_ScalarHalf, paint);

        paint.setColor(SK_ColorLTGRAY);
        canvas->drawRect(fClip, paint);

        paint.setAntiAlias(true);
        paint.setColor(SK_ColorBLUE);
        paint.setStyle(SkPaint::kStroke_Style);
      //  paint.setStrokeWidth(SkIntToScalar(3));
        paint.setStrokeCap(SkPaint::kRound_Cap);

        paint1.setAntiAlias(true);
        paint1.setColor(SK_ColorRED);
        paint1.setStyle(SkPaint::kStroke_Style);
        gProcs[fProcIndex](fPts, fClip, canvas, paint, paint1);
    }

    virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y) {
     //   fProcIndex = (fProcIndex + 1) % SK_ARRAY_COUNT(gProcs);
        if (x < 50 && y < 50) {
            this->randPts();
        }
        this->inval(NULL);
        return NULL;
    }

    virtual bool onClick(Click* click) {
        return false;
    }

private:
    typedef SkView INHERITED;
};

//////////////////////////////////////////////////////////////////////////////

static SkView* MyFactory() { return new LineClipperView; }
static SkViewRegister reg(MyFactory);

<commit_msg>inherit from SampleView<commit_after>#include "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkGradientShader.h"
#include "SkGraphics.h"
#include "SkImageDecoder.h"
#include "SkPath.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "SkXfermode.h"
#include "SkColorPriv.h"
#include "SkColorFilter.h"
#include "SkTime.h"
#include "SkRandom.h"

#include "SkLineClipper.h"
#include "SkEdgeClipper.h"

#define AUTO_ANIMATE    true

static int test0(SkPoint pts[], SkRect* clip) {
    pts[0].set(200000, 140);
    pts[1].set(-740000, 483);
    pts[2].set(1.00000102e-06f, 9.10000017e-05f);
    clip->set(0, 0, 640, 480);
    return 2;
}

///////////////////////////////////////////////////////////////////////////////

static void drawQuad(SkCanvas* canvas, const SkPoint pts[3], const SkPaint& p) {
    SkPath path;
    path.moveTo(pts[0]);
    path.quadTo(pts[1], pts[2]);
    canvas->drawPath(path, p);
}

static void drawCubic(SkCanvas* canvas, const SkPoint pts[4], const SkPaint& p) {
    SkPath path;
    path.moveTo(pts[0]);
    path.cubicTo(pts[1], pts[2], pts[3]);
    canvas->drawPath(path, p);
}

typedef void (*clipper_proc)(const SkPoint src[], const SkRect& clip,
                            SkCanvas*, const SkPaint&, const SkPaint&);

static void check_clipper(int count, const SkPoint pts[], const SkRect& clip) {
    for (int i = 0; i < count; i++) {
        SkASSERT(pts[i].fX >= clip.fLeft);
        SkASSERT(pts[i].fX <= clip.fRight);
        SkASSERT(pts[i].fY >= clip.fTop);
        SkASSERT(pts[i].fY <= clip.fBottom);
    }

    if (count > 1) {
        sk_assert_monotonic_y(pts, count);
    }
}

static void line_intersector(const SkPoint src[], const SkRect& clip,
                         SkCanvas* canvas, const SkPaint& p0, const SkPaint& p1) {
    canvas->drawPoints(SkCanvas::kLines_PointMode, 2, src, p1);

    SkPoint dst[2];
    if (SkLineClipper::IntersectLine(src, clip, dst)) {
        check_clipper(2, dst, clip);
        canvas->drawPoints(SkCanvas::kLines_PointMode, 2, dst, p0);
    }
}

static void line_clipper(const SkPoint src[], const SkRect& clip,
                         SkCanvas* canvas, const SkPaint& p0, const SkPaint& p1) {
    canvas->drawPoints(SkCanvas::kLines_PointMode, 2, src, p1);

    SkPoint dst[SkLineClipper::kMaxPoints];
    int count = SkLineClipper::ClipLine(src, clip, dst);
    for (int i = 0; i < count; i++) {
        check_clipper(2, &dst[i], clip);
        canvas->drawPoints(SkCanvas::kLines_PointMode, 2, &dst[i], p0);
    }
}

static void quad_clipper(const SkPoint src[], const SkRect& clip,
                         SkCanvas* canvas, const SkPaint& p0, const SkPaint& p1) {
    drawQuad(canvas, src, p1);

    SkEdgeClipper clipper;
    if (clipper.clipQuad(src, clip)) {
        SkPoint pts[4];
        SkPath::Verb verb;
        while ((verb = clipper.next(pts)) != SkPath::kDone_Verb) {
            switch (verb) {
                case SkPath::kLine_Verb:
                    check_clipper(2, pts, clip);
                    canvas->drawPoints(SkCanvas::kLines_PointMode, 2, pts, p0);
                    break;
                case SkPath::kQuad_Verb:
                    check_clipper(3, pts, clip);
                    drawQuad(canvas, pts, p0);
                    break;
                default:
                    SkASSERT(!"unexpected verb");
            }
        }
    }
}

static void cubic_clipper(const SkPoint src[], const SkRect& clip,
                       SkCanvas* canvas, const SkPaint& p0, const SkPaint& p1) {
    drawCubic(canvas, src, p1);

    SkEdgeClipper clipper;
    if (clipper.clipCubic(src, clip)) {
        SkPoint pts[4];
        SkPath::Verb verb;
        while ((verb = clipper.next(pts)) != SkPath::kDone_Verb) {
            switch (verb) {
                case SkPath::kLine_Verb:
                    check_clipper(2, pts, clip);
                    canvas->drawPoints(SkCanvas::kLines_PointMode, 2, pts, p0);
                    break;
                case SkPath::kCubic_Verb:
                 //   check_clipper(4, pts, clip);
                    drawCubic(canvas, pts, p0);
                    break;
                default:
                    SkASSERT(!"unexpected verb");
            }
        }
    }
}

static const clipper_proc gProcs[] = {
    line_intersector,
    line_clipper,
    quad_clipper,
    cubic_clipper
};

///////////////////////////////////////////////////////////////////////////////

enum {
    W = 640/3,
    H = 480/3
};

class LineClipperView : public SampleView {
    SkMSec      fNow;
    int         fCounter;
    int         fProcIndex;
    SkRect      fClip;
    SkRandom    fRand;
    SkPoint     fPts[4];

    void randPts() {
        for (size_t i = 0; i < SK_ARRAY_COUNT(fPts); i++) {
            fPts[i].set(fRand.nextUScalar1() * 640,
                        fRand.nextUScalar1() * 480);
        }
        fCounter += 1;
    }

public:
	LineClipperView() {
        fProcIndex = 0;
        fCounter = 0;
        fNow = 0;

        int x = (640 - W)/2;
        int y = (480 - H)/2;
        fClip.set(SkIntToScalar(x), SkIntToScalar(y),
                  SkIntToScalar(x + W), SkIntToScalar(y + H));
        this->randPts();
    }

protected:
    // overrides from SkEventSink
    virtual bool onQuery(SkEvent* evt) {
        if (SampleCode::TitleQ(*evt)) {
            SampleCode::TitleR(evt, "LineClipper");
            return true;
        }
        return this->INHERITED::onQuery(evt);
    }

    static void drawVLine(SkCanvas* canvas, SkScalar x, const SkPaint& paint) {
        canvas->drawLine(x, -999, x, 999, paint);
    }

    static void drawHLine(SkCanvas* canvas, SkScalar y, const SkPaint& paint) {
        canvas->drawLine(-999, y, 999, y, paint);
    }

    virtual void onDrawContent(SkCanvas* canvas) {
        SkMSec now = SampleCode::GetAnimTime();
        if (fNow != now) {
            fNow = now;
            this->randPts();
            this->inval(NULL);
        }

     //   fProcIndex = test0(fPts, &fClip);

        SkPaint paint, paint1;

        drawVLine(canvas, fClip.fLeft + SK_ScalarHalf, paint);
        drawVLine(canvas, fClip.fRight - SK_ScalarHalf, paint);
        drawHLine(canvas, fClip.fTop + SK_ScalarHalf, paint);
        drawHLine(canvas, fClip.fBottom - SK_ScalarHalf, paint);

        paint.setColor(SK_ColorLTGRAY);
        canvas->drawRect(fClip, paint);

        paint.setAntiAlias(true);
        paint.setColor(SK_ColorBLUE);
        paint.setStyle(SkPaint::kStroke_Style);
      //  paint.setStrokeWidth(SkIntToScalar(3));
        paint.setStrokeCap(SkPaint::kRound_Cap);

        paint1.setAntiAlias(true);
        paint1.setColor(SK_ColorRED);
        paint1.setStyle(SkPaint::kStroke_Style);
        gProcs[fProcIndex](fPts, fClip, canvas, paint, paint1);
        this->inval(NULL);
    }

    virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y) {
     //   fProcIndex = (fProcIndex + 1) % SK_ARRAY_COUNT(gProcs);
        if (x < 50 && y < 50) {
            this->randPts();
        }
        this->inval(NULL);
        return NULL;
    }

    virtual bool onClick(Click* click) {
        return false;
    }

private:
    typedef SampleView INHERITED;
};

//////////////////////////////////////////////////////////////////////////////

static SkView* MyFactory() { return new LineClipperView; }
static SkViewRegister reg(MyFactory);

<|endoftext|>


<commit_before>/* +---------------------------------------------------------------------------+
   |                 The Mobile Robot Programming Toolkit (MRPT)               |
   |                                                                           |
   |                          http://www.mrpt.org/                             |
   |                                                                           |
   | Copyright (c) 2005-2013, Individual contributors, see AUTHORS file        |
   | Copyright (c) 2005-2013, MAPIR group, University of Malaga                |
   | Copyright (c) 2012-2013, University of Almeria                            |
   | 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 the copyright holders 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 HOLDERS BE LIABLE |
   | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL|
   | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR|
   |  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)       |
   | HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,       |
   | STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN  |
   | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE           |
   | POSSIBILITY OF SUCH DAMAGE.                                               |
   +---------------------------------------------------------------------------+ */

#include <mrpt/hwdrivers/CInterfaceNI845x.h>
#include <mrpt/system.h>

using namespace std;
using namespace mrpt;
using namespace mrpt::hwdrivers;

// ------------------------------------------------------
//				TestNI_USB_845x
// ------------------------------------------------------
void TestNI_USB_845x()
{
	CInterfaceNI845x  ni_usb;

	// Open first connected device:
	cout << "Openning device...\n";
	ni_usb.open();
	cout << "Done! Connected to: " << ni_usb.getDeviceDescriptor() << endl;

	ni_usb.setIOVoltageLevel( 12 ); // 1.2 volts

#if 0
	ni_usb.setIOPortDirection(0, 0xFF);
	while (!mrpt::system::os::kbhit())
	{
		ni_usb.writeIOPort(0, 0xFF);
		mrpt::system::sleep(500);
		ni_usb.writeIOPort(0, 0x00);
		mrpt::system::sleep(500);
	}
#endif

#if 1
	ni_usb.create_SPI_configurations(1);
	ni_usb.set_SPI_configuration(0 /*idx*/, 0 /* CS */, 48 /* Khz */, true /* clock_polarity_idle_low */, false /* clock_phase_first_edge */ );

	while (!mrpt::system::os::kbhit())
	{
		const uint8_t write[4] = { 0x11, 0x22, 0x33, 0x44 };
		uint8_t read[4];
		size_t nRead;
		ni_usb.read_write_SPI(0, 4, write, nRead, read );
	}

#endif

	mrpt::system::pause();
}

// ------------------------------------------------------
//						MAIN
// ------------------------------------------------------
int main()
{
	try
	{
		TestNI_USB_845x();
		return 0;
	} catch (std::exception &e)
	{
		std::cout << "MRPT exception caught: " << e.what() << std::endl;
		return -1;
	}
}

<commit_msg>update of ni sample<commit_after>/* +---------------------------------------------------------------------------+
   |                 The Mobile Robot Programming Toolkit (MRPT)               |
   |                                                                           |
   |                          http://www.mrpt.org/                             |
   |                                                                           |
   | Copyright (c) 2005-2013, Individual contributors, see AUTHORS file        |
   | Copyright (c) 2005-2013, MAPIR group, University of Malaga                |
   | Copyright (c) 2012-2013, University of Almeria                            |
   | 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 the copyright holders 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 HOLDERS BE LIABLE |
   | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL|
   | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR|
   |  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)       |
   | HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,       |
   | STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN  |
   | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE           |
   | POSSIBILITY OF SUCH DAMAGE.                                               |
   +---------------------------------------------------------------------------+ */

#include <mrpt/hwdrivers/CInterfaceNI845x.h>
#include <mrpt/system.h>
#include <mrpt/gui.h>

using namespace std;
using namespace mrpt;
using namespace mrpt::gui;
using namespace mrpt::hwdrivers;

// ------------------------------------------------------
//				TestNI_USB_845x
// ------------------------------------------------------
void TestNI_USB_845x()
{
	CInterfaceNI845x  ni_usb;

	// Open first connected device:
	cout << "Openning device...\n";
	ni_usb.open();
	cout << "Done! Connected to: " << ni_usb.getDeviceDescriptor() << endl;

	ni_usb.setIOVoltageLevel( 25 ); // 2.5 volts

#if 0
	ni_usb.setIOPortDirection(0, 0xFF);
	while (!mrpt::system::os::kbhit())
	{
		ni_usb.writeIOPort(0, 0xFF);
		mrpt::system::sleep(500);
		ni_usb.writeIOPort(0, 0x00);
		mrpt::system::sleep(500);
	}
#endif

#if 0
	const size_t N=1000;
	std::vector<double> d0(N),d1(N),d2(N);

	ni_usb.setIOPortDirection(0, 0x00);
	for (size_t i=0;i<N;i++)
	{
		uint8_t d = ni_usb.readIOPort(0);
		mrpt::system::sleep(1);
		d0[i]= (d & 0x01) ? 1.0 : 0.0;
		d1[i]= (d & 0x02) ? 3.0 : 2.0;
		d2[i]= (d & 0x04) ? 5.0 : 4.0;
	}

	CDisplayWindowPlots win("Signals",640,480);

	win.hold_on();
	win.plot(d0, "b-");
	win.plot(d1, "r-");
	win.plot(d2, "k-");
	win.axis_fit();
	win.waitForKey();
#endif

#if 1
	ni_usb.create_SPI_configurations(1);
	ni_usb.set_SPI_configuration(0 /*idx*/, 0 /* CS */, 1000 /* Khz */, false /* clock_polarity_idle_high */, false /* clock_phase_first_edge */ );

	{
		const uint8_t write[2] = { 0x20, 0xFF };
		uint8_t read[2];
		size_t nRead;
		printf("TX: %02X %02X\n", write[0],write[1]);
		ni_usb.read_write_SPI(0 /* config idx */, 2, write, nRead, read );
	}

	const uint8_t write[2] = { 0x80 | 0x28, 0x00 };
	uint8_t read[2];
	size_t nRead;
	while (!mrpt::system::os::kbhit())
	{
		printf("TX: %02X %02X\n", write[0],write[1]);
		ni_usb.read_write_SPI(0 /* config idx */, 2, write, nRead, read );
		printf("RX: %02X %02X\n\n", read[0],read[1]);
		mrpt::system::sleep(100);
	}

#endif

	mrpt::system::pause();
}

// ------------------------------------------------------
//						MAIN
// ------------------------------------------------------
int main()
{
	try
	{
		TestNI_USB_845x();
		return 0;
	} catch (std::exception &e)
	{
		std::cout << "MRPT exception caught: " << e.what() << std::endl;
		return -1;
	}
}

<|endoftext|>


<commit_before><commit_msg>sandbox/linux/bpf_dsl: collapse similar ResultExprImpl subclasses<commit_after><|endoftext|>


<commit_before><commit_msg>Remove stray fprintf<commit_after><|endoftext|>


<commit_before>#include "Halide.h"
#include <stdio.h>
using namespace Halide;
#include "halide_image_io.h"
using namespace Halide::Tools;

Func rgb_to_grey(Image<uint8_t> input)
{
  Var x("x"), y("y"), c("c"), d("d");
  Func clamped("clamped");
  clamped = BoundaryConditions::repeat_edge(input);
  Func greyImg("greyImg");
  greyImg(x,y,d) =
    clamped(x,y,0) * 0.3f
    + clamped(x,y,1) * 0.59f
    + clamped(x,y,2) * 0.11f;
  return greyImg;
}

void imwrite(std::string fname, int width, int height, Func continuation)
{
  Image<uint8_t> result(width, height, 1);
  continuation.realize(result);
  save_image(result, fname);
}

Func blurX(Func continuation)
{
  Var x("x"), y("y"), c("c");
  Func input_16("input_16");
  input_16(x, y, c) = cast<uint16_t>(continuation(x, y, c));
  Func blur_x("blur_x");
  blur_x(x, y, c) = (input_16(x-1, y, c) +
                     2 * input_16(x, y, c) +
                     input_16(x+1, y, c)) / 4;
  blur_x.vectorize(x, 8).parallel(y);
  blur_x.compute_root();
  Func output("outputBlurX");
  output(x, y, c) = cast<uint8_t>(blur_x(x, y, c));
  return output;
}

Func blurY(Func continuation)
{
  Var x("x"), y("y"), c("c");
  Func input_16("input_16");
  input_16(x, y, c) = cast<uint16_t>(continuation(x, y, c));
  Func blur_y("blur_y");
  blur_y(x, y, c) = (input_16(x, y-1, c) +
                     2 * input_16(x, y, c) +
                     input_16(x, y+1, c)) / 4;
  blur_y.vectorize(y, 8).parallel(x);
  blur_y.compute_root();
  Func output("outputBlurY");
  output(x, y, c) = cast<uint8_t>(blur_y(x, y, c));
  return output;
}

Func brightenBy(int brightenByVal, Func continuation)
{
  Func brighten("brighten");
  Var x, y, c;
  Expr value = continuation(x, y, c);
  value = Halide::cast<float>(value);
  value = value + brightenByVal;
  value = Halide::min(value, 255.0f);
  value = Halide::cast<uint8_t>(value);
  brighten(x, y, c) = value;
  brighten.vectorize(x, 8).parallel(y);
  brighten.compute_root();
  return brighten;
}

Func darkenBy(int darkenByVal, Func continuation)
{
  Func darken("darken");
  Var x, y, c;
  Expr value = continuation(x, y, c);
  value = Halide::cast<float>(value);
  value = value - darkenByVal;
  value = Halide::cast<uint8_t>(value);
  darken(x, y, c) = value;
  darken.vectorize(x, 8).parallel(y);
  darken.compute_root();
  return darken;
}
<commit_msg>(Halide) imwrite writes .realize(..) time to stdout in seconds<commit_after>#include "Halide.h"
#include <stdio.h>
using namespace Halide;
#include "halide_image_io.h"
using namespace Halide::Tools;
#include "clock.h"

Func rgb_to_grey(Image<uint8_t> input)
{
  Var x("x"), y("y"), c("c"), d("d");
  Func clamped("clamped");
  clamped = BoundaryConditions::repeat_edge(input);
  Func greyImg("greyImg");
  greyImg(x,y,d) =
    clamped(x,y,0) * 0.3f
    + clamped(x,y,1) * 0.59f
    + clamped(x,y,2) * 0.11f;
  return greyImg;
}

void imwrite(std::string fname, int width, int height, Func continuation)
{
  Image<uint8_t> result(width, height, 1);

  double t1 = current_time();
  continuation.realize(result);
  double t2 = current_time();
  std::cout << ((t2 - t1) / 1000.0) << "\n";

  save_image(result, fname);
}

Func blurX(Func continuation)
{
  Var x("x"), y("y"), c("c");
  Func input_16("input_16");
  input_16(x, y, c) = cast<uint16_t>(continuation(x, y, c));
  Func blur_x("blur_x");
  blur_x(x, y, c) = (input_16(x-1, y, c) +
                     2 * input_16(x, y, c) +
                     input_16(x+1, y, c)) / 4;
  blur_x.vectorize(x, 8).parallel(y);
  blur_x.compute_root();
  Func output("outputBlurX");
  output(x, y, c) = cast<uint8_t>(blur_x(x, y, c));
  return output;
}

Func blurY(Func continuation)
{
  Var x("x"), y("y"), c("c");
  Func input_16("input_16");
  input_16(x, y, c) = cast<uint16_t>(continuation(x, y, c));
  Func blur_y("blur_y");
  blur_y(x, y, c) = (input_16(x, y-1, c) +
                     2 * input_16(x, y, c) +
                     input_16(x, y+1, c)) / 4;
  blur_y.vectorize(y, 8).parallel(x);
  blur_y.compute_root();
  Func output("outputBlurY");
  output(x, y, c) = cast<uint8_t>(blur_y(x, y, c));
  return output;
}

Func brightenBy(int brightenByVal, Func continuation)
{
  Func brighten("brighten");
  Var x, y, c;
  Expr value = continuation(x, y, c);
  value = Halide::cast<float>(value);
  value = value + brightenByVal;
  value = Halide::min(value, 255.0f);
  value = Halide::cast<uint8_t>(value);
  brighten(x, y, c) = value;
  brighten.vectorize(x, 8).parallel(y);
  brighten.compute_root();
  return brighten;
}

Func darkenBy(int darkenByVal, Func continuation)
{
  Func darken("darken");
  Var x, y, c;
  Expr value = continuation(x, y, c);
  value = Halide::cast<float>(value);
  value = value - darkenByVal;
  value = Halide::cast<uint8_t>(value);
  darken(x, y, c) = value;
  darken.vectorize(x, 8).parallel(y);
  darken.compute_root();
  return darken;
}
<|endoftext|>


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

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

#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/uno/Sequence.hxx>

#include "unitconv.hxx"
#include "global.hxx"
#include "viewopti.hxx"         //! move ScLinkConfigItem to separate header!

using namespace utl;
using namespace rtl;
using namespace com::sun::star::uno;

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

const sal_Unicode cDelim = 0x01;        // Delimiter zwischen From und To

// --- ScUnitConverterData --------------------------------------------

ScUnitConverterData::ScUnitConverterData( const String& rFromUnit,
            const String& rToUnit, double fVal )
        :
        StrData( rFromUnit ),
        fValue( fVal )
{
    String aTmp;
    ScUnitConverterData::BuildIndexString( aTmp, rFromUnit, rToUnit );
    SetString( aTmp );
}

ScUnitConverterData::ScUnitConverterData( const ScUnitConverterData& r )
        :
        StrData( r ),
        fValue( r.fValue )
{
}

DataObject* ScUnitConverterData::Clone() const
{
    return new ScUnitConverterData( *this );
}

// static
void ScUnitConverterData::BuildIndexString( String& rStr,
            const String& rFromUnit, const String& rToUnit )
{
#if 1
// case sensitive
    rStr = rFromUnit;
    rStr += cDelim;
    rStr += rToUnit;
#else
// not case sensitive
    rStr = rFromUnit;
    String aTo( rToUnit );
    ScGlobal::pCharClass->toUpper( rStr );
    ScGlobal::pCharClass->toUpper( aTo );
    rStr += cDelim;
    rStr += aTo;
#endif
}

// --- ScUnitConverter ------------------------------------------------

#define CFGPATH_UNIT        "Office.Calc/UnitConversion"
#define CFGSTR_UNIT_FROM    "FromUnit"
#define CFGSTR_UNIT_TO      "ToUnit"
#define CFGSTR_UNIT_FACTOR  "Factor"

ScUnitConverter::ScUnitConverter( USHORT nInit, USHORT nDeltaP ) :
        StrCollection( nInit, nDeltaP, FALSE )
{
    //  read from configuration - "convert.ini" is no longer used
    //! config item as member to allow change of values

    ScLinkConfigItem aConfigItem( OUString::createFromAscii( CFGPATH_UNIT ) );

    // empty node name -> use the config item's path itself
    OUString aEmptyString;
    Sequence<OUString> aNodeNames = aConfigItem.GetNodeNames( aEmptyString );

    long nNodeCount = aNodeNames.getLength();
    if ( nNodeCount )
    {
        const OUString* pNodeArray = aNodeNames.getConstArray();
        Sequence<OUString> aValNames( nNodeCount * 3 );
        OUString* pValNameArray = aValNames.getArray();
        const OUString sSlash('/');

        long nIndex = 0;
        for (long i=0; i<nNodeCount; i++)
        {
            OUString sPrefix = pNodeArray[i];
            sPrefix += sSlash;

            pValNameArray[nIndex] = sPrefix;
            pValNameArray[nIndex++] += OUString::createFromAscii( CFGSTR_UNIT_FROM );
            pValNameArray[nIndex] = sPrefix;
            pValNameArray[nIndex++] += OUString::createFromAscii( CFGSTR_UNIT_TO );
            pValNameArray[nIndex] = sPrefix;
            pValNameArray[nIndex++] += OUString::createFromAscii( CFGSTR_UNIT_FACTOR );
        }

        Sequence<Any> aProperties = aConfigItem.GetProperties(aValNames);

        if (aProperties.getLength() == aValNames.getLength())
        {
            const Any* pProperties = aProperties.getConstArray();

            OUString sFromUnit;
            OUString sToUnit;
            double fFactor = 0;

            nIndex = 0;
            for (long i=0; i<nNodeCount; i++)
            {
                pProperties[nIndex++] >>= sFromUnit;
                pProperties[nIndex++] >>= sToUnit;
                pProperties[nIndex++] >>= fFactor;

                ScUnitConverterData* pNew = new ScUnitConverterData( sFromUnit, sToUnit, fFactor );
                if ( !Insert( pNew ) )
                    delete pNew;
            }
        }
    }
}

BOOL ScUnitConverter::GetValue( double& fValue, const String& rFromUnit,
                const String& rToUnit ) const
{
    ScUnitConverterData aSearch( rFromUnit, rToUnit );
    USHORT nIndex;
    if ( Search( &aSearch, nIndex ) )
    {
        fValue = ((const ScUnitConverterData*)(At( nIndex )))->GetValue();
        return TRUE;
    }
    fValue = 1.0;
    return FALSE;
}

<commit_msg>INTEGRATION: CWS changefileheader (1.7.320); FILE MERGED 2008/03/31 17:14:19 rt 1.7.320.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: unitconv.cxx,v $
 * $Revision: 1.8 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/uno/Sequence.hxx>

#include "unitconv.hxx"
#include "global.hxx"
#include "viewopti.hxx"         //! move ScLinkConfigItem to separate header!

using namespace utl;
using namespace rtl;
using namespace com::sun::star::uno;

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

const sal_Unicode cDelim = 0x01;        // Delimiter zwischen From und To

// --- ScUnitConverterData --------------------------------------------

ScUnitConverterData::ScUnitConverterData( const String& rFromUnit,
            const String& rToUnit, double fVal )
        :
        StrData( rFromUnit ),
        fValue( fVal )
{
    String aTmp;
    ScUnitConverterData::BuildIndexString( aTmp, rFromUnit, rToUnit );
    SetString( aTmp );
}

ScUnitConverterData::ScUnitConverterData( const ScUnitConverterData& r )
        :
        StrData( r ),
        fValue( r.fValue )
{
}

DataObject* ScUnitConverterData::Clone() const
{
    return new ScUnitConverterData( *this );
}

// static
void ScUnitConverterData::BuildIndexString( String& rStr,
            const String& rFromUnit, const String& rToUnit )
{
#if 1
// case sensitive
    rStr = rFromUnit;
    rStr += cDelim;
    rStr += rToUnit;
#else
// not case sensitive
    rStr = rFromUnit;
    String aTo( rToUnit );
    ScGlobal::pCharClass->toUpper( rStr );
    ScGlobal::pCharClass->toUpper( aTo );
    rStr += cDelim;
    rStr += aTo;
#endif
}

// --- ScUnitConverter ------------------------------------------------

#define CFGPATH_UNIT        "Office.Calc/UnitConversion"
#define CFGSTR_UNIT_FROM    "FromUnit"
#define CFGSTR_UNIT_TO      "ToUnit"
#define CFGSTR_UNIT_FACTOR  "Factor"

ScUnitConverter::ScUnitConverter( USHORT nInit, USHORT nDeltaP ) :
        StrCollection( nInit, nDeltaP, FALSE )
{
    //  read from configuration - "convert.ini" is no longer used
    //! config item as member to allow change of values

    ScLinkConfigItem aConfigItem( OUString::createFromAscii( CFGPATH_UNIT ) );

    // empty node name -> use the config item's path itself
    OUString aEmptyString;
    Sequence<OUString> aNodeNames = aConfigItem.GetNodeNames( aEmptyString );

    long nNodeCount = aNodeNames.getLength();
    if ( nNodeCount )
    {
        const OUString* pNodeArray = aNodeNames.getConstArray();
        Sequence<OUString> aValNames( nNodeCount * 3 );
        OUString* pValNameArray = aValNames.getArray();
        const OUString sSlash('/');

        long nIndex = 0;
        for (long i=0; i<nNodeCount; i++)
        {
            OUString sPrefix = pNodeArray[i];
            sPrefix += sSlash;

            pValNameArray[nIndex] = sPrefix;
            pValNameArray[nIndex++] += OUString::createFromAscii( CFGSTR_UNIT_FROM );
            pValNameArray[nIndex] = sPrefix;
            pValNameArray[nIndex++] += OUString::createFromAscii( CFGSTR_UNIT_TO );
            pValNameArray[nIndex] = sPrefix;
            pValNameArray[nIndex++] += OUString::createFromAscii( CFGSTR_UNIT_FACTOR );
        }

        Sequence<Any> aProperties = aConfigItem.GetProperties(aValNames);

        if (aProperties.getLength() == aValNames.getLength())
        {
            const Any* pProperties = aProperties.getConstArray();

            OUString sFromUnit;
            OUString sToUnit;
            double fFactor = 0;

            nIndex = 0;
            for (long i=0; i<nNodeCount; i++)
            {
                pProperties[nIndex++] >>= sFromUnit;
                pProperties[nIndex++] >>= sToUnit;
                pProperties[nIndex++] >>= fFactor;

                ScUnitConverterData* pNew = new ScUnitConverterData( sFromUnit, sToUnit, fFactor );
                if ( !Insert( pNew ) )
                    delete pNew;
            }
        }
    }
}

BOOL ScUnitConverter::GetValue( double& fValue, const String& rFromUnit,
                const String& rToUnit ) const
{
    ScUnitConverterData aSearch( rFromUnit, rToUnit );
    USHORT nIndex;
    if ( Search( &aSearch, nIndex ) )
    {
        fValue = ((const ScUnitConverterData*)(At( nIndex )))->GetValue();
        return TRUE;
    }
    fValue = 1.0;
    return FALSE;
}

<|endoftext|>