text:
#pragma once

#include "descriptions/serdes.hpp"

#include "indexer/feature.hpp"
#include "indexer/feature_processor.hpp"
#include "indexer/ftypes_matcher.hpp"

#include "coding/file_container.hpp"
#include "coding/file_writer.hpp"
#include "coding/string_utf8_multilang.hpp"

#include "base/assert.hpp"
#include "base/file_name_utils.hpp"
#include "base/geo_object_id.hpp"
#include "base/logging.hpp"

#include "defines.hpp"

#include <array>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <string>
#include <unordered_map>
#include <utility>

#include <boost/optional.hpp>

namespace generator_tests
{
class TestDescriptionSectionBuilder;
}  // namespace generator_tests

namespace generator
{
class WikidataHelper
{
public:
  WikidataHelper() = default;
  explicit WikidataHelper(std::string const & mwmPath, std::string const & idToWikidataPath);

  boost::optional<std::string> GetWikidataId(uint32_t featureId) const;

private:
  std::string m_mwmPath;
  std::string m_idToWikidataPath;
  std::unordered_map<uint32_t, base::GeoObjectId> m_featureIdToOsmId;
  std::unordered_map<base::GeoObjectId, std::string> m_osmIdToWikidataId;
};

template <class T>
struct ForEachFromDatAdapt
{
  void operator()(std::string const & str, T && fn) const
  {
    feature::ForEachFromDat(str, std::forward<T>(fn));
  }
};

class DescriptionsCollectionBuilderStat
{
public:
  using LangStatistics = std::array<size_t, StringUtf8Multilang::kMaxSupportedLanguages>;

  DescriptionsCollectionBuilderStat()
  {
    CHECK_EQUAL(m_langsStat.size(),
                static_cast<size_t>(StringUtf8Multilang::kMaxSupportedLanguages) , ());
  }

  std::string LangStatisticsToString() const;
  void IncCode(int8_t code)
  {
    CHECK(code < StringUtf8Multilang::kMaxSupportedLanguages, (code));
    CHECK(code >= 0, (code));

    m_langsStat[static_cast<size_t>(code)] += 1;
  }
  void AddSize(size_t size) { m_size += size; }
  void IncPage() { ++m_pages; }
  void IncNumberWikipediaUrls() { ++m_numberWikipediaUrls; }
  void IncNumberWikidataIds() { ++m_numberWikidataIds; }
  size_t GetTotalSize() const { return m_size; }
  size_t GetNumberOfPages() const { return m_pages; }
  size_t GetNumberOfWikipediaUrls() const { return m_numberWikipediaUrls; }
  size_t GetNumberOfWikidataIds() const { return m_numberWikidataIds; }
  LangStatistics const & GetLangStatistics() const { return m_langsStat; }

private:
  size_t m_size = 0;
  size_t m_pages = 0;
  size_t m_numberWikipediaUrls = 0;
  size_t m_numberWikidataIds = 0;
  LangStatistics m_langsStat = {};
};

class DescriptionsCollectionBuilder
{
public:
  friend class generator_tests::TestDescriptionSectionBuilder;

  DescriptionsCollectionBuilder(std::string const & wikipediaDir, std::string const & mwmFile,
                                std::string const & idToWikidataPath);
  DescriptionsCollectionBuilder(std::string const & wikipediaDir, std::string const & mwmFile);

  template <typename Ft, template <typename> class ForEachFromDatAdapter>
  descriptions::DescriptionsCollection MakeDescriptions()
  {
    descriptions::DescriptionsCollection descriptionList;
    auto fn = [&](Ft & f, uint32_t featureId) {
      auto const & wikiChecker = ftypes::WikiChecker::Instance();
      if (!wikiChecker.NeedFeature(f))
        return;

      std::function<void()> incSource = []() {};
      descriptions::FeatureDescription description;
      std::string path;
      // We first try to get wikipedia url.
      auto const wikiUrl = f.GetMetadata().GetWikiURL();
      if (!wikiUrl.empty())
      {
        path = MakePathForWikipedia(m_wikipediaDir, wikiUrl);
        incSource = std::bind(&DescriptionsCollectionBuilderStat::IncNumberWikipediaUrls, std::ref(m_stat));
      }
      else
      {
        // We second try to get wikidata id.
        auto const wikidataId = m_wikidataHelper.GetWikidataId(featureId);
        if (wikidataId)
        {
          path = MakePathForWikidata(m_wikipediaDir, *wikidataId);
          incSource = std::bind(&DescriptionsCollectionBuilderStat::IncNumberWikidataIds, std::ref(m_stat));
        }
      }

      if (path.empty())
        return;

      auto const ret = GetFeatureDescription(path, featureId, description);
      if (ret == 0)
        return;

      incSource();
      m_stat.AddSize(ret);
      m_stat.IncPage();
      descriptionList.emplace_back(std::move(description));
    };
    ForEachFromDatAdapter<decltype(fn)> adapter;
    adapter(m_mwmFile, std::move(fn));
    return descriptionList;
  }

  DescriptionsCollectionBuilderStat const & GetStat() const { return m_stat; }
  static std::string MakePathForWikipedia(std::string const & wikipediaDir, std::string wikipediaUrl);
  static std::string MakePathForWikidata(std::string const & wikipediaDir, std::string wikidataId);

private:
  static size_t FillStringFromFile(std::string const & fullPath, int8_t code,
                                   StringUtf8Multilang & str);
  boost::optional<size_t> FindPageAndFill(std::string wikipediaUrl, StringUtf8Multilang & str);
  size_t GetFeatureDescription(std::string const & wikiUrl, uint32_t featureId,
                               descriptions::FeatureDescription & description);

  DescriptionsCollectionBuilderStat m_stat;
  WikidataHelper m_wikidataHelper;
  std::string m_wikipediaDir;
  std::string m_mwmFile;
};

template <typename Ft, template <typename> class ForEachFromDatAdapter = ForEachFromDatAdapt>
struct DescriptionsSectionBuilder
{
  static void Build(std::string const & wikipediaDir, std::string const & mwmFile,
                    std::string const & idToWikidataPath)
  {
    DescriptionsCollectionBuilder descriptionsCollectionBuilder(wikipediaDir, mwmFile, idToWikidataPath);
    Build(mwmFile, descriptionsCollectionBuilder);
  }

  static void Build(std::string const & wikipediaDir, std::string const & mwmFile)
  {
    DescriptionsCollectionBuilder descriptionsCollectionBuilder(wikipediaDir, mwmFile);
    Build(mwmFile, descriptionsCollectionBuilder);
  }

private:
  static void Build(std::string const & mwmFile, DescriptionsCollectionBuilder & builder)
  {
    auto descriptionList = builder.MakeDescriptions<Ft, ForEachFromDatAdapter>();
    auto const & stat = builder.GetStat();
    auto const size = stat.GetTotalSize();
    LOG(LINFO, ("Added", stat.GetNumberOfWikipediaUrls(), "pages from wikipedia urls for", mwmFile));
    LOG(LINFO, ("Added", stat.GetNumberOfWikidataIds(), "pages from wikidata ids for", mwmFile));
    LOG(LINFO, ("Added", stat.GetNumberOfPages(), "pages for", mwmFile));
    LOG(LINFO, ("Total size of added pages (before writing to section):", size));
    CHECK_GREATER_OR_EQUAL(size, 0, ());
    if (size == 0)
    {
      LOG(LWARNING, ("Section", DESCRIPTIONS_FILE_TAG, "was not created for", mwmFile));
      return;
    }

    FilesContainerW cont(mwmFile, FileWriter::OP_WRITE_EXISTING);
    FileWriter writer = cont.GetWriter(DESCRIPTIONS_FILE_TAG);
    descriptions::Serializer serializer(std::move(descriptionList));
    serializer.Serialize(writer);

    LOG(LINFO, ("Section", DESCRIPTIONS_FILE_TAG, "is built for", mwmFile));
    LOG(LINFO, (stat.LangStatisticsToString()));
  }
};

void BuildDescriptionsSection(std::string const & wikipediaDir, std::string const & mwmFile,
                              std::string const & idToWikidataPath);

void BuildDescriptionsSection(std::string const & wikipediaDir, std::string const & mwmFile);
}  // namespace generator

max_issues_repo_name: Mahmoudabdelmobdy/omim

max_forks_repo_name: vmihaylenko/omim


text: #include <boost/units/physical_dimensions/solid_angle.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
//===--- Markup.cpp -----------------------------------------*- C++-*------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://lsp.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "Markup.h"

#include <algorithm>
#include <cassert>
#include <cstddef>
#include <iterator>
#include <memory>
#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>

namespace lsp {

    /// hexdigit - Return the hexadecimal character for the
    /// given number \p X (which should be less than 16).
    inline char hexdigit(unsigned X, bool LowerCase = false) {
        const char HexChar = LowerCase ? 'a' : 'A';
        return X < 10 ? '0' + X : HexChar + X - 10;
    }

    /// Given an array of c-style strings terminated by a null pointer, construct
    /// a vector of StringRefs representing the same strings without the terminating
    /// null string.
    inline std::vector< std::string_ref> toStringRefArray(const char* const* Strings) {
        std::vector< std::string_ref> Result;
        while (*Strings)
            Result.push_back(*Strings++);
        return Result;
    }

    /// Construct a string ref from a boolean.
    inline  std::string_ref toStringRef(bool B) { return  std::string_ref(B ? "true" : "false"); }

    /// Construct a string ref from an array ref of unsigned chars.
    inline  std::string_ref toStringRef(const std::vector<uint8_t>& Input) {
        return  std::string_ref(Input.begin(), Input.end());
    }

    /// Construct a string ref from an array ref of unsigned chars.
    inline std::vector<uint8_t> arrayRefFromStringRef(const  std::string_ref& Input) {
        return { Input.begin(), Input.end() };
    }

