text:
/**
 * BCL to FASTQ file converter
 * Copyright (c) 2007-2017 Illumina, Inc.
 *
 * This software is covered by the accompanying EULA
 * and certain third party copyright/licenses, and any user of this
 * source file is bound by the terms therein.
 *
 * \file FileReader.hh
 *
 * \brief Declaration of FileReader file.
 *
 * \author Aaron Day
 */

#ifndef BCL2FASTQ_DATA_FILEREADER_HPP
#define BCL2FASTQ_DATA_FILEREADER_HPP

#include <boost/function.hpp>

namespace bcl2fastq
{
namespace data
{

template<typename HEADER>
bool BinaryFileReader::readHeader(HEADER& header)
{
    std::streamsize headerLength = this->read(reinterpret_cast<char *>(&header), sizeof(header));

    int errnum = errno;
    if (headerLength != sizeof(header))
    {
        boost::format errFormat(boost::format(
            "Unable to read header of '%s' file '%s' : bytes_read=%d bytes_expected=%d") %
            this->getFileTypeStr() % this->getPath().string() % headerLength % sizeof(header));

        if (ignoreErrors_)
        {
            BCL2FASTQ_LOG(common::LogLevel::WARNING)
                << errFormat
                << ":" << std::strerror(errnum) << " (" << errnum << ")" << std::endl;

            return false;
        }
        else
        {
            BOOST_THROW_EXCEPTION(
                common::InputDataError(errnum,
                                       errFormat.str()));
        }
    }

    return true;
}

} // namespace data
} // namespace bcl2fastq

#endif // BCL2FASTQ_DATA_FILEREADER_HPP

ext: hpp


text:
/*! \file
    \brief A file storage.

    Copyright (C) 2019-2022 kaoru  https://www.tetengo.org/
*/

#include <filesystem>
#include <fstream>
#include <memory>
#include <stdexcept>
#include <utility>

#include <boost/core/noncopyable.hpp>

#include <tetengo/json/comment_removing_reader.hpp>
#include <tetengo/json/json_parser.hpp>
#include <tetengo/json/line_counting_reader.hpp>
#include <tetengo/json/stream_reader.hpp>
#include <tetengo/platform_dependent/propertyX.hpp>
#include <tetengo/property/file_storage.hpp>
#include <tetengo/property/storage.hpp>

#include "tetengo.property.json_parser.hpp"
#include "tetengo.property.json_writer.hpp"

namespace tetengo::property
{
    class file_storage::impl : private boost::noncopyable
    {
    public:
        // constructors and destructor

        explicit impl(const std::filesystem::path& path) : m_path{ path } {}

        // functions

        void save_impl(const file_storage& self) const
        {
            const auto native_path =
                tetengo::platform_dependent::property_set_file_path::instance().to_native_path(m_path);
            if (!std::filesystem::exists(native_path.parent_path()))
            {
                std::filesystem::create_directories(native_path.parent_path());
            }
            std::ofstream stream{ native_path };
            if (!stream)
            {
                throw std::runtime_error{ "Can't save the property set." };
            }
            json_writer::instance().write(self.value_map(), stream);
        }

    private:
        // variables

        const std::filesystem::path m_path;
    };

    file_storage::~file_storage() = default;

    file_storage::file_storage(value_map_type value_map, const std::filesystem::path& path) :
    storage{ std::move(value_map) },
    m_p_impl{ std::make_unique<impl>(path) }
    {}

    void file_storage::save_impl() const
    {
        m_p_impl->save_impl(*this);
    }

    class file_storage_loader::impl : private boost::noncopyable
    {
    public:
        // functions

        std::unique_ptr<storage> load_impl(const std::filesystem::path& path) const
        {
            const auto native_path =
                tetengo::platform_dependent::property_set_file_path::instance().to_native_path(path);

            struct storage_impl : public file_storage
            {
                storage_impl(value_map_type value_map, const std::filesystem::path& path) :
                file_storage{ std::move(value_map), path }
                {}
            };
            return std::make_unique<storage_impl>(load_value_map(native_path), path);
        }

    private:
        // types

        using value_map_type = storage::value_map_type;

        // static functions

        static value_map_type load_value_map(const std::filesystem::path& native_path)
        {
            auto p_stream = std::make_unique<std::ifstream>(native_path);
            if (!p_stream || !*p_stream)
            {
                return value_map_type{};
            }

            auto p_parser = build_json_parser(std::move(p_stream));
            try
            {
                return json_parser::instance().parse(*p_parser);
            }
            catch (const std::runtime_error&)
            {
                return value_map_type{};
            }
        }

        static std::unique_ptr<tetengo::json::json_parser> build_json_parser(std::unique_ptr<std::istream>&& p_stream)
        {
            auto p_stream_reader = std::make_unique<tetengo::json::stream_reader>(std::move(p_stream));
            auto p_line_counting_reader =
                std::make_unique<tetengo::json::line_counting_reader>(std::move(p_stream_reader));
            auto p_comment_removing_reader =
                std::make_unique<tetengo::json::comment_removing_reader>(std::move(p_line_counting_reader), "#");
            return std::make_unique<tetengo::json::json_parser>(std::move(p_comment_removing_reader));
        }
    };

    file_storage_loader::file_storage_loader() : m_p_impl{ std::make_unique<impl>() } {}

    file_storage_loader::~file_storage_loader() = default;

    std::unique_ptr<storage> file_storage_loader::load_impl(const std::filesystem::path& path) const
    {
        return m_p_impl->load_impl(path);
    }

}

ext: cpp

max_stars_repo_name: tetengo/tetengo

max_issues_repo_name: tetengo/tetengo

max_forks_repo_name: tetengo/tetengo


text:
#include <Sx/Signals/Signal.hpp>
#include <boost/signals2.hpp>
#include <chrono>
#include <iostream>
#include <limits>

struct PerfTest
{
    static PerfTest& instance()
    {
        static PerfTest p;
        return p;
    }

    static void static_slot(size_t val)
    {
        instance().slot(val);
    }

    size_t slot(size_t val) const
    {
        if ((result > val) && ((val % 2) == 0))
            result -= val;
        else
            result += val;
        return result;
    }

    mutable size_t result = 0;
};

using namespace boost::signals2;
using namespace Sx::Signals;
using namespace std::chrono;

void RunPerfTest(size_t count = 1000000000)
{
    signal_type<void(size_t), keywords::mutex_type<dummy_mutex>>::type b_signal;
    b_signal.connect(&PerfTest::static_slot);
    auto b_start = high_resolution_clock::now();
    for (size_t i = 0; i < count; ++i)
        b_signal(i);
    auto b_end  = high_resolution_clock::now();
    auto b_time = duration_cast<microseconds>(b_end - b_start).count();

    Signal<void(size_t)> o_signal;
    o_signal.connect<&PerfTest::static_slot>();
    auto o_start = high_resolution_clock::now();
    for (size_t i = 0; i < count; ++i)
        o_signal(i);
    auto o_end  = high_resolution_clock::now();
    auto o_time = duration_cast<microseconds>(o_end - o_start).count();

    using Callback    = void (*)(size_t);
    Callback p_signal = &PerfTest::static_slot;
    auto     p_start  = high_resolution_clock::now();
    for (size_t i = 0; i < count; ++i)
        p_signal(i);
    auto p_end  = high_resolution_clock::now();
    auto p_time = duration_cast<microseconds>(p_end - p_start).count();

    std::cout << "**> Result (MAX)           : " << std::numeric_limits<size_t>::max() << std::endl
              << "**> Test calls count       : " << count << std::endl
              << "**> Boost signal2 duration : " << b_time << std::endl
              << "**> Own signal duration    : " << o_time << std::endl
              << "**> Plain callback duration: " << p_time << std::endl
              << "**> Boost/Plain            : " << double(b_time) / double(p_time) << std::endl
              << "**> Own/Plain              : " << double(o_time) / double(p_time) << std::endl
              << "**> Boost/Own              : " << double(b_time) / double(o_time) << std::endl
              << "**> Result                 : " << PerfTest::instance().result << std::endl;
}

int main()
{
    RunPerfTest();
    return 0;
}

max_stars_repo_name: vsemyonoff/observer

max_issues_repo_name: vsemyonoff/observer

max_forks_repo_name: vsemyonoff/observer


text:
// Copyright (c) 2022, ETH Zurich and UNC Chapel Hill.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of ETH Zurich and UNC Chapel Hill nor the names of
//       its contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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.
//
// Author: Johannes L. Schoenberger (jsch-at-demuc-dot-de)

#include "estimators/homography_matrix.h"

#include <Eigen/Geometry>
#include <Eigen/LU>
#include <Eigen/SVD>

#include "base/projection.h"
#include "estimators/utils.h"
#include "util/logging.h"

