<commit_before>/*  This file is part of the KDE project
    Copyright (C) 2006-2008 Matthias Kretz <kretz@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) version 3, or any
    later version accepted by the membership of KDE e.V. (or its
    successor approved by the membership of KDE e.V.), Nokia Corporation
    (or its successors, if any) and the KDE Free Qt Foundation, which shall
    act as a proxy defined in Section 6 of version 3 of the license.

    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, see <http://www.gnu.org/licenses/>.

*/

#include "globalconfig_p.h"

#include "factory_p.h"
#include "objectdescription.h"
#include "phonondefs_p.h"
#include "platformplugin.h"
#include "backendinterface.h"
#include "qsettingsgroup_p.h"
#include "phononnamespace_p.h"
#include "pulsesupport_p.h"

#include <QtCore/QList>
#include <QtCore/QVariant>

QT_BEGIN_NAMESPACE

namespace Phonon
{

GlobalConfig::GlobalConfig() : m_config(QLatin1String("kde.org"), QLatin1String("libphonon"))
{
}

GlobalConfig::~GlobalConfig()
{
}

enum WhatToFilter {
    FilterAdvancedDevices = 1,
    FilterHardwareDevices = 2,
    FilterUnavailableDevices = 4
};

static void filter(ObjectDescriptionType type, BackendInterface *backendIface, QList<int> *list, int whatToFilter)
{
    QMutableListIterator<int> it(*list);
    while (it.hasNext()) {
        const QHash<QByteArray, QVariant> properties = backendIface->objectDescriptionProperties(type, it.next());
        QVariant var;
        if (whatToFilter & FilterAdvancedDevices) {
            var = properties.value("isAdvanced");
            if (var.isValid() && var.toBool()) {
                it.remove();
                continue;
            }
        }
        if (whatToFilter & FilterHardwareDevices) {
            var = properties.value("isHardwareDevice");
            if (var.isValid() && var.toBool()) {
                it.remove();
                continue;
            }
        }
        if (whatToFilter & FilterUnavailableDevices) {
            var = properties.value("available");
            if (var.isValid() && !var.toBool()) {
                it.remove();
                continue;
            }
        }
    }
}

static QList<int> listSortedByConfig(const QSettingsGroup &backendConfig, Phonon::Category category, QList<int> &defaultList)
{
    if (defaultList.size() <= 1) {
        // nothing to sort
        return defaultList;
    } else {
        // make entries unique
        QSet<int> seen;
        QMutableListIterator<int> it(defaultList);
        while (it.hasNext()) {
            if (seen.contains(it.next())) {
                it.remove();
            } else {
                seen.insert(it.value());
            }
        }
    }

    QString categoryKey = QLatin1String("Category_") + QString::number(static_cast<int>(category));
    if (!backendConfig.hasKey(categoryKey)) {
        // no list in config for the given category
        categoryKey = QLatin1String("Category_") + QString::number(static_cast<int>(Phonon::NoCategory));
        if (!backendConfig.hasKey(categoryKey)) {
            // no list in config for NoCategory
            return defaultList;
        }
    }

    //Now the list from m_config
    QList<int> deviceList = backendConfig.value(categoryKey, QList<int>());

    //if there are devices in m_config that the backend doesn't report, remove them from the list
    QMutableListIterator<int> i(deviceList);
    while (i.hasNext()) {
        if (0 == defaultList.removeAll(i.next())) {
            i.remove();
        }
    }

    //if the backend reports more devices that are not in m_config append them to the list
    deviceList += defaultList;

    return deviceList;
}

bool GlobalConfig::getHideAdvancedDevices() const
{
    //The devices need to be stored independently for every backend
    const QSettingsGroup generalGroup(&m_config, QLatin1String("General"));
    return generalGroup.value(QLatin1String("HideAdvancedDevices"), true);
}

void GlobalConfig::hideAdvancedDevices(bool hide)
{
    QSettingsGroup generalGroup(&m_config, QLatin1String("General"));
    generalGroup.value(QLatin1String("HideAdvancedDevices"), hide);
}

bool GlobalConfig::isHiddenAudioOutputDevice(int i) const
{
    if (!getHideAdvancedDevices())
        return false;

    AudioOutputDevice ad = AudioOutputDevice::fromIndex(i);
    const QVariant var = ad.property("isAdvanced");
    return (var.isValid() && var.toBool());
}

void GlobalConfig::setAudioOutputDeviceListFor(Phonon::Category category, QList<int> order)
{
    QSettingsGroup backendConfig(&m_config, QLatin1String("AudioOutputDevice")); // + Factory::identifier());

    const QList<int> noCategoryOrder = audioOutputDeviceListFor(Phonon::NoCategory, ShowUnavailableDevices|ShowAdvancedDevices);
    if (category != Phonon::NoCategory && order == noCategoryOrder) {
        backendConfig.removeEntry(QLatin1String("Category_") + QString::number(category));
    } else {
        backendConfig.setValue(QLatin1String("Category_") + QString::number(category), order);
    }
}

QList<int> GlobalConfig::audioOutputDeviceListFor(Phonon::Category category, int override) const
{
    //The devices need to be stored independently for every backend
    const QSettingsGroup backendConfig(&m_config, QLatin1String("AudioOutputDevice")); // + Factory::identifier());
    const bool hideAdvancedDevices = ((override & AdvancedDevicesFromSettings)
            ? getHideAdvancedDevices()
            : static_cast<bool>(override & HideAdvancedDevices));

    QList<int> defaultList;
    BackendInterface *backendIface = qobject_cast<BackendInterface *>(Factory::backend());

#ifndef QT_NO_PHONON_PLATFORMPLUGIN
    if (!backendIface || !PulseSupport::getInstance()->isActive()) {
        if (PlatformPlugin *platformPlugin = Factory::platformPlugin()) {
            // the platform plugin lists the audio devices for the platform
            // this list already is in default order (as defined by the platform plugin)
            defaultList = platformPlugin->objectDescriptionIndexes(Phonon::AudioOutputDeviceType);
            if (hideAdvancedDevices) {
                QMutableListIterator<int> it(defaultList);
                while (it.hasNext()) {
                    AudioOutputDevice objDesc = AudioOutputDevice::fromIndex(it.next());
                    const QVariant var = objDesc.property("isAdvanced");
                    if (var.isValid() && var.toBool()) {
                        it.remove();
                    }
                }
            }
        }
    }
#endif //QT_NO_PHONON_PLATFORMPLUGIN

    // lookup the available devices directly from the backend
    if (backendIface) {
        // this list already is in default order (as defined by the backend)
        QList<int> list = backendIface->objectDescriptionIndexes(Phonon::AudioOutputDeviceType);
        if (hideAdvancedDevices || !defaultList.isEmpty() || (override & HideUnavailableDevices)) {
            filter(AudioOutputDeviceType, backendIface, &list,
                    (hideAdvancedDevices ? FilterAdvancedDevices : 0)
                    // the platform plugin already provided the hardware devices
                    | (defaultList.isEmpty() ? 0 : FilterHardwareDevices)
                    | ((override & HideUnavailableDevices) ? FilterUnavailableDevices : 0)
                    );
        }
        defaultList += list;
    }

    return listSortedByConfig(backendConfig, category, defaultList);
}

int GlobalConfig::audioOutputDeviceFor(Phonon::Category category, int override) const
{
    QList<int> ret = audioOutputDeviceListFor(category, override);
    if (ret.isEmpty())
        return -1;
    return ret.first();
}

#ifndef QT_NO_PHONON_AUDIOCAPTURE
bool GlobalConfig::isHiddenAudioCaptureDevice(int i) const
{
    if (!getHideAdvancedDevices())
        return false;

    AudioCaptureDevice ad = AudioCaptureDevice::fromIndex(i);
    const QVariant var = ad.property("isAdvanced");
    return (var.isValid() && var.toBool());
}

void GlobalConfig::setAudioCaptureDeviceListFor(Phonon::Category category, QList<int> order)
{
    QSettingsGroup backendConfig(&m_config, QLatin1String("AudioCaptureDevice")); // + Factory::identifier());

    const QList<int> noCategoryOrder = audioCaptureDeviceListFor(Phonon::NoCategory, ShowUnavailableDevices|ShowAdvancedDevices);
    if (category != Phonon::NoCategory && order == noCategoryOrder) {
        backendConfig.removeEntry(QLatin1String("Category_") + QString::number(category));
    } else {
        backendConfig.setValue(QLatin1String("Category_") + QString::number(category), order);
    }
}

QList<int> GlobalConfig::audioCaptureDeviceListFor(Phonon::Category category, int override) const
{
    //The devices need to be stored independently for every backend
    const QSettingsGroup backendConfig(&m_config, QLatin1String("AudioCaptureDevice")); // + Factory::identifier());
    const bool hideAdvancedDevices = ((override & AdvancedDevicesFromSettings)
            ? getHideAdvancedDevices()
            : static_cast<bool>(override & HideAdvancedDevices));

    QList<int> defaultList;
    BackendInterface *backendIface = qobject_cast<BackendInterface *>(Factory::backend());

#ifndef QT_NO_PHONON_PLATFORMPLUGIN
    if (!backendIface || !PulseSupport::getInstance()->isActive()) {
        if (PlatformPlugin *platformPlugin = Factory::platformPlugin()) {
            // the platform plugin lists the audio devices for the platform
            // this list already is in default order (as defined by the platform plugin)
            defaultList = platformPlugin->objectDescriptionIndexes(Phonon::AudioCaptureDeviceType);
            if (hideAdvancedDevices) {
                QMutableListIterator<int> it(defaultList);
                while (it.hasNext()) {
                    AudioCaptureDevice objDesc = AudioCaptureDevice::fromIndex(it.next());
                    const QVariant var = objDesc.property("isAdvanced");
                    if (var.isValid() && var.toBool()) {
                        it.remove();
                    }
                }
            }
        }
    }
#endif //QT_NO_PHONON_PLATFORMPLUGIN

    // lookup the available devices directly from the backend
    if (backendIface) {
        // this list already is in default order (as defined by the backend)
        QList<int> list = backendIface->objectDescriptionIndexes(Phonon::AudioCaptureDeviceType);
        if (hideAdvancedDevices || !defaultList.isEmpty() || (override & HideUnavailableDevices)) {
            filter(AudioCaptureDeviceType, backendIface, &list,
                    (hideAdvancedDevices ? FilterAdvancedDevices : 0)
                    // the platform plugin already provided the hardware devices
                    | (defaultList.isEmpty() ? 0 : FilterHardwareDevices)
                    | ((override & HideUnavailableDevices) ? FilterUnavailableDevices : 0)
                  );
        }
        defaultList += list;
    }

    return listSortedByConfig(backendConfig, category, defaultList);
}

int GlobalConfig::audioCaptureDeviceFor(Phonon::Category category, int override) const
{
    QList<int> ret = audioCaptureDeviceListFor(category, override);
    if (ret.isEmpty())
        return -1;
    return ret.first();
}
#endif //QT_NO_PHONON_AUDIOCAPTURE

} // namespace Phonon

QT_END_NAMESPACE
<commit_msg>pulseaudio: If the results are coming from pulseaudio, there is no need to sort.<commit_after>/*  This file is part of the KDE project
    Copyright (C) 2006-2008 Matthias Kretz <kretz@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) version 3, or any
    later version accepted by the membership of KDE e.V. (or its
    successor approved by the membership of KDE e.V.), Nokia Corporation
    (or its successors, if any) and the KDE Free Qt Foundation, which shall
    act as a proxy defined in Section 6 of version 3 of the license.

    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, see <http://www.gnu.org/licenses/>.

*/

#include "globalconfig_p.h"

#include "factory_p.h"
#include "objectdescription.h"
#include "phonondefs_p.h"
#include "platformplugin.h"
#include "backendinterface.h"
#include "qsettingsgroup_p.h"
#include "phononnamespace_p.h"
#include "pulsesupport_p.h"

#include <QtCore/QList>
#include <QtCore/QVariant>