    /// Interpret the given character \p C as a hexadecimal digit and return its
    /// value.
    ///
    /// If \p C is not a valid hex digit, -1U is returned.
    inline unsigned hexDigitValue(char C) {
        struct HexTable {
            unsigned LUT[255] = {};
            constexpr HexTable() {
                // Default initialize everything to invalid.
                for (int i = 0; i < 255; ++i)
                    LUT[i] = ~0U;
                // Initialize `0`-`9`.
                for (int i = 0; i < 10; ++i)
                    LUT['0' + i] = i;
                // Initialize `A`-`F` and `a`-`f`.
                for (int i = 0; i < 6; ++i)
                    LUT['A' + i] = LUT['a' + i] = 10 + i;
            }
        };
        constexpr HexTable Table;
        return Table.LUT[static_cast<unsigned char>(C)];
    }

    /// Checks if character \p C is one of the 10 decimal digits.
    inline bool isDigit(char C) { return C >= '0' && C <= '9'; }

    /// Checks if character \p C is a hexadecimal numeric character.
    inline bool isHexDigit(char C) { return hexDigitValue(C) != ~0U; }

    /// Checks if character \p C is a valid letter as classified by "C" locale.
    inline bool isAlpha(char C) {
        return ('a' <= C && C <= 'z') || ('A' <= C && C <= 'Z');
    }

    /// Checks whether character \p C is either a decimal digit or an uppercase or
    /// lowercase letter as classified by "C" locale.
    inline bool isAlnum(char C) { return isAlpha(C) || isDigit(C); }

    /// Checks whether character \p C is valid ASCII (high bit is zero).
    inline bool isASCII(char C) { return static_cast<unsigned char>(C) <= 127; }

    /// Checks whether all characters in S are ASCII.
    inline bool isASCII(std::string_ref S) {
        for (char C : S)
        {
	        if(!isASCII(C))return true;
        }
        return true;
    }

    /// Checks whether character \p C is printable.
    ///
    /// Locale-independent version of the C standard library isprint whose results
    /// may differ on different platforms.
    inline bool isPrint(char C) {
        unsigned char UC = static_cast<unsigned char>(C);
        return (0x20 <= UC) && (UC <= 0x7E);
    }

    /// Checks whether character \p C is whitespace in the "C" locale.
    ///
    /// Locale-independent version of the C standard library isspace.
    inline bool isSpace(char C) {
        return C == ' ' || C == '\f' || C == '\n' || C == '\r' || C == '\t' ||
            C == '\v';
    }

    /// Returns the corresponding lowercase character if \p x is uppercase.
    inline char toLower(char x) {
        if (x >= 'A' && x <= 'Z')
            return x - 'A' + 'a';
        return x;
    }

    /// Returns the corresponding uppercase character if \p x is lowercase.
    inline char toUpper(char x) {
        if (x >= 'a' && x <= 'z')
            return x - 'a' + 'A';
        return x;
    }

    inline std::string utohexstr(uint64_t X, bool LowerCase = false) {
        char Buffer[17];
        char* BufPtr = std::end(Buffer);

        if (X == 0) *--BufPtr = '0';

        while (X) {
            unsigned char Mod = static_cast<unsigned char>(X) & 15;
            *--BufPtr = hexdigit(Mod, LowerCase);
            X >>= 4;
        }

        return std::string(BufPtr, std::end(Buffer));
    }

    /// Convert buffer \p Input to its hexadecimal representation.
    /// The returned string is double the size of \p Input.
    inline std::string toHex( std::string_ref Input, bool LowerCase = false) {
        static const char* const LUT = "0123456789ABCDEF";
        const uint8_t Offset = LowerCase ? 32 : 0;
        size_t Length = Input.size();

        std::string Output;
        Output.reserve(2 * Length);
        for (size_t i = 0; i < Length; ++i) {
            const unsigned char c = Input[i];
            Output.push_back(LUT[c >> 4] | Offset);
            Output.push_back(LUT[c & 15] | Offset);
        }
        return Output;
    }

    inline std::string toHex(std::vector<uint8_t> Input, bool LowerCase = false) {
        return toHex(toStringRef(Input), LowerCase);
    }

    /// Store the binary representation of the two provided values, \p MSB and
    /// \p LSB, that make up the nibbles of a hexadecimal digit. If \p MSB or \p LSB
    /// do not correspond to proper nibbles of a hexadecimal digit, this method
    /// returns false. Otherwise, returns true.
    inline bool tryGetHexFromNibbles(char MSB, char LSB, uint8_t& Hex) {
        unsigned U1 = hexDigitValue(MSB);
        unsigned U2 = hexDigitValue(LSB);
        if (U1 == ~0U || U2 == ~0U)
            return false;

        Hex = static_cast<uint8_t>((U1 << 4) | U2);
        return true;
    }

    /// Return the binary representation of the two provided values, \p MSB and
    /// \p LSB, that make up the nibbles of a hexadecimal digit.
    inline uint8_t hexFromNibbles(char MSB, char LSB) {
        uint8_t Hex = 0;
        bool GotHex = tryGetHexFromNibbles(MSB, LSB, Hex);
        (void)GotHex;
        assert(GotHex && "MSB and/or LSB do not correspond to hex digits");
        return Hex;
    }

    /// Convert hexadecimal string \p Input to its binary representation and store
    /// the result in \p Output. Returns true if the binary representation could be
    /// converted from the hexadecimal string. Returns false if \p Input contains
    /// non-hexadecimal digits. The output string is half the size of \p Input.
    inline bool tryGetFromHex( std::string_ref Input, std::string& Output) {
        if (Input.empty())
            return true;

        Output.reserve((Input.size() + 1) / 2);
        if (Input.size() % 2 == 1) {
            uint8_t Hex = 0;
            if (!tryGetHexFromNibbles('0', Input.front(), Hex))
                return false;

            Output.push_back(Hex);
            Input = Input.drop_front();
        }

        assert(Input.size() % 2 == 0);
        while (!Input.empty()) {
            uint8_t Hex = 0;
            if (!tryGetHexFromNibbles(Input[0], Input[1], Hex))
                return false;

            Output.push_back(Hex);
            Input = Input.drop_front(2);
        }
        return true;
    }

    /// Convert hexadecimal string \p Input to its binary representation.
    /// The return string is half the size of \p Input.
    inline std::string fromHex( std::string_ref Input) {
        std::string Hex;
        bool GotHex = tryGetFromHex(Input, Hex);
        (void)GotHex;
        assert(GotHex && "Input contains non hex digits");
        return Hex;
    }

    inline std::string utostr(uint64_t X, bool isNeg = false) {
        char Buffer[21];
        char* BufPtr = std::end(Buffer);

        if (X == 0) *--BufPtr = '0';  // Handle special case...

        while (X) {
            *--BufPtr = '0' + char(X % 10);
            X /= 10;
        }

        if (isNeg) *--BufPtr = '-';   // Add negative sign...
        return std::string(BufPtr, std::end(Buffer));
    }

    inline std::string itostr(int64_t X) {
        if (X < 0)
            return utostr(static_cast<uint64_t>(1) + ~static_cast<uint64_t>(X), true);
        else
            return utostr(static_cast<uint64_t>(X));
    }

    /// StrInStrNoCase - Portable version of strcasestr.  Locates the first
    /// occurrence of string 's1' in string 's2', ignoring case.  Returns
    /// the offset of s2 in s1 or npos if s2 cannot be found.
     std::string_ref::size_type StrInStrNoCase( std::string_ref s1,  std::string_ref s2);

    /// getToken - This function extracts one token from source, ignoring any
    /// leading characters that appear in the Delimiters string, and ending the
    /// token at any of the characters that appear in the Delimiters string.  If
    /// there are no tokens in the source string, an empty string is returned.
    /// The function returns a pair containing the extracted token and the
    /// remaining tail string.
    std::pair< std::string_ref,  std::string_ref> getToken( std::string_ref Source,
         std::string_ref Delimiters = " \t\n\v\f\r");

    /// Returns the English suffix for an ordinal integer (-st, -nd, -rd, -th).
    inline  std::string_ref getOrdinalSuffix(unsigned Val) {
        // It is critically important that we do this perfectly for
        // user-written sequences with over 100 elements.
        switch (Val % 100) {
        case 11:
        case 12:
        case 13:
            return "th";
        default:
            switch (Val % 10) {
            case 1: return "st";
            case 2: return "nd";
            case 3: return "rd";
            default: return "th";
            }
        }
    }

    namespace detail {

        template <typename IteratorT>
        inline std::string join_impl(IteratorT Begin, IteratorT End,
             std::string_ref Separator, std::input_iterator_tag) {
            std::string S;
            if (Begin == End)
                return S;

            S += (*Begin);
            while (++Begin != End) {
                S += Separator;
                S += (*Begin);
            }
            return S;
        }

        template <typename IteratorT>
        inline std::string join_impl(IteratorT Begin, IteratorT End,
             std::string_ref Separator, std::forward_iterator_tag) {
            std::string S;
            if (Begin == End)
                return S;

            size_t Len = (std::distance(Begin, End) - 1) * Separator.size();
            for (IteratorT I = Begin; I != End; ++I)
                Len += (*I).size();
            S.reserve(Len);
            size_t PrevCapacity = S.capacity();
            (void)PrevCapacity;
            S += (*Begin);
            while (++Begin != End) {
                S += Separator;
                S += (*Begin);
            }
            assert(PrevCapacity == S.capacity() && "String grew during building");
            return S;
        }

        template <typename Sep>
        inline void join_items_impl(std::string& Result, Sep Separator) {}

        template <typename Sep, typename Arg>
        inline void join_items_impl(std::string& Result, Sep Separator,
            const Arg& Item) {
            Result += Item;
        }

        template <typename Sep, typename Arg1, typename... Args>
        inline void join_items_impl(std::string& Result, Sep Separator, const Arg1& A1,
            Args &&... Items) {
            Result += A1;
            Result += Separator;
            join_items_impl(Result, Separator, std::forward<Args>(Items)...);
        }

        inline size_t join_one_item_size(char) { return 1; }
        inline size_t join_one_item_size(const char* S) { return S ? ::strlen(S) : 0; }