namespace colmap {

std::vector<HomographyMatrixEstimator::M_t> HomographyMatrixEstimator::Estimate(
    const std::vector<X_t>& points1, const std::vector<Y_t>& points2) {
  CHECK_EQ(points1.size(), points2.size());

  const size_t N = points1.size();

  // Center and normalize image points for better numerical stability.
  std::vector<X_t> normed_points1;
  std::vector<Y_t> normed_points2;
  Eigen::Matrix3d points1_norm_matrix;
  Eigen::Matrix3d points2_norm_matrix;
  CenterAndNormalizeImagePoints(points1, &normed_points1, &points1_norm_matrix);
  CenterAndNormalizeImagePoints(points2, &normed_points2, &points2_norm_matrix);

  // Setup constraint matrix.
  Eigen::Matrix<double, Eigen::Dynamic, 9> A = Eigen::MatrixXd::Zero(2 * N, 9);

  for (size_t i = 0, j = N; i < points1.size(); ++i, ++j) {
    const double s_0 = normed_points1[i](0);
    const double s_1 = normed_points1[i](1);
    const double d_0 = normed_points2[i](0);
    const double d_1 = normed_points2[i](1);

    A(i, 0) = -s_0;
    A(i, 1) = -s_1;
    A(i, 2) = -1;
    A(i, 6) = s_0 * d_0;
    A(i, 7) = s_1 * d_0;
    A(i, 8) = d_0;

    A(j, 3) = -s_0;
    A(j, 4) = -s_1;
    A(j, 5) = -1;
    A(j, 6) = s_0 * d_1;
    A(j, 7) = s_1 * d_1;
    A(j, 8) = d_1;
  }

  // Solve for the nullspace of the constraint matrix.
  Eigen::JacobiSVD<Eigen::Matrix<double, Eigen::Dynamic, 9>> svd(
      A, Eigen::ComputeFullV);

  const Eigen::VectorXd nullspace = svd.matrixV().col(8);
  Eigen::Map<const Eigen::Matrix3d> H_t(nullspace.data());

  const std::vector<M_t> models = {points2_norm_matrix.inverse() *
                                   H_t.transpose() * points1_norm_matrix};
  return models;
}

void HomographyMatrixEstimator::Residuals(const std::vector<X_t>& points1,
                                          const std::vector<Y_t>& points2,
                                          const M_t& H,
                                          std::vector<double>* residuals) {
  CHECK_EQ(points1.size(), points2.size());

  residuals->resize(points1.size());

  // Note that this code might not be as nice as Eigen expressions,
  // but it is significantly faster in various tests.

  const double H_00 = H(0, 0);
  const double H_01 = H(0, 1);
  const double H_02 = H(0, 2);
  const double H_10 = H(1, 0);
  const double H_11 = H(1, 1);
  const double H_12 = H(1, 2);
  const double H_20 = H(2, 0);
  const double H_21 = H(2, 1);
  const double H_22 = H(2, 2);

  for (size_t i = 0; i < points1.size(); ++i) {
    const double s_0 = points1[i](0);
    const double s_1 = points1[i](1);
    const double d_0 = points2[i](0);
    const double d_1 = points2[i](1);

    const double pd_0 = H_00 * s_0 + H_01 * s_1 + H_02;
    const double pd_1 = H_10 * s_0 + H_11 * s_1 + H_12;
    const double pd_2 = H_20 * s_0 + H_21 * s_1 + H_22;

    const double inv_pd_2 = 1.0 / pd_2;
    const double dd_0 = d_0 - pd_0 * inv_pd_2;
    const double dd_1 = d_1 - pd_1 * inv_pd_2;

    (*residuals)[i] = dd_0 * dd_0 + dd_1 * dd_1;
  }
}

}  // namespace colmap

ext: cc

max_stars_repo_name: ashishd/colmap

max_issues_repo_name: hyowonha/colmap

max_forks_repo_name: hyowonha/colmap


text:
#pragma once

#include "shared/log/badbotlogger.hpp"
#include <boost/signals2/signal.hpp>

#include "zmq.hpp"

#include "shared/messaging/cppsrc/message.pb.h"

using namespace badbot::messages;

class MessagingServer : BadBotLogger
{
    public:
        typedef boost::signals2::signal<void(const BadMessage *msg)> signal_message;
        typedef signal_message::slot_type signal_message_slot_type;

    public:
        MessagingServer(std::string logName);
        void init(std::string configSectionQualifier);
        void connectToSignalMessage(const signal_message_slot_type &slot);
        void txMsg(badbot::messages::BadMessage *msg);

    protected:
        void onSysShutdown();
        void serverThread();
        void raiseSignalMessage(const BadMessage *msg);

    protected:
        std::thread _thread_server;
        bool _keep_running = true;
        bool _telemetry_enabled = false;
        signal_message _signal_message;

        zmq::socket_t sockRx;
        zmq::socket_t sockTx;

};


text:
#include <ndt_calibration/ndt_calib.h>

#include <ndt_map/ndt_map.h>
#include <ndt_map/ndt_cell.h>
#include <ndt_map/pointcloud_utils.h>
#include <tf_conversions/tf_eigen.h>
#include <eigen_conversions/eigen_msg.h>
#include <cstdio>
#include <Eigen/Eigen>
#include <Eigen/Geometry>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <algorithm>

#include <ros/ros.h>

#include <boost/program_options.hpp>

namespace po = boost::program_options;
using namespace std;

int main(int argc, char **argv){

  po::options_description desc("Allowed options");
  desc.add_options()
    ("help", "produce help message")
    ;

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);
    if (vm.count("help"))
    {
	cout << desc << "\n";
	return 1;
    }

    {
      Eigen::Affine3d T1 = getAsAffine3d(Eigen::Vector3d(1, 0, 0), Eigen::Vector3d(0, 0, 0));
      NDTCalibScan scan(T1, T1, 0.);
      std::cout << "Should give zeros";
      std::cout << "scan.getTs() : " << affine3dToString(scan.getTs()) << std::endl;
    }

    {
      Eigen::Affine3d T1 = getAsAffine3d(Eigen::Vector3d(1, 0, 0), Eigen::Vector3d(0, 0, 0));
      Eigen::Affine3d T2 = getAsAffine3d(Eigen::Vector3d(2, 0, 0), Eigen::Vector3d(0, 0, M_PI/2.));
      NDTCalibScan scan(T1, T2, 0.);
      std::cout << "Should give 1 0 0 0 0 M_PI/2..." << std::endl;
      std::cout << "scan.getTs() : " << affine3dToString(scan.getTs()) << std::endl;
    }

    {
      Eigen::Affine3d T1 = getAsAffine3d(Eigen::Vector3d(1, 0, 0), Eigen::Vector3d(0, 0, 0));
      Eigen::Affine3d T2 = getAsAffine3d(Eigen::Vector3d(2, 0, 0), Eigen::Vector3d(0, 0, M_PI/2.));
      Eigen::Affine3d Ts = getAsAffine3d(Eigen::Vector3d(3.,0, 1.2), Eigen::Vector3d(0,0,0));

      NDTCalibScan scan1(T1, T1*Ts, 0.);
      NDTCalibScan scan2(T2, T2*Ts, 0.);
      NDTCalibScanPair pair;
      pair.first = scan1;
      pair.second = scan2;

      std::cout << "Should give 1 0 0 0 0 M_PI/2..." << std::endl;
      std::cout << "pair.getRelativePose() : " << affine3dToString(pair.getRelativePose()) << std::endl;
      std::cout << "Should give -2 3 0 0 0 M_PI/2..." << std::endl;
      std::cout << "pair.getRelativeEstSensorPose() : " << affine3dToString(pair.getRelativeEstSensorPose()) << std::endl;

      std::cout << "Should give 1 0 0 0 0 M_PI/2..." << std::endl;
      Eigen::Affine3d Ts2 = getAsAffine3d(Eigen::Vector3d(0, 0, 0), Eigen::Vector3d(0, 0, 0));
      std::cout << "pair.getPredictedRelativeEstSensorPose(Ts2) : " << affine3dToString(pair.getPredictedRelativeEstSensorPose(Ts2)) << std::endl;

      std::cout << "Should give -2 3 0 0 0 M_PI/2..." << std::endl;
      std::cout << "pair.getPredictedRelativeEstSensorPose(Ts) : " << affine3dToString(pair.getPredictedRelativeEstSensorPose(Ts)) << std::endl;

      std::cout << "Shold give 0 0 0 0 0 0 0" << ::endl;
      std::cout << "pair.getDifference(Ts) : " << affine3dToString(pair.getDifference(Ts)) << std::endl;
    }

}

max_stars_repo_name: lllray/ndt-loam

max_issues_repo_name: lllray/ndt-loam

max_forks_repo_name: lllray/ndt-loam


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

#include <GraphMol/QueryOps.h>
#include <GraphMol/ChemReactions/Reaction.h>
#include <GraphMol/ChemReactions/ReactionParser.h>
#include <GraphMol/FileParsers/FileParsers.h>
#include <GraphMol/FileParsers/FileParserUtils.h>
#include <sstream>
#include <RDGeneral/StreamOps.h>
#include <RDGeneral/FileParseException.h>

#include <fstream>
#include <RDGeneral/BoostStartInclude.h>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/tokenizer.hpp>
#include <RDGeneral/BoostEndInclude.h>

#include "ReactionUtils.h"

