<commit_before>#include "regex_selector.hh"
#include "exception.hh"

namespace Kakoune
{

RegexSelector::RegexSelector(const std::string& exp)
    : m_regex(exp) {}

Selection RegexSelector::operator()(const BufferIterator& cursor) const
{
    try
    {
        boost::match_results<BufferIterator> matches;

        if (boost::regex_search(cursor, cursor.buffer().end(), matches, m_regex, boost::match_nosubs))
            return Selection(matches.begin()->first, matches.begin()->second-1);
        else if (boost::regex_search(cursor.buffer().begin(), cursor, matches, m_regex, boost::match_nosubs))
            return Selection(matches.begin()->first, matches.begin()->second-1);
    }
    catch (boost::regex_error& err)
    {
        throw runtime_error("regex error");
    }

    return Selection(cursor, cursor);
}

SelectionList RegexSelector::operator()(const Selection& selection) const
{
    boost::regex_iterator<BufferIterator> re_it(selection.begin(),
                                                selection.end(),
                                                m_regex, boost::match_nosubs);
    boost::regex_iterator<BufferIterator> re_end;

    SelectionList result;
    for (; re_it != re_end; ++re_it)
    {
        BufferIterator begin = (*re_it)[0].first;
        BufferIterator end   = (*re_it)[0].second;
        assert(begin != end);

        result.push_back(Selection(begin, end-1));
    }
    return result;
}

}
<commit_msg>RegexSelector: support captures<commit_after>#include "regex_selector.hh"
#include "exception.hh"

namespace Kakoune
{

RegexSelector::RegexSelector(const std::string& exp)
    : m_regex(exp) {}

Selection RegexSelector::operator()(const BufferIterator& cursor) const
{
    BufferIterator begin = cursor;
    BufferIterator end = cursor;
    Selection::CaptureList captures;

    try
    {
        boost::match_results<BufferIterator> matches;

        if (boost::regex_search(cursor, cursor.buffer().end(), matches,
                                m_regex))
        {
            begin = matches[0].first;
            end   = matches[0].second;
            std::copy(matches.begin(), matches.end(),
                      std::back_inserter(captures));
        }
        else if (boost::regex_search(cursor.buffer().begin(), cursor, matches,
                                     m_regex))
        {
            begin = matches[0].first;
            end   = matches[0].second;
            std::copy(matches.begin(), matches.end(),
                      std::back_inserter(captures));
        }
    }
    catch (boost::regex_error& err)
    {
        throw runtime_error("regex error");
    }

    if (begin == end)
        ++end;

    return Selection(begin, end - 1, std::move(captures));
}

SelectionList RegexSelector::operator()(const Selection& selection) const
{
    boost::regex_iterator<BufferIterator> re_it(selection.begin(),
                                                selection.end(),
                                                m_regex);
    boost::regex_iterator<BufferIterator> re_end;

    SelectionList result;
    for (; re_it != re_end; ++re_it)
    {
        BufferIterator begin = (*re_it)[0].first;
        BufferIterator end   = (*re_it)[0].second;

        if (begin == end)
           ++end;

        Selection::CaptureList captures(re_it->begin(), re_it->end());
        result.push_back(Selection(begin, end-1, std::move(captures)));
    }
    return result;
}

}
<|endoftext|>


<commit_before>#include <ap_int.h>
#include "spbits.h"
#define num_levels 4
#include "sort.h"
using namespace std;
void sorter::best3(ap_uint<bwr> rank_ex[cnrex],
		ap_uint<bwr> winner[3],
		int station,
		ap_uint<bpow+1> winid[3])

{
#pragma HLS LATENCY max=3
#pragma HLS INTERFACE ap_ctrl_none port=return

	ap_uint<bwr> ret_a[cnrex],ret_a1[cnrex],ret_a2[cnrex];
	ap_uint<bwr> ret_win[cnr],ret_win1[cnr],ret_win2[cnr];

for(int i=0;i<cnrex;i++){
#pragma HLS UNROLL
	rankr[i]=rank_ex[i];
}

 sorter inst;
		this->sort( &winner[0],&winid[0], station,ret_win);//INLINE OFF

		this->sort1( ret_win, &winner[1],&winid[1],ret_win1);//INLINE

		this->sort1( ret_win1,&winner[2],&winid[2], ret_win2);//INLINE

}

<commit_msg>Delete zones_best3.cpp<commit_after><|endoftext|>


<commit_before>//===- lib/Core/InputGraph.cpp --------------------------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lld/Core/InputGraph.h"

#include "lld/Core/Resolver.h"

#include <memory>

using namespace lld;

ErrorOr<File &> InputGraph::getNextFile() {
  // When getNextFile() is called for the first time, _currentInputElement is
  // not initialized. Initialize it with the first element of the input graph.
  if (_currentInputElement == nullptr) {
    ErrorOr<InputElement *> elem = getNextInputElement();
    if (elem.getError() == InputGraphError::no_more_elements)
      return make_error_code(InputGraphError::no_more_files);
    _currentInputElement = *elem;
  }

  // Otherwise, try to get the next file of _currentInputElement. If the current
  // input element points to an archive file, and there's a file left in the
  // archive, it will succeed. If not, try to get the next file in the input
  // graph.
  for (;;) {
    ErrorOr<File &> nextFile = _currentInputElement->getNextFile();
    if (nextFile.getError() != InputGraphError::no_more_files)
      return std::move(nextFile);

    ErrorOr<InputElement *> elem = getNextInputElement();
    if (elem.getError() == InputGraphError::no_more_elements ||
        *elem == nullptr)
      return make_error_code(InputGraphError::no_more_files);
    _currentInputElement = *elem;
  }
}

void InputGraph::notifyProgress() { _currentInputElement->notifyProgress(); }

bool InputGraph::addInputElement(std::unique_ptr<InputElement> ie) {
  _inputArgs.push_back(std::move(ie));
  return true;
}

bool InputGraph::dump(raw_ostream &diagnostics) {
  for (std::unique_ptr<InputElement> &ie : _inputArgs)
    if (!ie->dump(diagnostics))
      return false;
  return true;
}

/// \brief Insert element at position
void InputGraph::insertElementAt(std::unique_ptr<InputElement> element,
                                 Position position) {
  if (position == InputGraph::Position::BEGIN) {
    _inputArgs.insert(_inputArgs.begin(), std::move(element));
    return;
  }
  assert(position == InputGraph::Position::END);
  _inputArgs.push_back(std::move(element));
}

/// \brief Helper functions for the resolver
ErrorOr<InputElement *> InputGraph::getNextInputElement() {
  if (_nextElementIndex >= _inputArgs.size())
    return make_error_code(InputGraphError::no_more_elements);
  return _inputArgs[_nextElementIndex++].get();
}

void InputGraph::normalize() {
  auto iterb = _inputArgs.begin();
  auto itere = _inputArgs.end();
  auto currentIter = _inputArgs.begin();

  std::vector<std::unique_ptr<InputElement> > _workInputArgs;
  while (iterb != itere) {
    bool expand = (*iterb)->shouldExpand();
    currentIter = iterb++;
    if (expand) {
      _workInputArgs.insert(
          _workInputArgs.end(),
          std::make_move_iterator((*currentIter)->expandElements().begin()),
          std::make_move_iterator((*currentIter)->expandElements().end()));
    } else {
      _workInputArgs.push_back(std::move(*currentIter));
    }
  }
  _inputArgs = std::move(_workInputArgs);
}

/// \brief Read the file into _buffer.
error_code FileNode::getBuffer(StringRef filePath) {
  // Create a memory buffer
  std::unique_ptr<MemoryBuffer> mb;
  if (error_code ec = MemoryBuffer::getFileOrSTDIN(filePath, mb))
    return ec;
  _buffer = std::move(mb);
  return error_code::success();
}

/// \brief Return the next file that need to be processed by the resolver.
/// This also processes input elements depending on the resolve status
/// of the input elements contained in the group.
ErrorOr<File &> Group::getNextFile() {
  // If there are no elements, move on to the next input element
  if (_elements.empty())
    return make_error_code(InputGraphError::no_more_files);

  for (;;) {
    // If we have processed all the elements, and have made no progress on
    // linking, we cannot resolve any symbol from this group. Continue to the
    // next one by returning no_more_files.
    if (_nextElementIndex == _elements.size()) {
      if (!_madeProgress)
        return make_error_code(InputGraphError::no_more_files);
      resetNextIndex();
    }

    _currentElementIndex = _nextElementIndex;
    auto file = _elements[_nextElementIndex]->getNextFile();
    // Move on to the next element if we have finished processing all
    // the files in the input element
    if (file.getError() == InputGraphError::no_more_files) {
      _nextElementIndex++;
      continue;
    }
    return *file;
  }
}
<commit_msg>Use range-based for loop. No functionality change.<commit_after>//===- lib/Core/InputGraph.cpp --------------------------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lld/Core/InputGraph.h"

#include "lld/Core/Resolver.h"

#include <memory>

using namespace lld;

ErrorOr<File &> InputGraph::getNextFile() {
  // When getNextFile() is called for the first time, _currentInputElement is
  // not initialized. Initialize it with the first element of the input graph.
  if (_currentInputElement == nullptr) {
    ErrorOr<InputElement *> elem = getNextInputElement();
    if (elem.getError() == InputGraphError::no_more_elements)
      return make_error_code(InputGraphError::no_more_files);
    _currentInputElement = *elem;
  }

  // Otherwise, try to get the next file of _currentInputElement. If the current
  // input element points to an archive file, and there's a file left in the
  // archive, it will succeed. If not, try to get the next file in the input
  // graph.
  for (;;) {
    ErrorOr<File &> nextFile = _currentInputElement->getNextFile();
    if (nextFile.getError() != InputGraphError::no_more_files)
      return std::move(nextFile);

    ErrorOr<InputElement *> elem = getNextInputElement();
    if (elem.getError() == InputGraphError::no_more_elements ||
        *elem == nullptr)
      return make_error_code(InputGraphError::no_more_files);
    _currentInputElement = *elem;
  }
}

void InputGraph::notifyProgress() { _currentInputElement->notifyProgress(); }

bool InputGraph::addInputElement(std::unique_ptr<InputElement> ie) {
  _inputArgs.push_back(std::move(ie));
  return true;
}

bool InputGraph::dump(raw_ostream &diagnostics) {
  for (std::unique_ptr<InputElement> &ie : _inputArgs)
    if (!ie->dump(diagnostics))
      return false;
  return true;
}

/// \brief Insert element at position
void InputGraph::insertElementAt(std::unique_ptr<InputElement> element,
                                 Position position) {
  if (position == InputGraph::Position::BEGIN) {
    _inputArgs.insert(_inputArgs.begin(), std::move(element));
    return;
  }
  assert(position == InputGraph::Position::END);
  _inputArgs.push_back(std::move(element));
}