QT_BEGIN_NAMESPACE

namespace Phonon
{

GlobalConfig::GlobalConfig() : m_config(QLatin1String("kde.org"), QLatin1String("libphonon"))
{
}

GlobalConfig::~GlobalConfig()
{
}

enum WhatToFilter {
    FilterAdvancedDevices = 1,
    FilterHardwareDevices = 2,
    FilterUnavailableDevices = 4
};

static void filter(ObjectDescriptionType type, BackendInterface *backendIface, QList<int> *list, int whatToFilter)
{
    QMutableListIterator<int> it(*list);
    while (it.hasNext()) {
        const QHash<QByteArray, QVariant> properties = backendIface->objectDescriptionProperties(type, it.next());
        QVariant var;
        if (whatToFilter & FilterAdvancedDevices) {
            var = properties.value("isAdvanced");
            if (var.isValid() && var.toBool()) {
                it.remove();
                continue;
            }
        }
        if (whatToFilter & FilterHardwareDevices) {
            var = properties.value("isHardwareDevice");
            if (var.isValid() && var.toBool()) {
                it.remove();
                continue;
            }
        }
        if (whatToFilter & FilterUnavailableDevices) {
            var = properties.value("available");
            if (var.isValid() && !var.toBool()) {
                it.remove();
                continue;
            }
        }
    }
}

static QList<int> listSortedByConfig(const QSettingsGroup &backendConfig, Phonon::Category category, QList<int> &defaultList)
{
    if (PulseSupport::getInstance()->isActive() || defaultList.size() <= 1) {
        // nothing to sort
        return defaultList;
    } else {
        // make entries unique
        QSet<int> seen;
        QMutableListIterator<int> it(defaultList);
        while (it.hasNext()) {
            if (seen.contains(it.next())) {
                it.remove();
            } else {
                seen.insert(it.value());
            }
        }
    }

    QString categoryKey = QLatin1String("Category_") + QString::number(static_cast<int>(category));
    if (!backendConfig.hasKey(categoryKey)) {
        // no list in config for the given category
        categoryKey = QLatin1String("Category_") + QString::number(static_cast<int>(Phonon::NoCategory));
        if (!backendConfig.hasKey(categoryKey)) {
            // no list in config for NoCategory
            return defaultList;
        }
    }

    //Now the list from m_config
    QList<int> deviceList = backendConfig.value(categoryKey, QList<int>());

    //if there are devices in m_config that the backend doesn't report, remove them from the list
    QMutableListIterator<int> i(deviceList);
    while (i.hasNext()) {
        if (0 == defaultList.removeAll(i.next())) {
            i.remove();
        }
    }

    //if the backend reports more devices that are not in m_config append them to the list
    deviceList += defaultList;

    return deviceList;
}

bool GlobalConfig::getHideAdvancedDevices() const
{
    //The devices need to be stored independently for every backend
    const QSettingsGroup generalGroup(&m_config, QLatin1String("General"));
    return generalGroup.value(QLatin1String("HideAdvancedDevices"), true);
}

void GlobalConfig::hideAdvancedDevices(bool hide)
{
    QSettingsGroup generalGroup(&m_config, QLatin1String("General"));
    generalGroup.value(QLatin1String("HideAdvancedDevices"), hide);
}

bool GlobalConfig::isHiddenAudioOutputDevice(int i) const
{
    if (!getHideAdvancedDevices())
        return false;

    AudioOutputDevice ad = AudioOutputDevice::fromIndex(i);
    const QVariant var = ad.property("isAdvanced");
    return (var.isValid() && var.toBool());
}

void GlobalConfig::setAudioOutputDeviceListFor(Phonon::Category category, QList<int> order)
{
    QSettingsGroup backendConfig(&m_config, QLatin1String("AudioOutputDevice")); // + Factory::identifier());

    const QList<int> noCategoryOrder = audioOutputDeviceListFor(Phonon::NoCategory, ShowUnavailableDevices|ShowAdvancedDevices);
    if (category != Phonon::NoCategory && order == noCategoryOrder) {
        backendConfig.removeEntry(QLatin1String("Category_") + QString::number(category));
    } else {
        backendConfig.setValue(QLatin1String("Category_") + QString::number(category), order);
    }
}

QList<int> GlobalConfig::audioOutputDeviceListFor(Phonon::Category category, int override) const
{
    //The devices need to be stored independently for every backend
    const QSettingsGroup backendConfig(&m_config, QLatin1String("AudioOutputDevice")); // + Factory::identifier());
    const bool hideAdvancedDevices = ((override & AdvancedDevicesFromSettings)
            ? getHideAdvancedDevices()
            : static_cast<bool>(override & HideAdvancedDevices));

    QList<int> defaultList;
    BackendInterface *backendIface = qobject_cast<BackendInterface *>(Factory::backend());

#ifndef QT_NO_PHONON_PLATFORMPLUGIN
    if (!backendIface || !PulseSupport::getInstance()->isActive()) {
        if (PlatformPlugin *platformPlugin = Factory::platformPlugin()) {
            // the platform plugin lists the audio devices for the platform
            // this list already is in default order (as defined by the platform plugin)
            defaultList = platformPlugin->objectDescriptionIndexes(Phonon::AudioOutputDeviceType);
            if (hideAdvancedDevices) {
                QMutableListIterator<int> it(defaultList);
                while (it.hasNext()) {
                    AudioOutputDevice objDesc = AudioOutputDevice::fromIndex(it.next());
                    const QVariant var = objDesc.property("isAdvanced");
                    if (var.isValid() && var.toBool()) {
                        it.remove();
                    }
                }
            }
        }
    }
#endif //QT_NO_PHONON_PLATFORMPLUGIN

    // lookup the available devices directly from the backend
    if (backendIface) {
        // this list already is in default order (as defined by the backend)
        QList<int> list = backendIface->objectDescriptionIndexes(Phonon::AudioOutputDeviceType);
        if (hideAdvancedDevices || !defaultList.isEmpty() || (override & HideUnavailableDevices)) {
            filter(AudioOutputDeviceType, backendIface, &list,
                    (hideAdvancedDevices ? FilterAdvancedDevices : 0)
                    // the platform plugin already provided the hardware devices
                    | (defaultList.isEmpty() ? 0 : FilterHardwareDevices)
                    | ((override & HideUnavailableDevices) ? FilterUnavailableDevices : 0)
                    );
        }
        defaultList += list;
    }

    return listSortedByConfig(backendConfig, category, defaultList);
}

int GlobalConfig::audioOutputDeviceFor(Phonon::Category category, int override) const
{
    QList<int> ret = audioOutputDeviceListFor(category, override);
    if (ret.isEmpty())
        return -1;
    return ret.first();
}

#ifndef QT_NO_PHONON_AUDIOCAPTURE
bool GlobalConfig::isHiddenAudioCaptureDevice(int i) const
{
    if (!getHideAdvancedDevices())
        return false;

    AudioCaptureDevice ad = AudioCaptureDevice::fromIndex(i);
    const QVariant var = ad.property("isAdvanced");
    return (var.isValid() && var.toBool());
}

void GlobalConfig::setAudioCaptureDeviceListFor(Phonon::Category category, QList<int> order)
{
    QSettingsGroup backendConfig(&m_config, QLatin1String("AudioCaptureDevice")); // + Factory::identifier());

    const QList<int> noCategoryOrder = audioCaptureDeviceListFor(Phonon::NoCategory, ShowUnavailableDevices|ShowAdvancedDevices);
    if (category != Phonon::NoCategory && order == noCategoryOrder) {
        backendConfig.removeEntry(QLatin1String("Category_") + QString::number(category));
    } else {
        backendConfig.setValue(QLatin1String("Category_") + QString::number(category), order);
    }
}

QList<int> GlobalConfig::audioCaptureDeviceListFor(Phonon::Category category, int override) const
{
    //The devices need to be stored independently for every backend
    const QSettingsGroup backendConfig(&m_config, QLatin1String("AudioCaptureDevice")); // + Factory::identifier());
    const bool hideAdvancedDevices = ((override & AdvancedDevicesFromSettings)
            ? getHideAdvancedDevices()
            : static_cast<bool>(override & HideAdvancedDevices));

    QList<int> defaultList;
    BackendInterface *backendIface = qobject_cast<BackendInterface *>(Factory::backend());

#ifndef QT_NO_PHONON_PLATFORMPLUGIN
    if (!backendIface || !PulseSupport::getInstance()->isActive()) {
        if (PlatformPlugin *platformPlugin = Factory::platformPlugin()) {
            // the platform plugin lists the audio devices for the platform
            // this list already is in default order (as defined by the platform plugin)
            defaultList = platformPlugin->objectDescriptionIndexes(Phonon::AudioCaptureDeviceType);
            if (hideAdvancedDevices) {
                QMutableListIterator<int> it(defaultList);
                while (it.hasNext()) {
                    AudioCaptureDevice objDesc = AudioCaptureDevice::fromIndex(it.next());
                    const QVariant var = objDesc.property("isAdvanced");
                    if (var.isValid() && var.toBool()) {
                        it.remove();
                    }
                }
            }
        }
    }
#endif //QT_NO_PHONON_PLATFORMPLUGIN

    // lookup the available devices directly from the backend
    if (backendIface) {
        // this list already is in default order (as defined by the backend)
        QList<int> list = backendIface->objectDescriptionIndexes(Phonon::AudioCaptureDeviceType);
        if (hideAdvancedDevices || !defaultList.isEmpty() || (override & HideUnavailableDevices)) {
            filter(AudioCaptureDeviceType, backendIface, &list,
                    (hideAdvancedDevices ? FilterAdvancedDevices : 0)
                    // the platform plugin already provided the hardware devices
                    | (defaultList.isEmpty() ? 0 : FilterHardwareDevices)
                    | ((override & HideUnavailableDevices) ? FilterUnavailableDevices : 0)
                  );
        }
        defaultList += list;
    }

    return listSortedByConfig(backendConfig, category, defaultList);
}

int GlobalConfig::audioCaptureDeviceFor(Phonon::Category category, int override) const
{
    QList<int> ret = audioCaptureDeviceListFor(category, override);
    if (ret.isEmpty())
        return -1;
    return ret.first();
}
#endif //QT_NO_PHONON_AUDIOCAPTURE

} // namespace Phonon

QT_END_NAMESPACE
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// buffer_pool_test.cpp
//
// Identification: tests/logging/buffer_pool_test.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "harness.h"
#include "backend/logging/circular_buffer_pool.h"
#include "logging/logging_tests_util.h"
#include "executor/executor_tests_util.h"
#include <stdlib.h>