        template <typename T> inline size_t join_one_item_size(const T& Str) {
            return Str.size();
        }

        inline size_t join_items_size() { return 0; }

        template <typename A1> inline size_t join_items_size(const A1& A) {
            return join_one_item_size(A);
        }
        template <typename A1, typename... Args>
        inline size_t join_items_size(const A1& A, Args &&... Items) {
            return join_one_item_size(A) + join_items_size(std::forward<Args>(Items)...);
        }

    } // end namespace detail

    /// Joins the strings in the range [Begin, End), adding Separator between
    /// the elements.
    template <typename IteratorT>
    inline std::string join(IteratorT Begin, IteratorT End,  std::string_ref Separator) {
        using tag = typename std::iterator_traits<IteratorT>::iterator_category;
        return detail::join_impl(Begin, End, Separator, tag());
    }

    /// Joins the strings in the range [R.begin(), R.end()), adding Separator
    /// between the elements.
    template <typename Range>
    inline std::string join(Range&& R,  std::string_ref Separator) {
        return join(R.begin(), R.end(), Separator);
    }

    /// Joins the strings in the parameter pack \p Items, adding \p Separator
    /// between the elements.  All arguments must be implicitly convertible to
    /// std::string, or there should be an overload of std::string::operator+=()
    /// that accepts the argument explicitly.
    template <typename Sep, typename... Args>
    inline std::string join_items(Sep Separator, Args &&... Items) {
        std::string Result;
        if (sizeof...(Items) == 0)
            return Result;

        size_t NS = detail::join_one_item_size(Separator);
        size_t NI = detail::join_items_size(std::forward<Args>(Items)...);
        Result.reserve(NI + (sizeof...(Items) - 1) * NS + 1);
        detail::join_items_impl(Result, Separator, std::forward<Args>(Items)...);
        return Result;
    }

    /// A helper class to return the specified delimiter string after the first
    /// invocation of operator  std::string_ref().  Used to generate a comma-separated
    /// list from a loop like so:
    ///
    /// \code
    ///   ListSeparator LS;
    ///   for (auto &I : C)
    ///     OS << LS << I.getName();
    /// \end
    class ListSeparator {
        bool First = true;
         std::string_ref Separator;

    public:
        ListSeparator( std::string_ref Separator = ", ") : Separator(Separator) {}
        operator  std::string_ref() {
            if (First) {
                First = false;
                return {};
            }
            return Separator;
        }
    };

} // end namespace lsp

namespace lsp{

// Is <contents a plausible start to an HTML tag?
// Contents may not be the rest of the line, but it's the rest of the plain
// text, so we expect to see at least the tag name.
bool looksLikeTag(std::string_ref& Contents) {
  if (Contents.empty())
    return false;
  if (Contents.front() == '!' || Contents.front() == '?' ||
      Contents.front() == '/')
    return true;
  // Check the start of the tag name.
  if (!lsp::isAlpha(Contents.front()))
    return false;
  // Drop rest of the tag name, and following whitespace.
  Contents = Contents
                 .drop_while([](char C) {
                   return lsp::isAlnum(C) || C == '-' || C == '_' || C == ':';
                 })
                 .drop_while(lsp::isSpace);
  // The rest of the tag consists of attributes, which have restrictive names.
  // If we hit '=', all bets are off (attribute values can contain anything).
  for (; !Contents.empty(); Contents = Contents.drop_front()) {
    if (lsp::isAlnum(Contents.front()) || lsp::isSpace(Contents.front()))
      continue;
    if (Contents.front() == '>' || Contents.start_with("/>"))
      return true; // May close the tag.
    if (Contents.front() == '=')
      return true; // Don't try to parse attribute values.
    return false;  // Random punctuation means this isn't a tag.
  }
  return true; // Potentially incomplete tag.
}

// Tests whether C should be backslash-escaped in markdown.
// The string being escaped is Before + C + After. This is part of a paragraph.
// StartsLine indicates whether `Before` is the start of the line.
// After may not be everything until the end of the line.
//
// It's always safe to escape punctuation, but want minimal escaping.
// The strategy is to escape the first character of anything that might start
// a markdown grammar construct.
bool needsLeadingEscape(char C, std::string_ref Before,  std::string_ref After,
                        bool StartsLine) {

  auto RulerLength = [&]() -> /*Length*/ unsigned {
    if (!StartsLine || !Before.empty())
      return false;
    std::string_ref A = After.trim_right();
    return std::all_of(A.begin(),A.end(), [C](char D) { return C == D; }) ? 1 + A.size() : 0;
  };
  auto IsBullet = [&]() {
    return StartsLine && Before.empty() &&
           (After.empty() || After.start_with(" "));
  };
  auto SpaceSurrounds = [&]() {
    return (After.empty() || std::isspace(After.front())) &&
           (Before.empty() || std::isspace(Before.back()));
  };

  auto WordSurrounds = [&]() {
    return (!After.empty() && std::isalnum(After.front())) &&
           (!Before.empty() && std::isalnum(Before.back()));
  };

  switch (C) {
  case '\\': // Escaped character.
    return true;
  case '`': // Code block or inline code
    // Any number of backticks can delimit an inline code block that can end
    // anywhere (including on another line). We must escape them all.
    return true;
  case '~': // Code block
    return StartsLine && Before.empty() && After.start_with("~~");
  case '#': { // ATX heading.
    if (!StartsLine || !Before.empty())
      return false;
    std::string_ref& Rest = After.trim_left(C);
    return Rest.empty() || Rest.start_with(" ");
  }
  case ']': // Link or link reference.
    // We escape ] rather than [ here, because it's more constrained:
    //   ](...) is an in-line link
    //   ]: is a link reference
    // The following are only links if the link reference exists:
    //   ] by itself is a shortcut link
    //   ][...] is an out-of-line link
    // Because we never emit link references, we don't need to handle these.
    return After.start_with(":") || After.start_with("(");
  case '=': // Setex heading.
    return RulerLength() > 0;
  case '_': // Horizontal ruler or matched delimiter.
    if (RulerLength() >= 3)
      return true;
    // Not a delimiter if surrounded by space, or inside a word.
    // (The rules at word boundaries are subtle).
    return !(SpaceSurrounds() || WordSurrounds());
  case '-': // Setex heading, horizontal ruler, or bullet.
    if (RulerLength() > 0)
      return true;
    return IsBullet();
  case '+': // Bullet list.
    return IsBullet();
  case '*': // Bullet list, horizontal ruler, or delimiter.
    return IsBullet() || RulerLength() >= 3 || !SpaceSurrounds();
  case '<': // HTML tag (or autolink, which we choose not to escape)
    return looksLikeTag(After);
  case '>': // Quote marker. Needs escaping at start of line.
    return StartsLine && Before.empty();
  case '&': { // HTML entity reference
    auto End = After.find(';');
    if (End == std::string_ref::npos)
      return false;
    std::string_ref Content = After.substr(0, End);
    if (Content.consume_front("#"))
    {
      if (Content.consume_front("x") || Content.consume_front("X"))
      {
          return std::all_of(Content.begin(),Content.end(), lsp::isHexDigit);
      }

      return std::all_of(Content.begin(), Content.end(), [](char c)
      {
	      return lsp::isDigit(c);
      });
    }
    return std::all_of(Content.begin(), Content.end(), [](char c)
        {
            return lsp::isAlpha(c);
        });
  }
  case '.': // Numbered list indicator. Escape 12. -> 12\. at start of line.
  case ')':
    return StartsLine && !Before.empty() &&
           std::all_of(Before.begin(), Before.end(), [](char c)
               {
                   return lsp::isDigit(c);
               }) && After.start_with(" ");
  default:
    return false;
  }
}

/// Escape a markdown text block. Ensures the punctuation will not introduce
/// any of the markdown constructs.
 std::string_ref renderText(const std::string_ref& Input, bool StartsLine) {
  std::string_ref R;
  for (unsigned I = 0; I < Input.size(); ++I) {
    if (needsLeadingEscape(Input[I], Input.substr(0, I), Input.substr(I + 1),
                           StartsLine))
      R.push_back('\\');
    R.push_back(Input[I]);
  }
  return R;
}

/// Renders \p Input as an inline block of code in markdown. The returned value
/// is surrounded by backticks and the inner contents are properly escaped.
 std::string_ref renderInlineBlock(const std::string_ref& Input) {
  std::string_ref R;
  // Double all backticks to make sure we don't close the inline block early.
  for (size_t From = 0; From < Input.size();) {
    size_t Next = Input.find("`", From);
    R += Input.substr(From, Next - From);
    if (Next == std::string_ref::npos)
      break;
    R += "``"; // double the found backtick.

    From = Next + 1;
  }
  // If results starts with a backtick, add spaces on both sides. The spaces
  // are ignored by markdown renderers.
  if (std::string_ref(R).start_with("`") || std::string_ref(R).end_with("`"))
    return "` " + std::move(R) + " `";
  // Markdown render should ignore first and last space if both are there. We
  // add an extra pair of spaces in that case to make sure we render what the
  // user intended.
  if (std::string_ref(R).start_with(" ") && std::string_ref(R).end_with(" "))
    return "` " + std::move(R) + " `";
  return "`" + std::move(R) + "`";
}

/// Get marker required for \p Input to represent a markdown codeblock. It
/// consists of at least 3 backticks(`). Although markdown also allows to use
/// tilde(~) for code blocks, they are never used.
 std::string_ref getMarkerForCodeBlock(const std::string_ref& Input) {
  // Count the maximum number of consecutive backticks in \p Input. We need to
  // start and end the code block with more.
  unsigned MaxBackticks = 0;
  unsigned Backticks = 0;
  for (char C : Input) {
    if (C == '`') {
      ++Backticks;
      continue;
    }
    MaxBackticks = std::max(MaxBackticks, Backticks);
    Backticks = 0;
  }
  MaxBackticks = std::max(Backticks, MaxBackticks);
  // Use the corresponding number of backticks to start and end a code block.
  return std::string_ref(/*Repeat=*/std::max(3u, MaxBackticks + 1), '`');
}