namespace RDKit {

namespace {
void ParseV2000RxnBlock(std::istream &inStream, unsigned int &line,
                        bool sanitize, bool removeHs, bool strictParsing,
                        ChemicalReaction *&rxn) {
  std::string tempStr;
  // FIX: parse name and comment fields
  line++;
  tempStr = getLine(inStream);
  line++;
  tempStr = getLine(inStream);
  line++;
  tempStr = getLine(inStream);
  line++;
  tempStr = getLine(inStream);
  if (inStream.eof()) {
    throw ChemicalReactionParserException("premature EOF hit.");
  }

  unsigned int nReacts = 0, nProds = 0, nAgents = 0;
  unsigned int spos = 0;
  if (tempStr.size() < 6) {
    throw ChemicalReactionParserException("rxn counts line is too short");
  }
  rxn = new ChemicalReaction();
  try {
    nReacts =
        FileParserUtils::stripSpacesAndCast<unsigned int>(tempStr.substr(0, 3));
    spos = 3;
    nProds = FileParserUtils::stripSpacesAndCast<unsigned int>(
        tempStr.substr(spos, 3));
    spos = 6;
    ;
    if (tempStr.size() > 6) {
      std::string trimmed = boost::trim_copy(tempStr.substr(spos, 3));
      if (trimmed.size() > 0) {
        nAgents = FileParserUtils::stripSpacesAndCast<unsigned int>(
            tempStr.substr(spos, 3));
        spos = 9;
      }
    }
  } catch (boost::bad_lexical_cast &) {
    std::ostringstream errout;
    errout << "Cannot convert " << tempStr.substr(spos, 3) << " to int";
    throw ChemicalReactionParserException(errout.str());
  }
  for (unsigned int i = 0; i < nReacts; ++i) {
    line++;
    tempStr = getLine(inStream);
    if (inStream.eof()) {
      throw ChemicalReactionParserException("premature EOF hit.");
    }
    if (tempStr.substr(0, 4) != "$MOL") {
      throw ChemicalReactionParserException("$MOL header not found");
    }
    ROMol *react;
    try {
      react =
          MolDataStreamToMol(inStream, line, sanitize, removeHs, strictParsing);
    } catch (FileParseException &e) {
      std::ostringstream errout;
      errout << "Cannot parse reactant " << i << ". The error was:\n\t"
             << e.what();
      throw ChemicalReactionParserException(errout.str());
    }
    if (!react) {
      throw ChemicalReactionParserException("Null reactant in reaction file.");
    }
    rxn->addReactantTemplate(ROMOL_SPTR(react));
  }
  for (unsigned int i = 0; i < nProds; ++i) {
    line++;
    tempStr = getLine(inStream);
    if (inStream.eof()) {
      throw ChemicalReactionParserException("premature EOF hit.");
    }
    if (tempStr.substr(0, 4) != "$MOL") {
      throw ChemicalReactionParserException("$MOL header not found");
    }
    ROMol *prod;
    try {
      prod =
          MolDataStreamToMol(inStream, line, sanitize, removeHs, strictParsing);
    } catch (FileParseException &e) {
      std::ostringstream errout;
      errout << "Cannot parse product " << i << ". The error was:\n\t"
             << e.what();
      throw ChemicalReactionParserException(errout.str());
    }
    if (!prod) {
      throw ChemicalReactionParserException("Null product in reaction file.");
    }
    rxn->addProductTemplate(ROMOL_SPTR(prod));
  }

  for (unsigned int i = 0; i < nAgents; ++i) {
    line++;
    tempStr = getLine(inStream);
    if (inStream.eof()) {
      throw ChemicalReactionParserException("premature EOF hit.");
    }
    if (tempStr.substr(0, 4) != "$MOL") {
      throw ChemicalReactionParserException("$MOL header not found");
    }
    ROMol *agent;
    try {
      agent = MolDataStreamToMol(inStream, line, false);
    } catch (FileParseException &e) {
      std::ostringstream errout;
      errout << "Cannot parse agent " << i << ". The error was:\n\t"
             << e.what();
      throw ChemicalReactionParserException(errout.str());
    }
    rxn->addAgentTemplate(ROMOL_SPTR(agent));
  }
}

void ParseV3000RxnBlock(std::istream &inStream, unsigned int &line,
                        bool sanitize, bool removeHs, bool strictParsing,
                        ChemicalReaction *&rxn) {
  std::string tempStr;

  // skip the header block:
  line++;
  tempStr = getLine(inStream);
  line++;
  tempStr = getLine(inStream);
  line++;
  tempStr = getLine(inStream);
  line++;

  tempStr = FileParserUtils::getV3000Line(&inStream, line);
  boost::to_upper(tempStr);
  tempStr = boost::trim_copy(tempStr);
  std::vector<std::string> tokens;
  boost::split(tokens, tempStr, boost::is_any_of(" \t"),
               boost::token_compress_on);
  if (tokens.size() < 3 || tokens[0] != "COUNTS") {
    throw ChemicalReactionParserException("bad counts line");
  }
  auto nReacts = FileParserUtils::stripSpacesAndCast<unsigned int>(tokens[1]);
  auto nProds = FileParserUtils::stripSpacesAndCast<unsigned int>(tokens[2]);
  unsigned int nAgents = 0;
  if (tokens.size() > 3) {
    nAgents = FileParserUtils::stripSpacesAndCast<unsigned int>(tokens[3]);
  }

  tempStr = FileParserUtils::getV3000Line(&inStream, line);
  boost::to_upper(tempStr);
  if (tempStr.length() < 14 || tempStr.substr(0, 14) != "BEGIN REACTANT") {
    throw FileParseException("BEGIN REACTANT line not found");
  }
  rxn = new ChemicalReaction();
  const bool expectMEND = false;
  for (unsigned int i = 0; i < nReacts; ++i) {
    RWMol *react;
    unsigned int natoms, nbonds;
    bool chiralityPossible = false;
    Conformer *conf = nullptr;
    react = new RWMol();
    try {
      FileParserUtils::ParseV3000CTAB(&inStream, line, react, conf,
                                      chiralityPossible, natoms, nbonds,
                                      strictParsing, expectMEND);
      FileParserUtils::finishMolProcessing(react, chiralityPossible, sanitize,
                                           removeHs);
    } catch (FileParseException &e) {
      std::ostringstream errout;
      errout << "Cannot parse reactant " << i << ". The error was:\n\t"
             << e.what();
      delete react;
      throw ChemicalReactionParserException(errout.str());
    }
    if (!react) {
      throw ChemicalReactionParserException("Null reactant in reaction file.");
    }
    rxn->addReactantTemplate(ROMOL_SPTR(dynamic_cast<ROMol *>(react)));
  }
  tempStr = FileParserUtils::getV3000Line(&inStream, line);
  boost::to_upper(tempStr);
  if (tempStr.length() < 12 || tempStr.substr(0, 12) != "END REACTANT") {
    delete rxn;
    throw FileParseException("END REACTANT line not found");
  }
  tempStr = FileParserUtils::getV3000Line(&inStream, line);
  boost::to_upper(tempStr);
  if (tempStr.length() < 13 || tempStr.substr(0, 13) != "BEGIN PRODUCT") {
    delete rxn;
    throw FileParseException("BEGIN PRODUCT line not found");
  }
  for (unsigned int i = 0; i < nProds; ++i) {
    RWMol *prod;
    unsigned int natoms, nbonds;
    bool chiralityPossible = false;
    Conformer *conf = nullptr;
    prod = new RWMol();
    try {
      FileParserUtils::ParseV3000CTAB(&inStream, line, prod, conf,
                                      chiralityPossible, natoms, nbonds,
                                      strictParsing, expectMEND);
      FileParserUtils::finishMolProcessing(prod, chiralityPossible, sanitize,
                                           removeHs);
    } catch (FileParseException &e) {
      std::ostringstream errout;
      errout << "Cannot parse product " << i << ". The error was:\n\t"
             << e.what();
      delete prod;
      throw ChemicalReactionParserException(errout.str());
    }
    if (!prod) {
      throw ChemicalReactionParserException("Null product in reaction file.");
    }
    rxn->addProductTemplate(ROMOL_SPTR(dynamic_cast<ROMol *>(prod)));
  }
  tempStr = FileParserUtils::getV3000Line(&inStream, line);
  boost::to_upper(tempStr);
  if (tempStr.length() < 11 || tempStr.substr(0, 11) != "END PRODUCT") {
    delete rxn;
    throw FileParseException("END PRODUCT line not found");
  }

  if (nAgents) {
    tempStr = FileParserUtils::getV3000Line(&inStream, line);
    boost::to_upper(tempStr);
    if (tempStr.length() < 14 || tempStr.substr(0, 14) != "BEGIN AGENT") {
      delete rxn;
      throw FileParseException("BEGIN AGENT line not found");
    }
  }
  for (unsigned int i = 0; i < nAgents; ++i) {
    RWMol *agent;
    unsigned int natoms, nbonds;
    bool chiralityPossible;
    Conformer *conf = nullptr;
    agent = new RWMol();
    try {
      FileParserUtils::ParseV3000CTAB(&inStream, line, agent, conf,
                                      chiralityPossible, natoms, nbonds, true,
                                      false);
    } catch (FileParseException &e) {
      std::ostringstream errout;
      errout << "Cannot parse agent " << i << ". The error was:\n\t"
             << e.what();
      delete agent;
      throw ChemicalReactionParserException(errout.str());
    }
    rxn->addAgentTemplate(ROMOL_SPTR(dynamic_cast<ROMol *>(agent)));
  }
  if (nAgents) {
    tempStr = FileParserUtils::getV3000Line(&inStream, line);
    boost::to_upper(tempStr);
    if (tempStr.length() < 12 || tempStr.substr(0, 12) != "END AGENT") {
      delete rxn;
      throw FileParseException("END AGENT line not found");
    }
  }
}
}  // namespace

//! Parse a text stream in MDL rxn format into a ChemicalReaction
ChemicalReaction *RxnDataStreamToChemicalReaction(std::istream &inStream,
                                                  unsigned int &line,
                                                  bool sanitize, bool removeHs,
                                                  bool strictParsing) {
  std::string tempStr;

  // header line
  line++;
  tempStr = getLine(inStream);
  if (inStream.eof()) {
    throw ChemicalReactionParserException("premature EOF hit.");
  }
  if (tempStr.substr(0, 4) != "$RXN") {
    throw ChemicalReactionParserException("$RXN header not found");
  }
  int version = 2000;
  if (tempStr.size() >= 10 && tempStr.substr(5, 5) == "V3000") {
    version = 3000;
  }

  ChemicalReaction *res = nullptr;
  try {
    if (version == 2000) {
      ParseV2000RxnBlock(inStream, line, sanitize, removeHs, strictParsing,
                         res);
    } else {
      ParseV3000RxnBlock(inStream, line, sanitize, removeHs, strictParsing,
                         res);
    }
  } catch (ChemicalReactionParserException &e) {
    // catch our exceptions and throw them back after cleanup
    delete res;
    res = nullptr;
    throw e;
  }
  // convert atoms to queries:
  for (MOL_SPTR_VECT::const_iterator iter = res->beginReactantTemplates();
       iter != res->endReactantTemplates(); ++iter) {
    // to write the mol block, we need ring information:
    for (ROMol::AtomIterator atomIt = (*iter)->beginAtoms();
         atomIt != (*iter)->endAtoms(); ++atomIt) {
      QueryOps::replaceAtomWithQueryAtom((RWMol *)iter->get(), (*atomIt));
    }
  }
  for (MOL_SPTR_VECT::const_iterator iter = res->beginProductTemplates();
       iter != res->endProductTemplates(); ++iter) {
    // to write the mol block, we need ring information:
    for (ROMol::AtomIterator atomIt = (*iter)->beginAtoms();
         atomIt != (*iter)->endAtoms(); ++atomIt) {
      QueryOps::replaceAtomWithQueryAtom((RWMol *)iter->get(), (*atomIt));
    }
  }
  updateProductsStereochem(res);

  // RXN-based reactions do not have implicit properties
  res->setImplicitPropertiesFlag(false);
  return res;
};

ChemicalReaction *RxnBlockToChemicalReaction(const std::string &rxnBlock,
                                             bool sanitize, bool removeHs,
                                             bool strictParsing) {
  std::istringstream inStream(rxnBlock);
  unsigned int line = 0;
  return RxnDataStreamToChemicalReaction(inStream, line, sanitize, removeHs,
                                         strictParsing);
};

ChemicalReaction *RxnFileToChemicalReaction(const std::string &fName,
                                            bool sanitize, bool removeHs,
                                            bool strictParsing) {
  std::ifstream inStream(fName.c_str());
  if (!inStream) {
    return nullptr;
  }
  ChemicalReaction *res = nullptr;
  if (!inStream.eof()) {
    unsigned int line = 0;
    res = RxnDataStreamToChemicalReaction(inStream, line, sanitize, removeHs,
                                          strictParsing);
  }
  return res;
};
}  // namespace RDKit