namespace peloton {
namespace test {

//===--------------------------------------------------------------------===//
// Buffer Pool Tests
//===--------------------------------------------------------------------===//

class BufferPoolTests : public PelotonTest {};

void EnqueueTest(logging::CircularBufferPool *buffer_pool, unsigned int count) {
  for (unsigned int i = 0; i < count; i++) {
    std::unique_ptr<logging::LogBuffer> buf(new logging::LogBuffer(nullptr));
    buf->SetSize(i);
    buffer_pool->Put(std::move(buf));
  }
}

void DequeueTest(logging::CircularBufferPool *buffer_pool, unsigned int count) {
  for (unsigned int i = 0; i < count; i++) {
    auto buf = std::move(buffer_pool->Get());
    assert(buf);
    EXPECT_EQ(buf->GetSize(), i);
  }
}

void BackendThread(logging::WriteAheadBackendLogger *logger,
                   unsigned int count) {
  for (unsigned int i = 1; i <= count; i++) {
    logging::TransactionRecord begin_record(LOGRECORD_TYPE_TRANSACTION_COMMIT,
                                            i);
    logger->Log(&begin_record);
  }
}

void FrontendThread(logging::WriteAheadFrontendLogger *logger,
                    unsigned int count) {
  srand(time(NULL));
  while (true) {
    for (int i = 0; i < 10; i++) {
      logger->CollectLogRecordsFromBackendLoggers();
    }
    logger->FlushLogRecords();
    auto cid = logger->GetMaxFlushedCommitId();
    if (cid == count) {
      break;
    }
    int rand_num = rand() % 5 + 1;
    std::chrono::milliseconds sleep_time(rand_num);
    std::this_thread::sleep_for(sleep_time);
  }
}

TEST_F(BufferPoolTests, BufferPoolBasicTest) {
  logging::CircularBufferPool buffer_pool0;
  EnqueueTest(&buffer_pool0, 5);
  EXPECT_EQ(buffer_pool0.GetSize(), 5);

  DequeueTest(&buffer_pool0, 5);
  EXPECT_EQ(buffer_pool0.GetSize(), 0);

  EnqueueTest(&buffer_pool0, BUFFER_POOL_SIZE);
  EXPECT_EQ(buffer_pool0.GetSize(), BUFFER_POOL_SIZE);

  for (int i = 0; i < 10; i++) {
    logging::CircularBufferPool buffer_pool1;
    std::thread enqueue_thread(EnqueueTest, &buffer_pool1, BUFFER_POOL_SIZE);
    std::thread dequeue_thread(DequeueTest, &buffer_pool1, BUFFER_POOL_SIZE);
    enqueue_thread.join();
    dequeue_thread.join();
  }
}

TEST_F(BufferPoolTests, LogBufferBasicTest) {
  size_t tile_group_size = TESTS_TUPLES_PER_TILEGROUP;
  size_t table_tile_group_count = 3;

  std::unique_ptr<storage::DataTable> recovery_table(
      ExecutorTestsUtil::CreateTable(tile_group_size));

  // prepare tuples
  auto mutate = true;
  auto random = false;
  int num_rows = tile_group_size * table_tile_group_count;
  std::vector<std::shared_ptr<storage::Tuple>> tuples =
      LoggingTestsUtil::BuildTuples(recovery_table.get(), num_rows, mutate,
                                    random);
  std::vector<logging::TupleRecord> records =
      LoggingTestsUtil::BuildTupleRecords(tuples, tile_group_size,
                                          table_tile_group_count);
  logging::LogBuffer log_buffer(0);
  size_t total_length = 0;
  for (auto record : records) {
    assert(record.GetTuple()->GetSchema());
    CopySerializeOutput output_buffer;
    record.Serialize(output_buffer);
    size_t len = record.GetMessageLength();
    total_length += len;
    log_buffer.WriteRecord(&record);
  }
  EXPECT_EQ(log_buffer.GetSize(), total_length);
}

TEST_F(BufferPoolTests, BufferPoolConcurrentTest) {
  unsigned int txn_count = 1000000;

  auto &log_manager = logging::LogManager::GetInstance();
  logging::LogManager::Configure(LOGGING_TYPE_DRAM_NVM, true);
  log_manager.SetLoggingStatus(LOGGING_STATUS_TYPE_LOGGING);

  logging::WriteAheadFrontendLogger *frontend_logger =
      reinterpret_cast<logging::WriteAheadFrontendLogger *>(
          log_manager.GetFrontendLogger());
  logging::WriteAheadBackendLogger *backend_logger =
      reinterpret_cast<logging::WriteAheadBackendLogger *>(
          log_manager.GetBackendLogger());

  std::thread backend_thread(BackendThread, backend_logger, txn_count);
  std::thread frontend_thread(FrontendThread, frontend_logger, txn_count);
  backend_thread.join();
  frontend_thread.join();
}

}  // End test namespace
}  // End peloton namespace
<commit_msg>Fix buffer pool test<commit_after>//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// buffer_pool_test.cpp
//
// Identification: tests/logging/buffer_pool_test.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "harness.h"
#include "backend/logging/circular_buffer_pool.h"
#include "logging/logging_tests_util.h"
#include "executor/executor_tests_util.h"
#include <stdlib.h>

namespace peloton {
namespace test {

//===--------------------------------------------------------------------===//
// Buffer Pool Tests
//===--------------------------------------------------------------------===//

class BufferPoolTests : public PelotonTest {};

void EnqueueTest(logging::CircularBufferPool *buffer_pool, unsigned int count) {
  for (unsigned int i = 0; i < count; i++) {
    std::unique_ptr<logging::LogBuffer> buf(new logging::LogBuffer(nullptr));
    buf->SetSize(i);
    buffer_pool->Put(std::move(buf));
  }
}

void DequeueTest(logging::CircularBufferPool *buffer_pool, unsigned int count) {
  for (unsigned int i = 0; i < count; i++) {
    auto buf = std::move(buffer_pool->Get());
    assert(buf);
    EXPECT_EQ(buf->GetSize(), i);
  }
}

void BackendThread(logging::WriteAheadBackendLogger *logger,
                   unsigned int count) {
  for (unsigned int i = 1; i <= count; i++) {
    logging::TransactionRecord begin_record(LOGRECORD_TYPE_TRANSACTION_COMMIT,
                                            i);
    logger->Log(&begin_record);
  }
}

void FrontendThread(logging::WriteAheadFrontendLogger *logger,
                    unsigned int count) {
  srand(time(NULL));
  while (true) {
    for (int i = 0; i < 10; i++) {
      logger->CollectLogRecordsFromBackendLoggers();
    }
    logger->FlushLogRecords();
    auto cid = logger->GetMaxFlushedCommitId();
    if (cid == count) {
      break;
    }
    int rand_num = rand() % 5 + 1;
    std::chrono::milliseconds sleep_time(rand_num);
    std::this_thread::sleep_for(sleep_time);
  }
}

TEST_F(BufferPoolTests, BufferPoolBasicTest) {
  logging::CircularBufferPool buffer_pool0;
  EnqueueTest(&buffer_pool0, 5);
  EXPECT_EQ(buffer_pool0.GetSize(), 5);

  DequeueTest(&buffer_pool0, 5);
  EXPECT_EQ(buffer_pool0.GetSize(), 0);

  EnqueueTest(&buffer_pool0, BUFFER_POOL_SIZE);
  EXPECT_EQ(buffer_pool0.GetSize(), BUFFER_POOL_SIZE);

  for (int i = 0; i < 10; i++) {
    logging::CircularBufferPool buffer_pool1;
    std::thread enqueue_thread(EnqueueTest, &buffer_pool1, BUFFER_POOL_SIZE);
    std::thread dequeue_thread(DequeueTest, &buffer_pool1, BUFFER_POOL_SIZE);
    enqueue_thread.join();
    dequeue_thread.join();
  }
}

TEST_F(BufferPoolTests, LogBufferBasicTest) {
  size_t tile_group_size = TESTS_TUPLES_PER_TILEGROUP;
  size_t table_tile_group_count = 3;

  std::unique_ptr<storage::DataTable> recovery_table(
      ExecutorTestsUtil::CreateTable(tile_group_size));

  // prepare tuples
  auto mutate = true;
  auto random = false;
  int num_rows = tile_group_size * table_tile_group_count;
  std::vector<std::shared_ptr<storage::Tuple>> tuples =
      LoggingTestsUtil::BuildTuples(recovery_table.get(), num_rows, mutate,
                                    random);
  std::vector<logging::TupleRecord> records =
      LoggingTestsUtil::BuildTupleRecords(tuples, tile_group_size,
                                          table_tile_group_count);
  logging::LogBuffer log_buffer(0);
  size_t total_length = 0;
  for (auto record : records) {
    assert(record.GetTuple()->GetSchema());
    CopySerializeOutput output_buffer;
    record.Serialize(output_buffer);
    size_t len = record.GetMessageLength();
    total_length += len;
    log_buffer.WriteRecord(&record);
  }
  EXPECT_EQ(log_buffer.GetSize(), total_length);
}

TEST_F(BufferPoolTests, BufferPoolConcurrentTest) {
  unsigned int txn_count = 1000000;

  auto &log_manager = logging::LogManager::GetInstance();
  logging::LogManager::Configure(LOGGING_TYPE_DRAM_NVM, true);
  log_manager.SetLoggingStatus(LOGGING_STATUS_TYPE_LOGGING);
  log_manager.InitFrontendLoggers();

  logging::WriteAheadFrontendLogger *frontend_logger =
      reinterpret_cast<logging::WriteAheadFrontendLogger *>(
          log_manager.GetFrontendLogger(0));
  logging::WriteAheadBackendLogger *backend_logger =
      reinterpret_cast<logging::WriteAheadBackendLogger *>(
          log_manager.GetBackendLogger());

  std::thread backend_thread(BackendThread, backend_logger, txn_count);
  std::thread frontend_thread(FrontendThread, frontend_logger, txn_count);
  backend_thread.join();
  frontend_thread.join();
}

}  // End test namespace
}  // End peloton namespace
<|endoftext|>


<commit_before>/*
    Copyright 2011 Google Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */

#include "gm.h"
#include "SkRandom.h"

namespace skiagm {

#define W   400
#define H   400
#define N   100

static const SkScalar SW = SkIntToScalar(W);
static const SkScalar SH = SkIntToScalar(H);

class StrokeRectGM : public GM {
public:
	StrokeRectGM() {}

protected:
    virtual SkString onShortName() {
        return SkString("strokerects");
    }

	virtual SkISize onISize() {
        return make_isize(W*2, H*2);
    }

    static void rnd_rect(SkRect* r, SkRandom& rand) {
        SkScalar x = rand.nextUScalar1() * W;
        SkScalar y = rand.nextUScalar1() * H;
        SkScalar w = rand.nextUScalar1() * (W >> 2);
        SkScalar h = rand.nextUScalar1() * (H >> 2);

        r->set(x, y, x + w, y + h);
        r->offset(-w/2 + rand.nextSScalar1(), -h/2 +  + rand.nextSScalar1());
    }

    virtual void onDraw(SkCanvas* canvas) {
        canvas->drawColor(SK_ColorWHITE);

        SkPaint paint;
        paint.setStyle(SkPaint::kStroke_Style);

        for (int y = 0; y < 2; y++) {
            paint.setAntiAlias(!!y);
            for (int x = 0; x < 2; x++) {
                paint.setStrokeWidth(x * SkIntToScalar(3));

                SkAutoCanvasRestore acr(canvas, true);
                canvas->translate(SW * x, SH * y);
                canvas->clipRect(SkRect::MakeLTRB(2, 2, SW - 2, SH - 2));

                SkRandom rand;
                for (int i = 0; i < N; i++) {
                    SkRect r;
                    rnd_rect(&r, rand);
                    canvas->drawRect(r, paint);
                }
            }
        }
    }

private:
    typedef GM INHERITED;
};

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

static GM* MyFactory(void*) { return new StrokeRectGM; }
static GMRegistry reg(MyFactory);

}

<commit_msg>Fix clipping in StrokeRectGM test for fixed point.<commit_after>/*
    Copyright 2011 Google Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */

#include "gm.h"
#include "SkRandom.h"

namespace skiagm {

#define W   400
#define H   400
#define N   100

static const SkScalar SW = SkIntToScalar(W);
static const SkScalar SH = SkIntToScalar(H);

class StrokeRectGM : public GM {
public:
	StrokeRectGM() {}

protected:
    virtual SkString onShortName() {
        return SkString("strokerects");
    }

	virtual SkISize onISize() {
        return make_isize(W*2, H*2);
    }

    static void rnd_rect(SkRect* r, SkRandom& rand) {
        SkScalar x = rand.nextUScalar1() * W;
        SkScalar y = rand.nextUScalar1() * H;
        SkScalar w = rand.nextUScalar1() * (W >> 2);
        SkScalar h = rand.nextUScalar1() * (H >> 2);

        r->set(x, y, x + w, y + h);
        r->offset(-w/2 + rand.nextSScalar1(), -h/2 +  + rand.nextSScalar1());
    }