 /// SplitString - Split up the specified string according to the specified
/// delimiters, appending the result fragments to the output list.
 void SplitString(const std::string& Source,
                  std::vector<std::string_ref>& OutFragments,
     std::string Delimiters = " \t\n\v\f\r")
{
     boost::split(OutFragments, Source, boost::is_any_of(Delimiters));
}

// Trims the input and concatenates whitespace blocks into a single ` `.
 std::string_ref canonicalizeSpaces(const std::string_ref& Input) {
  std::vector<std::string_ref> Words;
  SplitString(Input, Words);

  return lsp::join(Words, " ");
}

 std::string_ref renderBlocks( std::vector<Block*>&& Children,
     void (Block::* RenderFunc)(std::ostringstream&) const) {
     std::string_ref R;
     std::ostringstream OS(R);

     std::vector<int> v{ 1, 2, 3 };

     // Trim rulers.
     Children.erase(std::remove_if(Children.begin(), Children.end(), [](const Block* C)
	  {
		  return C->isRuler();
	  }), Children.end());

     bool LastBlockWasRuler = true;
     for (const auto& C : Children) {
         if (C->isRuler() && LastBlockWasRuler)
             continue;
         LastBlockWasRuler = C->isRuler();
         ((*C).*RenderFunc)(OS);
     }

     // Get rid of redundant empty lines introduced in plaintext while imitating
     // padding in markdown.
     std::string_ref AdjustedResult;
     std::string_ref TrimmedText(OS.str());
     TrimmedText = TrimmedText.trim();

     std::copy_if(TrimmedText.begin(), TrimmedText.end(),
         std::back_inserter(AdjustedResult),
         [&TrimmedText](const char& C) {
             return !std::string_ref(TrimmedText.data(),
                 &C - TrimmedText.data() + 1)
                 // We allow at most two newlines.
                 .end_with("\n\n\n");
         });

     return AdjustedResult;
 };
 std::string_ref renderBlocks(const std::vector<std::unique_ptr<Block> >& children,
     void (Block::* renderFunc)(std::ostringstream&) const)
 {
    std::vector<Block*> temp(children.size(), nullptr);
 	for(size_t i = 0 ; i < children.size() ; ++i)
 	{
        temp[i]=(children[i].get());
 	}
    return renderBlocks(std::move(temp), renderFunc);
 }
// Separates two blocks with extra spacing. Note that it might render strangely
// in vscode if the trailing block is a codeblock, see
// https://github.com/microsoft/vscode/issues/88416 for details.
class Ruler : public Block {
public:
  void renderMarkdown(std::ostringstream &OS) const override {
    // Note that we need an extra new line before the ruler, otherwise we might
    // make previous block a title instead of introducing a ruler.
    OS << "\n---\n";
  }
  void renderPlainText(std::ostringstream &OS) const override { OS << '\n'; }
  std::unique_ptr<Block> clone() const override {
    return std::make_unique<Ruler>(*this);
  }
  bool isRuler() const override { return true; }
};

class CodeBlock : public Block {
public:
  void renderMarkdown(std::ostringstream &OS) const override {
    std::string_ref Marker = getMarkerForCodeBlock(Contents);
    // No need to pad from previous blocks, as they should end with a new line.
    OS << Marker << Language << '\n' << Contents << '\n' << Marker << '\n';
  }

  void renderPlainText(std::ostringstream &OS) const override {
    // In plaintext we want one empty line before and after codeblocks.
    OS << '\n' << Contents << "\n\n";
  }

  std::unique_ptr<Block> clone() const override {
    return std::make_unique<CodeBlock>(*this);
  }

  CodeBlock( std::string_ref Contents, std::string_ref Language)
      : Contents(std::move(Contents)), Language(std::move(Language)) {}

private:

  std::string_ref Contents;
  std::string_ref Language;
};

// Inserts two spaces after each `\n` to indent each line. First line is not
// indented.
 std::string_ref indentLines(const std::string_ref& Input) {
  assert(!Input.end_with("\n") && "Input should've been trimmed.");
  std::string_ref IndentedR;
  // We'll add 2 spaces after each new line.
  IndentedR.reserve(Input.size() + Input.count("\n") * 2);
  for (char C : Input) {
    IndentedR += C;
    if (C == '\n')
      IndentedR.append("  ");
  }
  return IndentedR;
}

class Heading : public Paragraph {
public:
  Heading(size_t Level) : Level(Level) {}
  void renderMarkdown(std::ostringstream &OS) const override {
    OS << std::string_ref(Level, '#') << ' ';
    Paragraph::renderMarkdown(OS);
  }

private:
  size_t Level;
};

 std::string_ref Block::asMarkdown() const {
  std::string_ref R;
  std::ostringstream OS(R);
  renderMarkdown(OS);
  return std::string_ref(OS.str()).trim();
}

 std::string_ref Block::asPlainText() const {
  std::string_ref R;
  std::ostringstream OS(R);
  renderPlainText(OS);
  return std::string_ref(OS.str()).trim().c_str();
}

     void Paragraph::renderMarkdown(std::ostringstream& OS) const {
         bool NeedsSpace = false;
         bool HasChunks = false;
         for (auto& C : Chunks) {
             if (C.SpaceBefore || NeedsSpace)
                 OS << " ";
             switch (C.Kind) {
             case Chunk::PlainText:
                 OS << renderText(C.Contents, !HasChunks);
                 break;
             case Chunk::InlineCode:
                 OS << renderInlineBlock(C.Contents);
                 break;
             }
             HasChunks = true;
             NeedsSpace = C.SpaceAfter;
         }
         // Paragraphs are translated into markdown lines, not markdown paragraphs.
         // Therefore it only has a single linebreak afterwards.
         // VSCode requires two spaces at the end of line to start a new one.
         OS << "  \n";
     }

     std::unique_ptr<Block> Paragraph::clone() const {
         return std::make_unique<Paragraph>(*this);
     }

     /// Choose a marker to delimit `Text` from a prioritized list of options.
     /// This is more readable than escaping for plain-text.
     std::string_ref chooseMarker(std::vector<std::string_ref> Options,
         const std::string_ref& Text)
     {
         // Prefer a delimiter whose characters don't appear in the text.
         for (std::string_ref& S : Options)
             if (Text.find_first_of(S) == std::string_ref::npos)
                 return S;
         return Options.front();
     }

     void Paragraph::renderPlainText(std::ostringstream& OS) const {
         bool NeedsSpace = false;
         for (auto& C : Chunks) {
             if (C.SpaceBefore || NeedsSpace)
                 OS << " ";
             std::string_ref Marker = "";
             if (C.Preserve && C.Kind == Chunk::InlineCode)
                 Marker = chooseMarker({ "`", "'", "\"" }, C.Contents);
             OS << Marker << C.Contents << Marker;
             NeedsSpace = C.SpaceAfter;
         }
         OS << '\n';
     }

     void BulletList::renderMarkdown(std::ostringstream& OS) const {
         for (auto& D : Items) {
             // Instead of doing this we might prefer passing Indent to children to get
             // rid of the copies, if it turns out to be a bottleneck.

             OS << "- ";
             OS << indentLines(D.asMarkdown()) << '\n';
         }
         // We need a new line after list to terminate it in markdown.
         OS << '\n';
     }

     void BulletList::renderPlainText(std::ostringstream& OS) const {
         for (auto& D : Items) {
             // Instead of doing this we might prefer passing Indent to children to get
             // rid of the copies, if it turns out to be a bottleneck.
             OS << "- " << indentLines(D.asPlainText()) << '\n';
         }
     }

     Paragraph& Paragraph::appendSpace() {
         if (!Chunks.empty())
             Chunks.back().SpaceAfter = true;
         return *this;
     }

     Paragraph& Paragraph::appendText(const std::string_ref& Text) {
         std::string_ref Norm = canonicalizeSpaces(Text);
         if (Norm.empty())
             return *this;
         Chunks.emplace_back();
         Chunk& C = Chunks.back();
         C.Contents = std::move(Norm);
         C.Kind = Chunk::PlainText;

         C.SpaceBefore = std::isspace(Text.front());
         C.SpaceAfter = std::isspace(Text.back());
         return *this;
     }

     Paragraph& Paragraph::appendCode(const std::string_ref& Code, bool Preserve) {
         bool AdjacentCode =
             !Chunks.empty() && Chunks.back().Kind == Chunk::InlineCode;
         std::string_ref Norm = canonicalizeSpaces(Code);
         if (Norm.empty())
             return *this;
         Chunks.emplace_back();
         Chunk& C = Chunks.back();
         C.Contents = std::move(Norm);
         C.Kind = Chunk::InlineCode;
         C.Preserve = Preserve;
         // Disallow adjacent code spans without spaces, markdown can't render them.
         C.SpaceBefore = AdjacentCode;
         return *this;
     }

     std::unique_ptr<Block> BulletList::clone() const {
         return std::make_unique<BulletList>(*this);
     }

     class Document& BulletList::addItem() {
         Items.emplace_back();
         return Items.back();
     }

     Document& Document::operator=(const Document& Other) {
         Children.clear();
         for (const auto& C : Other.Children)
             Children.push_back(C->clone());
         return *this;
     }

     void Document::append(Document Other) {
         std::move(Other.Children.begin(), Other.Children.end(),
             std::back_inserter(Children));
     }

     Paragraph& Document::addParagraph() {
         Children.push_back(std::make_unique<Paragraph>());
         return *static_cast<Paragraph*>(Children.back().get());
     }

     void Document::addRuler() { Children.push_back(std::make_unique<Ruler>()); }

     void Document::addCodeBlock(std::string_ref Code, std::string_ref Language) {
         Children.emplace_back(
             std::make_unique<CodeBlock>(std::move(Code), std::move(Language)));
     }