max_stars_repo_name: jungb-basf/rdkit

max_issues_repo_name: jungb-basf/rdkit

max_forks_repo_name: jungb-basf/rdkit


text:
// Copyright (c) 2006, 2007 Julio M. Merino Vidal
// Copyright (c) 2008 Ilya Sokolov, Boris Schaeling
// Copyright (c) 2009 Boris Schaeling
// Copyright (c) 2010 Felipe Tanus, Boris Schaeling
// Copyright (c) 2011, 2012 Jeff Flinn, Boris Schaeling
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_PROCESS_POSIX_INITIALIZERS_SET_ON_ERROR_HPP
#define BOOST_PROCESS_POSIX_INITIALIZERS_SET_ON_ERROR_HPP

#include <boost/process/config.hpp>
#include <boost/process/posix/initializers/initializer_base.hpp>
#include <boost/system/error_code.hpp>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

namespace boost { namespace process { namespace posix { namespace initializers {

class set_on_error : public initializer_base
{
public:
    explicit set_on_error(boost::system::error_code &ec) : ec_(ec) {}

    template <class PosixExecutor>
    void on_fork_setup(PosixExecutor&) const
    {
        if (::pipe(fds_) == -1)
            BOOST_PROCESS_RETURN_LAST_SYSTEM_ERROR(ec_);
        if (::fcntl(fds_[1], F_SETFD, FD_CLOEXEC) == -1)
        {
            BOOST_PROCESS_RETURN_LAST_SYSTEM_ERROR(ec_);
            ::close(fds_[0]);
            ::close(fds_[1]);
        }
    }

    template <class PosixExecutor>
    void on_fork_error(PosixExecutor&) const
    {
        if (!ec_)
        {
            BOOST_PROCESS_RETURN_LAST_SYSTEM_ERROR(ec_);
            ::close(fds_[0]);
            ::close(fds_[1]);
        }
    }

    template <class PosixExecutor>
    void on_fork_success(PosixExecutor&) const
    {
        if (!ec_)
        {
            ::close(fds_[1]);
            int code;
            if (::read(fds_[0], &code, sizeof(int)) > 0)
            {
                ec_ = boost::system::error_code(code,
                    boost::system::system_category());
            }
            ::close(fds_[0]);
        }
    }

    template <class PosixExecutor>
    void on_exec_setup(PosixExecutor&) const
    {
        if (!ec_)
        {
            ::close(fds_[0]);
        }
    }

    template <class PosixExecutor>
    void on_exec_error(PosixExecutor&) const
    {
        if (!ec_)
        {
            int e = errno;
            while (::write(fds_[1], &e, sizeof(int)) == -1 && errno == EINTR)
                ;
            ::close(fds_[1]);
        }
    }

private:
    boost::system::error_code &ec_;
    mutable int fds_[2];
};

}}}}

#endif

max_stars_repo_name: johny-c/ViZDoom

max_issues_repo_name: johny-c/ViZDoom

max_forks_repo_name: johny-c/ViZDoom


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

#include "Vector_ClosestPoint.h"

#include <assert.h>

#include <Urho3D/Math/Vector3.h>

#include <Eigen/Core>

using namespace Urho3D;

String Vector_ClosestPoint::iconTexture = "Textures/Icons/Vector_ClosestPoint.png";

Vector_ClosestPoint::Vector_ClosestPoint(Context* context) : IoComponentBase(context, 2, 3)
{
	SetName("ClosePoint");
	SetFullName("Closest Point");
	SetDescription("Which point in list is closest");
	SetGroup(IoComponentGroup::VECTOR);
	SetSubgroup("Point");

	inputSlots_[0]->SetName("Point");
	inputSlots_[0]->SetVariableName("P");
	inputSlots_[0]->SetDescription("Query point");
	inputSlots_[0]->SetVariantType(VariantType::VAR_VECTOR3);
	inputSlots_[0]->SetDefaultValue(Vector3(0.0f, 0.0f, 0.0f));
	inputSlots_[0]->DefaultSet();

	inputSlots_[1]->SetName("Point List");
	inputSlots_[1]->SetVariableName("L");
	inputSlots_[1]->SetDescription("List of points");
	inputSlots_[1]->SetVariantType(VariantType::VAR_VECTOR3);
	inputSlots_[1]->SetDataAccess(DataAccess::LIST);
	inputSlots_[1]->SetDefaultValue(Vector3(0.0f, 0.0f, 0.0f));
	inputSlots_[1]->DefaultSet();

	outputSlots_[0]->SetName("Closest Point");
	outputSlots_[0]->SetVariableName("C");
	outputSlots_[0]->SetDescription("Closest point in list to P");
	outputSlots_[0]->SetVariantType(VariantType::VAR_VECTOR3);

	outputSlots_[1]->SetName("Index");
	outputSlots_[1]->SetVariableName("I");
	outputSlots_[1]->SetDescription("Index into L of closest point");
	outputSlots_[1]->SetVariantType(VariantType::VAR_INT);

	outputSlots_[2]->SetName("Distance");
	outputSlots_[2]->SetVariableName("D");
	outputSlots_[2]->SetDescription("Distance to closest point");
	outputSlots_[2]->SetVariantType(VariantType::VAR_FLOAT);
}