    virtual void onDraw(SkCanvas* canvas) {
        canvas->drawColor(SK_ColorWHITE);

        SkPaint paint;
        paint.setStyle(SkPaint::kStroke_Style);

        for (int y = 0; y < 2; y++) {
            paint.setAntiAlias(!!y);
            for (int x = 0; x < 2; x++) {
                paint.setStrokeWidth(x * SkIntToScalar(3));

                SkAutoCanvasRestore acr(canvas, true);
                canvas->translate(SW * x, SH * y);
                canvas->clipRect(SkRect::MakeLTRB(SkIntToScalar(2), SkIntToScalar(2), SW - SkIntToScalar(2), SH - SkIntToScalar(2)));

                SkRandom rand;
                for (int i = 0; i < N; i++) {
                    SkRect r;
                    rnd_rect(&r, rand);
                    canvas->drawRect(r, paint);
                }
            }
        }
    }

private:
    typedef GM INHERITED;
};

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

static GM* MyFactory(void*) { return new StrokeRectGM; }
static GMRegistry reg(MyFactory);

}

<|endoftext|>


<commit_before>#include "catch.hpp"

#include <shadow.hpp>

class tmfapi1
{
public:
    tmfapi1() : public_value(0)
    {
    }

    tmfapi1(int i) : public_value(i)
    {
    }

    int public_value;

    void
    fun1()
    {
        public_value = 100;
    }

    void
    fun2(int i)
    {
        public_value = i;
    }

    int
    fun3() const
    {
        return 23;
    }

    int
    fun4(int i) const
    {
        return 2 * i;
    }

    void
    fun5(int& i)
    {
        i = 20000;
    }
};

namespace tmfapi_space
{
REGISTER_TYPE_BEGIN()
REGISTER_TYPE(tmfapi1)
REGISTER_TYPE_END()

REGISTER_MEMBER_FUNCTION(tmfapi1, fun1)
REGISTER_MEMBER_FUNCTION(tmfapi1, fun2)
REGISTER_MEMBER_FUNCTION(tmfapi1, fun3)
REGISTER_MEMBER_FUNCTION(tmfapi1, fun4)
REGISTER_MEMBER_FUNCTION(tmfapi1, fun5)

SHADOW_INIT()
}

TEST_CASE("set up shadow::variable containing a tmfapi object",
          "[reflection_manager]")
{
    auto test_obj = tmfapi_space::static_create<tmfapi1>(20);

    auto mem_fun_pair = test_obj.member_functions();

    SECTION("find fun1 and call it")
    {
        auto found = std::find_if(
            mem_fun_pair.first, mem_fun_pair.second, [](const auto& mf) {
                return mf.name() == std::string("fun1");
            });

        REQUIRE(found != mem_fun_pair.second);

        auto res = test_obj.call_member_function(*found);

        REQUIRE(res.type().name() == std::string("void"));
        REQUIRE(
            tmfapi_space::static_value_cast<tmfapi1>(test_obj).public_value ==
            100);
    }

    SECTION("find fun2 and call it")
    {
        auto found = std::find_if(
            mem_fun_pair.first, mem_fun_pair.second, [](const auto& mf) {
                return mf.name() == std::string("fun2");
            });

        REQUIRE(found != mem_fun_pair.second);

        shadow::variable args[] = {tmfapi_space::static_create<int>(55)};

        auto res = test_obj.call_member_function(
            *found, std::begin(args), std::end(args));

        REQUIRE(res.type().name() == std::string("void"));
        REQUIRE(
            tmfapi_space::static_value_cast<tmfapi1>(test_obj).public_value ==
            55);
    }

    SECTION("find fun3 and call it")
    {
        auto found = std::find_if(
            mem_fun_pair.first, mem_fun_pair.second, [](const auto& mf) {
                return mf.name() == std::string("fun3");
            });

        REQUIRE(found != mem_fun_pair.second);

        std::vector<shadow::variable> empty_args;

        auto res = test_obj.call_member_function(
            *found, empty_args.begin(), empty_args.end());

        REQUIRE(res.type().name() == std::string("int"));
        REQUIRE(tmfapi_space::static_value_cast<int>(res) == 23);
        REQUIRE(
            tmfapi_space::static_value_cast<tmfapi1>(test_obj).public_value ==
            20);
    }

    SECTION("find fun4 and call it")
    {
        auto found = std::find_if(
            mem_fun_pair.first, mem_fun_pair.second, [](const auto& mf) {
                return mf.name() == std::string("fun4");
            });

        REQUIRE(found != mem_fun_pair.second);

        std::vector<shadow::variable> args{
            tmfapi_space::static_create<int>(30)};

        auto res =
            test_obj.call_member_function(*found, args.begin(), args.end());

        REQUIRE(res.type().name() == std::string("int"));
        REQUIRE(tmfapi_space::static_value_cast<int>(res) == 60);
        REQUIRE(
            tmfapi_space::static_value_cast<tmfapi1>(test_obj).public_value ==
            20);
    }

    SECTION("find fun5 and call it")
    {
        auto found = std::find_if(
            mem_fun_pair.first, mem_fun_pair.second, [](const auto& mf) {
                return mf.name() == std::string("fun5");
            });

        REQUIRE(found != mem_fun_pair.second);

        auto arg = tmfapi_space::static_create<int>();

        auto res = test_obj.call_member_function(*found, &arg, &arg + 1);

        REQUIRE(res.type().name() == std::string("void"));
        REQUIRE(tmfapi_space::static_value_cast<int>(arg) == 20000);
    }
}
<commit_msg>Add more unit tests. 	modified:   tests/test_member_function_api.cpp<commit_after>#include "catch.hpp"

#include <list>
#include <shadow.hpp>

class tmfapi1
{
public:
    tmfapi1() : public_value(0)
    {
    }

    tmfapi1(int i) : public_value(i)
    {
    }

    int public_value;

    void
    fun1()
    {
        public_value = 100;
    }

    void
    fun2(int i)
    {
        public_value = i;
    }

    int
    fun3() const
    {
        return 23;
    }

    int
    fun4(int i) const
    {
        return 2 * i;
    }

    void
    fun5(int& i)
    {
        i = 20000;
    }

    double
    fun6(const int& i, const double& j)
    {
        return i * j;
    }
};

namespace tmfapi_space
{
REGISTER_TYPE_BEGIN()
REGISTER_TYPE(tmfapi1)
REGISTER_TYPE_END()

REGISTER_MEMBER_FUNCTION(tmfapi1, fun1)
REGISTER_MEMBER_FUNCTION(tmfapi1, fun2)
REGISTER_MEMBER_FUNCTION(tmfapi1, fun3)
REGISTER_MEMBER_FUNCTION(tmfapi1, fun4)
REGISTER_MEMBER_FUNCTION(tmfapi1, fun5)
REGISTER_MEMBER_FUNCTION(tmfapi1, fun6)

SHADOW_INIT()
}