     std::string_ref Document::asMarkdown() const {
         return renderBlocks(Children, &Block::renderMarkdown);
     }

     std::string_ref Document::asPlainText() const {
         return renderBlocks(Children, &Block::renderPlainText);
     }

     BulletList& Document::addBulletList() {
         Children.emplace_back(std::make_unique<BulletList>());
         return *static_cast<BulletList*>(Children.back().get());
     }

     Paragraph& Document::addHeading(size_t Level) {
         assert(Level > 0);
         Children.emplace_back(std::make_unique<Heading>(Level));
         return *static_cast<Paragraph*>(Children.back().get());
     }
 };

ext: cpp

max_stars_repo_name: supakorn-ras/LspCpp

max_issues_repo_name: supakorn-ras/LspCpp

max_forks_repo_name: supakorn-ras/LspCpp


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

#ifndef VISIONCORE_IO_PLYMODEL_HPP
#define VISIONCORE_IO_PLYMODEL_HPP

#include <stdint.h>
#include <stddef.h>
#include <cstring>

#include <stdexcept>
#include <vector>
#include <string>
#include <memory>
#include <functional>

#include <VisionCore/Platform.hpp>

#include <Eigen/Dense>
#include <Eigen/StdVector>

namespace vc
{

struct ColorPoint
{
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW

    Eigen::Matrix<float,3,1> Position;
    Eigen::Matrix<float,3,1> Color;
};

struct NormalPoint
{
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW

    Eigen::Matrix<float,3,1> Position;
    Eigen::Matrix<float,3,1> Normal;
};

struct ColorNormalPoint
{
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW

    Eigen::Matrix<float,3,1> Position;
    Eigen::Matrix<float,3,1> Color;
    Eigen::Matrix<float,3,1> Normal;
};

struct Surfel
{
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW

    Eigen::Matrix<float,3,1> Position;
    Eigen::Matrix<float,3,1> Color;
    Eigen::Matrix<float,3,1> Normal;
    float                    Radius;
};

namespace io
{

template<typename T>
bool loadPLY(const std::string& plyfilename, std::vector<T, Eigen::aligned_allocator<T>>& vec, float scalePos = 1.0f, std::vector<std::vector<std::size_t>>* idx = nullptr);

template<typename T>
bool savePLY(const std::string& plyfilename, const std::vector<T,Eigen::aligned_allocator<T>>& vec, float scalePos = 1.0f, const std::vector<std::vector<std::size_t>>* idx = nullptr);

inline std::ostream& operator<<(std::ostream& os, const Surfel& s)
{
    os << "Surfel(p = " << s.Position(0) << " , " << s.Position(1) << " , " << s.Position(2)
           << " | c = " << s.Color(0) << " , " << s.Color(1) << " , " << s.Color(2)
           << " | n = " << s.Normal(0) << " , " << s.Normal(1) << " , " << s.Normal(2)
           << " | r = " << s.Radius << ")";
    return os;
}

}

template<> struct type_traits<Surfel>
{
    typedef float ChannelType;
    static constexpr int ChannelCount = 10;
    static constexpr bool IsCUDAType = false;
    static constexpr bool IsEigenType = false;
};

template<> struct type_traits<ColorPoint>
{
    typedef float ChannelType;
    static constexpr int ChannelCount = 6;
    static constexpr bool IsCUDAType = false;
    static constexpr bool IsEigenType = false;
};

template<> struct type_traits<NormalPoint>
{
    typedef float ChannelType;
    static constexpr int ChannelCount = 6;
    static constexpr bool IsCUDAType = false;
    static constexpr bool IsEigenType = false;
};

template<> struct type_traits<ColorNormalPoint>
{
    typedef float ChannelType;
    static constexpr int ChannelCount = 9;
    static constexpr bool IsCUDAType = false;
    static constexpr bool IsEigenType = false;
};

}

#endif // VISIONCORE_IO_PLYMODEL_HPP


text:
/******************************************************************************
* Copyright (C) 2009 - Ikaro Games   www.ikarogames.com                       *
*                                                                             *
* This program is free software; you can redistribute it and/or               *
* modify it under the terms of the GNU General Public License                 *
* as published by the Free Software Foundation; either version 2              *
* of the License, or (at your option) any later version.                      *
*                                                                             *
* 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 General Public License           *
* along with this program; if not, write to the Free Software                 *
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. *
*                                                                             *
*                                                                             *
******************************************************************************/

#include <stdio.h>
#include <boost/filesystem.hpp>
#include <Ogre.h>

#include "projectfootball_config.h"
#include "CResourceManager.h"
#include "CLog.h"
#include "../engine/option/CSystemOptionManager.h"
#include "../exceptions/PFException.h"

extern std::string dataPath;

CResourceManager* CResourceManager::getInstance()
{
    static CResourceManager instance;
    return &instance;
}

CResourceManager::CResourceManager()
{
    LOG_DEBUG("CResourceManager()");
}

CResourceManager::~CResourceManager()
{
    LOG_DEBUG("~CResourceManager()");
}

void CResourceManager::defineResources()
{
    defineGeneral();
    defineShields();
    defineConfederations();
    defineFlags();
    defineSkin();
    definePhotos();
}

void CResourceManager::defineGeneral()
{
    Ogre::String archName, typeName, secName;
    archName = CONCAT_PATH(dataPath, "graphics/simulation/textures");
    typeName = "FileSystem";
    secName  = "General";
    boost::filesystem::path path(archName.c_str());
    if(boost::filesystem::is_directory(path)) {
        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName);
    } else {
        throw PFEXCEPTION("Can't load \"%s\" directory", archName.c_str());
    }

    archName = CONCAT_PATH(dataPath, "graphics/simulation/meshes");
    path = archName.c_str();
    if(boost::filesystem::is_directory(path)) {
        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName);
    } else {
        throw PFEXCEPTION("Can't load \"%s\" directory", archName.c_str());
    }

    archName = CONCAT_PATH(dataPath, "graphics/simulation/materials");
    path = archName.c_str();
    if(boost::filesystem::is_directory(path)) {
        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName);
    } else {
        throw PFEXCEPTION("Can't load \"%s\" directory", archName.c_str());
    }
}

void CResourceManager::defineSkin()
{
    Ogre::String skin = CSystemOptionManager::getInstance()->getGUISkin();
    Ogre::String archName, typeName, secName;
    archName = (Ogre::String)CONCAT_PATH(dataPath, "graphics/skins/") + skin;
    typeName = "FileSystem";
    secName  = skin;
    boost::filesystem::path path(archName.c_str());
    if(boost::filesystem::is_directory(path)) {
        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName+"/fonts", typeName, secName);
        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName+"/imagesets", typeName, secName);
        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName+"/layouts", typeName, secName);
        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName+"/looknfeel", typeName, secName);
        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName+"/lua_scripts", typeName, secName);
        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName+"/schemes", typeName, secName);
    } else {
        throw PFEXCEPTION("Can't load \"%s\" directory", archName.c_str());
    }
}

void CResourceManager::defineShields()
{
    Ogre::String shields = CSystemOptionManager::getInstance()->getGUIShields();
    Ogre::String archName, typeName, secName;
    archName = (Ogre::String)CONCAT_PATH(dataPath, "graphics/shields/") + shields;
    typeName = "FileSystem";
    secName  = shields;
    boost::filesystem::path path(archName.c_str());
    if(boost::filesystem::is_directory(path)) {
        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName);
    } else {
        throw PFEXCEPTION("Can't load \"%s\" directory", archName.c_str());
    }
}

void CResourceManager::defineFlags()
{
    Ogre::String flags = CSystemOptionManager::getInstance()->getGUIFlags();
    Ogre::String archName, typeName, secName;
    archName = (Ogre::String)CONCAT_PATH(dataPath, "graphics/countries/") + flags;
    typeName = "FileSystem";
    secName  = flags;
    boost::filesystem::path path(archName.c_str());
    if(boost::filesystem::is_directory(path)) {
        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName);
    } else {
        throw PFEXCEPTION("Can't load \"%s\" directory", archName.c_str());
    }
}

void CResourceManager::defineConfederations()
{
    Ogre::String conf = CSystemOptionManager::getInstance()->getGUIConfederations();
    Ogre::String archName, typeName, secName;
    archName = (Ogre::String)CONCAT_PATH(dataPath, "graphics/confederations/") + conf;
    typeName = "FileSystem";
    secName  = conf;
    boost::filesystem::path path(archName.c_str());
    if(boost::filesystem::is_directory(path)) {
        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName);
    } else {
        throw PFEXCEPTION("Can't load \"%s\" directory", archName.c_str());
    }
}

void CResourceManager::definePhotos()
{
    Ogre::String photos = CSystemOptionManager::getInstance()->getGUIPhotos();
    Ogre::String archName, typeName, secName;
    archName = (Ogre::String)CONCAT_PATH(dataPath, "graphics/photos/") + photos;
    typeName = "FileSystem";
    secName  = photos;
    boost::filesystem::path path(archName.c_str());
    if(boost::filesystem::is_directory(path)) {
        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName);
    } else {
        throw PFEXCEPTION("Can't load \"%s\" directory", archName.c_str());
    }
}

std::string CResourceManager::getDbFileName()
{
	const char *str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    std::string filename = "";

    srand(time(NULL));
    do{
        std::string cfg_path = CFG_PATH;
        if (cfg_path.at(0) == '~')
            cfg_path.replace(0, 1, getenv("HOME"));

		std::string destPath(CONCAT_PATH(cfg_path, "database/savedgames/"));
    	filename = destPath;
    	for (int i = 0; i < 8; i++)
    		filename += str[rand()%52];
    	filename += ".sql3";
    } while(boost::filesystem::exists(filename));

	return filename;
}

max_stars_repo_name: dividio/projectfootball

max_issues_repo_name: dividio/projectfootball

max_forks_repo_name: dividio/projectfootball


text:
/**
 * @file FileLogger.hpp
 *
 * @brief Logger that outputs data to files, with rotational features.
 *
 * @author Nicolae Natea
 * Contact: nicu@natea.ro
 */