void Vector_ClosestPoint::SolveInstance(
	const Vector<Variant>& inSolveInstance,
	Vector<Variant>& outSolveInstance
)
{
	///////////////////
	// EXTRACT & VERIFY

	// query point
	Variant queryPointVar = inSolveInstance[0];
	if (queryPointVar.GetType() != VariantType::VAR_VECTOR3) {
		URHO3D_LOGWARNING("P must be a valid Vector3");
		outSolveInstance[0] = Variant();
		outSolveInstance[1] = Variant();
		outSolveInstance[2] = Variant();
		return;
	}
	Vector3 q = queryPointVar.GetVector3();

	// point list
	Variant pointListVar = inSolveInstance[1];
	if (pointListVar.GetType() != VariantType::VAR_VARIANTVECTOR) {
		URHO3D_LOGWARNING("L must be a list of Vector3's");
		outSolveInstance[0] = Variant();
		outSolveInstance[1] = Variant();
		outSolveInstance[2] = Variant();
		return;
	}
	Vector<Variant> pointList = pointListVar.GetVariantVector();

	//////////////////////////////////////////////
	// COMPONENT'S WORK & VERIFICATION DURING LOOP

	// output holders needed now to store data as we loop
	int index = -1; // index of closest point
	Vector3 r; // closest point
	float distance = -1.0f;

	/* due to the nature of this computation, we unpack and compute at the same time */
	if (pointList.Size() > 0) {

		Variant pointVar = pointList[0];
		if (pointVar.GetType() != VariantType::VAR_VECTOR3) {
			URHO3D_LOGWARNING("L must be a list of Vector3's only");
			outSolveInstance[0] = Variant();
			outSolveInstance[1] = Variant();
			outSolveInstance[2] = Variant();
			return;
		}
		Vector3 p = pointVar.GetVector3();
		float minDistanceSquared = (p - q).LengthSquared();
		index = 0;
		r = p;

		for (unsigned i = 1; i < pointList.Size(); ++i) {
			pointVar = pointList[i];
			if (pointVar.GetType() != VariantType::VAR_VECTOR3) {
				URHO3D_LOGWARNING("L must be a list of Vector3's only");
				outSolveInstance[0] = Variant();
				outSolveInstance[1] = Variant();
				outSolveInstance[2] = Variant();
				return;
			}
			p = pointVar.GetVector3();
			float distanceSquared = (p - q).LengthSquared();
			if (distanceSquared < minDistanceSquared) {
				minDistanceSquared = distanceSquared;
				index = i;
				r = p;
			}
		}

		distance = sqrt(minDistanceSquared);
	}

	/////////////////
	// ASSIGN OUTPUTS

	if (index > -1) {
		// inputs were good
		outSolveInstance[0] = Variant(r);
		outSolveInstance[1] = Variant((int)index);
		outSolveInstance[2] = Variant(distance);
	}
	else {
		// inputs were bad -- null sets?
		outSolveInstance[0] = Variant();
		outSolveInstance[1] = Variant();
		outSolveInstance[2] = Variant();
	}
}


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

#include "stdafx.h"

#include <cursespp/Colors.h>
#include <cursespp/Screen.h>
#include <cursespp/Text.h>
#include <core/library/LocalLibraryConstants.h>
#include <app/util/Hotkeys.h>
#include <app/overlay/PlayQueueOverlays.h>
#include <app/util/PreferenceKeys.h>
#include <core/library/query/local/NowPlayingTrackListQuery.h>
#include <core/library/query/local/GetPlaylistQuery.h>
#include <core/library/query/local/PersistedPlayQueueQuery.h>
#include <core/support/Duration.h>
#include "NowPlayingLayout.h"

#include <set>
#include <boost/format.hpp>

using namespace musik::core::library::constants;

using namespace musik::core;
using namespace musik::core::audio;
using namespace musik::core::library;
using namespace musik::cube;
using namespace musik::core::db::local;
using namespace cursespp;

namespace keys = musik::cube::prefs::keys;
namespace components = musik::core::prefs::components;

static std::set<std::string> EDIT_KEYS;

static std::string formatWithAlbum(TrackPtr track, size_t index, size_t width);

NowPlayingLayout::NowPlayingLayout(
    musik::core::audio::PlaybackService& playback,
    musik::core::ILibraryPtr library)
: LayoutBase()
, playback(playback)
, library(library)
, lastPlaylistQueryId(-1)
, reselectIndex(-1) {
    this->prefs = Preferences::ForComponent(components::Settings);
    this->InitializeWindows();

    this->playback.QueueEdited.connect(this, &NowPlayingLayout::RequeryTrackList);

    EDIT_KEYS = {
        Hotkeys::Get(Hotkeys::PlayQueueMoveUp),
        Hotkeys::Get(Hotkeys::PlayQueueMoveDown),
        Hotkeys::Get(Hotkeys::PlayQueueDelete)
    };
}

NowPlayingLayout::~NowPlayingLayout() {
}

int64_t NowPlayingLayout::RowDecorator(musik::core::TrackPtr track, size_t index) {
    bool selected = index == trackListView->GetSelectedIndex();

    int64_t attrs = selected
        ? COLOR_PAIR(CURSESPP_HIGHLIGHTED_LIST_ITEM)
        : CURSESPP_DEFAULT_COLOR;

    size_t playingIndex = playback.GetIndex();

    if (index == playingIndex) {
        TrackPtr playing = playback.GetPlaying();

        if (playing &&
            playing->GetId() == track->GetId() &&
            playing->LibraryId() == track->LibraryId())
        {
            if (selected) {
                attrs = COLOR_PAIR(CURSESPP_HIGHLIGHTED_SELECTED_LIST_ITEM);
            }
            else {
                attrs = COLOR_PAIR(CURSESPP_SELECTED_LIST_ITEM);
            }
        }
    }

    return attrs;
}

void NowPlayingLayout::OnLayout() {
    this->trackListView->MoveAndResize(
        0,
        0,
        this->GetWidth(),
        this->GetHeight());

    this->trackListView->SetFocusOrder(0);
}

void NowPlayingLayout::InitializeWindows() {
    this->trackListView.reset(new TrackListView(
        this->playback,
        this->library,
        std::bind(formatWithAlbum, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3),
        std::bind(&NowPlayingLayout::RowDecorator, this, std::placeholders::_1, std::placeholders::_2)));

    this->trackListView->SetFrameTitle(_TSTR("playqueue_title"));
    this->trackListView->Requeried.connect(this, &NowPlayingLayout::OnTrackListRequeried);
    this->AddWindow(this->trackListView);
}

void NowPlayingLayout::OnVisibilityChanged(bool visible) {
    LayoutBase::OnVisibilityChanged(visible);

    if (visible) {
        this->RequeryTrackList();
    }
    else {
        this->trackListView->Clear();
    }
}

void NowPlayingLayout::OnTrackListRequeried(musik::core::db::local::TrackListQueryBase* query) {
    /* in most cases we pull the TrackList directly from the PlaybackService.
    however, some user operations cause the TrackList to be loaded from
    the database, e.g. loading regular playlists. in these cases, copy
    the tracks TO the PlaybackService, then refresh! */
    if (query && query->GetId() == this->lastPlaylistQueryId) {
        this->playback.CopyFrom(*query->GetResult());
        this->lastPlaylistQueryId = -1;
    }

    if (playback.Count()) {
        /* regular logic (i.e, no edit operation) */
        if (this->reselectIndex == -1) {
            size_t index = playback.GetIndex();

            if (index == ListWindow::NO_SELECTION) { /* not playing? */
                this->trackListView->ScrollTo(0);
                this->trackListView->SetSelectedIndex(0);
            }
            else { /* playing... */
                size_t scrollToIndex = index == 0 ? index : index - 1;
                if (!this->trackListView->IsEntryVisible(scrollToIndex)) {
                    this->trackListView->ScrollTo(scrollToIndex);
                }

                this->trackListView->SetSelectedIndex(index);
            }
        }
        /* user just finished an edit. this is a bit of a hack; we're notified
        of the edit completion asynchronously, so before we complete the edit
        we stash the index we need to re-select. */
        else {
            /* ensure the correct index is selected, and that it's properly
            scrolled into view */
            this->reselectIndex = std::min((int) this->trackListView->TrackCount() - 1, this->reselectIndex);
            this->trackListView->SetSelectedIndex((size_t)this->reselectIndex);

            if (!this->trackListView->IsEntryVisible((size_t) this->reselectIndex)) {
                this->trackListView->ScrollTo((size_t)this->reselectIndex);
            }

            this->reselectIndex = -1;
        }

        /* if after a bunch of monkeying around there's still nothing
        selected, but we have contents, let's just select the first item */
        auto sel = this->trackListView->GetSelectedIndex();
        if (sel == ListWindow::NO_SELECTION || sel >= this->trackListView->TrackCount()) {
            this->trackListView->SetSelectedIndex(0);
            this->trackListView->ScrollTo(0);
        }
    }
    else {
        this->trackListView->ScrollTo(0);
    }
}

void NowPlayingLayout::RequeryTrackList() {
    auto noconst = std::const_pointer_cast<TrackList>(this->playback.GetTrackList());
    this->trackListView->SetTrackList(noconst);
    this->OnTrackListRequeried(nullptr);
}

void NowPlayingLayout::OnPlaylistSelected(int64_t playlistId) {
    auto query = std::shared_ptr<GetPlaylistQuery>(
        new GetPlaylistQuery(library, playlistId));

    this->lastPlaylistQueryId = query->GetId();
    this->trackListView->Requery(query);
}

bool NowPlayingLayout::KeyPress(const std::string& key) {
    if (Hotkeys::Is(Hotkeys::PlayQueuePlaylistLoad, key)) {
        PlayQueueOverlays::ShowLoadPlaylistOverlay(
            this->playback,
            this->library,
            std::bind(&NowPlayingLayout::OnPlaylistSelected, this, std::placeholders::_1));
        return true;
    }
    else if (Hotkeys::Is(Hotkeys::PlayQueuePlaylistSave, key)) {
        PlayQueueOverlays::ShowSavePlaylistOverlay(
            this->MessageQueue(), this->playback, this->library);
        return true;
    }
    else if (Hotkeys::Is(Hotkeys::PlayQueuePlaylistRename, key)) {
        PlayQueueOverlays::ShowRenamePlaylistOverlay(this->library);
        return true;
    }
    else if (Hotkeys::Is(Hotkeys::PlayQueuePlaylistDelete, key)) {
        PlayQueueOverlays::ShowDeletePlaylistOverlay(this->library);
        return true;
    }
    else if (ProcessEditOperation(key)) {
        return true;
    }

    return LayoutBase::KeyPress(key);
}