TEST_CASE("set up shadow::variable containing a tmfapi object",
          "[reflection_manager]")
{
    auto test_obj = tmfapi_space::static_create<tmfapi1>(20);

    auto mem_fun_pair = test_obj.member_functions();

    SECTION("find fun1 and call it")
    {
        auto found = std::find_if(
            mem_fun_pair.first, mem_fun_pair.second, [](const auto& mf) {
                return mf.name() == std::string("fun1");
            });

        REQUIRE(found != mem_fun_pair.second);

        auto res = test_obj.call_member_function(*found);

        REQUIRE(res.type().name() == std::string("void"));
        REQUIRE(
            tmfapi_space::static_value_cast<tmfapi1>(test_obj).public_value ==
            100);
    }

    SECTION("find fun2 and call it")
    {
        auto found = std::find_if(
            mem_fun_pair.first, mem_fun_pair.second, [](const auto& mf) {
                return mf.name() == std::string("fun2");
            });

        REQUIRE(found != mem_fun_pair.second);

        shadow::variable args[] = {tmfapi_space::static_create<int>(55)};

        auto res = test_obj.call_member_function(
            *found, std::begin(args), std::end(args));

        REQUIRE(res.type().name() == std::string("void"));
        REQUIRE(
            tmfapi_space::static_value_cast<tmfapi1>(test_obj).public_value ==
            55);
    }

    SECTION("find fun3 and call it")
    {
        auto found = std::find_if(
            mem_fun_pair.first, mem_fun_pair.second, [](const auto& mf) {
                return mf.name() == std::string("fun3");
            });

        REQUIRE(found != mem_fun_pair.second);

        std::vector<shadow::variable> empty_args;

        auto res = test_obj.call_member_function(
            *found, empty_args.begin(), empty_args.end());

        REQUIRE(res.type().name() == std::string("int"));
        REQUIRE(tmfapi_space::static_value_cast<int>(res) == 23);
        REQUIRE(
            tmfapi_space::static_value_cast<tmfapi1>(test_obj).public_value ==
            20);
    }

    SECTION("find fun4 and call it")
    {
        auto found = std::find_if(
            mem_fun_pair.first, mem_fun_pair.second, [](const auto& mf) {
                return mf.name() == std::string("fun4");
            });

        REQUIRE(found != mem_fun_pair.second);

        std::vector<shadow::variable> args{
            tmfapi_space::static_create<int>(30)};

        auto res =
            test_obj.call_member_function(*found, args.begin(), args.end());

        REQUIRE(res.type().name() == std::string("int"));
        REQUIRE(tmfapi_space::static_value_cast<int>(res) == 60);
        REQUIRE(
            tmfapi_space::static_value_cast<tmfapi1>(test_obj).public_value ==
            20);
    }

    SECTION("find fun5 and call it")
    {
        auto found = std::find_if(
            mem_fun_pair.first, mem_fun_pair.second, [](const auto& mf) {
                return mf.name() == std::string("fun5");
            });

        REQUIRE(found != mem_fun_pair.second);

        auto arg = tmfapi_space::static_create<int>();

        auto res = test_obj.call_member_function(*found, &arg, &arg + 1);

        REQUIRE(res.type().name() == std::string("void"));
        REQUIRE(tmfapi_space::static_value_cast<int>(arg) == 20000);
    }

    SECTION("find fun6 and call it")
    {
        auto found = std::find_if(
            mem_fun_pair.first, mem_fun_pair.second, [](const auto& mf) {
                return mf.name() == std::string("fun6");
            });

        REQUIRE(found != mem_fun_pair.second);

        std::list<shadow::variable> args{
            tmfapi_space::static_create<int>(2),
            tmfapi_space::static_create<double>(10.0)};

        auto res =
            test_obj.call_member_function(*found, args.begin(), args.end());

        REQUIRE(res.type().name() == std::string("double"));
        REQUIRE(tmfapi_space::static_value_cast<double>(res) == Approx(20.0));
        REQUIRE(tmfapi_space::static_value_cast<int>(args.front()) == 2);
        REQUIRE(tmfapi_space::static_value_cast<double>(args.back()) == 10.0);
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2019, Arm Limited and affiliates.
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "QUECTEL_EC2X.h"

#include "PinNames.h"
#include "AT_CellularNetwork.h"
#include "rtos/ThisThread.h"
#include "UARTSerial.h"

using namespace mbed;
using namespace rtos;
using namespace events;

#if !defined(MBED_CONF_QUECTEL_EC2X_PWR)
#define MBED_CONF_QUECTEL_EC2X_PWR    NC
#endif

#if !defined(MBED_CONF_QUECTEL_EC2X_RST)
#define MBED_CONF_QUECTEL_EC2X_RST    NC
#endif

#if !defined(MBED_CONF_QUECTEL_EC2X_TX)
#define MBED_CONF_QUECTEL_EC2X_TX    NC
#endif

#if !defined(MBED_CONF_QUECTEL_EC2X_RX)
#define MBED_CONF_QUECTEL_EC2X_RX    NC
#endif

#if !defined(MBED_CONF_QUECTEL_EC2X_POLARITY)
#define MBED_CONF_QUECTEL_EC2X_POLARITY    1 // active high
#endif

static const intptr_t cellular_properties[AT_CellularBase::PROPERTY_MAX] = {
    AT_CellularNetwork::RegistrationModeLAC,    // C_EREG
    AT_CellularNetwork::RegistrationModeLAC,    // C_GREG
    AT_CellularNetwork::RegistrationModeLAC,    // C_REG
    0,  // AT_CGSN_WITH_TYPE
    1,  // AT_CGDATA
    0,  // AT_CGAUTH
    1,  // AT_CNMI
    1,  // AT_CSMP
    1,  // AT_CMGF
    1,  // AT_CSDH
    1,  // PROPERTY_IPV4_STACK
    1,  // PROPERTY_IPV6_STACK
    1,  // PROPERTY_IPV4V6_STACK
    0,  // PROPERTY_NON_IP_PDP_TYPE
    1,  // PROPERTY_AT_CGEREP
};

QUECTEL_EC2X::QUECTEL_EC2X(FileHandle *fh, PinName pwr, bool active_high, PinName rst)
    : AT_CellularDevice(fh),
      _active_high(active_high),
      _pwr_key(pwr, !_active_high),
      _rst(rst, !_active_high)
{
    AT_CellularBase::set_cellular_properties(cellular_properties);
}

CellularDevice *CellularDevice::get_default_instance()
{
    static UARTSerial serial(MBED_CONF_QUECTEL_EC2X_TX,
                             MBED_CONF_QUECTEL_EC2X_RX,
                             MBED_CONF_QUECTEL_EC2X_BAUDRATE);
#if defined(MBED_CONF_QUECTEL_EC2X_RTS) && defined(MBED_CONF_QUECTEL_EC2X_CTS)
    serial.set_flow_control(SerialBase::RTSCTS, MBED_CONF_QUECTEL_EC2X_RTS, MBED_CONF_QUECTEL_EC2X_CTS);
#endif
    static QUECTEL_EC2X device(&serial,
                               MBED_CONF_QUECTEL_EC2X_PWR,
                               MBED_CONF_QUECTEL_EC2X_POLARITY,
                               MBED_CONF_QUECTEL_EC2X_RST);
    return &device;
}

nsapi_error_t QUECTEL_EC2X::press_power_button(uint32_t timeout)
{
    _pwr_key = _active_high;
    ThisThread::sleep_for(timeout);
    _pwr_key = !_active_high;
    ThisThread::sleep_for(100);

    return NSAPI_ERROR_OK;
}

nsapi_error_t QUECTEL_EC2X::hard_power_on()
{
    return press_power_button(600);
}

nsapi_error_t QUECTEL_EC2X::hard_power_off()

{
    return press_power_button(750);
}

nsapi_error_t QUECTEL_EC2X::soft_power_on()
{
    if (_rst.is_connected()) {
        _rst = _active_high;
        ThisThread::sleep_for(460);
        _rst = !_active_high;
        ThisThread::sleep_for(100);

        _at->lock();

        _at->set_at_timeout(5000);
        _at->resp_start();
        _at->set_stop_tag("RDY");
        bool rdy = _at->consume_to_stop_tag();
        _at->set_stop_tag(OK);

        _at->unlock();

        if (!rdy) {
            return NSAPI_ERROR_DEVICE_ERROR;
        }
    }

    return NSAPI_ERROR_OK;
}

nsapi_error_t QUECTEL_EC2X::soft_power_off()
{
    return hard_power_off();
}
<commit_msg>Flagging WEAK method implementation for default construction<commit_after>/*
 * Copyright (c) 2019, Arm Limited and affiliates.
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "QUECTEL_EC2X.h"

#include "PinNames.h"
#include "AT_CellularNetwork.h"
#include "rtos/ThisThread.h"
#include "UARTSerial.h"

using namespace mbed;
using namespace rtos;
using namespace events;

#if !defined(MBED_CONF_QUECTEL_EC2X_PWR)
#define MBED_CONF_QUECTEL_EC2X_PWR    NC
#endif

#if !defined(MBED_CONF_QUECTEL_EC2X_RST)
#define MBED_CONF_QUECTEL_EC2X_RST    NC
#endif

#if !defined(MBED_CONF_QUECTEL_EC2X_TX)
#define MBED_CONF_QUECTEL_EC2X_TX    NC
#endif

#if !defined(MBED_CONF_QUECTEL_EC2X_RX)
#define MBED_CONF_QUECTEL_EC2X_RX    NC
#endif

#if !defined(MBED_CONF_QUECTEL_EC2X_POLARITY)
#define MBED_CONF_QUECTEL_EC2X_POLARITY    1 // active high
#endif

static const intptr_t cellular_properties[AT_CellularBase::PROPERTY_MAX] = {
    AT_CellularNetwork::RegistrationModeLAC,    // C_EREG
    AT_CellularNetwork::RegistrationModeLAC,    // C_GREG
    AT_CellularNetwork::RegistrationModeLAC,    // C_REG
    0,  // AT_CGSN_WITH_TYPE
    1,  // AT_CGDATA
    0,  // AT_CGAUTH
    1,  // AT_CNMI
    1,  // AT_CSMP
    1,  // AT_CMGF
    1,  // AT_CSDH
    1,  // PROPERTY_IPV4_STACK
    1,  // PROPERTY_IPV6_STACK
    1,  // PROPERTY_IPV4V6_STACK
    0,  // PROPERTY_NON_IP_PDP_TYPE
    1,  // PROPERTY_AT_CGEREP
};

QUECTEL_EC2X::QUECTEL_EC2X(FileHandle *fh, PinName pwr, bool active_high, PinName rst)
    : AT_CellularDevice(fh),
      _active_high(active_high),
      _pwr_key(pwr, !_active_high),
      _rst(rst, !_active_high)
{
    AT_CellularBase::set_cellular_properties(cellular_properties);
}

#if MBED_CONF_QUECTEL_EC2X_PROVIDE_DEFAULT
CellularDevice *CellularDevice::get_default_instance()
{
    static UARTSerial serial(MBED_CONF_QUECTEL_EC2X_TX,
                             MBED_CONF_QUECTEL_EC2X_RX,
                             MBED_CONF_QUECTEL_EC2X_BAUDRATE);
#if defined(MBED_CONF_QUECTEL_EC2X_RTS) && defined(MBED_CONF_QUECTEL_EC2X_CTS)
    serial.set_flow_control(SerialBase::RTSCTS, MBED_CONF_QUECTEL_EC2X_RTS, MBED_CONF_QUECTEL_EC2X_CTS);
#endif
    static QUECTEL_EC2X device(&serial,
                               MBED_CONF_QUECTEL_EC2X_PWR,
                               MBED_CONF_QUECTEL_EC2X_POLARITY,
                               MBED_CONF_QUECTEL_EC2X_RST);
    return &device;
}
#endif

nsapi_error_t QUECTEL_EC2X::press_power_button(uint32_t timeout)
{
    _pwr_key = _active_high;
    ThisThread::sleep_for(timeout);
    _pwr_key = !_active_high;
    ThisThread::sleep_for(100);

    return NSAPI_ERROR_OK;
}

nsapi_error_t QUECTEL_EC2X::hard_power_on()
{
    return press_power_button(600);
}

nsapi_error_t QUECTEL_EC2X::hard_power_off()

{
    return press_power_button(750);
}

nsapi_error_t QUECTEL_EC2X::soft_power_on()
{
    if (_rst.is_connected()) {
        _rst = _active_high;
        ThisThread::sleep_for(460);
        _rst = !_active_high;
        ThisThread::sleep_for(100);

        _at->lock();

        _at->set_at_timeout(5000);
        _at->resp_start();
        _at->set_stop_tag("RDY");
        bool rdy = _at->consume_to_stop_tag();
        _at->set_stop_tag(OK);

        _at->unlock();

        if (!rdy) {
            return NSAPI_ERROR_DEVICE_ERROR;
        }
    }

    return NSAPI_ERROR_OK;
}

nsapi_error_t QUECTEL_EC2X::soft_power_off()
{
    return hard_power_off();
}
<|endoftext|>


<commit_before>
#pragma once

#include "numerics/fast_sin_cos_2π.hpp"

#include <pmmintrin.h>

#include "base/macros.hpp"
#include "numerics/polynomial.hpp"
#include "numerics/polynomial_evaluators.hpp"

namespace principia {
namespace numerics {

namespace {

using P2 = PolynomialInMonomialBasis</*Value=*/double,
                                     /*Argument=*/double,
                                     /*degree=*/2,
                                     /*Evaluator=*/EstrinEvaluator>;

using P3 = PolynomialInMonomialBasis</*Value=*/double,
                                     /*Argument=*/double,
                                     /*degree=*/3,
                                     /*Evaluator=*/EstrinEvaluator>;

// 2nd-degree polynomials that minimize the absolute error on sin and cos over
// the interval [0, 1/8].  The minimization algorithm is run on
// Sin(2 π √x)/√x and (Cos(2 π √x) - 1)/x to ensure that the functions have
// the right behavior near 0 and the proper parity.  Because of extra
// oscillations, the lower bounds of the minimization intervals are 1/36 and
// 1/24 respectively.  This is where the maximum error is found.
P2 sin_polynomial(P2::Coefficients{6.28315387593158874093559349802,
                                   -41.3255673715186216778612605095,
                                   79.5314110676979262924240784281});
P3 cos_polynomial(P3::Coefficients{1.0,
                                   -19.7391672615468690589481752820,
                                   64.9232282990046449731568966307,
                                   -83.6659064641344641438100039739});

struct Decomposition {
  std::int64_t integer_part;
  double fractional_part;
};

Decomposition Decompose(double const x) {
  Decomposition decomposition;
#if PRINCIPIA_USE_SSE3_INTRINSICS
  __m128d const x_128d = _mm_set_sd(x);
  decomposition.integer_part = _mm_cvtsd_si64(x_128d);
  decomposition.fractional_part = _mm_cvtsd_f64(
      _mm_sub_sd(x_128d,
                 _mm_cvtsi64_sd(__m128d{}, decomposition.integer_part)));
#else
  decomposition.integer_part = std::nearbyint(x);
  decomposition.fractional_part = x - decomposition.integer_part;
#endif
  return decomposition;
}

}  // namespace

void FastSinCos2π(double cycles, double& sin, double& cos) {
  // Argument reduction.  cycles_reduced is in [-1/8, 1/8] and quadrant goes
  // from 0 to 3, with 0 indicating the principal quadrant and the others
  // numbered in the trigonometric direction.  These quantities are computed by
  // extracting the integer and fractional parts of 4 * cycles.
  Decomposition const decomposition = Decompose(4.0 * cycles);
  double const cycles_reduced = 0.25 * decomposition.fractional_part;
  std::int64_t const quadrant = decomposition.integer_part & 0b11;

  double const cycles_reduced² = cycles_reduced * cycles_reduced;
  double const s = sin_polynomial.Evaluate(cycles_reduced²) * cycles_reduced;
  double const c = cos_polynomial.Evaluate(cycles_reduced²);

  switch (quadrant) {
    case 0:
      sin = s;
      cos = c;
      break;
    case 1:
      sin = c;
      cos = -s;
      break;
    case 2:
      sin = -s;
      cos = -c;
      break;
    case 3:
      sin = -c;
      cos = s;
      break;
  }
}

}  // namespace numerics
}  // namespace principia
<commit_msg>fold the multiplication by 1/4 into the polynomials; IACA: 55 cycles -> 50 cycles, 17588 ns -> 16238 ns<commit_after>
#pragma once

#include "numerics/fast_sin_cos_2π.hpp"

#include <intrin.h>
#include <pmmintrin.h>
//#include <Intel/IACA 2.1/iacaMarks.h>
#define VOLATILE
#define IACA_VC64_START
#define IACA_VC64_END

#include "base/macros.hpp"
#include "numerics/polynomial.hpp"
#include "numerics/polynomial_evaluators.hpp"