/// \brief Helper functions for the resolver
ErrorOr<InputElement *> InputGraph::getNextInputElement() {
  if (_nextElementIndex >= _inputArgs.size())
    return make_error_code(InputGraphError::no_more_elements);
  return _inputArgs[_nextElementIndex++].get();
}

void InputGraph::normalize() {
  std::vector<std::unique_ptr<InputElement>> vec;
  for (std::unique_ptr<InputElement> &ie : _inputArgs) {
    if (!ie->shouldExpand()) {
      vec.push_back(std::move(ie));
      continue;
    }
    range<InputElementIterT> expanded = ie->expandElements();
    vec.insert(vec.end(), std::make_move_iterator(expanded.begin()),
               std::make_move_iterator(expanded.end()));
  }
  _inputArgs = std::move(vec);
}

/// \brief Read the file into _buffer.
error_code FileNode::getBuffer(StringRef filePath) {
  // Create a memory buffer
  std::unique_ptr<MemoryBuffer> mb;
  if (error_code ec = MemoryBuffer::getFileOrSTDIN(filePath, mb))
    return ec;
  _buffer = std::move(mb);
  return error_code::success();
}

/// \brief Return the next file that need to be processed by the resolver.
/// This also processes input elements depending on the resolve status
/// of the input elements contained in the group.
ErrorOr<File &> Group::getNextFile() {
  // If there are no elements, move on to the next input element
  if (_elements.empty())
    return make_error_code(InputGraphError::no_more_files);

  for (;;) {
    // If we have processed all the elements, and have made no progress on
    // linking, we cannot resolve any symbol from this group. Continue to the
    // next one by returning no_more_files.
    if (_nextElementIndex == _elements.size()) {
      if (!_madeProgress)
        return make_error_code(InputGraphError::no_more_files);
      resetNextIndex();
    }

    _currentElementIndex = _nextElementIndex;
    auto file = _elements[_nextElementIndex]->getNextFile();
    // Move on to the next element if we have finished processing all
    // the files in the input element
    if (file.getError() == InputGraphError::no_more_files) {
      _nextElementIndex++;
      continue;
    }
    return *file;
  }
}
<|endoftext|>


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

#include "romcollection.h"

RomCollection::RomCollection(QStringList fileTypes, QString romPath, QWidget *parent) : QObject(parent)
{
    this->fileTypes = fileTypes;
    this->romPath = romPath;
    this->parent = parent;

    this->romDir = QDir(romPath);

    setupDatabase();
}

Rom RomCollection::addRom(QByteArray *romData, QString fileName, QString zipFile, QSqlQuery query)
{
    Rom currentRom;

    currentRom.fileName = fileName;
    currentRom.internalName = QString(romData->mid(32, 20)).trimmed();
    currentRom.romMD5 = QString(QCryptographicHash::hash(*romData,
                                QCryptographicHash::Md5).toHex());
    currentRom.zipFile = zipFile;
    currentRom.sortSize = romData->size();

    query.bindValue(":filename",      currentRom.fileName);
    query.bindValue(":internal_name", currentRom.internalName);
    query.bindValue(":md5",           currentRom.romMD5);
    query.bindValue(":zip_file",      currentRom.zipFile);
    query.bindValue(":size",          currentRom.sortSize);
    query.exec();

    initializeRom(&currentRom, romDir, false);

    return currentRom;
}

void RomCollection::addRoms()
{
    emit updateStarted();

    database.open();

    QSqlQuery query("DELETE FROM rom_collection", database);
    query.prepare(QString("INSERT INTO rom_collection ")
                  + "(filename, internal_name, md5, zip_file, size) "
                  + "VALUES (:filename, :internal_name, :md5, :zip_file, :size)");

    scrapper = new TheGamesDBScrapper(parent);

    QList<Rom> roms;

    if (romPath != "") {
        if (romDir.exists()) {
            QStringList files = romDir.entryList(fileTypes, QDir::Files | QDir::NoSymLinks);

            if (files.size() > 0) {
                setupProgressDialog(files.size());

                int count = 0;
                foreach (QString fileName, files)
                {
                    QString completeFileName = romDir.absoluteFilePath(fileName);
                    QFile file(completeFileName);

                    //If file is a zip file, extract info from any zipped ROMs
                    if (QFileInfo(file).suffix().toLower() == "zip") {
                        foreach (QString zippedFile, getZippedFiles(completeFileName))
                        {
                            QString ext = zippedFile.right(4).toLower();

                            //check for ROM files
                            if (fileTypes.contains("*" + ext)) {
                                QByteArray *romData = getZippedRom(zippedFile, completeFileName);

                                if (fileTypes.contains("*.v64"))
                                    *romData = byteswap(*romData);

                                if (romData->left(4).toHex() == "80371240") //Else invalid
                                    roms.append(addRom(romData, zippedFile, fileName, query));

                                delete romData;
                            }
                        }
                    } else { //Just a normal ROM file
                        file.open(QIODevice::ReadOnly);
                        QByteArray *romData = new QByteArray(file.readAll());
                        file.close();

                        if (fileTypes.contains("*.v64"))
                            *romData = byteswap(*romData);

                        if (romData->left(4).toHex() == "80371240") //Else invalid
                            roms.append(addRom(romData, fileName, "", query));

                        delete romData;
                    }

                    count++;
                    progress->setValue(count);
                }

                progress->close();
            } else {
            QMessageBox::warning(parent, "Warning", "No ROMs found.");
            }
        } else {
            QMessageBox::warning(parent, "Warning", "Failed to open ROM directory.");
        }
    }

    delete scrapper;

    database.close();

    qSort(roms.begin(), roms.end(), romSorter);

    for (int i = 0; i < roms.size(); i++)
        emit romAdded(&roms[i], i);

    emit updateEnded(roms.size());
}

void RomCollection::cachedRoms(bool imageUpdated)
{
    emit updateStarted(imageUpdated);

    database.open();
    QSqlQuery query("SELECT filename, md5, internal_name, zip_file, size FROM rom_collection", database);

    query.last();
    int romCount = query.at() + 1;
    query.seek(-1);

    if (romCount == -1) { //Nothing cached so try adding ROMs instead
        addRoms();
        return;
    }

    QList<Rom> roms;

    int count = 0;
    bool showProgress = false;
    QTime checkPerformance;

    while (query.next())
    {
        Rom currentRom;

        currentRom.fileName = query.value(0).toString();
        currentRom.romMD5 = query.value(1).toString();
        currentRom.internalName = query.value(2).toString();
        currentRom.zipFile = query.value(3).toString();
        currentRom.sortSize = query.value(4).toInt();

        //Check performance of adding first item to see if progress dialog needs to be shown
        if (count == 0) checkPerformance.start();

        initializeRom(&currentRom, romDir, true);
        roms.append(currentRom);

        if (count == 0) {
            int runtime = checkPerformance.elapsed();

            //check if operation expected to take longer than two seconds
            if (runtime * romCount > 2000) {
                setupProgressDialog(romCount);
                showProgress = true;
            }
        }

        count++;

        if (showProgress)
            progress->setValue(count);
    }

    database.close();

    if (showProgress)
        progress->close();

    qSort(roms.begin(), roms.end(), romSorter);

    for (int i = 0; i < roms.size(); i++)
        emit romAdded(&roms[i], i);

    emit updateEnded(roms.size(), true);
}

QStringList RomCollection::getFileTypes(bool archives)
{
    QStringList returnList = fileTypes;

    if (!archives)
        returnList.removeOne("*.zip");

    return returnList;
}

void RomCollection::initializeRom(Rom *currentRom, QDir romDir, bool cached)
{
    QSettings *romCatalog = new QSettings(parent);
    QString dataPath = SETTINGS.value("Paths/data", "").toString();
    QDir dataDir(dataPath);
    QString catalogFile = dataDir.absoluteFilePath("mupen64plus.ini");

    //Default text for GoodName to notify user
    currentRom->goodName = "Requires catalog file";
    currentRom->imageExists = false;

    bool getGoodName = false;
    if (QFileInfo(catalogFile).exists()) {
        romCatalog = new QSettings(catalogFile, QSettings::IniFormat, parent);
        getGoodName = true;
    }

    QFile file(romDir.absoluteFilePath(currentRom->fileName));

    currentRom->romMD5 = currentRom->romMD5.toUpper();
    currentRom->baseName = QFileInfo(file).completeBaseName();
    currentRom->size = QObject::tr("%1 MB").arg((currentRom->sortSize + 1023) / 1024 / 1024);

    if (getGoodName) {
        //Join GoodName on ", ", otherwise entries with a comma won't show
        QVariant goodNameVariant = romCatalog->value(currentRom->romMD5+"/GoodName","Unknown ROM");
        currentRom->goodName = goodNameVariant.toStringList().join(", ");

        QStringList CRC = romCatalog->value(currentRom->romMD5+"/CRC","").toString().split(" ");

        if (CRC.size() == 2) {
            currentRom->CRC1 = CRC[0];
            currentRom->CRC2 = CRC[1];
        }

        QString newMD5 = romCatalog->value(currentRom->romMD5+"/RefMD5","").toString();
        if (newMD5 == "")
            newMD5 = currentRom->romMD5;

        currentRom->players = romCatalog->value(newMD5+"/Players","").toString();
        currentRom->saveType = romCatalog->value(newMD5+"/SaveType","").toString();
        currentRom->rumble = romCatalog->value(newMD5+"/Rumble","").toString();
    }

    if (!cached && SETTINGS.value("Other/downloadinfo", "").toString() == "true") {
        if (currentRom->goodName != "Unknown ROM" && currentRom->goodName != "Requires catalog file") {
            scrapper->downloadGameInfo(currentRom->romMD5, currentRom->goodName);
        } else {
            //tweak internal name by adding spaces to get better results
            QString search = currentRom->internalName;
            search.replace(QRegExp("([a-z])([A-Z])"),"\\1 \\2");
            search.replace(QRegExp("([^ \\d])(\\d)"),"\\1 \\2");
            scrapper->downloadGameInfo(currentRom->romMD5, search);
        }

    }

    if (SETTINGS.value("Other/downloadinfo", "").toString() == "true") {
        QString cacheDir = getDataLocation() + "/cache";

        QString dataFile = cacheDir + "/" + currentRom->romMD5.toLower() + "/data.xml";
        QFile file(dataFile);

        file.open(QIODevice::ReadOnly);
        QString dom = file.readAll();
        file.close();

        QDomDocument xml;
        xml.setContent(dom);
        QDomNode game = xml.elementsByTagName("Game").at(0);

        //Remove any non-standard characters
        QString regex = "[^A-Za-z 0-9 \\.,\\?'""!@#\\$%\\^&\\*\\(\\)-_=\\+;:<>\\/\\\\|\\}\\{\\[\\]`~]*";

        currentRom->gameTitle = game.firstChildElement("GameTitle").text().remove(QRegExp(regex));
        if (currentRom->gameTitle == "") currentRom->gameTitle = "Not found";

        currentRom->releaseDate = game.firstChildElement("ReleaseDate").text();

        //Fix missing 0's in date
        currentRom->releaseDate.replace(QRegExp("^(\\d)/(\\d{2})/(\\d{4})"), "0\\1/\\2/\\3");
        currentRom->releaseDate.replace(QRegExp("^(\\d{2})/(\\d)/(\\d{4})"), "\\1/0\\2/\\3");
        currentRom->releaseDate.replace(QRegExp("^(\\d)/(\\d)/(\\d{4})"), "0\\1/0\\2/\\3");

        currentRom->sortDate = currentRom->releaseDate;
        currentRom->sortDate.replace(QRegExp("(\\d{2})/(\\d{2})/(\\d{4})"), "\\3-\\1-\\2");

        currentRom->overview = game.firstChildElement("Overview").text().remove(QRegExp(regex));
        currentRom->esrb = game.firstChildElement("ESRB").text();

        int count = 0;
        QDomNode genreNode = game.firstChildElement("Genres").firstChild();
        while(!genreNode.isNull())
        {
            if (count != 0)
                currentRom->genre += "/" + genreNode.toElement().text();
            else
                currentRom->genre = genreNode.toElement().text();

            genreNode = genreNode.nextSibling();
            count++;
        }

        currentRom->publisher = game.firstChildElement("Publisher").text();
        currentRom->developer = game.firstChildElement("Developer").text();
        currentRom->rating = game.firstChildElement("Rating").text();

        foreach (QString ext, QStringList() << "jpg" << "png")
        {
            QString imageFile = getDataLocation() + "/cache/"
                                + currentRom->romMD5.toLower() + "/boxart-front." + ext;
            QFile cover(imageFile);

            if (cover.exists()&& currentRom->image.load(imageFile)) {
                currentRom->imageExists = true;
                break;
            }
        }
    }
}