#ifndef _CORE_LOGGER_IMPL_FILE_LOGGER_HPP_
#define _CORE_LOGGER_IMPL_FILE_LOGGER_HPP_

#include <boost/property_tree/ptree.hpp>

#include <core/logger/Logger.hpp>

namespace util
{
    namespace logger
	{
        /** File logger class */
        class FileLogger: public Logger
        {
            // Construction
        public:
            /**
             *  @param[in] config Logger configuration details
             */
            FileLogger(const boost::property_tree::ptree::value_type &config);
            virtual ~FileLogger();

            // Methods
        public:
            void log_event(const util::logger::LogEntryCPtr& entry);

            /**
             * @param[in] index The file index
             * @return The path to the file with the specified index.
             */
            std::string get_file_path(uint32_t index) const;

            /**
             * Detect next index and clean old logs.
             */
            void initialize_fs();

            // Encapsulated data
        private:

            /** Prefix to be added to the file name */
            std::string m_file_prefix;

            /** Suffix to be added to the file name */
            std::string m_file_suffix;

            /** The path to the directory where the log messages are stored */
            std::string m_file_path;

            /** Maximum number of files */
            uint32_t m_max_nbr_of_files;

            /** Maximum file size, in bytes */
            uint32_t m_max_file_size_b;

            /** Specifies the current index */
            uint32_t m_current_index;

            /** Specifies the current file */
            std::string m_current_file;
        };
    }
}

#endif /* _CORE_LOGGER_IMPL_FILE_LOGGER_HPP_ */

max_stars_repo_name: nicsor/BreadCrumbs

max_issues_repo_name: nicsor/BreadCrumbs

max_forks_repo_name: nicsor/BreadCrumbs


text:
//
// connect_pair.cpp
// ~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2011 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// 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)
//

// Disable autolinking for unit tests.
#if !defined(BOOST_ALL_NO_LIB)
#define BOOST_ALL_NO_LIB 1
#endif // !defined(BOOST_ALL_NO_LIB)

// Test that header file is self-contained.
#include <boost/asio/local/connect_pair.hpp>

#include <boost/asio/io_service.hpp>
#include <boost/asio/local/datagram_protocol.hpp>
#include <boost/asio/local/stream_protocol.hpp>
#include "../unit_test.hpp"

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

// local_connect_pair_compile test
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// The following test checks that all host_name functions compile and link
// correctly. Runtime failures are ignored.

namespace local_connect_pair_compile {

void test()
{
#if defined(BOOST_ASIO_HAS_LOCAL_SOCKETS)
  using namespace boost::asio;
  namespace local = boost::asio::local;
  typedef local::datagram_protocol dp;
  typedef local::stream_protocol sp;

  try
  {
    boost::asio::io_service io_service;
    boost::system::error_code ec1;
    boost::system::error_code ec2;

    dp::socket s1(io_service);
    dp::socket s2(io_service);
    local::connect_pair(s1, s2);

    dp::socket s3(io_service);
    dp::socket s4(io_service);
    ec1 = local::connect_pair(s3, s4, ec2);

    sp::socket s5(io_service);
    sp::socket s6(io_service);
    local::connect_pair(s5, s6);

    sp::socket s7(io_service);
    sp::socket s8(io_service);
    ec1 = local::connect_pair(s7, s8, ec2);
  }
  catch (std::exception&)
  {
  }
#endif // defined(BOOST_ASIO_HAS_LOCAL_SOCKETS)
}

} // namespace local_connect_pair_compile

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

test_suite* init_unit_test_suite(int, char*[])
{
  test_suite* test = BOOST_TEST_SUITE("local/connect_pair");
  test->add(BOOST_TEST_CASE(&local_connect_pair_compile::test));
  return test;
}


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.

// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.

// Use, modification and distribution is subject to 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_GEOMETRY_STRATEGIES_CARTESIAN_POINT_IN_BOX_HPP
#define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_POINT_IN_BOX_HPP

#include <boost/geometry/core/access.hpp>
#include <boost/geometry/core/coordinate_dimension.hpp>
#include <boost/geometry/strategies/covered_by.hpp>
#include <boost/geometry/strategies/within.hpp>

namespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry { namespace strategy
{

namespace within
{

struct within_range
{
    template <typename Value1, typename Value2>
    static inline bool apply(Value1 const& value, Value2 const& min_value, Value2 const& max_value)
    {
        return value > min_value && value < max_value;
    }
};

struct covered_by_range
{
    template <typename Value1, typename Value2>
    static inline bool apply(Value1 const& value, Value2 const& min_value, Value2 const& max_value)
    {
        return value >= min_value && value <= max_value;
    }
};

template
<
    typename SubStrategy,
    typename Point,
    typename Box,
    std::size_t Dimension,
    std::size_t DimensionCount
>
struct relate_point_box_loop
{
    static inline bool apply(Point const& point, Box const& box)
    {
        if (! SubStrategy::apply(get<Dimension>(point),
                    get<min_corner, Dimension>(box),
                    get<max_corner, Dimension>(box))
            )
        {
            return false;
        }

        return relate_point_box_loop
            <
                SubStrategy,
                Point, Box,
                Dimension + 1, DimensionCount
            >::apply(point, box);
    }
};

template
<
    typename SubStrategy,
    typename Point,
    typename Box,
    std::size_t DimensionCount
>
struct relate_point_box_loop<SubStrategy, Point, Box, DimensionCount, DimensionCount>
{
    static inline bool apply(Point const& , Box const& )
    {
        return true;
    }
};

template
<
    typename Point,
    typename Box,
    typename SubStrategy = within_range
>
struct point_in_box
{
    static inline bool apply(Point const& point, Box const& box)
    {
        return relate_point_box_loop
            <
                SubStrategy,
                Point, Box,
                0, dimension<Point>::type::value
            >::apply(point, box);
    }
};

} // namespace within

#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS

namespace within { namespace services
{

template <typename Point, typename Box>
struct default_strategy
    <
        point_tag, box_tag,
        point_tag, areal_tag,
        cartesian_tag, cartesian_tag,
        Point, Box
    >
{
    typedef within::point_in_box<Point, Box> type;
};

}} // namespace within::services

namespace covered_by { namespace services
{

template <typename Point, typename Box>
struct default_strategy
    <
        point_tag, box_tag,
        point_tag, areal_tag,
        cartesian_tag, cartesian_tag,
        Point, Box
    >
{
    typedef within::point_in_box
                <
                    Point, Box,
                    within::covered_by_range
                > type;
};

}} // namespace covered_by::services

#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS

}}} // namespace geofeatures_boost::geometry::strategy

#endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_POINT_IN_BOX_HPP

max_stars_repo_name: xarvey/Yuuuuuge

max_issues_repo_name: xarvey/Yuuuuuge

max_forks_repo_name: xarvey/Yuuuuuge


text:
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <Eigen/Core>
#include <unsupported/Eigen/FFT>
#include "VMD.h"
#include "MMDFileIOUtil.h"
#include "fpschanger.h"
#include "smoothvmd.h"
#include "reducevmd.h"

using namespace Eigen;
using namespace MMDFileIOUtil;
using namespace std;

// VMDモーションの平滑化および間引きを行う
bool smooth_and_reduce(VMD& vmd, float cutoff_freq, float threshold_pos, float threshold_rot,
                       float threshold_morph, float srcfps, float tgtfps, bool bezier)
{
  cout << "vmd.frame.size(original): " << vmd.frame.size() << endl;
  // キーフレームをボーンごとに分ける
  map<string, vector<VMD_Frame>> frame_map;
  for (unsigned int i = 0; i < vmd.frame.size(); i++) {
    VMD_Frame frame = vmd.frame[i];
    string name;
    sjis_to_utf8(frame.bonename, name, frame.bonename_len);
    frame_map[name].push_back(frame);
  }
  // ボーンごとに平滑化と間引きを行い、vmdのボーンキーフレームを入れ替える
  vmd.frame.clear();
  for (auto iter = frame_map.begin(); iter != frame_map.end(); iter++) {
    vector<VMD_Frame>& fv = iter->second;
    if (fv.size() > 2) {
      smooth_bone_frame(fv, cutoff_freq, bezier);
      if (srcfps != tgtfps) {
        fv = change_fps_bone(fv, srcfps, tgtfps, bezier);
      }
      fv = reduce_bone_frame(fv, 0, fv.size() - 1, threshold_pos, threshold_rot, bezier);
    }
    for (unsigned int i = 0; i < fv.size(); i++) {
      vmd.frame.push_back(fv[i]);
    }
  }
  cout << "vmd.frame.size(reduced): " << vmd.frame.size() << endl;

  cout << "vmd.morph.size(original): " << vmd.morph.size() << endl;
  // キーフレームをモーフごとに分ける
  map<string, vector<VMD_Morph>> morph_map;
  for (unsigned int i = 0; i < vmd.morph.size(); i++) {
    VMD_Morph morph = vmd.morph[i];
    string name;
    sjis_to_utf8(morph.name, name, morph.name_len);
    morph_map[name].push_back(morph);
  }
  // モーフごとに平滑化と間引きを行い、vmdの表情キーフレームを入れ替える
  vmd.morph.clear();
  for (auto iter = morph_map.begin(); iter != morph_map.end(); iter++) {
    vector<VMD_Morph>& mv = iter->second;
    if (mv.size() > 2) {
      smooth_morph_frame(mv, cutoff_freq);
      if (srcfps != tgtfps) {
        mv = change_fps_morph(mv, srcfps, tgtfps);
      }
      mv = reduce_morph_frame(mv, 0, mv.size() - 1, threshold_morph);
    }
    for (unsigned int i = 0; i < mv.size(); i++) {
      vmd.morph.push_back(mv[i]);
    }
  }
  cout << "vmd.morph.size(reduced) : " << vmd.morph.size() << endl;

  return true;
}

ext: cc

max_stars_repo_name: ikeno-ikeo/readfacevmd