namespace principia {
namespace numerics {

namespace {

using P2 = PolynomialInMonomialBasis</*Value=*/double,
                                     /*Argument=*/double,
                                     /*degree=*/2,
                                     /*Evaluator=*/EstrinEvaluator>;

using P3 = PolynomialInMonomialBasis</*Value=*/double,
                                     /*Argument=*/double,
                                     /*degree=*/3,
                                     /*Evaluator=*/EstrinEvaluator>;

// 2nd-degree polynomials that minimize the absolute error on sin and cos over
// the interval [0, 1/8].  The minimization algorithm is run on
// Sin(2 π √x)/√x and (Cos(2 π √x) - 1)/x to ensure that the functions have
// the right behavior near 0 and the proper parity.  Because of extra
// oscillations, the lower bounds of the minimization intervals are 1/36 and
// 1/24 respectively.  This is where the maximum error is found.
P2 sin_polynomial(P2::Coefficients{6.28315387593158874093559349802 / 4,
                                   -41.3255673715186216778612605095 / (4 * 16),
                                   79.5314110676979262924240784281 / (4 * 16 * 16)});
P3 cos_polynomial(P3::Coefficients{1.0,
                                   -19.7391672615468690589481752820 / 16,
                                   64.9232282990046449731568966307 / (16 * 16),
                                   -83.6659064641344641438100039739 / (16 * 16 * 16)});

struct Decomposition {
  std::int64_t integer_part;
  double fractional_part;
};

Decomposition Decompose(double const x) {
  Decomposition decomposition;
#if PRINCIPIA_USE_SSE3_INTRINSICS
  __m128d const x_128d = _mm_set_sd(x);
  decomposition.integer_part = _mm_cvtsd_si64(x_128d);
  decomposition.fractional_part = _mm_cvtsd_f64(
      _mm_sub_sd(x_128d,
                 _mm_cvtsi64_sd(__m128d{}, decomposition.integer_part)));
#else
  decomposition.integer_part = std::nearbyint(x);
  decomposition.fractional_part = x - decomposition.integer_part;
#endif
  return decomposition;
}

}  // namespace

void FastSinCos2π(double cycles, double& sin, double& cos) {
  VOLATILE double vcycles = cycles;
  IACA_VC64_START
  // Argument reduction.  cycles_reduced is in [-1/8, 1/8] and quadrant goes
  // from 0 to 3, with 0 indicating the principal quadrant and the others
  // numbered in the trigonometric direction.  These quantities are computed by
  // extracting the integer and fractional parts of 4 * cycles.
  Decomposition const decomposition = Decompose(4.0 * vcycles);
  double const cycles_reduced = decomposition.fractional_part;
  double const cycles_reduced² = cycles_reduced * cycles_reduced;
  std::int64_t const quadrant = decomposition.integer_part & 0b11;

  double const s = sin_polynomial.Evaluate(cycles_reduced²) * cycles_reduced;
  double const c = cos_polynomial.Evaluate(cycles_reduced²);

  VOLATILE double const vs = s;
  VOLATILE double const vc = c;

  IACA_VC64_END
  switch (quadrant) {
    case 0:
      sin = vs;
      cos = vc;
      break;
    case 1:
      sin = c;
      cos = -s;
      break;
    case 2:
      sin = -s;
      cos = -c;
      break;
    case 3:
      sin = -c;
      cos = s;
      break;
  }
}

}  // namespace numerics
}  // namespace principia
<|endoftext|>


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

#include <ydk/crud_service.hpp>
#include <ydk/netconf_provider.hpp>
#include <ydk/path_api.hpp>
#include <ydk/types.hpp>

#include <iostream>
#include <spdlog/spdlog.h>

#include "ydk.h"

using namespace std;

//////////////////////////////////////////////////////////////////////////
// structs
//////////////////////////////////////////////////////////////////////////
typedef struct RpcWrapper
{
    RpcWrapper(shared_ptr<ydk::path::Rpc> rpc)
        : priv(rpc)
    {
    }

    shared_ptr<ydk::path::Rpc> priv;
} RpcWrapper;

typedef struct DataNodeWrapper
{
    DataNodeWrapper(shared_ptr<ydk::path::DataNode> data)
        : priv(data)
    {
    }

    shared_ptr<ydk::path::DataNode> priv;
} DataNodeWrapper;

//////////////////////////////////////////////////////////////////////////
// Utility functions
//////////////////////////////////////////////////////////////////////////
static DataNodeWrapper* wrap(ydk::path::DataNode* datanode)
{
    return (new DataNodeWrapper(shared_ptr<ydk::path::DataNode>(datanode)));
}

static DataNodeWrapper* wrap(shared_ptr<ydk::path::DataNode> datanode)
{
    return (new DataNodeWrapper(datanode));
}

static ydk::path::DataNode* unwrap(DataNodeWrapper* datanode_wrapper)
{
    return datanode_wrapper->priv.get();
}

static RpcWrapper* wrap(shared_ptr<ydk::path::Rpc> rpc)
{
    return (new RpcWrapper(rpc));
}

static ydk::path::Rpc* unwrap(RpcWrapper* rpc_wrapper)
{
    return rpc_wrapper->priv.get();
}

static ydk::EncodingFormat get_real_encoding(EncodingFormat encoding)
{
    switch(encoding)
    {
        case XML:
            return ydk::EncodingFormat::XML;
        case JSON:
                return ydk::EncodingFormat::JSON;
    }
}

static const char* string_to_array(const string & str)
{
    char * cstr = new char [str.length()+1];
    std::strcpy (cstr, str.c_str());
    return cstr;
}

//////////////////////////////////////////////////////////////////////////
// Exported functions
//////////////////////////////////////////////////////////////////////////

Repository RepositoryInitWithPath(const char* path)
{
    ydk::path::Repository* real_repo = new ydk::path::Repository(path);
    return static_cast<void*>(real_repo);
}

Repository RepositoryInit()
{
    ydk::path::Repository* real_repo = new ydk::path::Repository();
    return static_cast<void*>(real_repo);
}

void RepositoryFree(Repository repo)
{
    ydk::path::Repository* real_repo = static_cast<ydk::path::Repository*>(repo);
    if(real_repo != NULL)
    {
        delete real_repo;
    }
}

ServiceProvider NetconfServiceProviderInit(const char * address, const char * username, const char * password, int port)
{
    try
    {
        ydk::NetconfServiceProvider * real_provider = new ydk::NetconfServiceProvider(address, username, password, port);
        return static_cast<void*>(real_provider);
    }
    catch(...)
    {
        return NULL;
    }
}

ServiceProvider NetconfServiceProviderInitWithRepo(Repository repo, const char * address, const char * username, const char * password, int port)
{
    try
    {
        ydk::path::Repository* real_repo = static_cast<ydk::path::Repository*>(repo);
        ydk::NetconfServiceProvider * real_provider = new ydk::NetconfServiceProvider(*real_repo, address, username, password, port);
        return static_cast<void*>(real_provider);
    }
    catch(...)
    {
        return NULL;
    }
}

void NetconfServiceProviderFree(ServiceProvider provider)
{
    ydk::NetconfServiceProvider * real_provider = static_cast<ydk::NetconfServiceProvider*>(provider);
    if(real_provider != NULL)
    {
        delete real_provider;
    }
}

RootSchemaNode ServiceProviderGetRootSchema(ServiceProvider provider)
{
    try
    {
    ydk::path::ServiceProvider * real_provider = static_cast<ydk::path::ServiceProvider*>(provider);
    ydk::path::RootSchemaNode* root_schema = &real_provider->get_root_schema();
    return static_cast<void*>(root_schema);
    }
    catch(...)
    {
        return NULL;
    }
}

CodecService CodecServiceInit(void)
{
    ydk::path::CodecService * codec = new ydk::path::CodecService();
    return static_cast<void*>(codec);
}

void CodecServiceFree(CodecService codec)
{
    ydk::path::CodecService * real_codec = (ydk::path::CodecService*)codec;
    if(real_codec != NULL)
    {
        delete real_codec;
    }
}

const char* CodecServiceEncode(CodecService codec, DataNode datanode, EncodingFormat encoding, boolean pretty)
{
    try
    {
        ydk::path::CodecService * real_codec = (ydk::path::CodecService*)codec;
        DataNodeWrapper* datanode_wrapper = (DataNodeWrapper*)datanode;
        ydk::path::DataNode* real_datanode = unwrap(datanode_wrapper);

        std::string payload = real_codec->encode(*real_datanode, get_real_encoding(encoding), pretty);
        return string_to_array(payload);
    }
    catch(...)
    {
        return NULL;
    }
}

DataNode CodecServiceDecode(CodecService codec, RootSchemaNode root_schema, const char* payload, EncodingFormat encoding)
{
    try
    {
        ydk::path::CodecService * real_codec = (ydk::path::CodecService*)codec;
        ydk::path::RootSchemaNode * real_root_schema = (ydk::path::RootSchemaNode*)root_schema;
        shared_ptr<ydk::path::DataNode> datanode = real_codec->decode(*real_root_schema, payload, get_real_encoding(encoding));

        return static_cast<void*>(wrap(datanode));
    }
    catch(...)
    {
        return NULL;
    }
}

DataNode RootSchemaNodeCreate(RootSchemaNode root_schema, const char* path)
{
    try
    {
        ydk::path::RootSchemaNode * real_root_schema = (ydk::path::RootSchemaNode*)root_schema;
        ydk::path::DataNode * datanode = &real_root_schema->create(path);

        return static_cast<void*>(wrap(datanode));
    }
    catch(...)
    {
        return NULL;
    }
}

Rpc RootSchemaNodeRpc(RootSchemaNode root_schema, const char* path)
{
    try
    {
        ydk::path::RootSchemaNode * real_root_schema = (ydk::path::RootSchemaNode*)root_schema;
        shared_ptr<ydk::path::Rpc> rpc = real_root_schema->rpc(path);

        return static_cast<void*>(wrap(rpc));
    }
    catch(...)
    {
        return NULL;
    }
}

DataNode RpcInput(Rpc rpc)
{
    try
    {
        RpcWrapper* rpc_wrapper = (RpcWrapper*)rpc;
        ydk::path::Rpc* real_rpc = unwrap(rpc_wrapper);

        ydk::path::DataNode * input = &real_rpc->input();

        return static_cast<void*>(wrap(input));
    }
    catch(...)
    {
        return NULL;
    }
}

DataNode RpcExecute(Rpc rpc, ServiceProvider provider)
{
    try
    {
        RpcWrapper* rpc_wrapper = (RpcWrapper*)rpc;
        ydk::path::Rpc* real_rpc = unwrap(rpc_wrapper);

        ydk::path::ServiceProvider * real_provider = (ydk::path::ServiceProvider *) provider;
        std::shared_ptr<ydk::path::DataNode> result = (*real_rpc)(*real_provider);

        return static_cast<void*>(wrap(result));
    }
    catch(...)
    {
        return NULL;
    }
}

DataNode DataNodeCreate(DataNode datanode, const char* path, const char* value)
{
    try
    {
        DataNodeWrapper* datanode_wrapper = (DataNodeWrapper*)datanode;
        ydk::path::DataNode* real_datanode = unwrap(datanode_wrapper);
        ydk::path::DataNode * result = &real_datanode->create(path, value);

        return static_cast<void*>(wrap(result));
    }
    catch(...)
    {
        return NULL;
    }
}

const char* DataNodeGetArgument(DataNode datanode)
{
    DataNodeWrapper* datanode_wrapper = (DataNodeWrapper*)datanode;
    ydk::path::DataNode* real_datanode = unwrap(datanode_wrapper);
    string s = real_datanode->schema().statement().arg;
    return string_to_array(s);
}

const char* DataNodeGetKeyword(DataNode datanode)
{
    DataNodeWrapper* datanode_wrapper = (DataNodeWrapper*)datanode;
    ydk::path::DataNode* real_datanode = unwrap(datanode_wrapper);
    string s = real_datanode->schema().statement().keyword;
    return string_to_array(s);
}

const char* DataNodeGetPath(DataNode datanode)
{
    DataNodeWrapper* datanode_wrapper = (DataNodeWrapper*)datanode;
    ydk::path::DataNode* real_datanode = unwrap(datanode_wrapper);
    string s = real_datanode->path();
    return string_to_array(s);
}