bool NowPlayingLayout::ProcessEditOperation(const std::string& key) {
    if (EDIT_KEYS.find(key) != EDIT_KEYS.end()) {
        if (!playback.IsShuffled()) {
            size_t selected = this->trackListView->GetSelectedIndex();
            this->reselectIndex = -1;

            {
                PlaybackService::Editor editor = this->playback.Edit();
                if (Hotkeys::Is(Hotkeys::PlayQueueMoveUp, key)) {
                    if (selected > 0) {
                        size_t to = selected - 1;
                        editor.Move(selected, to);
                        reselectIndex = (int)to;
                    }
                }
                else if (Hotkeys::Is(Hotkeys::PlayQueueMoveDown, key)) {
                    if (selected < this->playback.Count() - 1) {
                        size_t to = selected + 1;
                        editor.Move(selected, to);
                        reselectIndex = (int)to;
                    }
                }
                else if (Hotkeys::Is(Hotkeys::PlayQueueDelete, key)) {
                    editor.Delete(selected);
                    reselectIndex = (int)selected;
                }
            }

            return true;
        }
    }

    return false;
}

#define TRACK_COL_WIDTH 3
#define ARTIST_COL_WIDTH 14
#define ALBUM_COL_WIDTH 14
#define DURATION_COL_WIDTH 5 /* 00:00 */
#define DIGITS(x) (x > 9 ? (int) log10((double) x) + 1 : 1)

static std::string formatWithAlbum(TrackPtr track, size_t index, size_t width) {
    size_t trackColWidth = std::max(TRACK_COL_WIDTH, DIGITS(index + 1));
    std::string trackNum = text::Align(std::to_string(index + 1), text::AlignRight, trackColWidth);

    std::string duration = text::Align(
        duration::Duration(track->GetString(constants::Track::DURATION)),
        text::AlignRight,
        DURATION_COL_WIDTH);

    std::string album = text::Align(
        track->GetString(constants::Track::ALBUM),
        text::AlignLeft,
        ALBUM_COL_WIDTH);

    std::string artist = text::Align(
        track->GetString(constants::Track::ARTIST),
        text::AlignLeft,
        ARTIST_COL_WIDTH);

    int titleWidth =
        width -
        trackColWidth -
        DURATION_COL_WIDTH -
        ALBUM_COL_WIDTH -
        ARTIST_COL_WIDTH -
        (4 * 3); /* 3 = spacing */

    titleWidth = std::max(0, titleWidth);

    std::string title = text::Align(
        track->GetString(constants::Track::TITLE),
        text::AlignLeft,
        (int) titleWidth);

    return boost::str(
        boost::format("%s   %s   %s   %s   %s")
        % trackNum % title % duration % album % artist);
}

max_stars_repo_name: the-eater/musikcube

max_issues_repo_name: the-eater/musikcube

max_forks_repo_name: the-eater/musikcube


text:
#ifndef STD_AST_H
#define STD_AST_H

#include <algorithm>
#include <cstdint>
#include <list>
#include <map>
#include <memory>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <variant>
#include <vector>

#include <heap_obj.hpp>

#include <boost/fusion/include/adapt_struct.hpp>

namespace std_parser::rules::ast {

struct SourceLocation {
  uint16_t row = 0;
  uint16_t col = 0;
};

using Type_ = std::vector<std::string>;

struct Type;
struct LiteralExpression;

struct TemplateTypes {
  std::vector<std::variant<Type, LiteralExpression>> template_types;
};

struct unqulified_type {
  Type_ name;
  TemplateTypes template_types;
};

struct UnqulifiedType {
  std::vector<unqulified_type> type;
};

struct Literal {
  std::variant<std::vector<int64_t>, double, char, std::string> lit;
};

enum class TypeQualifier {
  Inline,
  Static,
  Const,
  Constexpr,
  L_Ref,
  R_Ref,
  Pointer
};

enum class MethodQualifier { NONE, L_REF, R_REF };

struct Type {
  std::vector<TypeQualifier> left_qualifiers;
  UnqulifiedType type;
  std::vector<TypeQualifier> right_qualifiers;

  bool is_lvalue_reference() const {
    return not right_qualifiers.empty() and
           right_qualifiers.back() == TypeQualifier::L_Ref;
  }

  bool is_lvalue_reference_to_const() const {
    return is_lvalue_reference() and
           ((right_qualifiers.size() > 1 and
             right_qualifiers[right_qualifiers.size() - 2] ==
                 TypeQualifier::Const) or
            (not left_qualifiers.empty() and
             std::find(left_qualifiers.begin(), left_qualifiers.end(),
                       TypeQualifier::Const) != left_qualifiers.end()));
  }

  bool is_rvalue_reference() const {
    return not right_qualifiers.empty() and
           right_qualifiers.back() == TypeQualifier::R_Ref;
  }

  bool is_reference() const {
    return is_lvalue_reference() or is_rvalue_reference();
  }

  bool is_value() const { return not is_reference() and not is_pointer(); }

  bool is_pointer() const {
    // FIXME: not correct since last can be const
    return not right_qualifiers.empty() and
           right_qualifiers.back() == TypeQualifier::Pointer;
  }
};

struct Expression;

struct var;

struct params {
  std::vector<var> parameters;
};

struct Params {
  std::vector<var> parameters;

  SourceLocation loc;
};

struct TemplateParameter {
  Type_ type;
  bool is_variadic;
  std::string name;
};

using TemplateParameters = std::vector<TemplateParameter>;

struct function_signature_old {
  TemplateParameters template_parameters;
  bool is_constexpr;
  Type return_type;
  std::string name;
  params parameters;
  bool is_noexcept;

  SourceLocation loc;
};

struct UserDeductionGuide {
  TemplateParameters template_parameters;
  std::string name;
  params parameters;
  Type return_type;

  SourceLocation loc;
};

struct FunctionDeclaration {
  TemplateParameters template_parameters;
  bool is_constexpr;
  Type return_type;
  std::string name;
  params parameters;
  bool is_noexcept;

  SourceLocation loc;
};

struct operator_signature {
  TemplateParameters template_parameters;
  bool is_constexpr;
  bool is_virtual;
  Type return_type;
  params parameters;
  bool is_noexcept;
  bool is_pure_virtual;

  SourceLocation loc;
};

struct method_signature {
  TemplateParameters template_parameters;
  bool is_constexpr;
  bool is_virtual;
  Type return_type;
  std::string name;
  params parameters;
  bool is_const;
  MethodQualifier qualifier = MethodQualifier::NONE;
  bool is_noexcept;
  bool is_override;
  bool is_pure_virtual;

  SourceLocation loc;
};

enum class Constructor { CONSTRUCTOR, DESTRUCTOR, NOTHING };

struct constructor {
  TemplateParameters template_parameters;
  bool is_constexpr;
  bool is_virtual;
  Constructor type = Constructor::CONSTRUCTOR;
  std::string name;
  params parameters;
  bool is_noexcept;
  bool is_pure_virtual;

  SourceLocation loc;
};

enum class class_type { CLASS, STRUCT, META_CLASS };

enum class access_modifier { PUBLIC, PROTECTED, PRIVATE, UNSPECIFIED };

struct class_inheritance {
  access_modifier modifier = access_modifier::PUBLIC;
  UnqulifiedType type;
};

struct class_bases {
  std::vector<class_inheritance> bases;
};

struct class_or_struct {
  std::optional<std::vector<TemplateParameter>> template_parameters;
  class_type type;
  std::string name;
  TemplateTypes specialization;
  class_bases bases;
};

enum class Operator {
  PlusEq,
  Plus,
  ArrowDeref,
  Arrow,
  MinusEq,
  Minus,
  DotDeref,
  Dot,
  MultiplyEq,
  Multiply,
  DivideEq,
  Divide,
  ModuleEq,
  Module,
  RShiftEq,
  RShift,
  GtEq,
  Gt,
  LShiftEq,
  LShift,
  LtEq,
  Lt,
  And,
  BitAndEq,
  BitAnd,
  Or,
  BitOrEq,
  BitOr,
  TildeEq,
  Tilde,
  BitXorEq,
  BitXor,
  NotEq,
  Not,
  EqEq,
  Eq,
  Comma
};

struct VariableExpression {
  UnqulifiedType expression;

  /**
   * Return true if no :: in name and not template params <>
   */
  bool has_name_only() const {
    return expression.type.size() == 1 and
           expression.type.front().name.size() == 1 and
           expression.type.front().template_types.template_types.empty();
  }

  std::string const& get_single_name() const {
    return expression.type.front().name.front();
  }
};

struct LiteralExpression {
  Literal lit;
  UnqulifiedType type;
};

struct RoundExpression;
struct CurlyExpression;
struct Lambda;

using ExpressionVariant = std::variant<VariableExpression,
                                       LiteralExpression,
                                       RoundExpression,
                                       CurlyExpression,
                                       Lambda>;

struct RoundExpression {
  std::optional<UnqulifiedType> functor;

  std::vector<ExpressionVariant> expressions;
  std::vector<Operator> operators;

  SourceLocation loc;

  RoundExpression() = default;
  RoundExpression(UnqulifiedType&& type) : functor{std::move(type)} {}