max_issues_repo_name: ikeno-ikeo/readfacevmd

max_forks_repo_name: ikeno-ikeo/readfacevmd


text:
#include "BeastContext.hpp"

#include "Options.hpp"

#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/address.hpp>
#include <boost/ref.hpp>

using namespace arepa::networking::websocket;
using arepa::networking::websocket::Options;
using boost::asio::io_context;
using boost::asio::ip::make_address;
using boost::system::error_code;
using std::shared_ptr;

static void thread_main(io_context* context) {
    context->run();
}

// ---------------------------------------------------------------------------------------------------------------------
#pragma mark - Constructors -
// ---------------------------------------------------------------------------------------------------------------------

BeastContext::BeastContext(const Options& options)
    : io_context(new boost::asio::io_context(options.threads.value_or(Options::DEFAULT_THREAD_COUNT)))
    , io_context_guard(boost::asio::make_work_guard(*this->io_context))
    , endpoint(make_address(options.bind_address.value_or("0.0.0.0")), options.bind_port) {

    // Start the threads.
    auto threadCount = options.threads.value_or(Options::DEFAULT_THREAD_COUNT);
    this->threads.reserve(threadCount);
    for (size_t i = 0; i < threadCount; i++) {
        this->threads.emplace_back(thread_main, this->io_context);
    }
}

BeastContext::~BeastContext() {
    this->io_context->stop();

    // Join the threads so it doesn't crash the entire program.
    for (auto& thread : this->threads) {
        thread.join();
    }
}

max_stars_repo_name: selfeki/social-gaming-platform

max_issues_repo_name: selfeki/social-gaming-platform

max_forks_repo_name: selfeki/social-gaming-platform


text:
#include "AsyncServer.h"
#include <spine/Exception.h>
#include <boost/thread.hpp>
#include <boost/bind.hpp>

namespace SmartMet
{
namespace Server
{
// Number of threads for asynchronous reads and writes
#ifndef ASYNC_THREAD_SIZE
#define ASYNC_THREAD_SIZE 6
#endif

AsyncServer::AsyncServer(const SmartMet::Spine::Options& theOptions,
                         SmartMet::Spine::Reactor& theReactor)
    : Server(theOptions, theReactor), itsNewConnection(), itsMutex(), itsConnections(0)

{
  try
  {
    // Fire the connect accept loop
    startAccept();
  }
  catch (...)
  {
    throw SmartMet::Spine::Exception(BCP, "Operation failed!", NULL);
  }
}

void AsyncServer::run()
{
  try
  {
    // Create some threads to handle connection accepting and asynchronous events
    boost::thread_group workerThreads;
    for (std::size_t i = 0; i < ASYNC_THREAD_SIZE; ++i)
    {
      workerThreads.add_thread(
          new boost::thread(boost::bind(&boost::asio::io_service::run, &itsIoService)));
    }

    // Start the Slow Thread Pool Executor
    itsSlowExecutor.start();

    // Start the Fast Thread Pool Executor
    itsFastExecutor.start();

    // Wait for all threads in the pool to exit.
    // Main thread waits here

    workerThreads.join_all();
  }
  catch (...)
  {
    throw SmartMet::Spine::Exception(BCP, "Operation failed!", NULL);
  }
}

void AsyncServer::shutdown()
{
  try
  {
    // STEP 1: Shutting down the server socket i.e we should not accept any more connections.

    itsAcceptor.close();

    // STEP 2: Shutdown the reactor (i.e. plugins and engines)

    itsReactor.shutdown();

    // STEP 3: Shutdown the thread pools

    // Let's sleep few seconds, because there might be still some
    // data that needs to be tranported.

    boost::this_thread::sleep(boost::posix_time::milliseconds(5000));

    itsSlowExecutor.setGracefulShutdown(true);
    itsFastExecutor.setGracefulShutdown(true);
    itsSlowExecutor.shutdown();
    itsFastExecutor.shutdown();
  }
  catch (...)
  {
    throw SmartMet::Spine::Exception(BCP, "Operation failed!", NULL);
  }
}

void AsyncServer::startAccept()
{
  try
  {
    if (itsShutdownRequested)
      return;

    // Make a new connection object and let it wait for an incoming connection
    // This should not need locking, since we accept connections from a single socket (handleAccepts
    // are implicity serialized)
    itsNewConnection.reset(new AsyncConnection(this,
                                               itsCanGzip,
                                               itsCompressLimit,
                                               itsTimeout,
                                               itsDumpRequests,
                                               itsIoService,
                                               itsReactor,
                                               itsSlowExecutor,
                                               itsFastExecutor));
    itsAcceptor.async_accept(
        itsNewConnection->socket(),
        boost::bind(&AsyncServer::handleAccept, this, boost::asio::placeholders::error));
  }
  catch (...)
  {
    throw SmartMet::Spine::Exception(BCP, "Operation failed!", NULL);
  }
}

void AsyncServer::handleAccept(const boost::system::error_code& e)
{
  try
  {
    if (itsShutdownRequested)
      return;

    if (!e)
    {
      // Start processing the new connection
      itsNewConnection->start();
    }

    // Go back to listen for the next connection
    startAccept();
  }
  catch (...)
  {
    throw SmartMet::Spine::Exception(BCP, "Operation failed!", NULL);
  }
}

}  // namespace Server
}  // namespace SmartMet


text: #include <boost/hana/accessors.hpp>


text:
#include <boost/program_options.hpp>
#include <iostream>
#include <map>
#include <fstream>

#include "deps/gbonds-2.0.3/doc-sbw.h"
#include "deps/gbonds-2.0.3/types.h"

constexpr char version[] = "1.0.0";

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

int main(int argc, char *argv[])
{
  po::options_description desc("Allowed options");
  // clang-format off
  desc.add_options()
      ("help", "produce help message")
      ("version", "show version and exit")
      ("output,o", po::value<string>(), "output file")
      ("input,i", po::value<vector<string>>()->required(), "input files");
  // clang-format on
  po::positional_options_description p;
  p.add("input", -1);

  po::variables_map vm;
  try
  {
    po::store(
        po::command_line_parser(argc, argv).options(desc).positional(p).run(),
        vm);

    if (vm.count("help"))
    {
      std::cout << "usage: " << desc << std::endl;
      return 0;
    }

    if (vm.count("version"))
    {
      std::cout << "sbw2csv version: " << version << std::endl;
      return 0;
    }

    po::notify(vm); // throws error to handle anything else
  }
  catch (po::error &e)
  {
    std::cerr << "ERROR: " << e.what() << std::endl
              << std::endl;
    std::cerr << desc << std::endl;
    return 1;
  }

  // write to a file or stdout if an output file has not been defined
  std::ofstream of;
  std::ostream output(nullptr);
  if (vm.count("output"))
  {
    cout << vm["output"].as<string>() << endl;
    of.open(vm["output"].as<string>(), std::ios::out | std::ios::trunc);
    output.rdbuf(of.rdbuf());
  }
  else
  {
    output.rdbuf(std::cout.rdbuf());
  }

  // print header
  output << "SERIES,DENOMINATION,PURCHASE PRICE,SERIAL NUMBER,ISSUE "
            "DATE,MATURITY DATE"
         << endl;

  // Loop trough the input file and conver each one. Try to be tolerant of errors
  // or bad files.
  for (auto sbwfile : vm["input"].as<vector<string>>())
  {
    try
    {
      gbStatus status = GB_OK;

      auto doc = gb_doc_sbw_open(sbwfile.c_str(), &status);
      if (status != GB_OK)
        throw std::invalid_argument(sbwfile);

      gbDocBond *bond = nullptr;
      GList *l = nullptr;
      auto count = g_list_length(doc->list);
      for (l = g_list_first(doc->list); l != nullptr; l = g_list_next(l))
      {
        bond = static_cast<gbDocBond *>(l->data);
        output << gb_series_fmt(bond->series) << ",";
        output << bond->denom << ",";
        output << bond->issue << ",";
        output << bond->sn << ",";
        output << gb_date_fmt(bond->idate) << ",";
        output << gb_date_fmt(bond->mdate);
        output << endl;
      }
    }
    catch (const std::exception &e)
    {
      std::cerr << "ERROR: " << e.what() << '\n';
    }
  }

  // close the output file if it exists
  if (of.is_open())
  {
    output.flush();
    of.close();
  }

  return 0;
}


text:
/*==============================================================================
    Copyright (c) 2010 Thomas Heller

    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)
==============================================================================*/

#if !BOOST_PHOENIX_IS_ITERATING

#define BOOST_PHOENIX_typename_A(N)                                             \
    BOOST_PP_ENUM_PARAMS(N, typename A)                                         \
/**/

#define BOOST_PHOENIX_typename_A_void(N)                                        \
    BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT(N, typename A, void)                    \
/**/

#define BOOST_PHOENIX_A(N)                                                      \
    BOOST_PP_ENUM_PARAMS(N, A)                                                  \
/**/

#define BOOST_PHOENIX_A_ref(N)                                                  \
    BOOST_PP_ENUM_BINARY_PARAMS(N, A, & BOOST_PP_INTERCEPT)                     \
/**/

#define BOOST_PHOENIX_A_const_ref(N)                                            \
    BOOST_PP_ENUM_BINARY_PARAMS(N, A, const& BOOST_PP_INTERCEPT)                \
/**/

#define BOOST_PHOENIX_A_a(N)                                                    \
    BOOST_PP_ENUM_BINARY_PARAMS(N, A, a)                                        \
/**/

#define BOOST_PHOENIX_A_ref_a(N)                                                \
    BOOST_PP_ENUM_BINARY_PARAMS(N, A, & a)                                      \
/**/

#define BOOST_PHOENIX_A_const_ref_a(N)                                          \
    BOOST_PP_ENUM_BINARY_PARAMS(N, A, const& a)                                 \
/**/

#define BOOST_PHOENIX_a(N)                                                      \
    BOOST_PP_ENUM_PARAMS(N, a)                                                  \