const char* DataNodeGetValue(DataNode datanode)
{
    DataNodeWrapper* datanode_wrapper = (DataNodeWrapper*)datanode;
    ydk::path::DataNode* real_datanode = unwrap(datanode_wrapper);
    string s = real_datanode->get();
    return string_to_array(s);
}

DataNodeChildren DataNodeGetChildren(DataNode datanode)
{
    DataNodeWrapper* datanode_wrapper = (DataNodeWrapper*)datanode;
    ydk::path::DataNode* real_datanode = unwrap(datanode_wrapper);

    std::vector<shared_ptr<ydk::path::DataNode>> children = real_datanode->children();
    DataNode* child_array = new DataNode[children.size()];
    for(size_t i=0; i < children.size(); i++)
    {
        child_array[i] = wrap(children[i]);
    }
    return {child_array, static_cast<int>(children.size())};
}

void DataNodeAddAnnotation(DataNode datanode, const char* operation)
{
    string oper{operation};
    if(oper.size() == 0)
    {
        return;
    }
    DataNodeWrapper* datanode_wrapper = (DataNodeWrapper*)datanode;
    ydk::path::DataNode* real_datanode = unwrap(datanode_wrapper);
    ydk::path::Annotation annotation{"ietf-netconf", "operation", operation};
    real_datanode->add_annotation(annotation);
}

DataNode DataNodeGetParent(DataNode datanode)
{
    DataNodeWrapper* datanode_wrapper = (DataNodeWrapper*)datanode;
    ydk::path::DataNode* real_datanode = unwrap(datanode_wrapper);
    ydk::path::DataNode* parent = real_datanode->parent();
    return static_cast<void*>(wrap(parent));
}

void EnableLogging(LogLevel level)
{
    auto console = spdlog::stdout_color_mt("ydk");
    switch(level)
    {
        case DEBUG:
            console->set_level(spdlog::level::debug);
            return;

        case INFO:
            console->set_level(spdlog::level::info);
            return;

        case WARNING:
            console->set_level(spdlog::level::warn);
            return;

        case ERROR:
            console->set_level(spdlog::level::err);
            return;

        case OFF:
            console->set_level(spdlog::level::off);
            return;
    }
}

LogLevel GetLoggingLevel(void)
{
    auto console = spdlog::get("ydk");
    if(console == nullptr)
    {
        return OFF;
    }

    auto level = console->level();
    switch(level)
    {
        case spdlog::level::off:
            return OFF;
        case spdlog::level::trace:
        case spdlog::level::debug:
            return DEBUG;

        case spdlog::level::info:
            return INFO;

        case spdlog::level::warn:
            return WARNING;

        case spdlog::level::critical:
        case spdlog::level::err:
            return ERROR;
    }
}
<commit_msg>Update ydk.cpp<commit_after>//////////////////////////////////////////////////////////////////
// @file ydk.cpp
//
// YANG Development Kit
// Copyright 2017 Cisco Systems. All rights reserved
//
////////////////////////////////////////////////////////////////
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//
//////////////////////////////////////////////////////////////////

#include "crud_service.hpp"
#include "netconf_provider.hpp"
#include "path_api.hpp"
#include "types.hpp"

#include <iostream>
#include <spdlog/spdlog.h>

#include "ydk.h"

using namespace std;

//////////////////////////////////////////////////////////////////////////
// structs
//////////////////////////////////////////////////////////////////////////
typedef struct RpcWrapper
{
    RpcWrapper(shared_ptr<ydk::path::Rpc> rpc)
        : priv(rpc)
    {
    }

    shared_ptr<ydk::path::Rpc> priv;
} RpcWrapper;

typedef struct DataNodeWrapper
{
    DataNodeWrapper(shared_ptr<ydk::path::DataNode> data)
        : priv(data)
    {
    }

    shared_ptr<ydk::path::DataNode> priv;
} DataNodeWrapper;

//////////////////////////////////////////////////////////////////////////
// Utility functions
//////////////////////////////////////////////////////////////////////////
static DataNodeWrapper* wrap(ydk::path::DataNode* datanode)
{
    return (new DataNodeWrapper(shared_ptr<ydk::path::DataNode>(datanode)));
}

static DataNodeWrapper* wrap(shared_ptr<ydk::path::DataNode> datanode)
{
    return (new DataNodeWrapper(datanode));
}

static ydk::path::DataNode* unwrap(DataNodeWrapper* datanode_wrapper)
{
    return datanode_wrapper->priv.get();
}

static RpcWrapper* wrap(shared_ptr<ydk::path::Rpc> rpc)
{
    return (new RpcWrapper(rpc));
}

static ydk::path::Rpc* unwrap(RpcWrapper* rpc_wrapper)
{
    return rpc_wrapper->priv.get();
}

static ydk::EncodingFormat get_real_encoding(EncodingFormat encoding)
{
    switch(encoding)
    {
        case XML:
            return ydk::EncodingFormat::XML;
        case JSON:
                return ydk::EncodingFormat::JSON;
    }
}

static const char* string_to_array(const string & str)
{
    char * cstr = new char [str.length()+1];
    std::strcpy (cstr, str.c_str());
    return cstr;
}

//////////////////////////////////////////////////////////////////////////
// Exported functions
//////////////////////////////////////////////////////////////////////////

Repository RepositoryInitWithPath(const char* path)
{
    ydk::path::Repository* real_repo = new ydk::path::Repository(path);
    return static_cast<void*>(real_repo);
}

Repository RepositoryInit()
{
    ydk::path::Repository* real_repo = new ydk::path::Repository();
    return static_cast<void*>(real_repo);
}

void RepositoryFree(Repository repo)
{
    ydk::path::Repository* real_repo = static_cast<ydk::path::Repository*>(repo);
    if(real_repo != NULL)
    {
        delete real_repo;
    }
}

ServiceProvider NetconfServiceProviderInit(const char * address, const char * username, const char * password, int port)
{
    try
    {
        ydk::NetconfServiceProvider * real_provider = new ydk::NetconfServiceProvider(address, username, password, port);
        return static_cast<void*>(real_provider);
    }
    catch(...)
    {
        return NULL;
    }
}

ServiceProvider NetconfServiceProviderInitWithRepo(Repository repo, const char * address, const char * username, const char * password, int port)
{
    try
    {
        ydk::path::Repository* real_repo = static_cast<ydk::path::Repository*>(repo);
        ydk::NetconfServiceProvider * real_provider = new ydk::NetconfServiceProvider(*real_repo, address, username, password, port);
        return static_cast<void*>(real_provider);
    }
    catch(...)
    {
        return NULL;
    }
}

void NetconfServiceProviderFree(ServiceProvider provider)
{
    ydk::NetconfServiceProvider * real_provider = static_cast<ydk::NetconfServiceProvider*>(provider);
    if(real_provider != NULL)
    {
        delete real_provider;
    }
}

RootSchemaNode ServiceProviderGetRootSchema(ServiceProvider provider)
{
    try
    {
    ydk::path::ServiceProvider * real_provider = static_cast<ydk::path::ServiceProvider*>(provider);
    ydk::path::RootSchemaNode* root_schema = &real_provider->get_root_schema();
    return static_cast<void*>(root_schema);
    }
    catch(...)
    {
        return NULL;
    }
}

CodecService CodecServiceInit(void)
{
    ydk::path::CodecService * codec = new ydk::path::CodecService();
    return static_cast<void*>(codec);
}

void CodecServiceFree(CodecService codec)
{
    ydk::path::CodecService * real_codec = (ydk::path::CodecService*)codec;
    if(real_codec != NULL)
    {
        delete real_codec;
    }
}

const char* CodecServiceEncode(CodecService codec, DataNode datanode, EncodingFormat encoding, boolean pretty)
{
    try
    {
        ydk::path::CodecService * real_codec = (ydk::path::CodecService*)codec;
        DataNodeWrapper* datanode_wrapper = (DataNodeWrapper*)datanode;
        ydk::path::DataNode* real_datanode = unwrap(datanode_wrapper);

        std::string payload = real_codec->encode(*real_datanode, get_real_encoding(encoding), pretty);
        return string_to_array(payload);
    }
    catch(...)
    {
        return NULL;
    }
}

DataNode CodecServiceDecode(CodecService codec, RootSchemaNode root_schema, const char* payload, EncodingFormat encoding)
{
    try
    {
        ydk::path::CodecService * real_codec = (ydk::path::CodecService*)codec;
        ydk::path::RootSchemaNode * real_root_schema = (ydk::path::RootSchemaNode*)root_schema;
        shared_ptr<ydk::path::DataNode> datanode = real_codec->decode(*real_root_schema, payload, get_real_encoding(encoding));

        return static_cast<void*>(wrap(datanode));
    }
    catch(...)
    {
        return NULL;
    }
}

DataNode RootSchemaNodeCreate(RootSchemaNode root_schema, const char* path)
{
    try
    {
        ydk::path::RootSchemaNode * real_root_schema = (ydk::path::RootSchemaNode*)root_schema;
        ydk::path::DataNode * datanode = &real_root_schema->create(path);

        return static_cast<void*>(wrap(datanode));
    }
    catch(...)
    {
        return NULL;
    }
}

Rpc RootSchemaNodeRpc(RootSchemaNode root_schema, const char* path)
{
    try
    {
        ydk::path::RootSchemaNode * real_root_schema = (ydk::path::RootSchemaNode*)root_schema;
        shared_ptr<ydk::path::Rpc> rpc = real_root_schema->rpc(path);

        return static_cast<void*>(wrap(rpc));
    }
    catch(...)
    {
        return NULL;
    }
}

DataNode RpcInput(Rpc rpc)
{
    try
    {
        RpcWrapper* rpc_wrapper = (RpcWrapper*)rpc;
        ydk::path::Rpc* real_rpc = unwrap(rpc_wrapper);

        ydk::path::DataNode * input = &real_rpc->input();

        return static_cast<void*>(wrap(input));
    }
    catch(...)
    {
        return NULL;
    }
}

DataNode RpcExecute(Rpc rpc, ServiceProvider provider)
{
    try
    {
        RpcWrapper* rpc_wrapper = (RpcWrapper*)rpc;
        ydk::path::Rpc* real_rpc = unwrap(rpc_wrapper);

        ydk::path::ServiceProvider * real_provider = (ydk::path::ServiceProvider *) provider;
        std::shared_ptr<ydk::path::DataNode> result = (*real_rpc)(*real_provider);

        return static_cast<void*>(wrap(result));
    }
    catch(...)
    {
        return NULL;
    }
}

DataNode DataNodeCreate(DataNode datanode, const char* path, const char* value)
{
    try
    {
        DataNodeWrapper* datanode_wrapper = (DataNodeWrapper*)datanode;
        ydk::path::DataNode* real_datanode = unwrap(datanode_wrapper);
        ydk::path::DataNode * result = &real_datanode->create(path, value);

        return static_cast<void*>(wrap(result));
    }
    catch(...)
    {
        return NULL;
    }
}

const char* DataNodeGetArgument(DataNode datanode)
{
    DataNodeWrapper* datanode_wrapper = (DataNodeWrapper*)datanode;
    ydk::path::DataNode* real_datanode = unwrap(datanode_wrapper);
    string s = real_datanode->schema().statement().arg;
    return string_to_array(s);
}

const char* DataNodeGetKeyword(DataNode datanode)
{
    DataNodeWrapper* datanode_wrapper = (DataNodeWrapper*)datanode;
    ydk::path::DataNode* real_datanode = unwrap(datanode_wrapper);
    string s = real_datanode->schema().statement().keyword;
    return string_to_array(s);
}

const char* DataNodeGetPath(DataNode datanode)
{
    DataNodeWrapper* datanode_wrapper = (DataNodeWrapper*)datanode;
    ydk::path::DataNode* real_datanode = unwrap(datanode_wrapper);
    string s = real_datanode->path();
    return string_to_array(s);
}

const char* DataNodeGetValue(DataNode datanode)
{
    DataNodeWrapper* datanode_wrapper = (DataNodeWrapper*)datanode;
    ydk::path::DataNode* real_datanode = unwrap(datanode_wrapper);
    string s = real_datanode->get();
    return string_to_array(s);
}