  bool is_begin() const { return expressions.size() <= operators.size(); }
};

struct CurlyExpression {
  std::optional<UnqulifiedType> type;

  std::vector<ExpressionVariant> expressions;
  std::vector<Operator> operators;

  SourceLocation loc;

  CurlyExpression() = default;
  CurlyExpression(UnqulifiedType&& type) : type{std::move(type)} {}

  bool is_begin() const { return expressions.size() <= operators.size(); }
};

class Scope;
struct Statement;
struct ReturnStatement;
struct Vars;
struct IfStatement;

using StatementVariant =
    std::variant<Vars, Scope, Statement, IfStatement, ReturnStatement>;

enum class LambdaState { Capture, Template, Arguments, Body };
struct Lambda {
  LambdaState state = LambdaState::Capture;

  std::vector<StatementVariant> statements;

  SourceLocation loc;
};

struct Expression {
  std::vector<ExpressionVariant> expressions;
  std::vector<Operator> operators;

  SourceLocation loc;

  Expression() = default;

  Expression(VariableExpression&& type) : expressions{std::move(type)} {}
  Expression(LiteralExpression&& type) : expressions{std::move(type)} {}

  explicit Expression(RoundExpression&& e) : expressions{std::move(e)} {}
  explicit Expression(CurlyExpression&& e) : expressions{std::move(e)} {}
  explicit Expression(Lambda&& e) : expressions{std::move(e)} {}

  operator bool() const { return not expressions.empty(); }

  // TODO: think of a better name
  // add contract that expressions size should never be < operators size
  bool is_begin() const { return expressions.size() <= operators.size(); }

  bool empty() const { return expressions.empty(); }
};

struct var {
  Type type;
  std::string name;
  SourceLocation loc;

  Expression init;
};

/**
 * Init is for the var initialization part,
 * Next is for after next variable
 */
enum class VarDefinition { Init, Next };
struct Vars {
  VarDefinition state = VarDefinition::Init;
  std::vector<var> variables;

  SourceLocation loc;

  Vars() = default;
  Vars(var&& v) : variables{std::move(v)} {}

  void add_var(std::string&& name, SourceLocation l) {
    auto type = variables.front().type;
    variables.push_back(var{std::move(type), std::move(name), l, {}});
  }
};

struct VarStatement : public Vars {};

/**
 * Used as a bridge between an UnqulifiedType and the Expression
 * Needed for the value_expression and expression rules
 */
struct ValueExpression {
  UnqulifiedType type;
  std::variant<RoundExpression, CurlyExpression, VariableExpression> exp;

  // TODO: maybe constraint it to variants that contain Expression
  template<class... Ts>
  operator std::variant<Ts...>() {
    return std::visit(
        [this](auto& exp) {
          return std::variant<Ts...>(
              std::remove_reference_t<decltype(exp)>{std::move(type)});
        },
        exp);
  }
};

struct Statement {
  Expression expression;

  SourceLocation loc;
};

struct ReturnStatement {
  Expression expression;

  SourceLocation loc;
};

enum class EnumType { ENUM, ENUM_CLASS };

struct enum_ {
  EnumType type = EnumType::ENUM;
  std::string name;
  Type_ as{"int"};
};

struct Enumeration {
  EnumType type = EnumType::ENUM;
  std::string name;
  Type_ as;
  std::vector<std::string> enumerators;

  SourceLocation loc;

  Enumeration(enum_&& e) :
      type{e.type}, name{std::move(e.name)}, as{std::move(e.as)} {}

  void set_enumerators(std::vector<std::string>&& e) { enumerators = std::move(e); }

  bool is_scoped() { return type == EnumType::ENUM_CLASS; }
};

struct Function {
  TemplateParameters template_parameters;
  bool is_constexpr = false;
  bool is_virtual = false;
  Constructor constructor_type = Constructor::NOTHING;
  Type return_type;
  std::string name;
  params parameters;
  bool is_const = false;
  MethodQualifier qualifier = MethodQualifier::NONE;
  bool is_noexcept = false;
  bool is_override = false;
  bool is_pure_virtual = false;

  std::vector<StatementVariant> statements;

  SourceLocation loc;

  // NOTE: used in the generation of meta classes
  // contains everything inside the brackets of the function
  std::string body;

  Function() = default;

  Function(function_signature_old&& fun) :
      template_parameters{std::move(fun.template_parameters)},
      is_constexpr{fun.is_constexpr},
      return_type{std::move(fun.return_type)},
      name{std::move(fun.name)},
      parameters{std::move(fun.parameters)},
      is_noexcept{fun.is_noexcept},
      loc{fun.loc} {}

  Function(FunctionDeclaration&& fun) :
      template_parameters{std::move(fun.template_parameters)},
      is_constexpr{fun.is_constexpr},
      return_type{std::move(fun.return_type)},
      name{std::move(fun.name)},
      parameters{std::move(fun.parameters)},
      is_noexcept{fun.is_noexcept},
      loc{fun.loc} {}

  Function(method_signature&& fun) :
      template_parameters{std::move(fun.template_parameters)},
      is_constexpr{fun.is_constexpr},
      is_virtual{fun.is_virtual},
      return_type{std::move(fun.return_type)},
      name{std::move(fun.name)},
      parameters{std::move(fun.parameters)},
      is_const{fun.is_const},
      qualifier{fun.qualifier},
      is_noexcept{fun.is_noexcept},
      is_override{fun.is_override},
      is_pure_virtual{fun.is_pure_virtual},
      loc{fun.loc} {}

  Function(constructor&& fun) :
      template_parameters{std::move(fun.template_parameters)},
      is_constexpr{fun.is_constexpr},
      is_virtual{fun.is_virtual},
      constructor_type{fun.type},
      return_type{},
      name{std::move(fun.name)},
      parameters{std::move(fun.parameters)},
      is_noexcept{fun.is_noexcept},
      is_pure_virtual{fun.is_pure_virtual},
      loc{fun.loc} {}

  Function(operator_signature&& fun) :
      template_parameters{std::move(fun.template_parameters)},
      is_constexpr{fun.is_constexpr},
      return_type{std::move(fun.return_type)},
      // TODO: need operator name
      name{"op"},
      parameters{std::move(fun.parameters)},
      is_noexcept{fun.is_noexcept},
      is_pure_virtual{fun.is_pure_virtual},
      loc{fun.loc} {}
};

struct Class {
  class_type type;
  std::string name;
  std::optional<TemplateParameters> template_parameters;
  TemplateTypes specialization;
  access_modifier state;

  std::vector<UnqulifiedType> public_bases;
  std::vector<UnqulifiedType> protected_bases;
  std::vector<UnqulifiedType> private_bases;

  // can have same class names i.e. specializations
  std::map<std::string, std::list<Class>> classes;
  std::map<std::string, Enumeration> enums;

  std::vector<Function> public_methods;
  std::vector<Function> protected_methods;
  std::vector<Function> private_methods;
  std::vector<Function> unspecified_methods;

  std::vector<var> public_members;
  std::vector<var> protected_members;
  std::vector<var> private_members;
  std::vector<var> unspecified_members;

  SourceLocation loc;

  Class(class_or_struct&& cs) :
      type{cs.type},
      name{std::move(cs.name)},
      template_parameters{std::move(cs.template_parameters)},
      specialization{std::move(cs.specialization)} {
    switch (type) {
      case class_type::CLASS:
        state = access_modifier::PRIVATE;
        break;
      case class_type::STRUCT:
        state = access_modifier::PUBLIC;
        break;
      case class_type::META_CLASS:
        state = access_modifier::UNSPECIFIED;
        break;
    }

    for (auto& base : cs.bases.bases) {
      switch (base.modifier) {
        case access_modifier::PUBLIC:
          public_bases.emplace_back(std::move(base.type));
          break;
        case access_modifier::PROTECTED:
          protected_bases.emplace_back(std::move(base.type));
          break;
        case access_modifier::PRIVATE:
          private_bases.emplace_back(std::move(base.type));
          break;
        case access_modifier::UNSPECIFIED:
          break;
      }
    }
  }

  void set_access_modifier(access_modifier mod) { state = mod; }

  bool is_templated() { return template_parameters.has_value(); }

  void add_class(Class&& class_or_struct) {
    auto name = class_or_struct.name;
    classes[name].push_back(std::move(class_or_struct));
  }

  void add_enum(Enumeration&& enumeration) {
    auto name = enumeration.name;
    enums.emplace(name, std::move(enumeration));
  }

  void add_function(Function&& fun) {
    switch (state) {
      case access_modifier::PUBLIC:
        public_methods.emplace_back(std::move(fun));
        break;
      case access_modifier::PROTECTED:
        protected_methods.emplace_back(std::move(fun));
        break;
      case access_modifier::PRIVATE:
        private_methods.emplace_back(std::move(fun));
        break;
      case access_modifier::UNSPECIFIED:
        unspecified_methods.emplace_back(std::move(fun));
        break;
    }
  }

  void add_variable(var&& var) {
    switch (state) {
      case access_modifier::PUBLIC:
        public_members.emplace_back(std::move(var));
        break;
      case access_modifier::PROTECTED:
        protected_members.emplace_back(std::move(var));
        break;
      case access_modifier::PRIVATE:
        private_members.emplace_back(std::move(var));
        break;
      case access_modifier::UNSPECIFIED:
        unspecified_members.emplace_back(std::move(var));
        break;
    }
  }