void RomCollection::setupDatabase()
{
    database = QSqlDatabase::addDatabase("QSQLITE");
    database.setDatabaseName(getDataLocation() + "/mupen64plus-qt.sqlite");

    if (!database.open())
        QMessageBox::warning(parent, "Database Not Loaded",
                             "Could not connect to Sqlite database. Application may misbehave.");

    QSqlQuery query(QString()
                    + "CREATE TABLE IF NOT EXISTS rom_collection ("
                        + "rom_id INTEGER PRIMARY KEY ASC, "
                        + "filename TEXT NOT NULL, "
                        + "md5 TEXT NOT NULL, "
                        + "internal_name TEXT, "
                        + "zip_file TEXT, "
                        + "size INTEGER)", database);

    database.close();
}

void RomCollection::setupProgressDialog(int size)
{
    progress = new QProgressDialog("Loading ROMs...", "Cancel", 0, size, parent);
#if QT_VERSION >= 0x050000
    progress->setWindowFlags(progress->windowFlags() & ~Qt::WindowCloseButtonHint);
    progress->setWindowFlags(progress->windowFlags() & ~Qt::WindowMinimizeButtonHint);
    progress->setWindowFlags(progress->windowFlags() & ~Qt::WindowContextHelpButtonHint);
#else
    progress->setWindowFlags(Qt::Dialog | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
#endif
    progress->setCancelButton(0);
    progress->setWindowModality(Qt::WindowModal);

    progress->show();
}

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

#include "romcollection.h"

RomCollection::RomCollection(QStringList fileTypes, QString romPath, QWidget *parent) : QObject(parent)
{
    this->fileTypes = fileTypes;
    this->romPath = romPath;
    this->parent = parent;

    this->romDir = QDir(romPath);

    setupDatabase();
}

Rom RomCollection::addRom(QByteArray *romData, QString fileName, QString zipFile, QSqlQuery query)
{
    Rom currentRom;

    currentRom.fileName = fileName;
    currentRom.internalName = QString(romData->mid(32, 20)).trimmed();
    currentRom.romMD5 = QString(QCryptographicHash::hash(*romData,
                                QCryptographicHash::Md5).toHex());
    currentRom.zipFile = zipFile;
    currentRom.sortSize = romData->size();

    query.bindValue(":filename",      currentRom.fileName);
    query.bindValue(":internal_name", currentRom.internalName);
    query.bindValue(":md5",           currentRom.romMD5);
    query.bindValue(":zip_file",      currentRom.zipFile);
    query.bindValue(":size",          currentRom.sortSize);
    query.exec();

    initializeRom(&currentRom, romDir, false);

    return currentRom;
}

void RomCollection::addRoms()
{
    emit updateStarted();

    database.open();

    QSqlQuery query("DELETE FROM rom_collection", database);
    query.prepare(QString("INSERT INTO rom_collection ")
                  + "(filename, internal_name, md5, zip_file, size) "
                  + "VALUES (:filename, :internal_name, :md5, :zip_file, :size)");

    scrapper = new TheGamesDBScrapper(parent);

    QList<Rom> roms;

    if (romPath != "") {
        if (romDir.exists()) {
            QStringList files = romDir.entryList(fileTypes, QDir::Files | QDir::NoSymLinks);

            if (files.size() > 0) {
                setupProgressDialog(files.size());

                int count = 0;
                foreach (QString fileName, files)
                {
                    QString completeFileName = romDir.absoluteFilePath(fileName);
                    QFile file(completeFileName);

                    //If file is a zip file, extract info from any zipped ROMs
                    if (QFileInfo(file).suffix().toLower() == "zip") {
                        foreach (QString zippedFile, getZippedFiles(completeFileName))
                        {
                            QString ext = zippedFile.right(4).toLower();

                            //check for ROM files
                            if (fileTypes.contains("*" + ext)) {
                                QByteArray *romData = getZippedRom(zippedFile, completeFileName);

                                if (fileTypes.contains("*.v64"))
                                    *romData = byteswap(*romData);

                                if (romData->left(4).toHex() == "80371240") //Else invalid
                                    roms.append(addRom(romData, zippedFile, fileName, query));

                                delete romData;
                            }
                        }
                    } else { //Just a normal ROM file
                        file.open(QIODevice::ReadOnly);
                        QByteArray *romData = new QByteArray(file.readAll());
                        file.close();

                        if (fileTypes.contains("*.v64"))
                            *romData = byteswap(*romData);

                        if (romData->left(4).toHex() == "80371240") //Else invalid
                            roms.append(addRom(romData, fileName, "", query));

                        delete romData;
                    }

                    count++;
                    progress->setValue(count);
                    QCoreApplication::processEvents(QEventLoop::AllEvents);
                }

                progress->close();
            } else {
            QMessageBox::warning(parent, "Warning", "No ROMs found.");
            }
        } else {
            QMessageBox::warning(parent, "Warning", "Failed to open ROM directory.");
        }
    }

    delete scrapper;

    database.close();

    qSort(roms.begin(), roms.end(), romSorter);

    for (int i = 0; i < roms.size(); i++)
        emit romAdded(&roms[i], i);

    emit updateEnded(roms.size());
}

void RomCollection::cachedRoms(bool imageUpdated)
{
    emit updateStarted(imageUpdated);

    database.open();
    QSqlQuery query("SELECT filename, md5, internal_name, zip_file, size FROM rom_collection", database);

    query.last();
    int romCount = query.at() + 1;
    query.seek(-1);

    if (romCount == -1) { //Nothing cached so try adding ROMs instead
        addRoms();
        return;
    }

    QList<Rom> roms;

    int count = 0;
    bool showProgress = false;
    QTime checkPerformance;

    while (query.next())
    {
        Rom currentRom;

        currentRom.fileName = query.value(0).toString();
        currentRom.romMD5 = query.value(1).toString();
        currentRom.internalName = query.value(2).toString();
        currentRom.zipFile = query.value(3).toString();
        currentRom.sortSize = query.value(4).toInt();

        //Check performance of adding first item to see if progress dialog needs to be shown
        if (count == 0) checkPerformance.start();

        initializeRom(&currentRom, romDir, true);
        roms.append(currentRom);

        if (count == 0) {
            int runtime = checkPerformance.elapsed();

            //check if operation expected to take longer than two seconds
            if (runtime * romCount > 2000) {
                setupProgressDialog(romCount);
                showProgress = true;
            }
        }

        count++;

        if (showProgress) {
            progress->setValue(count);
            QCoreApplication::processEvents(QEventLoop::AllEvents);
        }
    }

    database.close();

    if (showProgress)
        progress->close();

    qSort(roms.begin(), roms.end(), romSorter);

    for (int i = 0; i < roms.size(); i++)
        emit romAdded(&roms[i], i);

    emit updateEnded(roms.size(), true);
}

QStringList RomCollection::getFileTypes(bool archives)
{
    QStringList returnList = fileTypes;

    if (!archives)
        returnList.removeOne("*.zip");

    return returnList;
}

void RomCollection::initializeRom(Rom *currentRom, QDir romDir, bool cached)
{
    QSettings *romCatalog = new QSettings(parent);
    QString dataPath = SETTINGS.value("Paths/data", "").toString();
    QDir dataDir(dataPath);
    QString catalogFile = dataDir.absoluteFilePath("mupen64plus.ini");

    //Default text for GoodName to notify user
    currentRom->goodName = "Requires catalog file";
    currentRom->imageExists = false;

    bool getGoodName = false;
    if (QFileInfo(catalogFile).exists()) {
        romCatalog = new QSettings(catalogFile, QSettings::IniFormat, parent);
        getGoodName = true;
    }

    QFile file(romDir.absoluteFilePath(currentRom->fileName));

    currentRom->romMD5 = currentRom->romMD5.toUpper();
    currentRom->baseName = QFileInfo(file).completeBaseName();
    currentRom->size = QObject::tr("%1 MB").arg((currentRom->sortSize + 1023) / 1024 / 1024);

    if (getGoodName) {
        //Join GoodName on ", ", otherwise entries with a comma won't show
        QVariant goodNameVariant = romCatalog->value(currentRom->romMD5+"/GoodName","Unknown ROM");
        currentRom->goodName = goodNameVariant.toStringList().join(", ");

        QStringList CRC = romCatalog->value(currentRom->romMD5+"/CRC","").toString().split(" ");

        if (CRC.size() == 2) {
            currentRom->CRC1 = CRC[0];
            currentRom->CRC2 = CRC[1];
        }

        QString newMD5 = romCatalog->value(currentRom->romMD5+"/RefMD5","").toString();
        if (newMD5 == "")
            newMD5 = currentRom->romMD5;

        currentRom->players = romCatalog->value(newMD5+"/Players","").toString();
        currentRom->saveType = romCatalog->value(newMD5+"/SaveType","").toString();
        currentRom->rumble = romCatalog->value(newMD5+"/Rumble","").toString();
    }

    if (!cached && SETTINGS.value("Other/downloadinfo", "").toString() == "true") {
        if (currentRom->goodName != "Unknown ROM" && currentRom->goodName != "Requires catalog file") {
            scrapper->downloadGameInfo(currentRom->romMD5, currentRom->goodName);
        } else {
            //tweak internal name by adding spaces to get better results
            QString search = currentRom->internalName;
            search.replace(QRegExp("([a-z])([A-Z])"),"\\1 \\2");
            search.replace(QRegExp("([^ \\d])(\\d)"),"\\1 \\2");
            scrapper->downloadGameInfo(currentRom->romMD5, search);
        }

    }

    if (SETTINGS.value("Other/downloadinfo", "").toString() == "true") {
        QString cacheDir = getDataLocation() + "/cache";

        QString dataFile = cacheDir + "/" + currentRom->romMD5.toLower() + "/data.xml";
        QFile file(dataFile);

        file.open(QIODevice::ReadOnly);
        QString dom = file.readAll();
        file.close();

        QDomDocument xml;
        xml.setContent(dom);
        QDomNode game = xml.elementsByTagName("Game").at(0);

        //Remove any non-standard characters
        QString regex = "[^A-Za-z 0-9 \\.,\\?'""!@#\\$%\\^&\\*\\(\\)-_=\\+;:<>\\/\\\\|\\}\\{\\[\\]`~]*";

        currentRom->gameTitle = game.firstChildElement("GameTitle").text().remove(QRegExp(regex));
        if (currentRom->gameTitle == "") currentRom->gameTitle = "Not found";

        currentRom->releaseDate = game.firstChildElement("ReleaseDate").text();

        //Fix missing 0's in date
        currentRom->releaseDate.replace(QRegExp("^(\\d)/(\\d{2})/(\\d{4})"), "0\\1/\\2/\\3");
        currentRom->releaseDate.replace(QRegExp("^(\\d{2})/(\\d)/(\\d{4})"), "\\1/0\\2/\\3");
        currentRom->releaseDate.replace(QRegExp("^(\\d)/(\\d)/(\\d{4})"), "0\\1/0\\2/\\3");

        currentRom->sortDate = currentRom->releaseDate;
        currentRom->sortDate.replace(QRegExp("(\\d{2})/(\\d{2})/(\\d{4})"), "\\3-\\1-\\2");

        currentRom->overview = game.firstChildElement("Overview").text().remove(QRegExp(regex));
        currentRom->esrb = game.firstChildElement("ESRB").text();

        int count = 0;
        QDomNode genreNode = game.firstChildElement("Genres").firstChild();
        while(!genreNode.isNull())
        {
            if (count != 0)
                currentRom->genre += "/" + genreNode.toElement().text();
            else
                currentRom->genre = genreNode.toElement().text();

            genreNode = genreNode.nextSibling();
            count++;
        }

        currentRom->publisher = game.firstChildElement("Publisher").text();
        currentRom->developer = game.firstChildElement("Developer").text();
        currentRom->rating = game.firstChildElement("Rating").text();

        foreach (QString ext, QStringList() << "jpg" << "png")
        {
            QString imageFile = getDataLocation() + "/cache/"
                                + currentRom->romMD5.toLower() + "/boxart-front." + ext;
            QFile cover(imageFile);

            if (cover.exists()&& currentRom->image.load(imageFile)) {
                currentRom->imageExists = true;
                break;
            }
        }
    }
}

void RomCollection::setupDatabase()
{
    database = QSqlDatabase::addDatabase("QSQLITE");
    database.setDatabaseName(getDataLocation() + "/mupen64plus-qt.sqlite");

    if (!database.open())
        QMessageBox::warning(parent, "Database Not Loaded",
                             "Could not connect to Sqlite database. Application may misbehave.");

    QSqlQuery query(QString()
                    + "CREATE TABLE IF NOT EXISTS rom_collection ("
                        + "rom_id INTEGER PRIMARY KEY ASC, "
                        + "filename TEXT NOT NULL, "
                        + "md5 TEXT NOT NULL, "
                        + "internal_name TEXT, "
                        + "zip_file TEXT, "
                        + "size INTEGER)", database);

    database.close();
}

void RomCollection::setupProgressDialog(int size)
{
    progress = new QProgressDialog("Loading ROMs...", "Cancel", 0, size, parent);
#if QT_VERSION >= 0x050000
    progress->setWindowFlags(progress->windowFlags() & ~Qt::WindowCloseButtonHint);
    progress->setWindowFlags(progress->windowFlags() & ~Qt::WindowMinimizeButtonHint);
    progress->setWindowFlags(progress->windowFlags() & ~Qt::WindowContextHelpButtonHint);
#else
    progress->setWindowFlags(Qt::Dialog | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
#endif
    progress->setCancelButton(0);
    progress->setWindowModality(Qt::WindowModal);

    progress->show();
}

void RomCollection::updatePath(QString romPath)
{
    this->romPath = romPath;
    this->romDir = QDir(romPath);
}
<|endoftext|>


<commit_before>#include <pthread.h>
#include <iostream.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/time.h>

#include "../rtstuff/rtdefs.h"
#include "sockdefs.h"
#include "../H/dbug.h"

#include "notetags.h"

extern "C" {
  double parse_dispatch(char*, double*, int);
}

extern "C" int rtInteractive;

extern int noParse;

double schedtime; 	// up here so that rtsetoutput can access this info
// (see below)

extern int socknew; 	// defined in main.C, offset from MYPORT for more than one simultaneous instrument
extern int noaudio;
extern int audio_config;

extern pthread_mutex_t pfieldLock;

extern "C" {
  void *sockit(void*)
  {

    extern double baseTime;
    extern long elapsed;
    double buftime,sec,usec;
    struct timeval tv;
    struct timezone tz;
    char ttext[MAXTEXTARGS][512];
    int i,tmpint;

    // socket stuff
    int s, ns;
    int len;
    struct sockaddr_in sss;
    int err;
    struct sockdata *sinfo;
    int amt,tamt;
    char *sptr;
    int val,optlen;
    double a,b,c;
    int ntag,pval;

    // tz.tz_minuteswest = 0;
    // tz.tz_dsttime = DST_NONE;

    // timerclear(&tv);
    /* create the socket for listening */

    cout << "ENTERING sockit() FUNCTION **********\n";
    if( (s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
      perror("socket");
      exit(1);
    }

    /* set up the receive buffer nicely for us */
    optlen = sizeof(char);
    val = sizeof(struct sockdata);
    setsockopt(s, SOL_SOCKET, SO_RCVBUF, &val, optlen);

    /* set up the socket address */
    sss.sin_family = AF_INET;
    sss.sin_addr.s_addr = INADDR_ANY;
    // socknew is offset from MYPORT to allow more than one inst
    sss.sin_port = htons(MYPORT+socknew);

    if( err = bind(s, (struct sockaddr *)&sss, sizeof(sss)) < 0) {
      perror("bind");
      exit(1);
    }

    listen(s, 1);

    len = sizeof(sss);
    ns = accept(s, (struct sockaddr *)&sss, &len);
    if(ns < 0) {
      perror("accept");
      exit(1);
    }
    else {

      buftime = (float)RTBUFSAMPS/SR;
      cout << "buftime:  " << buftime << endl;

      sinfo = new (struct sockdata);
      // Zero the socket structure
      sinfo->name[0] = '\0';
      for (i=0;i<MAXDISPARGS;i++) {
	sinfo->data.p[i] = 0;
      }

      // we do this when the -n flag is set, it has to parse rtsetparams()
      // coming over the socket before it can access the values of RTBUFSAMPS,
      // SR, NCHANS, etc.
      if (noParse) {
	cout << "sockit():  waiting for audio config\n";

	sptr = (char *)sinfo;
	amt = read(ns, (void *)sptr, sizeof(struct sockdata));
	while (amt < sizeof(struct sockdata)) amt += read(ns, (void *)(sptr+amt), sizeof(struct sockdata)-amt);

	parse_dispatch(sinfo->name, sinfo->data.p, sinfo->n_args);
      }

      buftime = (float)RTBUFSAMPS/SR;

      // Main socket reading loop
      while(1) {

	sptr = (char *)sinfo;
	amt = read(ns, (void *)sptr, sizeof(struct sockdata));
	while (amt < sizeof(struct sockdata)) amt += read(ns, (void *)(sptr+amt), sizeof(struct sockdata)-amt);

	if ( (strcmp(sinfo->name, "rtinput") == 0) || (strcmp(sinfo->name, "rtoutput") == 0) ) {
	  // these two commands use text data
	  // replace the text[i] with p[i] pointers
	  for (i = 0; i < sinfo->n_args; i++)
	    strcpy(ttext[i],sinfo->data.text[i]);
	  for (i = 0; i < sinfo->n_args; i++) {
	    tmpint = (int)ttext[i];
	    sinfo->data.p[i] = (double)tmpint;
	  }
	}

	if ( (strcmp(sinfo->name, "end") == 0) ) {
	  rtInteractive = 0;
	}

	// if it is an rtupdate, set the pval array
	if (strcmp(sinfo->name, "rtupdate") == 0) {
				// rtupdate params are:
				//	p0 = note tag # 0 for all notes
				//	p1,2... pn,pn+1 = pfield, value
	  ntag = sinfo->data.p[0];
	  pthread_mutex_lock(&pfieldLock);
	  for (i = 1; i < sinfo->n_args; i += 2) {
	    pval = sinfo->data.p[i];
	    pupdatevals[ntag][pval] = sinfo->data.p[i+1];
	  }
	  pthread_mutex_unlock(&pfieldLock);
	  tag_sem=1;
	}

	else {

	  gettimeofday(&tv, &tz);
	  sec = (double)tv.tv_sec;
	  usec = (double)tv.tv_usec;
	  schedtime = (((sec * 1e6) + usec) - baseTime) * 1e-6;
	  schedtime += ((double)elapsed/(double)SR);
	  schedtime += buftime;

#ifdef DBUG
	  cout << "sockit(): schedtime = " << schedtime << endl;
	  cout << "sockit(): buftime = " << buftime << endl;
	  cout << "sockit(): baseTime = " << baseTime << endl;
	  cout << "sockit(): elapsed = " << elapsed << endl;
	  cout << "sockit(): SR = " << SR << endl;
#endif

	  // schedtime is accessed in rtsetoutput() to
	  // set the current time.  Plus, in interactive
	  // mode we have to run a slight delay from
	  // "0" or we wind up scheduling events in the past.

	  if(sinfo->name) {
#ifdef ALLBUG
	    cout << "SOCKET RECIEVED\n";
	    cout << "sinfo->name = " << sinfo->name << endl;
	    cout << "sinfo->n_args = " << sinfo->n_args << endl;
	    for (i=0;i<sinfo->n_args;i++) {
	      cout << "sinfo->data.p[" << i << "] =" << sinfo->data.p[i] << endl;
	    }
#endif
	    parse_dispatch(sinfo->name, sinfo->data.p, sinfo->n_args);

	  }
	}
      }
    }
    cout << "EXITING sockit() FUNCTION **********\n";
  }
}
<commit_msg><commit_after>#include <pthread.h>
#include <iostream.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/time.h>

#include "../rtstuff/rtdefs.h"
#include "sockdefs.h"
#include "../H/dbug.h"

#include "notetags.h"

extern "C" {
  double parse_dispatch(char*, double*, int);
}

extern "C" int rtInteractive;

extern int noParse;

double schedtime; 	// up here so that rtsetoutput can access this info
// (see below)

extern int socknew; 	// defined in main.C, offset from MYPORT for more than one simultaneous instrument
extern int noaudio;
extern int audio_config;

extern pthread_mutex_t pfieldLock;

extern "C" {
  void *sockit(void*)
  {

    extern double baseTime;
    extern long elapsed;
    double buftime,sec,usec;
    struct timeval tv;
    struct timezone tz;
    char ttext[MAXTEXTARGS][512];
    int i,tmpint;

    // socket stuff
    int s, ns;
    int len;
    struct sockaddr_in sss;
    int err;
    struct sockdata *sinfo;
    int amt,tamt;
    char *sptr;
    int val,optlen;
    double a,b,c;
    int ntag,pval;

    // tz.tz_minuteswest = 0;
    // tz.tz_dsttime = DST_NONE;

    // timerclear(&tv);
    /* create the socket for listening */

    cout << "ENTERING sockit() FUNCTION **********\n";
    if( (s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
      perror("socket");
      exit(1);
    }

    /* set up the receive buffer nicely for us */
    optlen = sizeof(char);
    val = sizeof(struct sockdata);
    setsockopt(s, SOL_SOCKET, SO_RCVBUF, &val, optlen);

    /* set up the socket address */
    sss.sin_family = AF_INET;
    sss.sin_addr.s_addr = INADDR_ANY;
    // socknew is offset from MYPORT to allow more than one inst
    sss.sin_port = htons(MYPORT+socknew);

    if( err = bind(s, (struct sockaddr *)&sss, sizeof(sss)) < 0) {
      perror("bind");
      exit(1);
    }

    listen(s, 1);

    len = sizeof(sss);
    ns = accept(s, (struct sockaddr *)&sss, &len);
    if(ns < 0) {
      perror("accept");
      exit(1);
    }
    else {

      buftime = (float)RTBUFSAMPS/SR;
      cout << "buftime:  " << buftime << endl;

      sinfo = new (struct sockdata);
      // Zero the socket structure
      sinfo->name[0] = '\0';
      for (i=0;i<MAXDISPARGS;i++) {
	sinfo->data.p[i] = 0;
      }

      // we do this when the -n flag is set, it has to parse rtsetparams()
      // coming over the socket before it can access the values of RTBUFSAMPS,
      // SR, NCHANS, etc.
      if (noParse) {
	cout << "sockit():  waiting for audio config\n";

	sptr = (char *)sinfo;
	amt = read(ns, (void *)sptr, sizeof(struct sockdata));
	while (amt < sizeof(struct sockdata)) amt += read(ns, (void *)(sptr+amt), sizeof(struct sockdata)-amt);

	parse_dispatch(sinfo->name, sinfo->data.p, sinfo->n_args);
      }

      buftime = (float)RTBUFSAMPS/SR;

      // Main socket reading loop
      while(1) {

	sptr = (char *)sinfo;
	amt = read(ns, (void *)sptr, sizeof(struct sockdata));
	while (amt < sizeof(struct sockdata)) amt += read(ns, (void *)(sptr+amt), sizeof(struct sockdata)-amt);

	if ( (strcmp(sinfo->name, "rtinput") == 0) || (strcmp(sinfo->name, "rtoutput") == 0) (strcmp(sinfo->name "set_option") == 0) ) {
	  // these two commands use text data
	  // replace the text[i] with p[i] pointers
	  for (i = 0; i < sinfo->n_args; i++)
	    strcpy(ttext[i],sinfo->data.text[i]);
	  for (i = 0; i < sinfo->n_args; i++) {
	    tmpint = (int)ttext[i];
	    sinfo->data.p[i] = (double)tmpint;
	  }
	}

	if ( (strcmp(sinfo->name, "end") == 0) ) {
	  rtInteractive = 0;
	}

	// if it is an rtupdate, set the pval array
	if (strcmp(sinfo->name, "rtupdate") == 0) {
				// rtupdate params are:
				//	p0 = note tag # 0 for all notes
				//	p1,2... pn,pn+1 = pfield, value
	  ntag = sinfo->data.p[0];
	  pthread_mutex_lock(&pfieldLock);
	  for (i = 1; i < sinfo->n_args; i += 2) {
	    pval = sinfo->data.p[i];
	    pupdatevals[ntag][pval] = sinfo->data.p[i+1];
	  }
	  pthread_mutex_unlock(&pfieldLock);
	  tag_sem=1;
	}

	else {

	  gettimeofday(&tv, &tz);
	  sec = (double)tv.tv_sec;
	  usec = (double)tv.tv_usec;
	  schedtime = (((sec * 1e6) + usec) - baseTime) * 1e-6;
	  schedtime += ((double)elapsed/(double)SR);
	  schedtime += buftime;

#ifdef DBUG
	  cout << "sockit(): schedtime = " << schedtime << endl;
	  cout << "sockit(): buftime = " << buftime << endl;
	  cout << "sockit(): baseTime = " << baseTime << endl;
	  cout << "sockit(): elapsed = " << elapsed << endl;
	  cout << "sockit(): SR = " << SR << endl;
#endif

	  // schedtime is accessed in rtsetoutput() to
	  // set the current time.  Plus, in interactive
	  // mode we have to run a slight delay from
	  // "0" or we wind up scheduling events in the past.

	  if(sinfo->name) {
#ifdef ALLBUG
	    cout << "SOCKET RECIEVED\n";
	    cout << "sinfo->name = " << sinfo->name << endl;
	    cout << "sinfo->n_args = " << sinfo->n_args << endl;
	    for (i=0;i<sinfo->n_args;i++) {
	      cout << "sinfo->data.p[" << i << "] =" << sinfo->data.p[i] << endl;
	    }
#endif
	    parse_dispatch(sinfo->name, sinfo->data.p, sinfo->n_args);

	  }
	}
      }
    }
    cout << "EXITING sockit() FUNCTION **********\n";
  }
}
<|endoftext|>


<commit_before>//===- Signals.cpp - Signal Handling support ------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines some helpful functions for dealing with the possibility of
// Unix signals occuring while your program is running.
//
//===----------------------------------------------------------------------===//

#include "Support/Signals.h"
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <cstdio>
//#include <execinfo.h>
#include <signal.h>
#include <unistd.h>
#include "Config/config.h"     // Get the signal handler return type
using namespace llvm;

static std::vector<std::string> FilesToRemove;

// IntSigs - Signals that may interrupt the program at any time.
static const int IntSigs[] = {
  SIGHUP, SIGINT, SIGQUIT, SIGKILL, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
};
static const int *IntSigsEnd = IntSigs + sizeof(IntSigs)/sizeof(IntSigs[0]);

// KillSigs - Signals that are synchronous with the program that will cause it
// to die.
static const int KillSigs[] = {
  SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGSYS, SIGXCPU, SIGXFSZ
#ifdef SIGEMT
  , SIGEMT
#endif
};
static const int *KillSigsEnd = KillSigs + sizeof(KillSigs)/sizeof(KillSigs[0]);

static void* StackTrace[256];

// SignalHandler - The signal handler that runs...
static RETSIGTYPE SignalHandler(int Sig) {
  while (!FilesToRemove.empty()) {
    std::remove(FilesToRemove.back().c_str());
    FilesToRemove.pop_back();
  }

  if (std::find(IntSigs, IntSigsEnd, Sig) != IntSigsEnd)
    exit(1);   // If this is an interrupt signal, exit the program

  // Otherwise if it is a fault (like SEGV) output the stacktrace to
  // STDERR and reissue the signal to die...
  //int depth = backtrace(StackTrace, sizeof(StackTrace)/sizeof(StackTrace[0]));
  //backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
  signal(Sig, SIG_DFL);
}

static void RegisterHandler(int Signal) { signal(Signal, SignalHandler); }

// RemoveFileOnSignal - The public API
void llvm::RemoveFileOnSignal(const std::string &Filename) {
  FilesToRemove.push_back(Filename);

  std::for_each(IntSigs, IntSigsEnd, RegisterHandler);
  std::for_each(KillSigs, KillSigsEnd, RegisterHandler);
}

/// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
/// SIGSEGV) is delivered to the process, print a stack trace and then exit.
void llvm::PrintStackTraceOnErrorSignal() {
  std::for_each(KillSigs, KillSigsEnd, RegisterHandler);
}
<commit_msg>Use backtrace() and include execinfo.h, if they were detected by autoconf.<commit_after>//===- Signals.cpp - Signal Handling support ------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines some helpful functions for dealing with the possibility of
// Unix signals occuring while your program is running.
//
//===----------------------------------------------------------------------===//

#include "Support/Signals.h"
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include "Config/config.h"     // Get the signal handler return type
#ifdef HAVE_EXECINFO_H
# include <execinfo.h>         // For backtrace().
#endif
#include <signal.h>
#include <unistd.h>
using namespace llvm;

static std::vector<std::string> FilesToRemove;

// IntSigs - Signals that may interrupt the program at any time.
static const int IntSigs[] = {
  SIGHUP, SIGINT, SIGQUIT, SIGKILL, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
};
static const int *IntSigsEnd = IntSigs + sizeof(IntSigs)/sizeof(IntSigs[0]);

// KillSigs - Signals that are synchronous with the program that will cause it
// to die.
static const int KillSigs[] = {
  SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGSYS, SIGXCPU, SIGXFSZ
#ifdef SIGEMT
  , SIGEMT
#endif
};
static const int *KillSigsEnd = KillSigs + sizeof(KillSigs)/sizeof(KillSigs[0]);

static void* StackTrace[256];

// SignalHandler - The signal handler that runs...
static RETSIGTYPE SignalHandler(int Sig) {
  while (!FilesToRemove.empty()) {
    std::remove(FilesToRemove.back().c_str());
    FilesToRemove.pop_back();
  }

  if (std::find(IntSigs, IntSigsEnd, Sig) != IntSigsEnd)
    exit(1);   // If this is an interrupt signal, exit the program

  // Otherwise if it is a fault (like SEGV) output the stacktrace to
  // STDERR (if we can) and reissue the signal to die...
#ifdef HAVE_BACKTRACE
  // Use backtrace() to output a backtrace on Linux systems with glibc.
  int depth = backtrace(StackTrace, sizeof(StackTrace)/sizeof(StackTrace[0]));
  backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
#endif
  signal(Sig, SIG_DFL);
}

static void RegisterHandler(int Signal) { signal(Signal, SignalHandler); }

// RemoveFileOnSignal - The public API
void llvm::RemoveFileOnSignal(const std::string &Filename) {
  FilesToRemove.push_back(Filename);

  std::for_each(IntSigs, IntSigsEnd, RegisterHandler);
  std::for_each(KillSigs, KillSigsEnd, RegisterHandler);
}

/// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
/// SIGSEGV) is delivered to the process, print a stack trace and then exit.
void llvm::PrintStackTraceOnErrorSignal() {
  std::for_each(KillSigs, KillSigsEnd, RegisterHandler);
}
<|endoftext|>


<commit_before>/*
 * Copyright 2016 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkSLUtil.h"

#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include <cinttypes>

namespace SkSL {

SkString to_string(double value) {
#ifdef SK_BUILD_FOR_WIN
    #define SNPRINTF    _snprintf
#else
    #define SNPRINTF    snprintf
#endif
#define MAX_DOUBLE_CHARS 25
    char buffer[MAX_DOUBLE_CHARS];
    SkDEBUGCODE(int len = )SNPRINTF(buffer, sizeof(buffer), "%.17g", value);
    ASSERT(len < MAX_DOUBLE_CHARS);
    SkString result(buffer);
    if (!strchr(buffer, '.') && !strchr(buffer, 'e')) {
        result += ".0";
    }
    return result;
#undef SNPRINTF
#undef MAX_DOUBLE_CHARS
}

SkString to_string(int32_t value) {
    return SkStringPrintf("%d", value);
}

SkString to_string(uint32_t value) {
    return SkStringPrintf("%u", value);
}

SkString to_string(int64_t value) {
    return SkStringPrintf("%" PRId64, value);
}

SkString to_string(uint64_t value) {
    return SkStringPrintf("%" PRIu64, value);
}

int stoi(SkString s) {
    if (s.size() > 2 && s[0] == '0' && s[1] == 'x') {
        char* p;
        int result = strtoul(s.c_str() + 2, &p, 16);
        ASSERT(*p == 0);
        return result;
    }
    return atoi(s.c_str());
}

double stod(SkString s) {
    return atof(s.c_str());
}

long stol(SkString s) {
    if (s.size() > 2 && s[0] == '0' && s[1] == 'x') {
        char* p;
        long result = strtoul(s.c_str() + 2, &p, 16);
        ASSERT(*p == 0);
        return result;
    }
    return atol(s.c_str());
}

void sksl_abort() {
#ifdef SKIA
    sk_abort_no_print();
    exit(1);
#else
    abort();
#endif
}

void write_data(const SkData& data, SkWStream& out) {
    out.write(data.data(), data.size());
}

SkString operator+(const SkString& s, const char* c) {
    SkString result(s);
    result += c;
    return result;
}

SkString operator+(const char* c, const SkString& s) {
    SkString result(c);
    result += s;
    return result;
}

SkString operator+(const SkString& s1, const SkString& s2) {
    SkString result(s1);
    result += s2;
    return result;
}

bool operator==(const SkString& s1, const char* s2) {
    return !strcmp(s1.c_str(), s2);
}

bool operator!=(const SkString& s1, const char* s2) {
    return strcmp(s1.c_str(), s2);
}

bool operator!=(const char* s1, const SkString& s2) {
    return strcmp(s1, s2.c_str());
}
} // namespace
<commit_msg>Force classic locale when parsing floats in skslc.<commit_after>/*
 * Copyright 2016 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkSLUtil.h"

#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include <cinttypes>
#include <locale>
#include <sstream>
#include <string>

namespace SkSL {

SkString to_string(double value) {
#ifdef SK_BUILD_FOR_WIN
    #define SNPRINTF    _snprintf
#else
    #define SNPRINTF    snprintf
#endif
#define MAX_DOUBLE_CHARS 25
    char buffer[MAX_DOUBLE_CHARS];
    SkDEBUGCODE(int len = )SNPRINTF(buffer, sizeof(buffer), "%.17g", value);
    ASSERT(len < MAX_DOUBLE_CHARS);
    SkString result(buffer);
    if (!strchr(buffer, '.') && !strchr(buffer, 'e')) {
        result += ".0";
    }
    return result;
#undef SNPRINTF
#undef MAX_DOUBLE_CHARS
}

SkString to_string(int32_t value) {
    return SkStringPrintf("%d", value);
}

SkString to_string(uint32_t value) {
    return SkStringPrintf("%u", value);
}

SkString to_string(int64_t value) {
    return SkStringPrintf("%" PRId64, value);
}

SkString to_string(uint64_t value) {
    return SkStringPrintf("%" PRIu64, value);
}

int stoi(SkString s) {
    if (s.size() > 2 && s[0] == '0' && s[1] == 'x') {
        char* p;
        int result = strtoul(s.c_str() + 2, &p, 16);
        ASSERT(*p == 0);
        return result;
    }
    return atoi(s.c_str());
}

double stod(SkString s) {
    double result;
    std::string str(s.c_str(), s.size());
    std::stringstream buffer(str);
    buffer.imbue(std::locale::classic());
    buffer >> result;
    return result;
}

long stol(SkString s) {
    if (s.size() > 2 && s[0] == '0' && s[1] == 'x') {
        char* p;
        long result = strtoul(s.c_str() + 2, &p, 16);
        ASSERT(*p == 0);
        return result;
    }
    return atol(s.c_str());
}

void sksl_abort() {
#ifdef SKIA
    sk_abort_no_print();
    exit(1);
#else
    abort();
#endif
}

void write_data(const SkData& data, SkWStream& out) {
    out.write(data.data(), data.size());
}

SkString operator+(const SkString& s, const char* c) {
    SkString result(s);
    result += c;
    return result;
}

SkString operator+(const char* c, const SkString& s) {
    SkString result(c);
    result += s;
    return result;
}

SkString operator+(const SkString& s1, const SkString& s2) {
    SkString result(s1);
    result += s2;
    return result;
}

bool operator==(const SkString& s1, const char* s2) {
    return !strcmp(s1.c_str(), s2);
}

bool operator!=(const SkString& s1, const char* s2) {
    return strcmp(s1.c_str(), s2);
}

bool operator!=(const char* s1, const SkString& s2) {
    return strcmp(s1, s2.c_str());
}
} // namespace
<|endoftext|>


<commit_before>#ifndef PYOSMIUM_GENERIC_HANDLER_HPP
#define PYOSMIUM_GENERIC_HANDLER_HPP

#include <osmium/area/assembler.hpp>
#include <osmium/area/multipolygon_collector.hpp>
#include <osmium/handler.hpp>
#include <osmium/handler/node_locations_for_ways.hpp>
#include <osmium/index/map/all.hpp>
#include <osmium/io/any_input.hpp>
#include <osmium/io/file.hpp>
#include <osmium/visitor.hpp>

#include <boost/python.hpp>

typedef osmium::index::map::Map<osmium::unsigned_object_id_type, osmium::Location> index_type;

class BaseHandler : public osmium::handler::Handler {

protected:
    enum pre_handler {
        no_handler,
        location_handler,
        area_handler
    };

public:
virtual void apply_start() {};
// handler functions
virtual void node(const osmium::Node&) = 0;
virtual void way(const osmium::Way&) = 0;
virtual void relation(const osmium::Relation&) = 0;
virtual void changeset(const osmium::Changeset&) = 0;
virtual void area(const osmium::Area&) = 0;

private:
void apply_with_location(osmium::io::Reader &r, const std::string &idx) {
    const auto& map_factory = osmium::index::MapFactory<osmium::unsigned_object_id_type, osmium::Location>::instance();
    std::unique_ptr<index_type> index = map_factory.create_map(idx);
    osmium::handler::NodeLocationsForWays<index_type> location_handler(*index);
    location_handler.ignore_errors();
    osmium::apply(r, location_handler, *this);
}

void apply_with_area(osmium::io::Reader &r,
                     osmium::area::MultipolygonCollector<osmium::area::Assembler> &collector,
                     const std::string &idx) {
    const auto& map_factory = osmium::index::MapFactory<osmium::unsigned_object_id_type, osmium::Location>::instance();
    std::unique_ptr<index_type> index = map_factory.create_map(idx);
    osmium::handler::NodeLocationsForWays<index_type> location_handler(*index);
    location_handler.ignore_errors();

    osmium::apply(r, location_handler, *this,
                  collector.handler([this](const osmium::memory::Buffer& area_buffer) {
                       osmium::apply(area_buffer, *this);
                  })
                 );
}

protected:
void apply(const osmium::io::File &file, osmium::osm_entity_bits::type types,
           pre_handler pre = no_handler,
           const std::string &idx = "sparse_mem_array") {

    switch (pre) {
    case no_handler:
        {
            osmium::io::Reader reader(file, types);
            osmium::apply(reader, *this);
            reader.close();
            break;
        }
    case location_handler:
        {
            osmium::io::Reader reader(file, types);
            apply_with_location(reader, idx);
            reader.close();
            break;
        }
    case area_handler:
        {
            osmium::area::Assembler::config_type assembler_config;
            osmium::area::MultipolygonCollector<osmium::area::Assembler> collector(assembler_config);

            osmium::io::Reader reader1(file);
            collector.read_relations(reader1);
            reader1.close();

            osmium::io::Reader reader2(file);
            apply_with_area(reader2, collector, idx);
            reader2.close();
            break;
        }
    }
}

};

using namespace boost::python;

struct SimpleHandlerWrap: BaseHandler, wrapper<BaseHandler> {

    void node(const osmium::Node& node) override {
        if (!(m_callbacks & osmium::osm_entity_bits::node))
            return;

        if (override f = this->get_override("node")) {
            f(boost::ref(node));
        }
    }

    void way(const osmium::Way& way) {
        if (!(m_callbacks & osmium::osm_entity_bits::way))
            return;

        if (override f = this->get_override("way"))
            f(boost::ref(way));
    }

    void relation(const osmium::Relation& rel) {
        if (!(m_callbacks & osmium::osm_entity_bits::relation))
            return;

        if (override f = this->get_override("relation"))
            f(boost::ref(rel));
    }

    void changeset(const osmium::Changeset& cs) {
        if (!(m_callbacks & osmium::osm_entity_bits::changeset))
            return;

        if (override f = this->get_override("changeset"))
            f(boost::ref(cs));
    }

    void area(const osmium::Area& area) {
        if (!(m_callbacks & osmium::osm_entity_bits::area))
            return;

        if (override f = this->get_override("area"))
            f(boost::ref(area));
    }

    void apply_file(const std::string &filename, bool locations = false,
                    const std::string &idx = "sparse_mem_array")
    {
        apply_object(osmium::io::File(filename), locations, idx);
    }

    void apply_buffer(const boost::python::object &buf, const boost::python::str &format,
                      bool locations = false,
                      const std::string &idx = "sparse_mem_array")
    {
        Py_buffer pybuf;
        PyObject_GetBuffer(buf.ptr(), &pybuf, PyBUF_C_CONTIGUOUS);
        size_t len = (size_t) pybuf.len;
        const char *cbuf = reinterpret_cast<const char *>(pybuf.buf);
        const char *cfmt = boost::python::extract<const char *>(format);

        apply_object(osmium::io::File(cbuf, len, cfmt), locations, idx);
    }

    void apply_start() override {
        m_callbacks = osmium::osm_entity_bits::nothing;
        if (hasfunc("node"))
            m_callbacks |= osmium::osm_entity_bits::node;
        if (hasfunc("way"))
            m_callbacks |= osmium::osm_entity_bits::way;
        if (hasfunc("relation"))
            m_callbacks |= osmium::osm_entity_bits::relation;
        if (hasfunc("area"))
            m_callbacks |= osmium::osm_entity_bits::area;
        if (hasfunc("changeset"))
            m_callbacks |= osmium::osm_entity_bits::changeset;
    }

private:
    void apply_object(osmium::io::File file, bool locations, const std::string &idx)
    {
        osmium::osm_entity_bits::type entities = osmium::osm_entity_bits::nothing;
        BaseHandler::pre_handler handler = locations?
                                            BaseHandler::location_handler
                                            :BaseHandler::no_handler;

        apply_start();

        if (m_callbacks & osmium::osm_entity_bits::area)
        {
            entities = osmium::osm_entity_bits::object;
            handler = BaseHandler::area_handler;
        } else {
            if (locations || m_callbacks & osmium::osm_entity_bits::node)
                entities |= osmium::osm_entity_bits::node;
            if (m_callbacks & osmium::osm_entity_bits::way)
                entities |= osmium::osm_entity_bits::way;
            if (m_callbacks & osmium::osm_entity_bits::relation)
                entities |= osmium::osm_entity_bits::relation;
        }

        if (m_callbacks & osmium::osm_entity_bits::changeset)
            entities |= osmium::osm_entity_bits::changeset;

        apply(file, entities, handler, idx);
    }

    bool hasfunc(char const *name) {
        reference_existing_object::apply<SimpleHandlerWrap*>::type converter;
        PyObject* obj = converter( this );

        if (PyObject_HasAttrString(obj, name)) {
            auto o = boost::python::object(handle<>(obj));
            return o.attr(name) != boost::python::object();
        }

        return false;
    }

    osmium::osm_entity_bits::type m_callbacks;
};

#endif
<commit_msg>switch to MultipolygonManager<commit_after>#ifndef PYOSMIUM_GENERIC_HANDLER_HPP
#define PYOSMIUM_GENERIC_HANDLER_HPP

#include <osmium/area/assembler.hpp>
#include <osmium/area/multipolygon_manager.hpp>
#include <osmium/handler.hpp>
#include <osmium/handler/node_locations_for_ways.hpp>
#include <osmium/index/map/all.hpp>
#include <osmium/io/any_input.hpp>
#include <osmium/io/file.hpp>
#include <osmium/visitor.hpp>

#include <boost/python.hpp>

typedef osmium::index::map::Map<osmium::unsigned_object_id_type, osmium::Location> index_type;

class BaseHandler : public osmium::handler::Handler {

protected:
    enum pre_handler {
        no_handler,
        location_handler,
        area_handler
    };

public:
virtual void apply_start() {};
// handler functions
virtual void node(const osmium::Node&) = 0;
virtual void way(const osmium::Way&) = 0;
virtual void relation(const osmium::Relation&) = 0;
virtual void changeset(const osmium::Changeset&) = 0;
virtual void area(const osmium::Area&) = 0;

private:
void apply_with_location(osmium::io::Reader &r, const std::string &idx) {
    const auto& map_factory = osmium::index::MapFactory<osmium::unsigned_object_id_type, osmium::Location>::instance();
    std::unique_ptr<index_type> index = map_factory.create_map(idx);
    osmium::handler::NodeLocationsForWays<index_type> location_handler(*index);
    location_handler.ignore_errors();
    osmium::apply(r, location_handler, *this);
}

void apply_with_area(osmium::io::Reader &r,
                     osmium::area::MultipolygonManager<osmium::area::Assembler> &mp_manager,
                     const std::string &idx) {
    const auto& map_factory = osmium::index::MapFactory<osmium::unsigned_object_id_type, osmium::Location>::instance();
    std::unique_ptr<index_type> index = map_factory.create_map(idx);
    osmium::handler::NodeLocationsForWays<index_type> location_handler(*index);
    location_handler.ignore_errors();

    osmium::apply(r, location_handler, *this,
                  mp_manager.handler([this](const osmium::memory::Buffer& area_buffer) {
                       osmium::apply(area_buffer, *this);
                  })
                 );
}

protected:
void apply(const osmium::io::File &file, osmium::osm_entity_bits::type types,
           pre_handler pre = no_handler,
           const std::string &idx = "sparse_mem_array") {

    switch (pre) {
    case no_handler:
        {
            osmium::io::Reader reader(file, types);
            osmium::apply(reader, *this);
            reader.close();
            break;
        }
    case location_handler:
        {
            osmium::io::Reader reader(file, types);
            apply_with_location(reader, idx);
            reader.close();
            break;
        }
    case area_handler:
        {
            osmium::area::Assembler::config_type assembler_config;
            osmium::area::MultipolygonManager<osmium::area::Assembler> mp_manager{assembler_config};

            osmium::relations::read_relations(file, mp_manager);

            osmium::io::Reader reader2(file);
            apply_with_area(reader2, mp_manager, idx);
            reader2.close();
            break;
        }
    }
}

};

using namespace boost::python;

struct SimpleHandlerWrap: BaseHandler, wrapper<BaseHandler> {

    void node(const osmium::Node& node) override {
        if (!(m_callbacks & osmium::osm_entity_bits::node))
            return;

        if (override f = this->get_override("node")) {
            f(boost::ref(node));
        }
    }

    void way(const osmium::Way& way) {
        if (!(m_callbacks & osmium::osm_entity_bits::way))
            return;

        if (override f = this->get_override("way"))
            f(boost::ref(way));
    }

    void relation(const osmium::Relation& rel) {
        if (!(m_callbacks & osmium::osm_entity_bits::relation))
            return;

        if (override f = this->get_override("relation"))
            f(boost::ref(rel));
    }

    void changeset(const osmium::Changeset& cs) {
        if (!(m_callbacks & osmium::osm_entity_bits::changeset))
            return;

        if (override f = this->get_override("changeset"))
            f(boost::ref(cs));
    }

    void area(const osmium::Area& area) {
        if (!(m_callbacks & osmium::osm_entity_bits::area))
            return;

        if (override f = this->get_override("area"))
            f(boost::ref(area));
    }

    void apply_file(const std::string &filename, bool locations = false,
                    const std::string &idx = "sparse_mem_array")
    {
        apply_object(osmium::io::File(filename), locations, idx);
    }

    void apply_buffer(const boost::python::object &buf, const boost::python::str &format,
                      bool locations = false,
                      const std::string &idx = "sparse_mem_array")
    {
        Py_buffer pybuf;
        PyObject_GetBuffer(buf.ptr(), &pybuf, PyBUF_C_CONTIGUOUS);
        size_t len = (size_t) pybuf.len;
        const char *cbuf = reinterpret_cast<const char *>(pybuf.buf);
        const char *cfmt = boost::python::extract<const char *>(format);

        apply_object(osmium::io::File(cbuf, len, cfmt), locations, idx);
    }

    void apply_start() override {
        m_callbacks = osmium::osm_entity_bits::nothing;
        if (hasfunc("node"))
            m_callbacks |= osmium::osm_entity_bits::node;
        if (hasfunc("way"))
            m_callbacks |= osmium::osm_entity_bits::way;
        if (hasfunc("relation"))
            m_callbacks |= osmium::osm_entity_bits::relation;
        if (hasfunc("area"))
            m_callbacks |= osmium::osm_entity_bits::area;
        if (hasfunc("changeset"))
            m_callbacks |= osmium::osm_entity_bits::changeset;
    }

private:
    void apply_object(osmium::io::File file, bool locations, const std::string &idx)
    {
        osmium::osm_entity_bits::type entities = osmium::osm_entity_bits::nothing;
        BaseHandler::pre_handler handler = locations?
                                            BaseHandler::location_handler
                                            :BaseHandler::no_handler;

        apply_start();

        if (m_callbacks & osmium::osm_entity_bits::area)
        {
            entities = osmium::osm_entity_bits::object;
            handler = BaseHandler::area_handler;
        } else {
            if (locations || m_callbacks & osmium::osm_entity_bits::node)
                entities |= osmium::osm_entity_bits::node;
            if (m_callbacks & osmium::osm_entity_bits::way)
                entities |= osmium::osm_entity_bits::way;
            if (m_callbacks & osmium::osm_entity_bits::relation)
                entities |= osmium::osm_entity_bits::relation;
        }

        if (m_callbacks & osmium::osm_entity_bits::changeset)
            entities |= osmium::osm_entity_bits::changeset;

        apply(file, entities, handler, idx);
    }

    bool hasfunc(char const *name) {
        reference_existing_object::apply<SimpleHandlerWrap*>::type converter;
        PyObject* obj = converter( this );

        if (PyObject_HasAttrString(obj, name)) {
            auto o = boost::python::object(handle<>(obj));
            return o.attr(name) != boost::python::object();
        }

        return false;
    }

    osmium::osm_entity_bits::type m_callbacks;
};

#endif
<|endoftext|>


<commit_before>/*
 * opencog/atomspace/TruthValue.cc
 *
 * Copyright (C) 2002-2007 Novamente LLC
 * All Rights Reserved
 *
 * Written by Welter Silva <welter@vettalabs.com>
 *            Guilherme Lamacie
 *
 * 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 <sstream>

#include <float.h>
#include <math.h>
#include <stdio.h>

#include <opencog/atoms/truthvalue/CountTruthValue.h>
#include <opencog/atoms/truthvalue/FuzzyTruthValue.h>
#include <opencog/atoms/truthvalue/IndefiniteTruthValue.h>
#include <opencog/atoms/truthvalue/ProbabilisticTruthValue.h>
#include <opencog/atoms/truthvalue/SimpleTruthValue.h>
#include <opencog/atoms/truthvalue/TruthValue.h>

namespace opencog {

const strength_t MAX_TRUTH  = 1.0;

std::string TruthValue::to_short_string(const std::string& indent) const
{
	return to_string(indent);
}

TruthValuePtr TruthValue::DEFAULT_TV()
{
	// True, but no confidence.
	static TruthValuePtr instance(std::make_shared<SimpleTruthValue>(MAX_TRUTH, 0.0f));
	return instance;
}

TruthValuePtr TruthValue::TRUE_TV()
{
	// True, with maximum confidence.
	static TruthValuePtr instance(std::make_shared<SimpleTruthValue>(MAX_TRUTH, 1.0f));
	return instance;
}

TruthValuePtr TruthValue::FALSE_TV()
{
	// False, with maximum confidence.
	static TruthValuePtr instance(std::make_shared<SimpleTruthValue>(0.0f, 1.0f));
	return instance;
}

TruthValuePtr TruthValue::TRIVIAL_TV()
{
	// False, with no confidence.
	static TruthValuePtr instance(std::make_shared<SimpleTruthValue>(0.0, 0.0));
	return instance;
}

bool TruthValue::isDefaultTV() const
{
	TruthValuePtr dtv = DEFAULT_TV();
	if (dtv.get() == this) return true;
	if (get_type() == dtv->get_type() and
	    get_mean() == dtv->get_mean() and
	    get_confidence() == dtv->get_confidence())
	{
		return true;
	}
	return false;
}

/**
 * Return true if the TV value is one of the pre-defined TV values.
 */
bool TruthValue::isDefinedTV() const
{
	TruthValuePtr dtv = DEFAULT_TV();
	if (dtv.get() == this) return true;
	if (get_type() == dtv->get_type() and
	    get_mean() == dtv->get_mean() and
	    get_confidence() == dtv->get_confidence())
	{
		return true;
	}

	dtv = TRUE_TV();
	if (dtv.get() == this) return true;

	dtv = FALSE_TV();
	if (dtv.get() == this) return true;

	dtv = TRIVIAL_TV();
	if (dtv.get() == this) return true;

	dtv = TRUE_TV();
	if (get_type() == dtv->get_type() and
	    get_mean() == dtv->get_mean() and
	    get_confidence() == dtv->get_confidence())
	{
		return true;
	}

	dtv = FALSE_TV();
	if (get_type() == dtv->get_type() and
	    get_mean() == dtv->get_mean() and
	    get_confidence() == dtv->get_confidence())
	{
		return true;
	}

	dtv = TRIVIAL_TV();
	if (get_type() == dtv->get_type() and
	    get_mean() == dtv->get_mean() and
	    get_confidence() == dtv->get_confidence())
	{
		return true;
	}
	return false;
}

bool TruthValue::nearly_equal(double a, double b)
{
	if (a == b) return true;

// Anything smaller than this will fail BasicSaveUTest
#define ACCEPTABLE_ERROR (5.0 * DBL_EPSILON)
	double diff = fabs(b - a);
	if (a == 0.0 or b == 0.0 or diff < DBL_MIN)
		return diff < ACCEPTABLE_ERROR * DBL_MIN;

	double absa = fabs(a);
	double absb = fabs(b);
	return diff / fmin (absa+absb, DBL_MAX) < ACCEPTABLE_ERROR;
}

TruthValuePtr
TruthValue::higher_confidence_merge(const TruthValuePtr& other) const
{
	if (other->get_confidence() > get_confidence()) {
		return other;
	}
	return std::dynamic_pointer_cast<const TruthValue>(shared_from_this());
}

TruthValuePtr TruthValue::factory(Type t, const std::vector<double>& v)
{
	ValuePtr pap = createFloatValue(t,v);
	return factory(pap);
}

TruthValuePtr TruthValue::factory(const ValuePtr& pap)
{
	Type t = pap->get_type();
	if (SIMPLE_TRUTH_VALUE == t)
		return SimpleTruthValue::createTV(pap);
	if (COUNT_TRUTH_VALUE == t)
		return CountTruthValue::createTV(pap);
	if (FUZZY_TRUTH_VALUE == t)
		return FuzzyTruthValue::createTV(pap);
	if (INDEFINITE_TRUTH_VALUE == t)
		return IndefiniteTruthValue::createTV(pap);
	if (PROBABILISTIC_TRUTH_VALUE == t)
		return ProbabilisticTruthValue::createTV(pap);

	throw RuntimeException(TRACE_INFO,
		"Unknown TruthValue type %d", t);
	return nullptr;
}

std::string oc_to_string(TruthValuePtr tv, const std::string& indent)
{
	if (tv)
		return tv->to_string();
	return "none";
}

std::string oc_to_string(const TruthValueSeq& tvs, const std::string& indent)
{
	std::stringstream ss;
	ss << indent << "size = " << tvs.size() << std::endl;
	size_t i = 0;
	for (const TruthValuePtr& tv : tvs) {
		ss << indent << "tv[" << i << "]: " << oc_to_string(tv);
		i++;
	}
	return ss.str();
}

} // ~namespace opencog
<commit_msg>Cleanup older style of code<commit_after>/*
 * opencog/atomspace/TruthValue.cc
 *
 * Copyright (C) 2002-2007 Novamente LLC
 * All Rights Reserved
 *
 * Written by Welter Silva <welter@vettalabs.com>
 *            Guilherme Lamacie
 *
 * 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 <sstream>

#include <float.h>
#include <math.h>
#include <stdio.h>

#include <opencog/atoms/truthvalue/CountTruthValue.h>
#include <opencog/atoms/truthvalue/FuzzyTruthValue.h>
#include <opencog/atoms/truthvalue/IndefiniteTruthValue.h>
#include <opencog/atoms/truthvalue/ProbabilisticTruthValue.h>
#include <opencog/atoms/truthvalue/SimpleTruthValue.h>
#include <opencog/atoms/truthvalue/TruthValue.h>

namespace opencog {

const strength_t MAX_TRUTH  = 1.0;

std::string TruthValue::to_short_string(const std::string& indent) const
{
	return to_string(indent);
}

TruthValuePtr TruthValue::DEFAULT_TV()
{
	// True, but no confidence.
	static TruthValuePtr instance(std::make_shared<SimpleTruthValue>(MAX_TRUTH, 0.0));
	return instance;
}

TruthValuePtr TruthValue::TRUE_TV()
{
	// True, with maximum confidence.
	static TruthValuePtr instance(std::make_shared<SimpleTruthValue>(MAX_TRUTH, 1.0));
	return instance;
}

TruthValuePtr TruthValue::FALSE_TV()
{
	// False, with maximum confidence.
	static TruthValuePtr instance(std::make_shared<SimpleTruthValue>(0.0, 1.0));
	return instance;
}

TruthValuePtr TruthValue::TRIVIAL_TV()
{
	// False, with no confidence.
	static TruthValuePtr instance(std::make_shared<SimpleTruthValue>(0.0, 0.0));
	return instance;
}

bool TruthValue::isDefaultTV() const
{
	static TruthValuePtr dtv(DEFAULT_TV());
	if (dtv.get() == this) return true;
	if (get_type() == dtv->get_type() and
	    get_mean() == dtv->get_mean() and
	    get_confidence() == dtv->get_confidence())
	{
		return true;
	}
	return false;
}

/**
 * Return true if the TV value is one of the pre-defined TV values.
 */
bool TruthValue::isDefinedTV() const
{
	TruthValuePtr dtv = DEFAULT_TV();
	if (dtv.get() == this) return true;
	if (get_type() == dtv->get_type() and
	    get_mean() == dtv->get_mean() and
	    get_confidence() == dtv->get_confidence())
	{
		return true;
	}

	dtv = TRUE_TV();
	if (dtv.get() == this) return true;

	dtv = FALSE_TV();
	if (dtv.get() == this) return true;

	dtv = TRIVIAL_TV();
	if (dtv.get() == this) return true;

	dtv = TRUE_TV();
	if (get_type() == dtv->get_type() and
	    get_mean() == dtv->get_mean() and
	    get_confidence() == dtv->get_confidence())
	{
		return true;
	}

	dtv = FALSE_TV();
	if (get_type() == dtv->get_type() and
	    get_mean() == dtv->get_mean() and
	    get_confidence() == dtv->get_confidence())
	{
		return true;
	}

	dtv = TRIVIAL_TV();
	if (get_type() == dtv->get_type() and
	    get_mean() == dtv->get_mean() and
	    get_confidence() == dtv->get_confidence())
	{
		return true;
	}
	return false;
}

bool TruthValue::nearly_equal(double a, double b)
{
	if (a == b) return true;

// Anything smaller than this will fail BasicSaveUTest
#define ACCEPTABLE_ERROR (5.0 * DBL_EPSILON)
	double diff = fabs(b - a);
	if (a == 0.0 or b == 0.0 or diff < DBL_MIN)
		return diff < ACCEPTABLE_ERROR * DBL_MIN;

	double absa = fabs(a);
	double absb = fabs(b);
	return diff / fmin (absa+absb, DBL_MAX) < ACCEPTABLE_ERROR;
}

TruthValuePtr
TruthValue::higher_confidence_merge(const TruthValuePtr& other) const
{
	if (other->get_confidence() > get_confidence()) {
		return other;
	}
	return std::dynamic_pointer_cast<const TruthValue>(shared_from_this());
}

TruthValuePtr TruthValue::factory(Type t, const std::vector<double>& v)
{
	ValuePtr pap = createFloatValue(t,v);
	return factory(pap);
}

TruthValuePtr TruthValue::factory(const ValuePtr& pap)
{
	Type t = pap->get_type();
	if (SIMPLE_TRUTH_VALUE == t)
		return SimpleTruthValue::createTV(pap);
	if (COUNT_TRUTH_VALUE == t)
		return CountTruthValue::createTV(pap);
	if (FUZZY_TRUTH_VALUE == t)
		return FuzzyTruthValue::createTV(pap);
	if (INDEFINITE_TRUTH_VALUE == t)
		return IndefiniteTruthValue::createTV(pap);
	if (PROBABILISTIC_TRUTH_VALUE == t)
		return ProbabilisticTruthValue::createTV(pap);

	throw RuntimeException(TRACE_INFO,
		"Unknown TruthValue type %d", t);
	return nullptr;
}

std::string oc_to_string(TruthValuePtr tv, const std::string& indent)
{
	if (tv)
		return tv->to_string();
	return "none";
}

std::string oc_to_string(const TruthValueSeq& tvs, const std::string& indent)
{
	std::stringstream ss;
	ss << indent << "size = " << tvs.size() << std::endl;
	size_t i = 0;
	for (const TruthValuePtr& tv : tvs) {
		ss << indent << "tv[" << i << "]: " << oc_to_string(tv);
		i++;
	}
	return ss.str();
}

} // ~namespace opencog
<|endoftext|>