DataNodeChildren DataNodeGetChildren(DataNode datanode)
{
    DataNodeWrapper* datanode_wrapper = (DataNodeWrapper*)datanode;
    ydk::path::DataNode* real_datanode = unwrap(datanode_wrapper);

    std::vector<shared_ptr<ydk::path::DataNode>> children = real_datanode->children();
    DataNode* child_array = new DataNode[children.size()];
    for(size_t i=0; i < children.size(); i++)
    {
        child_array[i] = wrap(children[i]);
    }
    return {child_array, static_cast<int>(children.size())};
}

void DataNodeAddAnnotation(DataNode datanode, const char* operation)
{
    string oper{operation};
    if(oper.size() == 0)
    {
        return;
    }
    DataNodeWrapper* datanode_wrapper = (DataNodeWrapper*)datanode;
    ydk::path::DataNode* real_datanode = unwrap(datanode_wrapper);
    ydk::path::Annotation annotation{"ietf-netconf", "operation", operation};
    real_datanode->add_annotation(annotation);
}

DataNode DataNodeGetParent(DataNode datanode)
{
    DataNodeWrapper* datanode_wrapper = (DataNodeWrapper*)datanode;
    ydk::path::DataNode* real_datanode = unwrap(datanode_wrapper);
    ydk::path::DataNode* parent = real_datanode->parent();
    return static_cast<void*>(wrap(parent));
}

void EnableLogging(LogLevel level)
{
    auto console = spdlog::stdout_color_mt("ydk");
    switch(level)
    {
        case DEBUG:
            console->set_level(spdlog::level::debug);
            return;

        case INFO:
            console->set_level(spdlog::level::info);
            return;

        case WARNING:
            console->set_level(spdlog::level::warn);
            return;

        case ERROR:
            console->set_level(spdlog::level::err);
            return;

        case OFF:
            console->set_level(spdlog::level::off);
            return;
    }
}

LogLevel GetLoggingLevel(void)
{
    auto console = spdlog::get("ydk");
    if(console == nullptr)
    {
        return OFF;
    }

    auto level = console->level();
    switch(level)
    {
        case spdlog::level::off:
            return OFF;
        case spdlog::level::trace:
        case spdlog::level::debug:
            return DEBUG;

        case spdlog::level::info:
            return INFO;

        case spdlog::level::warn:
            return WARNING;

        case spdlog::level::critical:
        case spdlog::level::err:
            return ERROR;
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * 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: pptimport.hxx,v $
 * $Revision: 1.5 $
 *
 * 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.
 *
 ************************************************************************/

#ifndef OOX_POWERPOINT_POWERPOINTIMPORT_HXX
#define OOX_POWERPOINT_POWERPOINTIMPORT_HXX

#include "oox/core/xmlfilterbase.hxx"

#include <com/sun/star/animations/XAnimationNode.hpp>
#include <oox/drawingml/theme.hxx>
#include "oox/ppt/presentationfragmenthandler.hxx"
#include "oox/ppt/slidepersist.hxx"
#include "tokens.hxx"
#include <vector>
#include <map>

namespace oox { namespace ppt {

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

class PowerPointImport : public oox::core::XmlFilterBase
{
public:

    PowerPointImport( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > & rSMgr  );
    virtual ~PowerPointImport();

    // from FilterBase
    virtual bool importDocument() throw();
    virtual bool exportDocument() throw();

    virtual sal_Int32 getSchemeClr( sal_Int32 nColorSchemeToken ) const;

    virtual const oox::vml::DrawingPtr getDrawings();
    virtual const oox::drawingml::table::TableStyleListPtr getTableStyles();
    virtual ::oox::drawingml::chart::ChartConverter& getChartConverter();

    void                                                    setActualSlidePersist( SlidePersistPtr pActualSlidePersist ){ mpActualSlidePersist = pActualSlidePersist; };
    std::map< rtl::OUString, oox::drawingml::ThemePtr >&    getThemes(){ return maThemes; };
    std::vector< SlidePersistPtr >&                         getDrawPages(){ return maDrawPages; };
    std::vector< SlidePersistPtr >&                         getMasterPages(){ return maMasterPages; };
    std::vector< SlidePersistPtr >&                         getNotesPages(){ return maNotesPages; };

private:
    virtual ::rtl::OUString implGetImplementationName() const;

private:
    rtl::OUString                                       maTableStyleListPath;
    oox::drawingml::table::TableStyleListPtr            mpTableStyleList;

    SlidePersistPtr                                     mpActualSlidePersist;
    std::map< rtl::OUString, oox::drawingml::ThemePtr > maThemes;

    std::vector< SlidePersistPtr > maDrawPages;
    std::vector< SlidePersistPtr > maMasterPages;
    std::vector< SlidePersistPtr > maNotesPages;

    ::boost::shared_ptr< ::oox::drawingml::chart::ChartConverter > mxChartConv;
};

} }

#endif // OOX_POWERPOINT_POWERPOINTIMPORT_HXX
<commit_msg>INTEGRATION: CWS xmlfilter06 (1.4.6); FILE MERGED 2008/06/30 09:56:35 dr 1.4.6.3: RESYNC: (1.4-1.5); FILE MERGED 2008/06/06 16:27:52 dr 1.4.6.2: chart formatting: builtin line/fill/effect styles, manual line formatting 2008/05/27 10:40:31 dr 1.4.6.1: joined changes from CWS xmlfilter05<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: pptimport.hxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef OOX_POWERPOINT_POWERPOINTIMPORT_HXX
#define OOX_POWERPOINT_POWERPOINTIMPORT_HXX

#include "oox/core/xmlfilterbase.hxx"

#include <com/sun/star/animations/XAnimationNode.hpp>
#include <oox/drawingml/theme.hxx>
#include "oox/ppt/presentationfragmenthandler.hxx"
#include "oox/ppt/slidepersist.hxx"
#include "tokens.hxx"
#include <vector>
#include <map>

namespace oox { namespace ppt {

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

class PowerPointImport : public oox::core::XmlFilterBase
{
public:

    PowerPointImport( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > & rSMgr  );
    virtual ~PowerPointImport();

    // from FilterBase
    virtual bool importDocument() throw();
    virtual bool exportDocument() throw();

    virtual const ::oox::drawingml::Theme* getCurrentTheme() const;

    virtual sal_Int32 getSchemeClr( sal_Int32 nColorSchemeToken ) const;

    virtual const oox::vml::DrawingPtr getDrawings();
    virtual const oox::drawingml::table::TableStyleListPtr getTableStyles();
    virtual ::oox::drawingml::chart::ChartConverter& getChartConverter();

    void                                                    setActualSlidePersist( SlidePersistPtr pActualSlidePersist ){ mpActualSlidePersist = pActualSlidePersist; };
    std::map< rtl::OUString, oox::drawingml::ThemePtr >&    getThemes(){ return maThemes; };
    std::vector< SlidePersistPtr >&                         getDrawPages(){ return maDrawPages; };
    std::vector< SlidePersistPtr >&                         getMasterPages(){ return maMasterPages; };
    std::vector< SlidePersistPtr >&                         getNotesPages(){ return maNotesPages; };

private:
    virtual ::rtl::OUString implGetImplementationName() const;

private:
    rtl::OUString                                       maTableStyleListPath;
    oox::drawingml::table::TableStyleListPtr            mpTableStyleList;

    SlidePersistPtr                                     mpActualSlidePersist;
    std::map< rtl::OUString, oox::drawingml::ThemePtr > maThemes;

    std::vector< SlidePersistPtr > maDrawPages;
    std::vector< SlidePersistPtr > maMasterPages;
    std::vector< SlidePersistPtr > maNotesPages;

    ::boost::shared_ptr< ::oox::drawingml::chart::ChartConverter > mxChartConv;
};

} }

#endif // OOX_POWERPOINT_POWERPOINTIMPORT_HXX
<|endoftext|>


<commit_before>/*
 * opencog/server/SaveRequest.cc
 *
 * Copyright (C) 2008 by Singularity Institute for Artificial Intelligence
 * All Rights Reserved
 *
 * Written by Jared Wigmore <jared.wigmore@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "SaveRequest.h"

#include <vector>
#include <fstream>

#include <opencog/server/CogServer.h>
#include <opencog/persist/xml/NMXmlExporter.h>
#include <opencog/util/Logger.h>
#include <opencog/util/exceptions.h>
#include <opencog/atomspace/HandleSet.h>

using namespace opencog;

SaveRequest::SaveRequest()
{
}

SaveRequest::~SaveRequest()
{
}

bool SaveRequest::execute()
{
    logger().debug("[SaveRequest] execute");
    std::ostringstream oss;

    if (_parameters.empty()) {
        oss << "invalid syntax: save <filename>" << std::endl;
        send(oss.str());
        return false;
    }

    AtomSpace* atomSpace = CogServer::getAtomSpace();

    std::string& filename = _parameters.front();
    HandleEntry *handles = atomSpace->getAtomTable().getHandleSet(ATOM, true);
    NMXmlExporter exporter;
    std::fstream file(filename.c_str(), std::fstream::out);
    bool rc = true;
    try {
        file << exporter.toXML(handles);
        oss << "Info: done" << std::endl;
        rc = true;
    } catch (StandardException &e) {
        oss << "Error: unable to save to XML (" << e.getMessage() << ")" << std::endl;
        rc = false;
    }

    file.flush();
    file.close();
    delete handles;
    send(oss.str());
    return rc;
}
<commit_msg>Add a fixme.<commit_after>/*
 * opencog/server/SaveRequest.cc
 *
 * Copyright (C) 2008 by Singularity Institute for Artificial Intelligence
 * All Rights Reserved
 *
 * Written by Jared Wigmore <jared.wigmore@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "SaveRequest.h"

#include <vector>
#include <fstream>

#include <opencog/server/CogServer.h>
#include <opencog/persist/xml/NMXmlExporter.h>
#include <opencog/util/Logger.h>
#include <opencog/util/exceptions.h>
#include <opencog/atomspace/HandleSet.h>

using namespace opencog;

SaveRequest::SaveRequest()
{
}

SaveRequest::~SaveRequest()
{
}

bool SaveRequest::execute()
{
    logger().debug("[SaveRequest] execute");
    std::ostringstream oss;

    if (_parameters.empty()) {
        oss << "invalid syntax: save <filename>" << std::endl;
        send(oss.str());
        return false;
    }

    AtomSpace* atomSpace = CogServer::getAtomSpace();

    std::string& filename = _parameters.front();

    // XXX/FIXME This is an insanely inefficient way to export the
    // atomspace! For anything containing a million or more handles,
    // this is just mind-bogglingly bad, as it will results in a vast
    // amount of mallocs & frees, and blow out RAM usage.  Strongly
    // suggest redesign using appropriate iterators.  Anyway, should
    // probably be exporting to scheme, not XML, anyway ... since XML
    // is slow in general.
    HandleEntry *handles = atomSpace->getAtomTable().getHandleSet(ATOM, true);
    NMXmlExporter exporter;
    std::fstream file(filename.c_str(), std::fstream::out);
    bool rc = true;
    try {
        file << exporter.toXML(handles);
        oss << "Info: done" << std::endl;
        rc = true;
    } catch (StandardException &e) {
        oss << "Error: unable to save to XML (" << e.getMessage() << ")" << std::endl;
        rc = false;
    }

    file.flush();
    file.close();
    delete handles;
    send(oss.str());
    return rc;
}
<|endoftext|>


<commit_before>#include "pxt.h"

using namespace pxt;

namespace olney {

    //% weight=58
    //% blockId=olney_servo_comment block="comment %msg"
    void comment(StringData *data) {
        //uBit.basic.showString(data);

}<commit_msg>Corrected missing brace<commit_after>#include "pxt.h"

using namespace pxt;

namespace olney {

    //% weight=58
    //% blockId=olney_servo_comment block="comment %msg"
    void comment(StringData *data) {
        //uBit.basic.showString(data);

    }
}<|endoftext|>