  void add_variables(std::vector<var>& vars) {
    auto& current = [this]() -> auto& {
      switch (state) {
        case access_modifier::PUBLIC:
          return public_members;
        case access_modifier::PROTECTED:
          return protected_members;
        case access_modifier::PRIVATE:
          return private_members;
        default:
          return unspecified_members;
      }
    }
    ();

    current.insert(current.end(), std::make_move_iterator(vars.begin()),
                   std::make_move_iterator(vars.end()));
    vars.clear();
  }
};

class Scope {
  std::unordered_map<std::string, Class> classes;
  std::unordered_map<std::string, var> variables;

 public:
  SourceLocation loc;
  std::vector<StatementVariant> statements;

  void add_class(Class&& class_or_struct) {
    auto name = class_or_struct.name;
    classes.emplace(name, std::move(class_or_struct));
  }

  auto get_class(const std::string& name) const { return classes.at(name); }
};

struct IfStatement {
  enum class State { Begin, IfExpression, CloseBracket, ElseIf, Done };

  State state = State::Begin;

  Vars if_init;
  Expression if_expression;

  HeapObj<StatementVariant> body;

  std::vector<IfStatement> else_if_statements;

  HeapObj<StatementVariant> else_body;

  SourceLocation loc;
};

class Namespace {
  using CodeFragment = std::
      variant<Class, Enumeration, Function, var, Namespace, UserDeductionGuide>;

  std::string name;
  std::vector<CodeFragment> code_fragments;

 public:
  SourceLocation loc;
  Namespace(const std::string& name) : name{name} {}
  Namespace(std::string&& name) : name{std::move(name)} {}

  auto const& get_all_code_fragments() const { return code_fragments; }

  void add_user_deduction_guide(UserDeductionGuide&& udg) {
    code_fragments.push_back(std::move(udg));
  }

  void add_class(Class&& class_or_struct) {
    code_fragments.push_back(std::move(class_or_struct));
  }

  void add_enum(Enumeration&& enumeration) {
    code_fragments.push_back(std::move(enumeration));
  }

  void add_function(Function&& fun) { code_fragments.push_back(std::move(fun)); }

  Function const* find_function(std::string_view name) const {
    auto found = std::find_if(
        code_fragments.cbegin(), code_fragments.cend(), [name](auto& fragment) {
          if (not std::holds_alternative<Function>(fragment)) {
            return false;
          }
          auto& fun = std::get<Function>(fragment);
          return fun.name == name;
        });

    if (found != code_fragments.cend()) {
      auto& fun = std::get<Function>(*found);
      return std::addressof(fun);
    }

    return {};
  }

  void add_variable(var&& var) { code_fragments.push_back(std::move(var)); }

  void add_variables(std::vector<var>& vars) {
    for (auto& var : vars) {
      add_variable(std::move(var));
    }
    vars.clear();
  }

  void add_namespace(Namespace&& n) { code_fragments.push_back(std::move(n)); }
};
} // namespace std_parser::rules::ast

BOOST_FUSION_ADAPT_STRUCT(std_parser::rules::ast::TemplateTypes, template_types)
BOOST_FUSION_ADAPT_STRUCT(std_parser::rules::ast::unqulified_type,
                          name,
                          template_types)
BOOST_FUSION_ADAPT_STRUCT(std_parser::rules::ast::UnqulifiedType, type)
BOOST_FUSION_ADAPT_STRUCT(std_parser::rules::ast::Type,
                          left_qualifiers,
                          type,
                          right_qualifiers)
BOOST_FUSION_ADAPT_STRUCT(std_parser::rules::ast::Literal, lit)
BOOST_FUSION_ADAPT_STRUCT(std_parser::rules::ast::var, type, name)
BOOST_FUSION_ADAPT_STRUCT(std_parser::rules::ast::LiteralExpression, lit, type)
BOOST_FUSION_ADAPT_STRUCT(std_parser::rules::ast::params, parameters)
BOOST_FUSION_ADAPT_STRUCT(std_parser::rules::ast::TemplateParameter,
                          type,
                          is_variadic,
                          name)
BOOST_FUSION_ADAPT_STRUCT(std_parser::rules::ast::ValueExpression, type, exp)
BOOST_FUSION_ADAPT_STRUCT(std_parser::rules::ast::function_signature_old,
                          template_parameters,
                          is_constexpr,
                          return_type,
                          name,
                          parameters,
                          is_noexcept)
BOOST_FUSION_ADAPT_STRUCT(std_parser::rules::ast::UserDeductionGuide,
                          template_parameters,
                          name,
                          parameters,
                          return_type)
BOOST_FUSION_ADAPT_STRUCT(std_parser::rules::ast::FunctionDeclaration,
                          template_parameters,
                          is_constexpr,
                          return_type,
                          name)
BOOST_FUSION_ADAPT_STRUCT(std_parser::rules::ast::method_signature,
                          template_parameters,
                          is_constexpr,
                          is_virtual,
                          return_type,
                          name,
                          parameters,
                          is_const,
                          qualifier,
                          is_noexcept,
                          is_override,
                          is_pure_virtual)
BOOST_FUSION_ADAPT_STRUCT(std_parser::rules::ast::operator_signature,
                          template_parameters,
                          is_constexpr,
                          is_virtual,
                          return_type,
                          parameters,
                          is_noexcept,
                          is_pure_virtual)
BOOST_FUSION_ADAPT_STRUCT(std_parser::rules::ast::constructor,
                          template_parameters,
                          is_constexpr,
                          is_virtual,
                          type,
                          name,
                          parameters,
                          is_noexcept,
                          is_pure_virtual)
BOOST_FUSION_ADAPT_STRUCT(std_parser::rules::ast::class_inheritance, modifier, type)
BOOST_FUSION_ADAPT_STRUCT(std_parser::rules::ast::class_bases, bases)
BOOST_FUSION_ADAPT_STRUCT(std_parser::rules::ast::enum_, type, name, as)
BOOST_FUSION_ADAPT_STRUCT(std_parser::rules::ast::class_or_struct,
                          template_parameters,
                          type,
                          name,
                          specialization,
                          bases)

#endif // STD_AST_H

max_stars_repo_name: OBorce/zero-preprocessor

max_issues_repo_name: OBorce/zero-preprocessor

max_forks_repo_name: OBorce/zero-preprocessor


text:
#include <qubus/cuda/support.hpp>

#include <hpx/runtime/threads/thread_helpers.hpp>
#include <hpx/runtime_fwd.hpp>

#include <qubus/util/assert.hpp>
#include <qubus/util/unused.hpp>

#include <boost/intrusive_ptr.hpp>

namespace qubus
{
namespace cuda
{

namespace
{

struct runtime_registration_wrapper
{
    runtime_registration_wrapper(hpx::runtime* rt) : rt_(rt)
    {
        QUBUS_ASSERT(rt, "Object was not properly initialized.");

        hpx::error_code ec(hpx::lightweight); // ignore errors
        hpx::register_thread(rt_, "qubus-cuda", ec);
    }

    ~runtime_registration_wrapper()
    {
        hpx::unregister_thread(rt_);
    }

    hpx::runtime* rt_;
};

///////////////////////////////////////////////////////////////////////
struct future_data : hpx::lcos::detail::future_data<void>
{
private:
    static void stream_callback(CUstream stream, CUresult status, void* user_data);

public:
    future_data();

    void init(stream& stream);

private:
    hpx::runtime* rt_;
};

struct release_on_exit
{
    release_on_exit(future_data* data) : data_(data)
    {
    }

    ~release_on_exit()
    {
        // release the shared state
        hpx::lcos::detail::intrusive_ptr_release(data_);
    }

    future_data* data_;
};

void future_data::stream_callback(CUstream QUBUS_UNUSED(stream), CUresult status, void* user_data)
{
    future_data* this_ = static_cast<future_data*>(user_data);

    runtime_registration_wrapper wrap(this_->rt_);

    // We need to run this as an HPX thread ...
    hpx::applier::register_thread_nullary(
        [this_, status]() {
            release_on_exit on_exit(this_);

            if (status != CUDA_SUCCESS)
            {
                this_->set_exception(std::make_exception_ptr(cuda_error(status)));
            }

            this_->set_data(hpx::util::unused);
        },
        "qubus::cuda::future_data_stream_callback");
}

future_data::future_data() : rt_(hpx::get_runtime_ptr())
{
}

void future_data::init(stream& s)
{
    try
    {
        // Hold on to the shared state on behalf of the cuda runtime
        // right away as the callback could be called immediately.
        hpx::lcos::detail::intrusive_ptr_add_ref(this);

        auto error = cuStreamAddCallback(s.native_handle(), stream_callback, this, 0);

        check_cuda_error(error);
    }
    catch (...)
    {
        hpx::lcos::detail::intrusive_ptr_release(this);

        throw;
    }
}
}

hpx::future<void> when_finished(stream& s)
{
    using shared_state_type = future_data;

    // Make sure shared state stays alive even if the callback is invoked
    // during initialization.
    hpx::memory::intrusive_ptr<shared_state_type> p(new shared_state_type());

    p->init(s);

    return hpx::traits::future_access<hpx::future<void>>::create(std::move(p));
}
}
}

max_stars_repo_name: qubusproject/Qubus

max_issues_repo_name: qubusproject/Qubus

max_forks_repo_name: qubusproject/Qubus