/**/

#else

#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/preprocessor/repetition/enum_binary_params.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/enum_params_with_a_default.hpp>
#include <boost/preprocessor/seq/elem.hpp>
#include <boost/preprocessor/seq/enum.hpp>
#include <boost/preprocessor/seq/for_each_i.hpp>
#include <boost/preprocessor/seq/for_each_product.hpp>
#include <boost/preprocessor/seq/size.hpp>
#include <boost/preprocessor/tuple/elem.hpp>

#define BOOST_PHOENIX_ITERATION                                                 \
    BOOST_PP_ITERATION()                                                        \
/**/

#define BOOST_PHOENIX_typename_A                                                \
    BOOST_PP_ENUM_PARAMS(BOOST_PHOENIX_ITERATION, typename A)                   \
/**/

#define BOOST_PHOENIX_typename_A_void                                           \
    BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT(BOOST_PHOENIX_ITERATION, typename A, void)
/**/

#define BOOST_PHOENIX_A                                                          \
    BOOST_PP_ENUM_PARAMS(BOOST_PHOENIX_ITERATION, A)                             \
/**/

#define BOOST_PHOENIX_A_ref                                                      \
    BOOST_PP_ENUM_BINARY_PARAMS(BOOST_PHOENIX_ITERATION, A, & BOOST_PP_INTERCEPT)\
/**/

#define BOOST_PHOENIX_A_const_ref                                                \
    BOOST_PP_ENUM_BINARY_PARAMS(BOOST_PHOENIX_ITERATION, A, const& BOOST_PP_INTERCEPT)\
/**/

#define BOOST_PHOENIX_A_a                                                        \
    BOOST_PP_ENUM_BINARY_PARAMS(BOOST_PHOENIX_ITERATION, A, a)                   \
/**/

#define BOOST_PHOENIX_A_ref_a                                                    \
    BOOST_PP_ENUM_BINARY_PARAMS(BOOST_PHOENIX_ITERATION, A, & a)                 \
/**/

#define BOOST_PHOENIX_A_const_ref_a                                              \
    BOOST_PP_ENUM_BINARY_PARAMS(BOOST_PHOENIX_ITERATION, A, const& a)            \
/**/

#define BOOST_PHOENIX_a                                                          \
    BOOST_PP_ENUM_PARAMS(BOOST_PHOENIX_ITERATION, a)                             \
/**/

    /////////////////////////////////////////////////////////////////////////////
    // Begin Perfect Forward argument permutation calculation
    /////////////////////////////////////////////////////////////////////////////
#define BOOST_PHOENIX_M0_R(_, N, __)                                            \
    (((A ## N)(&))((A ## N)(const&)))                                           \
/**/

#define BOOST_PHOENIX_M0                                                        \
    BOOST_PP_REPEAT(BOOST_PHOENIX_ITERATION, BOOST_PHOENIX_M0_R, _)             \
/**/

#define BOOST_PHOENIX_M1_R_R(_, N, SEQ)                                         \
    BOOST_PP_SEQ_ELEM(N, SEQ)                                                   \
/**/

#define BOOST_PHOENIX_M1_R(R, __, ___, ELEM)                                    \
    (BOOST_PP_REPEAT(BOOST_PP_SEQ_SIZE(ELEM), BOOST_PHOENIX_M1_R_R, ELEM))      \
/**/

#define BOOST_PHOENIX_M1(R, PRODUCT)                                            \
    ((BOOST_PP_SEQ_ENUM                                                         \
        (BOOST_PP_SEQ_FOR_EACH_I_R                                              \
            (R, BOOST_PHOENIX_M1_R, _, PRODUCT))))                              \
/**/

#define BOOST_PHOENIX_PERM_SEQ                                                  \
    BOOST_PP_SEQ_FOR_EACH_PRODUCT(BOOST_PHOENIX_M1, BOOST_PHOENIX_M0)           \
/**/
    ////////////////////////////////////////////////////////////////////////////
    // End
    ////////////////////////////////////////////////////////////////////////////

#define BOOST_PHOENIX_PERM_SIZE                                                 \
    BOOST_PP_SEQ_SIZE(BOOST_PHOENIX_PERM_SEQ)                                   \
/**/

#define BOOST_PHOENIX_M2(_, N, TUPLE)                                           \
    BOOST_PP_COMMA_IF(N) BOOST_PP_TUPLE_ELEM(BOOST_PHOENIX_ITERATION, N, TUPLE) \
/**/

#define BOOST_PHOENIX_M3(_, N, TUPLE)                                           \
    BOOST_PP_COMMA_IF(N) BOOST_PP_TUPLE_ELEM(BOOST_PHOENIX_ITERATION, N, TUPLE) a ## N\
/**/

#define BOOST_PHOENIX_PERM_ELEM(N)                                              \
    BOOST_PP_SEQ_ELEM(N, BOOST_PHOENIX_PERM_SEQ)                                \
/**/

#define BOOST_PHOENIX_PERM_A(N)                                                 \
    BOOST_PP_REPEAT(BOOST_PHOENIX_ITERATION, BOOST_PHOENIX_M2, BOOST_PHOENIX_PERM_ELEM(N))\
/**/

#define BOOST_PHOENIX_PERM_A_a(N)                                               \
    BOOST_PP_REPEAT(BOOST_PHOENIX_ITERATION, BOOST_PHOENIX_M3, BOOST_PHOENIX_PERM_ELEM(N))\
/**/

#endif

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
#include <gtest/gtest.h>
#include <fstream>
#include <iostream>
#include <cmath>
#include <Eigen/Dense>

// testing following API
#include "estimation/ParticleFilterSIR.h"
#include "probability/pdfs.h"
#include "probability/sampling.h"

using namespace std;
using namespace estimation;
using namespace probability;

namespace logTest
{
  // -----------------------------------------
  // logging for nice pictures
  // -----------------------------------------
  void f_log(VectorXd& x, const VectorXd& u)
  {
    x[0] = x[0];
  }
  void h_log(VectorXd& z, const VectorXd& x)
  {
    z[0] = x[0];
  }

  TEST(LogTest, logEstimationOfConstantNoisySignal)
  {
    // example 1: constant signal, but gaussian noisy with mean 0,
    // variance 1

    // create and open log file(s): signal, particles
    ofstream logSignal;
    logSignal.open("logEstimationOfConstantNoisySignal_signal.dat");
    ofstream logParticles;
    logParticles.open("logEstimationOfConstantNoisySignal_particles.dat");
    ofstream logWeights;
    logWeights.open("logEstimationOfConstantNoisySignal_weights.dat");
    ofstream logNeff;
    logNeff.open("logEstimationOfConstantNoisySignal_Neff.dat");
    ofstream logSignalEstimated;
    logSignalEstimated.open("logEstimationOfConstantNoisySignal_signalEstimated.dat");

    // init particle filter
    ParticleFilterSIR pf(1000);

    pf.setStateTransitionModel(f_log);
    pf.setObservationModel(h_log);
    MatrixXd Q(1,1); Q << 0.01;
    pf.setProcessNoiseCovariance(Q);
    MatrixXd R(1,1); R << 1;
    pf.setMeasurementNoiseCovariance(R);
    VectorXd x0(1); x0 << 1;
    pf.setInitialState(x0);

    pf.validate();

    // measurements
    VectorXd mean = VectorXd::Ones(1);		// mean = 1
    MatrixXd var = MatrixXd::Identity(1,1);	// variance = 1

    Input signal(InputValue(1));
    Output signalEstimated;

    // start filtering and log
    for (int i = 0; i < 40; i++)
    {
      // create new measurement
      double sample = sampleNormalDistribution(mean,var)[0];
      signal[0].setValue(sample);

      // estimate
      signalEstimated = pf.estimate(signal);

      // log
      logSignal << (i+1) << " "
		<< sample << endl;
      pf.log(logParticles, ParticleFilterSIR::PARTICLES, 0);
      pf.log(logWeights, ParticleFilterSIR::WEIGHTS, 0);
      logNeff << (i+1) << " ";
      pf.log(logNeff, ParticleFilterSIR::NEFF, 0);
      logSignalEstimated << (i+1) << " "
			 << signalEstimated[0].getValue() << " "
			 << sqrt(signalEstimated[0].getVariance())
			 << endl;
    }

    logSignal.close();
    logParticles.close();
    logWeights.close();
    logNeff.close();
    logSignalEstimated.close();
  }

  TEST(LogTest, logSampleNormalDistribution)
  {
    int N = 10000;
    VectorXd mean = VectorXd::Zero(1);
    MatrixXd cov = MatrixXd::Identity(1,1);

    ofstream logFile;
    logFile.open("logSampleNormalDistribution.dat");
    for (int i = 0; i < N; i++)
      logFile << sampleNormalDistribution(mean, cov)
    	      << endl;

    logFile.close();
  }

  TEST(LogTest, logSampleUniformDistribution)
  {
    int N = 10000;
    VectorXd a = VectorXd::Zero(1);
    VectorXd b = VectorXd::Ones(1);

    ofstream logFile;
    logFile.open("logSampleUniformDistribution.dat");
    for (int i = 0; i < N; i++)
      logFile << sampleUniformDistribution(a, b)
    	      << endl;

    logFile.close();
  }

  TEST(LogTest, logPdfNormalDistribution)
  {
    VectorXd x = VectorXd::Zero(1);
    VectorXd mean = VectorXd::Zero(1);
    MatrixXd cov = MatrixXd::Identity(1,1);

    ofstream logFile;
    logFile.open("logPdfNormalDistribution.dat");
    for (float i = -2.0; i < 2.0; i=i+0.1)
    {
      x[0] = i;
      logFile << i << " "
	      << pdfNormalDistribution(x, mean, cov)
    	      << endl;
    }
    logFile.close();
  }
}

max_stars_repo_name: tuw-cpsg/sf-pkg

max_issues_repo_name: ros-agriculture/sf-pkg

max_forks_repo_name: tuw-cpsg/sf-pkg