text:
#include "orwell/game/RGBColour.hpp"

#include <boost/property_tree/ptree.hpp>

namespace orwell
{
namespace game
{

RGBColour::RGBColour(
		uint8_t const iR,
		uint8_t const iG,
		uint8_t const iB)
	: m_r(iR)
	, m_g(iG)
	, m_b(iB)
{
}

uint8_t RGBColour::getRed() const
{
	return m_r;
}

uint8_t RGBColour::getGreen() const
{
	return m_g;
}

uint8_t RGBColour::getBlue() const
{
	return m_b;
}

bool RGBColour::operator==(RGBColour const & iOther) const
{
	return ((m_r == iOther.m_r) && (m_g == iOther.m_g) && (m_b == iOther.m_b));

}

RGBColour RGBColour::ParseConfig(
		std::string const & iMapLimitName,
		boost::property_tree::ptree const & iPtree)
{
	uint8_t const aR = iPtree.get< uint8_t >(iMapLimitName + ".r");
	uint8_t const aG = iPtree.get< uint8_t >(iMapLimitName + ".g");
	uint8_t const aB = iPtree.get< uint8_t >(iMapLimitName + ".b");
	return RGBColour(aR, aG, aB);
}

}
}

std::ostream & operator<<(
		std::ostream & ioOstream,
		orwell::game::RGBColour const & iColour)
{
	ioOstream << "Colour : { " <<
		"R = " << iColour.getRed() << " ; " <<
		"G = " << iColour.getGreen() << " ; " <<
		"B = " << iColour.getBlue() << " }";
	return ioOstream;
}

max_stars_repo_name: orwell-int/server-game

max_issues_repo_name: orwell-int/server-game

max_forks_repo_name: orwell-int/server-game


text:
// Copyright 2015-2018 Hans Dembinski
//
// 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)

#include <boost/core/lightweight_test.hpp>
#include <boost/histogram.hpp>
#include <string>
#include <utility>
#include "utility_histogram.hpp"
#include "utility_meta.hpp"

using namespace boost::histogram;

using def = use_default;

using regular = axis::regular<double, def, def, axis::option::growth>;

using integer = axis::integer<
    double, def,
    axis::join<axis::option::underflow, axis::option::overflow, axis::option::growth>>;

using category = axis::category<std::string, def, axis::option::growth>;

class custom_2d_axis {
public:
  auto index(std::tuple<double, double> xy) const {
    const auto x = std::get<0>(xy);
    const auto y = std::get<1>(xy);
    const auto r = std::sqrt(x * x + y * y);
    return std::min(static_cast<axis::index_type>(r), size());
  }

  auto update(std::tuple<double, double> xy) {
    const auto x = std::get<0>(xy);
    const auto y = std::get<1>(xy);
    const auto r = std::sqrt(x * x + y * y);
    const auto n = static_cast<int>(r);
    const auto old = size_;
    if (n >= size_) size_ = n + 1;
    return std::make_pair(n, old - size_);
  }

  axis::index_type size() const { return size_; }

private:
  axis::index_type size_ = 0;
};

template <typename Tag>
void run_tests() {
  {
    auto h = make(Tag(), regular(2, 0, 1));
    const auto& a = h.axis();
    BOOST_TEST_EQ(a.size(), 2);
    BOOST_TEST_EQ(h.size(), 2);
    // [0.0, 0.5, 1.0]
    h(0.1);
    h(0.9);
    BOOST_TEST_EQ(a.size(), 2);
    BOOST_TEST_EQ(h.size(), 2);
    h(-std::numeric_limits<double>::infinity());
    h(std::numeric_limits<double>::quiet_NaN());
    h(std::numeric_limits<double>::infinity());
    BOOST_TEST_EQ(a.size(), 2);
    BOOST_TEST_EQ(h.size(), 2);
    h(-0.3);
    // [-0.5, 0.0, 0.5, 1.0]
    BOOST_TEST_EQ(a.size(), 3);
    BOOST_TEST_EQ(h.size(), 3);
    BOOST_TEST_EQ(h[0], 1);
    BOOST_TEST_EQ(h[1], 1);
    BOOST_TEST_EQ(h[2], 1);
    h(1.9);
    // [-0.5, 0.0, 0.5, 1.0, 1.5, 2.0]
    BOOST_TEST_EQ(a.size(), 5);
    BOOST_TEST_EQ(h.size(), 5);
    BOOST_TEST_EQ(h[0], 1);
    BOOST_TEST_EQ(h[1], 1);
    BOOST_TEST_EQ(h[2], 1);
    BOOST_TEST_EQ(h[3], 0);
    BOOST_TEST_EQ(h[4], 1);
  }

  {
    auto h = make_s(Tag(), std::vector<int>(), integer());
    const auto& a = h.axis();
    h(-std::numeric_limits<double>::infinity());
    h(std::numeric_limits<double>::quiet_NaN());
    h(std::numeric_limits<double>::infinity());
    BOOST_TEST_EQ(a.size(), 0);
    BOOST_TEST_EQ(h.size(), 2);
    BOOST_TEST_EQ(h[-1], 1);
    BOOST_TEST_EQ(h[0], 2);
    h(0);
    BOOST_TEST_EQ(a.size(), 1);
    BOOST_TEST_EQ(h.size(), 3);
    BOOST_TEST_EQ(h[-1], 1);
    BOOST_TEST_EQ(h[0], 1);
    BOOST_TEST_EQ(h[1], 2);
    h(2);
    BOOST_TEST_EQ(a.size(), 3);
    BOOST_TEST_EQ(h.size(), 5);
    BOOST_TEST_EQ(h[-1], 1);
    BOOST_TEST_EQ(h[0], 1);
    BOOST_TEST_EQ(h[1], 0);
    BOOST_TEST_EQ(h[2], 1);
    BOOST_TEST_EQ(h[3], 2);
    h(-2);
    BOOST_TEST_EQ(a.size(), 5);
    BOOST_TEST_EQ(h.size(), 7);
    // BOOST_TEST_EQ(h[-1], 1)
    BOOST_TEST_EQ(h[0], 1);
    BOOST_TEST_EQ(h[1], 0);
    BOOST_TEST_EQ(h[2], 1);
    BOOST_TEST_EQ(h[3], 0);
    BOOST_TEST_EQ(h[4], 1);
    BOOST_TEST_EQ(h[5], 2);
  }

  {
    auto h = make_s(Tag(), std::vector<int>(), integer(), category());
    const auto& a = h.axis(0);
    const auto& b = h.axis(1);
    BOOST_TEST_EQ(a.size(), 0);
    BOOST_TEST_EQ(b.size(), 0);
    BOOST_TEST_EQ(h.size(), 0);
    h(0, "x");
    h(-std::numeric_limits<double>::infinity(), "x");
    h(std::numeric_limits<double>::infinity(), "x");
    h(std::numeric_limits<double>::quiet_NaN(), "x");
    BOOST_TEST_EQ(a.size(), 1);
    BOOST_TEST_EQ(b.size(), 1);
    BOOST_TEST_EQ(h.size(), 3);
    h(2, "x");
    BOOST_TEST_EQ(a.size(), 3);
    BOOST_TEST_EQ(b.size(), 1);
    BOOST_TEST_EQ(h.size(), 5);
    h(1, "y");
    BOOST_TEST_EQ(a.size(), 3);
    BOOST_TEST_EQ(b.size(), 2);
    BOOST_TEST_EQ(h.size(), 10);
    BOOST_TEST_EQ(h.at(-1, 0), 1);
    BOOST_TEST_EQ(h.at(-1, 1), 0);
    BOOST_TEST_EQ(h.at(3, 0), 2);
    BOOST_TEST_EQ(h.at(3, 1), 0);
    BOOST_TEST_EQ(h.at(a.index(0), b.index("x")), 1);
    BOOST_TEST_EQ(h.at(a.index(1), b.index("x")), 0);
    BOOST_TEST_EQ(h.at(a.index(2), b.index("x")), 1);
    BOOST_TEST_EQ(h.at(a.index(0), b.index("y")), 0);
    BOOST_TEST_EQ(h.at(a.index(1), b.index("y")), 1);
    BOOST_TEST_EQ(h.at(a.index(2), b.index("y")), 0);

    BOOST_TEST_THROWS(h(0, "x", 42), std::invalid_argument);
  }

  {
    auto h = make_s(Tag{}, std::vector<int>{}, custom_2d_axis{});
    BOOST_TEST_EQ(h.size(), 0);
    h(0, 0);
    BOOST_TEST_EQ(h.size(), 1);
    h(1, 0);
    h(0, 1);
    BOOST_TEST_EQ(h.size(), 2);
    h(10, 0);
    BOOST_TEST_EQ(h.size(), 11);
    BOOST_TEST_EQ(h[0], 1);
    BOOST_TEST_EQ(h[1], 2);
    BOOST_TEST_EQ(h[10], 1);
    BOOST_TEST_THROWS(h(0), std::invalid_argument);
  }
}

int main() {
  run_tests<static_tag>();
  run_tests<dynamic_tag>();

  return boost::report_errors();
}

ext: cpp

max_stars_repo_name: henryiii/histogram

max_issues_repo_name: henryiii/histogram

max_forks_repo_name: henryiii/histogram


text:
/*
 * Created: 27-01-2017
 * Modified: Fri 27 Jan 2017 11:29:06 GMT
 * Author: Jonas R. Glesaaen (jonas@glesaaen.com)
 */

#ifndef IRUBATARU_IO_HPP
#define IRUBATARU_IO_HPP

#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <fstream>
#include <vector>

namespace irubataru
{
namespace io
{

template <typename Value_Type>
class TableReader
{
public:
  using return_type = std::vector<std::vector<Value_Type>>;

  explicit TableReader() : TableReader({'#'}) {}

  explicit TableReader(std::vector<char> comments)
      : comment_chars{std::move(comments)}
  {}

  return_type Read(std::string filename, std::size_t skip_lines = 0,
                   std::size_t read_every = 0)
  {
    ifs.open(filename);
    if (!ifs)
      throw std::runtime_error{"Cannot open file \"" + filename +
                               "\" for reading."};

    read_preamble(skip_lines);
    if (!ifs)
      return {};

    return read_body(read_every);
  }

private:
  void read_preamble(std::size_t skip_lines)
  {
    auto lines_read = std::size_t{0ul};

    while (ifs and lines_read < skip_lines)
    {
      if (!is_comment())
        ++lines_read;

      discard_line();
    }

    discard_comments();
  }

  return_type read_body(std::size_t read_every)
  {
    auto result = return_type(determine_columns());

    auto read_lines = std::size_t{0ul};
    while (ifs)
    {
      if (is_comment())
      {
        discard_line();
        continue;
      }

      ++read_lines;
      if ((read_lines - 1) % read_every != 0)
      {
        discard_line();
        continue;
      }

      auto row = read_row(result.size());

      if (row.empty())
        continue;

      for (auto i = 0; i < result.size(); ++i)
        result[i].push_back(row[i]);
    }

    return result;
  }

  std::vector<Value_Type> read_row(std::size_t columns)
  {
    std::string single_line{};
    std::getline(ifs, single_line);

    if (single_line.empty())
      return {};

    auto str_vec = std::vector<std::string>{};
    boost::split(str_vec, single_line, boost::is_any_of("\t "));

    if (str_vec.size() != columns)
    {
      std::ostringstream oss;
      oss << "Inconsistent table format. Columns: " << columns << ", "
          << "current row has " << str_vec.size() << " columns.\n"
          << "Row is: " << single_line;
      throw std::runtime_error{oss.str()};
    }

    auto row = std::vector<Value_Type>(columns);

    std::transform(
        str_vec.begin(), str_vec.end(), row.begin(),
        [](std::string s) { return boost::lexical_cast<double>(s); });

    return row;
  }

  void discard_comments()
  {
    while (ifs and is_comment())
      discard_line();
  }

  void discard_line()
  {
    std::string throw_away{};
    std::getline(ifs, throw_away);
  }

  bool is_comment()
  {
    return std::find(comment_chars.begin(), comment_chars.end(), ifs.peek()) !=
           comment_chars.end();
  }

  std::size_t determine_columns()
  {
    auto init_pos = ifs.tellg();

    auto one_line = std::string{};
    std::getline(ifs, one_line);

    ifs.seekg(init_pos);
    return count_columns(one_line);
  }

  std::size_t count_columns(std::string str)
  {
    boost::trim_left(str);
    boost::trim_right(str);
    return std::count(str.begin(), str.end(), ' ') + 1;
  }

private:
  std::vector<char> comment_chars;
  std::ifstream ifs;
};

} // namespace io
} // namespace irubataru

#endif /* IRUBATARU_IO_HPP */

ext: hpp


text:
/*
   +----------------------------------------------------------------------+
   | HipHop for PHP                                                       |
   +----------------------------------------------------------------------+
   | Copyright (c) 2010-2014 Facebook, Inc. (http://www.facebook.com)     |
   +----------------------------------------------------------------------+
   | This source file is subject to version 3.01 of the PHP license,      |
   | that is bundled with this package in the file LICENSE, and is        |
   | available through the world-wide-web at the following url:           |
   | http://www.php.net/license/3_01.txt                                  |
   | If you did not receive a copy of the PHP license and are unable to   |
   | obtain it through the world-wide-web, please send a note to          |
   | license@php.net so we can mail you a copy immediately.               |
   +----------------------------------------------------------------------+
*/

#include "hphp/compiler/code_generator.h"
#include "hphp/compiler/code_model_enums.h"
#include "hphp/compiler/statement/statement_list.h"
#include "hphp/compiler/expression/expression_list.h"
#include "hphp/compiler/option.h"
#include "hphp/compiler/analysis/file_scope.h"
#include "hphp/compiler/analysis/function_scope.h"
#include "hphp/compiler/analysis/analysis_result.h"
#include "hphp/compiler/analysis/variable_table.h"
#include "hphp/runtime/base/zend-printf.h"
#include "hphp/util/text-util.h"
#include "hphp/util/hash.h"
#include "folly/Conv.h"
#include <boost/format.hpp>
#include <boost/scoped_array.hpp>
#include <algorithm>
#include <vector>

using namespace HPHP;

///////////////////////////////////////////////////////////////////////////////
// statics

void CodeGenerator::BuildJumpTable(const std::vector<const char *> &strings,
                                   MapIntToStringVec &out, int tableSize,
                                   bool caseInsensitive) {
  assert(!strings.empty());
  assert(out.empty());
  assert(tableSize > 0);

  for (unsigned int i = 0; i < strings.size(); i++) {
    const char *s = strings[i];
    int hash = (caseInsensitive ? hash_string_i(s) : hash_string(s)) %
               tableSize;
    out[hash].push_back(s);
  }
}

const char *CodeGenerator::STARTER_MARKER =
  "namespace hphp_impl_starter {}";
const char *CodeGenerator::SPLITTER_MARKER =
  "namespace hphp_impl_splitter {}";
const char *CodeGenerator::HASH_INCLUDE =
  "#include";

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

CodeGenerator::CodeGenerator(std::ostream *primary,
                             Output output /* = PickledPHP */,
                             const std::string *filename /* = NULL */)
    : m_out(nullptr), m_output(output),
      m_context(NoContext), m_itemIndex(-1) {
  for (int i = 0; i < StreamCount; i++) {
    m_streams[i] = nullptr;
    m_indentation[i] = 0;
    m_indentPending[i] = true;
    m_lineNo[i] = 1;
    m_inComments[i] = 0;
    m_wrappedExpression[i] = false;
    m_inExpression[i] = false;
  }
  setStream(PrimaryStream, primary);
  useStream(PrimaryStream);

  if (filename) m_filename = *filename;
  m_translatePredefined = false;
  m_scalarVariant = false;
  m_initListFirstElem = false;
  m_inFileOrClassHeader = false;
  m_inNamespace = false;
}

void CodeGenerator::useStream(Stream stream) {
  assert(stream >= NullStream && stream < StreamCount);
  m_curStream = stream;
  if (stream == NullStream) {
    m_out = nullptr;
  } else {
    m_out = m_streams[stream];
  }
}

bool CodeGenerator::usingStream(Stream stream) {
  assert(stream >= 0 && stream < StreamCount);
  return m_out == m_streams[stream];
}

std::ostream *CodeGenerator::getStream(Stream stream) const {
  assert(stream >= 0 && stream < StreamCount);
  return m_streams[stream];
}

void CodeGenerator::setStream(Stream stream, std::ostream *out) {
  assert(out);
  assert(stream >= 0 && stream < StreamCount);
  m_streams[stream] = out;
}

int CodeGenerator::getLineNo(Stream stream) const {
  assert(stream >= 0 && stream < StreamCount);
  return m_lineNo[stream];
}

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

void CodeGenerator::printf(const char *fmt, ...) {
  va_list ap; va_start(ap, fmt); print(fmt, ap); va_end(ap);
}

void CodeGenerator::indentBegin(const char *fmt, ...) {
  va_list ap; va_start(ap, fmt); print(fmt, ap); va_end(ap);
  m_indentation[m_curStream]++;
}

void CodeGenerator::indentBegin() {
  m_indentation[m_curStream]++;
}

void CodeGenerator::indentEnd(const char *fmt, ...) {
  assert(m_indentation[m_curStream]);
  m_indentation[m_curStream]--;
  va_list ap; va_start(ap, fmt); print(fmt, ap); va_end(ap);
}

void CodeGenerator::indentEnd() {
  assert(m_indentation[m_curStream]);
  m_indentation[m_curStream]--;
}

bool CodeGenerator::inComments() const {
  return m_inComments[m_curStream] > 0;
}

void CodeGenerator::startComments() {
  m_inComments[m_curStream]++;
  printf(" /*");
}

void CodeGenerator::endComments() {
  assert(m_inComments[m_curStream] > 0);
  m_inComments[m_curStream]--;
  printf(" */");
}

void CodeGenerator::printSection(const char *name, bool newline /* = true */) {
  if (newline) printf("\n");
  printf("// %s\n", name);
}

void CodeGenerator::printSeparator() {
  printf("///////////////////////////////////////"
         "////////////////////////////////////////\n");
}

void CodeGenerator::namespaceBegin() {
  always_assert(!m_inNamespace);
  m_inNamespace = true;
  printf("\n");
  printf("namespace HPHP {\n");
  printSeparator();
  printf("\n");
}

void CodeGenerator::namespaceEnd() {
  always_assert(m_inNamespace);
  m_inNamespace = false;
  printf("\n");
  printSeparator();
  printf("}\n");
}

std::string CodeGenerator::getFormattedName(const std::string &file) {
  char *fn = strdup(file.c_str());
  int len = strlen(fn);
  always_assert(len == (int)file.size());
  for (int i = 0; i < len; i++) {
    if (!isalnum(fn[i])) fn[i] = '_';
  }
  string formatted = fn;
  free(fn);
  int hash = hash_string(file.data(), file.size());
  formatted += boost::str(boost::format("%08x") % hash);
  return formatted;
}

bool CodeGenerator::ensureInNamespace() {
  if (m_inNamespace) return false;
  namespaceBegin();
  return true;
}

bool CodeGenerator::ensureOutOfNamespace() {
  if (!m_inNamespace) return false;
  namespaceEnd();
  return true;
}

void CodeGenerator::ifdefBegin(bool ifdef, const char *fmt, ...) {
  printf(ifdef ? "#ifdef " : "#ifndef ");
  va_list ap; va_start(ap, fmt); print(fmt, ap); va_end(ap);
  printf("\n");
}

void CodeGenerator::ifdefEnd(const char *fmt, ...) {
  printf("#endif // ");
  va_list ap; va_start(ap, fmt); print(fmt, ap); va_end(ap);
  printf("\n");
}

void CodeGenerator::printDocComment(const std::string comment) {
  if (comment.empty()) return;
  string escaped;
  escaped.reserve(comment.size() + 10);
  for (unsigned int i = 0; i < comment.size(); i++) {
    char ch = comment[i];
    escaped += ch;
    if (ch == '/' && i > 1 && comment[i+1] == '*') {
      escaped += '\\'; // splitting illegal /* into /\*
    }
  }
  print(escaped.c_str(), false);
  printf("\n");
}

std::string CodeGenerator::EscapeLabel(const std::string &name,
                                       bool *binary /* = NULL */) {
  return escapeStringForCPP(name, binary);
}

///////////////////////////////////////////////////////////////////////////////
// helpers

void CodeGenerator::print(const char *fmt, va_list ap) {
  if (!m_out) return;
  boost::scoped_array<char> buf;
  bool done = false;
  for (int len = 1024; !done; len <<= 1) {
    va_list v;
    va_copy(v, ap);

    buf.reset(new char[len]);
    if (vsnprintf(buf.get(), len, fmt, v) < len) done = true;

    va_end(v);
  }
  print(buf.get());
}

void CodeGenerator::print(const char *msg, bool indent /* = true */) {
  const char *start = msg;
  int length = 1;
  for (const char *iter = msg; ; ++iter, ++length) {
    if (*iter == '\n') {
      if (indent) {
        // Only indent if it is pending and if it is not an empty line
        if (m_indentPending[m_curStream] && length > 1) printIndent();

        // Printing substrings requires an additional copy operation,
        // so do it only if necessary
        if (iter[1] != '\0') {
          printSubstring(start, length);
        } else {
          *m_out << start;
        }
        start = iter + 1;
        length = 0;
      }
      m_lineNo[m_curStream]++;
      m_indentPending[m_curStream] = true;
    } else if (*iter == '\0') {
      // Perform print only in case what's left is not an empty string
      if (length > 1) {
        if (indent && m_indentPending[m_curStream]) {
          printIndent();
          m_indentPending[m_curStream] = false;
        }
        *m_out << start;
      }
      break;
    }
  }
}

void CodeGenerator::printSubstring(const char *start, int length) {
  const int BUF_LEN = 0x100;
  char buf[BUF_LEN];
  while (length > 0) {
    int curLength = std::min(length, BUF_LEN - 1);
    memcpy(buf, start, curLength);
    buf[curLength] = '\0';
    *m_out << buf;
    length -= curLength;
    start += curLength;
  }
}

void CodeGenerator::printIndent() {
  for (int i = 0; i < m_indentation[m_curStream]; i++) {
    *m_out << Option::Tab;
  }
}

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

int CodeGenerator::s_idLambda = 0;
string CodeGenerator::GetNewLambda() {
  return Option::LambdaPrefix + "lambda_" + folly::to<string>(++s_idLambda);
}

void CodeGenerator::resetIdCount(const std::string &key) {
  m_idCounters[key] = 0;
}

int CodeGenerator::createNewId(const std::string &key) {
  return ++m_idCounters[key];
}

int CodeGenerator::createNewId(ConstructPtr cs) {
  FileScopePtr fs = cs->getFileScope();
  if (fs) {
    return createNewId(fs->getName());
  }
  return createNewId("");
}

int CodeGenerator::createNewLocalId(ConstructPtr ar) {
  if (m_wrappedExpression[m_curStream]) {
    return m_localId[m_curStream]++;
  }
  FunctionScopePtr func = ar->getFunctionScope();
  if (func) {
    return func->nextInlineIndex();
  }
  FileScopePtr fs = ar->getFileScope();
  if (fs) {
    return createNewId(fs->getName());
  }
  return createNewId("");
}

void CodeGenerator::pushBreakScope(int labelId,
                                   bool loopCounter /* = true */) {
  m_breakScopes.push_back(labelId);
  if (loopCounter) {
    printf("LOOP_COUNTER(%d);\n", int(labelId & ~BreakScopeBitMask));
  }
}

void CodeGenerator::popBreakScope() {
  m_breakScopes.pop_back();
  if (m_breakScopes.size() == 0) {
    m_breakLabelIds.clear();
    m_contLabelIds.clear();
  }
}

void CodeGenerator::pushCallInfo(int cit) {
  m_callInfos.push_back(cit);
}
void CodeGenerator::popCallInfo() {
  m_callInfos.pop_back();
}
int CodeGenerator::callInfoTop() {
  if (m_callInfos.empty()) return -1;
  return m_callInfos.back();
}

void CodeGenerator::addLabelId(const char *name, int labelId) {
  if (!strcmp(name, "break")) {
    m_breakLabelIds.insert(labelId);
  } else if (!strcmp(name, "continue")) {
    m_contLabelIds.insert(labelId);
  } else {
    assert(false);
  }
}

bool CodeGenerator::findLabelId(const char *name, int labelId) {
  if (!strcmp(name, "break")) {
    return m_breakLabelIds.find(labelId) != m_breakLabelIds.end();
  } else if (!strcmp(name, "continue")) {
    return m_contLabelIds.find(labelId) != m_contLabelIds.end();
  } else {
    assert(false);
  }
  return false;
}

int CodeGenerator::ClassScopeCompare::cmp(const ClassScopeRawPtr &p1,
                                          const ClassScopeRawPtr &p2) const {
  int d = p1->getRedeclaringId() - p2->getRedeclaringId();
  if (d) return d;
  return strcasecmp(p1->getName().c_str(), p2->getName().c_str());
}

void CodeGenerator::printObjectHeader(const std::string className,
                                      int numProperties) {
  std::string prefixedClassName;
  prefixedClassName.append(m_astPrefix);
  prefixedClassName.append(className);
  m_astClassNames.push_back(prefixedClassName);
  printf("O:%d:\"%s\":%d:{",
    (int)prefixedClassName.length(), prefixedClassName.c_str(), numProperties);
}

void CodeGenerator::printObjectFooter() {
  printf("}");
  m_astClassNames.pop_back();
}

void CodeGenerator::printPropertyHeader(const std::string propertyName) {
  auto prefixedClassName = m_astClassNames.back();
  auto len = 2+prefixedClassName.length()+propertyName.length();
  printf("s:%d:\"", (int)len);
  *m_out << (char)0;
  printf("%s", prefixedClassName.c_str());
  *m_out << (char)0;
  printf("%s\";", propertyName.c_str());
}

void CodeGenerator::printNull() {
  printf("N;");
}

void CodeGenerator::printBool(bool value) {
  printf("b:%d;", value ? 1 : 0);
}

void CodeGenerator::printValue(double v) {
  *m_out << "d:";
  if (std::isnan(v)) {
    *m_out << "NAN";
  } else if (std::isinf(v)) {
    if (v < 0) *m_out << '-';
    *m_out << "INF";
  } else {
    char *buf;
    if (v == 0.0) v = 0.0; // so to avoid "-0" output
    vspprintf(&buf, 0, "%.*H", 14, v);
    m_out->write(buf, strlen(buf));
    free(buf);
  }
  *m_out << ';';
}

void CodeGenerator::printValue(int32_t value) {
  printf("i:%d;", value);
}

void CodeGenerator::printValue(int64_t value) {
  printf("i:%" PRId64 ";", value);
}

void CodeGenerator::printValue(std::string value) {
  printf("s:%d:\"", (int)value.length());
  getStream()->write(value.c_str(), value.length());
  printf("\";");
}

void CodeGenerator::printModifierVector(std::string value) {
  printf("V:9:\"HH\\Vector\":1:{");
  printObjectHeader("Modifier", 1);
  printPropertyHeader("name");
  printValue(value);
  printObjectFooter();
  printf("}");
}

void CodeGenerator::printTypeExpression(std::string value) {
  printObjectHeader("TypeExpression", 1);
  printPropertyHeader("name");
  printValue(value);
  printObjectFooter();
}

void CodeGenerator::printTypeExpression(ExpressionPtr expression) {
  printObjectHeader("TypeExpression", 2);
  printPropertyHeader("name");
  expression->outputCodeModel(*this);
  printPropertyHeader("sourceLocation");
  printLocation(expression->getLocation());
  printObjectFooter();
}

void CodeGenerator::printExpression(ExpressionPtr expression, bool isRef) {
  if (isRef) {
    printObjectHeader("UnaryOpExpression", 3);
    printPropertyHeader("expression");
    expression->outputCodeModel(*this);
    printPropertyHeader("operation");
    printValue(PHP_REFERENCE_OP);
    printPropertyHeader("sourceLocation");
    printLocation(expression->getLocation());
    printObjectFooter();
  } else {
    expression->outputCodeModel(*this);
  }
}

void CodeGenerator::printExpressionVector(ExpressionListPtr el) {
  auto count = el == nullptr ? 0 : el->getCount();
  printf("V:9:\"HH\\Vector\":%d:{", count);
  if (count > 0) {
    el->outputCodeModel(*this);
  }
  printf("}");
}

void CodeGenerator::printExpressionVector(ExpressionPtr e) {
  if (e->is(Expression::KindOfExpressionList)) {
    auto sl = static_pointer_cast<ExpressionList>(e);
    printExpressionVector(sl);
  } else {
    printf("V:9:\"HH\\Vector\":1:{");
    e->outputCodeModel(*this);
    printf("}");
  }
}

void CodeGenerator::printTypeExpressionVector(ExpressionListPtr el) {
  auto count = el == nullptr ? 0 : el->getCount();
  printf("V:9:\"HH\\Vector\":%d:{", count);
  for (int i = 0; i < count; i++) {
    auto te = (*el)[i];
    printTypeExpression(te);
  }
  printf("}");
}

void CodeGenerator::printAsBlock(StatementPtr s, bool isEnclosed) {
  if (s != nullptr && s->is(Statement::KindOfBlockStatement)) {
    s->outputCodeModel(*this);
  } else {
    auto numProps = s == nullptr ? 0 : 2;
    if (isEnclosed) numProps++;
    printObjectHeader("BlockStatement", numProps);
    if (s != nullptr) {
      printPropertyHeader("statements");
      printStatementVector(s);
      printPropertyHeader("sourceLocation");
      printLocation(s->getLocation());
    }
    if (isEnclosed) {
      printPropertyHeader("isEnclosed");
      printBool(true);
    }
    printObjectFooter();
  }
}

void CodeGenerator::printStatementVector(StatementListPtr sl) {
  printf("V:9:\"HH\\Vector\":%d:{", sl->getCount());
  if (sl->getCount() > 0) {
    sl->outputCodeModel(*this);
  }
  printf("}");
}

void CodeGenerator::printStatementVector(StatementPtr s) {
  if (s == nullptr) {
    printf("V:9:\"HH\\Vector\":0:{}");
  } else if (s->is(Statement::KindOfStatementList)) {
    auto sl = static_pointer_cast<StatementList>(s);
    printStatementVector(sl);
  } else {
    printf("V:9:\"HH\\Vector\":1:{");
    s->outputCodeModel(*this);
    printf("}");
  }
}

void CodeGenerator::printLocation(LocationPtr location) {
  if (location == nullptr) return;
  printObjectHeader("SourceLocation", 4);
  printPropertyHeader("startLine");
  printValue(location->line0);
  printPropertyHeader("endLine");
  printValue(location->line1);
  printPropertyHeader("startColumn");
  printValue(location->char0);
  printPropertyHeader("endColumn");
  printValue(location->char1);
  printObjectFooter();
}

max_stars_repo_name: bauerj/hhvm

max_issues_repo_name: mrliao/hhvm

max_forks_repo_name: mrliao/hhvm


text:
#include "ETL.h"
using namespace std;
#include <iostream>
#include <string>
#include <eigen3/Eigen/Dense>
#include <boost/algorithm/string.hpp>
#include <vector>

int main( int argc , char *argc[]){
     ETL etl(argc[1] , argc[2] , argc[3]);

     vector<vector<string>> dataset = etl.readCSV();
     return EXIT_SUCCESS ;

}


text:
#include "IndriPruneIndex.h"

#include <unordered_map>
#include <boost/foreach.hpp>

#include "indri/CompressedCollection.hpp"
#include "indri/DiskIndex.hpp"
#include "indri/IndexWriter.hpp"
#include "indri/Path.hpp"

#define __atomic_add __gnu_cxx::__atomic_add
#include "indri/Repository.hpp"

void copy_repository(indri::api::Parameters& parameters) {
    using indri::file::Path;

    vector<string> requiredKeys = { "from", "to" };
    requires(parameters, requiredKeys);

    string sourcePath = parameters["from"];
    string path = parameters["to"];

    // Load up the manifest
    indri::api::Parameters manifest;
    manifest.loadFile(Path::combine(sourcePath, "manifest"));

    if (manifest["indexes.index"].size() > 1)
	die("Source contains more than one index (run 'dumpindex compact' first)");

    // Load up the deletedList
    indri::index::DeletedDocumentList deletedList;
    deletedList.read(Path::combine(sourcePath, "deleted"));

    if (deletedList.deletedCount() > 0)
    	die("Source has non-empty deleted list (run 'dumpindex compact' first)");

    // Load up the index in the ``pruned mode''
    indri::index::DiskIndex diskIndex;

    diskIndex.open(Path::combine(sourcePath, "index"),
		   i64_to_string((INT64)manifest["indexes.index"]));

    if (diskIndex.documentMaximum() == 0)
	die("The index is empty");

    // Create the destination path as necessary
    if (!Path::exists(path)) Path::create(path);

    // Write out the new index
    {
	indri::index::IndexWriter writer;
	string indexPath = Path::combine(path, "index");
	Path::create(indexPath);

	vector<indri::index::Index::FieldDescription> fieldDescriptions;
	writer.write(diskIndex, fieldDescriptions, deletedList, Path::combine(indexPath, "0"));
    }

    // Copy the compressed collection
    {
	indri::collection::CompressedCollection sourceCollection, collection;
	sourceCollection.openRead(Path::combine(sourcePath, "collection"));

	string collectionPath = Path::combine(path, "collection");
	Path::create(collectionPath);
	collection.create(collectionPath,
			  sourceCollection.forwardFields(),
			  sourceCollection.reverseFields());
	collection.append(sourceCollection, deletedList, 0);
    }

    // Write out the deleted list
    deletedList.write(Path::combine(path, "deleted"));

    // Write out the manifest
    manifest["indexes"].set("index", 0);
    manifest.writeFile(Path::combine(path, "manifest"));
}

void check_index_health(indri::index::Index& index,
			bool dumpPostingList) {
    unique_ptr<indri::index::DocListFileIterator>
	docListFileIterator(index.docListFileIterator());

    if (dumpPostingList) {
	for (docListFileIterator->startIteration();
	     !docListFileIterator->finished();
	     docListFileIterator->nextEntry())
	{
	    indri::index::DocListFileIterator::DocListData* docListData = docListFileIterator->currentEntry();
	    indri::index::TermData* termData = docListData->termData;
	    indri::index::DocListIterator* docListIterator = docListData->iterator;

	    assert(termData);
	    int documentCount = 0;
	    for (; !docListIterator->finished(); docListIterator->nextEntry())
	    {
		indri::index::DocListIterator::DocumentData* documentData =
		    docListIterator->currentEntry();
		assert(documentData);
		++documentCount;
	    }

	    cout << documentCount << '\n';
	}
    }
    else {
	int termCount = 0;
	long postingCount = 0;

	for (docListFileIterator->startIteration();
	     !docListFileIterator->finished();
	     docListFileIterator->nextEntry())
	{
	    indri::index::DocListFileIterator::DocListData* docListData = docListFileIterator->currentEntry();
	    indri::index::TermData* termData = docListData->termData;
	    indri::index::DocListIterator* docListIterator = docListData->iterator;

	    assert(termData);
	    ++termCount;

	    for (; !docListIterator->finished(); docListIterator->nextEntry())
	    {
		indri::index::DocListIterator::DocumentData* documentData =
		    docListIterator->currentEntry();
		assert(documentData);
		++postingCount;
	    }
	}

	cout << "term count: " << termCount << '\n';
	cout << "posting count: " << postingCount << '\n';
    }
}

void print_direct_file(indri::api::Parameters& parameters) {
    using indri::file::Path;

    vector<string> requiredKeys = { "index", "docID" };
    requires(parameters, requiredKeys);

    string sourcePath = parameters["index"];
    int docID = static_cast<int>(parameters["docID"]);
    bool outputText = parameters.exists("outputText");

    indri::index::DiskIndex diskIndex;
    diskIndex.open(Path::combine(sourcePath, "index"), "0");

    indri::index::Index& original = diskIndex;
    unique_ptr<const indri::index::TermList> termList(original.termList(docID));

    if (outputText) {
	unordered_map<int, string> cache;
	BOOST_FOREACH (int termID, termList->terms()) {
	    unordered_map<int, string>::iterator match = cache.find(termID);
	    if (match != cache.end())
		cout << match->second << '(' << match->first << ')' << ' ';
	    else {
		string term = original.term(termID);
		cache[termID] = term;
		cout << term << '(' << termID << ')' << ' ';
	    }
	}
    }
    else{
	BOOST_FOREACH (int termID, termList->terms()) {
	    cout << termID << ' ';
	}
    }
    cout << endl;
}

// DocListFileIterator manages its own DocListIterators.  Manually deleting the
// iterators (e.g., `delete') can cause segfaults.  Each of these
// DocListIterator has been started (via startIteration()) once they are ready
// in the host object.  So additional calls are also harmful.
//
// Be sure to let these DocListIterators run to the end once initialized.
// Expect segfaults otherwise.
//
void print_inverted_list(indri::api::Parameters& parameters) {
    vector<string> requiredKeys = { "index", "term" };
    requires(parameters, requiredKeys);

    string sourcePath = parameters["index"];
    string term = parameters["term"];

    indri::index::DiskIndex diskIndex;
    diskIndex.open(indri::file::Path::combine(sourcePath, "index"), "0");

    indri::index::Index& original = diskIndex;
    int documentCount = original.documentCount();

    unique_ptr<indri::index::DocListFileIterator>
	docListFileIterator(original.docListFileIterator());

    docListFileIterator->startIteration();
    while (!docListFileIterator->finished()) {
	indri::index::DocListFileIterator::DocListData* docListData = docListFileIterator->currentEntry();
	indri::index::TermData* termData = docListData->termData;
	indri::index::DocListIterator* docListIterator = docListData->iterator;

	if (term == termData->term) {
	    while (!docListIterator->finished()) {
		indri::index::DocListIterator::DocumentData* documentData =
		    docListIterator->currentEntry();
		cout << documentData->document << ' ';
		docListIterator->nextEntry();
	    }
	    cout << endl;
	}
	else
	    while (!docListIterator->finished())
		docListIterator->nextEntry(documentCount + 1);

	docListFileIterator->nextEntry();
    }
}

void check_index_health(indri::api::Parameters& parameters) {
    using indri::file::Path;

    std::vector<std::string> requiredKeys = { "index" };
    requires(parameters, requiredKeys);

    std::string sourcePath = parameters["index"];
    bool dumpPostingList = parameters.exists("dump");

    indri::index::DiskIndex diskIndex;
    indri::api::Parameters manifest;
    manifest.loadFile(Path::combine(sourcePath, "manifest"));
    diskIndex.open(Path::combine(sourcePath, "index"),
		   i64_to_string((INT64)manifest["indexes.index"]));

    check_index_health(diskIndex, dumpPostingList);
}

void check_document_prior(indri::api::Parameters& parameters) {
    using indri::file::Path;

    std::vector<std::string> requiredKeys = { "index", "priorFile", "beta" };
    requires(parameters, requiredKeys);

    std::string sourcePath = parameters["index"];
    std::string priorPath = parameters["priorFile"];
    double beta = parameters["beta"];

    indri::collection::Repository repo;
    repo.openRead(sourcePath);

    indri::index::Index* index = (*repo.indexes())[0];
    indri::collection::CompressedCollection* collection = repo.collection();

    int documentCount = index->documentCount();

    std::vector<double> prior(documentCount + 1, 0.0);
    double cumsum = 0.0;

    {
	std::ifstream in(priorPath.c_str());

	std::vector<lemur::api::DOCID_T> result;
	std::string docno;
	double prob;

	while (in >> docno >> prob) {
	    result = collection->retrieveIDByMetadatum("docno", docno);
	    assert(result.size() == 1);
	    prior[result.front()] = prob;
	    cumsum += prob;
	}
    }

    for (int i = 1; i <= documentCount; ++i) {
	if (prior[i] == 0.0)
	    cout << i << ' ' << '*' << 1.0 << '\n';
	else
	    cout << i << ' ' << ' ' << 1.0 + prior[i] / (1 - cumsum + beta) * documentCount << '\n';
    }
}

max_stars_repo_name: rueycheng/Indri-PruningToolkit

max_issues_repo_name: rueycheng/Indri-PruningToolkit

max_forks_repo_name: rueycheng/Indri-PruningToolkit


text:
#include "../stdafx.h"
#include "Calc.h"
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_CASE( CalculatorTest )
{
	std::stringstream ss;
	ToReversePolish( std::cin, ss );
	double res = CalculateReversePolish( ss );
}

max_stars_repo_name: Wiki-fan/MIPT-all

max_issues_repo_name: Wiki-fan/MIPT-all

max_forks_repo_name: Wiki-fan/MIPT-all


text:
// Software License for MTL
//
// Copyright (c) 2007 The Trustees of Indiana University.
//               2008 Dresden University of Technology and the Trustees of Indiana University.
//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.
// All rights reserved.
// Authors: Peter Gottschling and Andrew Lumsdaine
//
// This file is part of the Matrix Template Library
//
// See also license.mtl.txt in the distribution.

#ifndef ITL_PC_ILUT_INCLUDE
#define ITL_PC_ILUT_INCLUDE

#include <boost/numeric/mtl/vector/sparse_vector.hpp>
#include <boost/numeric/mtl/operation/invert_diagonal.hpp>
#include <boost/numeric/mtl/interface/vpt.hpp>

namespace itl { namespace pc {

struct ilut_factorizer
{

    template <typename Matrix, typename Para, typename L_type, typename U_type>
    ilut_factorizer(const Matrix &A, const Para& p, L_type& L, U_type& U)
    { factorize(A, p, L, U, mtl::traits::is_row_major<Matrix>()); }

    // column-major matrices are copied first
    template <typename Matrix, typename Para, typename L_type, typename U_type, bool B>
    void factorize(const Matrix &A, const Para& p, L_type& L, U_type& U, boost::mpl::bool_<B>)
    {
	typedef typename mtl::Collection<Matrix>::value_type      value_type;
	typedef typename mtl::Collection<Matrix>::size_type       size_type;
	typedef mtl::matrix::parameters<mtl::row_major, mtl::index::c_index, mtl::non_fixed::dimensions, false, size_type> para;
	typedef mtl::matrix::compressed2D<value_type, para>  LU_type;
	LU_type LU(A);
	factorize(LU, p, L, U, boost::mpl::true_());
    }

    // According Yousef Saad: ILUT, NLAA, Vol 1(4), 387-402 (1994)
#if 0
    template <typename Value, typename MPara, typename Para, typename L_type, typename U_type>
    factorize(const mtl::matrix::compressed2D<Value, MPara>& A, const Para& p, L_type& L, U_type& U, boost::mpl::true_)
#endif

    template <typename Matrix, typename Para, typename L_type, typename U_type>
    void factorize(const Matrix& A, const Para& p, L_type& L, U_type& U, boost::mpl::true_)

    {
	mtl::vampir_trace<5049> tracer;
	using std::abs; using mtl::traits::range_generator; using mtl::begin; using mtl::end;
	using namespace mtl::tag;
	MTL_THROW_IF(num_rows(A) != num_cols(A), mtl::matrix_not_square());

	typedef typename mtl::Collection<Matrix>::value_type      value_type;
	typedef typename mtl::Collection<Matrix>::size_type       size_type;
	typedef typename range_generator<row, Matrix>::type       cur_type;
	typedef typename range_generator<nz, cur_type>::type      icur_type;
	typename mtl::traits::col<Matrix>::type                   col(A);
	typename mtl::traits::const_value<Matrix>::type           value(A);

	size_type n= num_rows(A);
	L.change_dim(n, n);
	U.change_dim(n, n);
	{
	    mtl::matrix::inserter<L_type> L_ins(L, p.first);
	    mtl::matrix::inserter<U_type> U_ins(U, p.first + 1); // plus one for diagonal

	    mtl::vector::sparse_vector<value_type> vec(n); // corr. row in paper
	    cur_type ic= begin<row>(A); // , iend= end<row>(A);
	    for (size_type i= 0; i < n; ++i, ++ic) {

		for (icur_type kc= begin<nz>(ic), kend= end<nz>(ic); kc != kend; ++kc) // row= A[i][*]
		    vec.insert(col(*kc), value(*kc));
		// std::cerr << "vec_" << i << " = " << vec << std::endl;
		value_type tau_i= p.second * two_norm(vec); // threshold for i-th row
		// loop over non-zeros in vec; changes in vec considered
		for (size_type j= 0; j < vec.nnz() && vec.index(j) < i; j++) {
		    size_type k= vec.index(j);
		    value_type ukk= U_ins.value(k, k);
		    MTL_DEBUG_THROW_IF(ukk == value_type(0), mtl::missing_diagonal());
		    value_type vec_k= vec.value(j)/= ukk;
		    // std::cout << "vec after updating from U[" << k << "][" << k << "] is " << vec << '\n';
		    for (size_type j0= U_ins.ref_major()[k], j1= U_ins.ref_slot_ends()[k]; j0 < j1; j0++) { // U[k][k+1:n]
			size_type k1= U_ins.ref_minor()[j0];
			if (k1 > k)
			    vec[k1]-= vec_k * U_ins.ref_elements()[j0];
			// std::cout << "vec after updating from U[" << k << "][" << k1 << "] is " << vec << '\n';
		    }
		    // if (i > 1000 && i < 1010) std::cout << "vec before crop in row " << i << ", updating from row " << k << ": \n" << vec << "\n";
		    vec.crop(tau_i);
		    // if (i > 1000 && i < 1010) std::cout << "vec after crop: \n" << vec << "\n";
		}
		// std::cerr << "vec_" << i << " = " << vec << std::endl;
		vec.sort_on_data();
		// std::cerr << "vec_" << i << " sorted on data = " << vec << std::endl;

		// std::cout << "vec at " << i << " is " << vec << '\n';
		// mtl::vampir_trace<9904> tracer2;
		bool diag_found= false;
		for (size_type cntu= 0, cntl= 0, j= 0; j < vec.nnz() && (cntu < p.first || cntl < p.first); j++) {
		    size_type k= vec.index(j);
		    value_type v= vec.value(j);
		    // if (abs(v) < tau_i) break;
		    if (i == k) {
			U_ins[i][i] << v; diag_found= true;
		    } else if (i < k) {
			if (cntu++ < p.first)
			    U_ins[i][k] << v;
		    } else // i > k
			if (cntl++ < p.first)
			    L_ins[i][k] << v;
		}
		if (!diag_found) std::cerr << "Deleted diagonal!!!!\n";
		vec.make_empty();
	    }
	} // destroy inserters
	invert_diagonal(U);
    }
};

// Not usable yet !!!!!
template <typename Matrix, typename Value= typename mtl::Collection<Matrix>::value_type>
class ilut
  : public ilu<Matrix, ilut_factorizer, Value>
{
    typedef ilu<Matrix, ilut_factorizer, Value> base;
  public:
    ilut(const Matrix& A, std::size_t p, typename mtl::Collection<Matrix>::value_type tau)
      : base(A, std::make_pair(p, tau)) {}
};

}} // namespace itl::pc

#endif // ITL_PC_ILUT_INCLUDE


text:
//
// Created by weitao on 16-2-11.
//

#ifndef BOOST_TEST1_COROUTINE_HPP
#define BOOST_TEST1_COROUTINE_HPP

#include <cstdint>
#include <memory>
#include <functional>
#include <boost/coroutine/all.hpp>

using coro_yield_t = boost::coroutines::symmetric_coroutine<uint32_t>::yield_type;
using coro_call_t  = boost::coroutines::symmetric_coroutine<uint32_t>::call_type;

#endif //BOOST_TEST1_COROUTINE_HPP

max_stars_repo_name: weijingtao/leopard

max_issues_repo_name: weijingtao/leopard

max_forks_repo_name: weijingtao/leopard


text:
#include "BoundingBox.h"

#include <Eigen/Dense>
#include <memory>

BoundingBox::BoundingBox()
{
    mMin.setZero();
    mMax.setZero();
    mMid.setZero();
    mSize.setZero();
}


text:
#include "bootstrapper.hpp"
#include <boost/filesystem.hpp>

using namespace boost::filesystem;

namespace hlserver {

Bootstrapper::Bootstrapper(const std::string &media_path)
    : media_path_(media_path)
{
}

void Bootstrapper::setup() throw (DirectoryInsufficientPrivilegesError, DirectoryNotFoundError, DirectoryNotWritable, DirectoryNotReadable, DirectoryNotReadableByGroup)
{
    path p(media_path_);

    try
    {
        if (!exists(p)) {
            if (false == create_directory(media_path_)) {
                throw DirectoryNotWritable(media_path_);
            }
        }

        file_status s = status(p);
        if (!(s.permissions() & perms::owner_read)) {
            throw DirectoryNotReadable(media_path_);
        }

        if (!(s.permissions() & perms::owner_write)) {
            throw DirectoryNotWritable(media_path_);
        }

        if (!(s.permissions() & perms::group_write)) {
            throw DirectoryNotReadableByGroup(media_path_);
        }
    }
    catch (const filesystem_error &ex)
    {
        // Log this
        throw DirectoryInsufficientPrivilegesError(media_path_);
    }
}

} // namespace hlserver


text:
#include "stdafx.h"

#include "config.h"

#ifdef SUPPORT_EXTERNAL_CONFIG

#include "../core/tools/strings.h"
#include "../core/tools/binary_stream.h"
#include "../core/tools/system.h"
#include "../core/utils.h"
#include "../common.h"

#include <boost/filesystem.hpp>

#endif // SUPPORT_EXTERNAL_CONFIG

#include "../json_unserialize_helpers.h"
#include "config_data.h"

#include "../spin_lock.h"

namespace config
{
    static auto is_less_by_first = [](const auto& x1, const auto& x2)
    {
        static_assert(std::is_same_v<decltype(x1), decltype(x2)>);
        auto key1 = x1.first;
        auto key2 = x2.first;
        return static_cast<
                std::underlying_type_t<decltype(key1)>>(key1) < static_cast<std::underlying_type_t<decltype(key2)>>(key2);

    };

    static auto get_string(const rapidjson::Value& json_value, std::string_view name)
    {
        return common::json::get_value<std::string>(json_value, name).value_or(std::string());
    }

    static auto get_bool(const rapidjson::Value& json_value, std::string_view name)
    {
        return common::json::get_value<bool>(json_value, name).value_or(false);
    }

    static auto get_int64(const rapidjson::Value& json_value, std::string_view name)
    {
        return common::json::get_value<int64_t>(json_value, name).value_or(0);
    }

    static std::optional<urls_array> parse_urls(const rapidjson::Value& _node)
    {
        if (const auto it = _node.FindMember("urls"); it != _node.MemberEnd())
        {
            urls_array res =
            {
                std::pair(urls::base, get_string(it->value, "base")),
                std::pair(urls::base_binary, get_string(it->value, "base_binary")),
                std::pair(urls::files_parser_url, get_string(it->value, "files_parser_url")),
                std::pair(urls::profile, get_string(it->value, "profile")),
                std::pair(urls::profile_agent, get_string(it->value, "profile_agent")),
                std::pair(urls::auth_mail_ru, get_string(it->value, "auth_mail_ru")),
                std::pair(urls::oauth2_mail_ru, get_string(it->value, "oauth2_mail_ru")),
                std::pair(urls::r_mail_ru, get_string(it->value, "r_mail_ru")),
                std::pair(urls::win_mail_ru, get_string(it->value, "win_mail_ru")),
                std::pair(urls::read_msg, get_string(it->value, "read_msg")),
                std::pair(urls::stickerpack_share, get_string(it->value, "stickerpack_share")),
                std::pair(urls::cicq_com, get_string(it->value, "c.icq.com")),
                std::pair(urls::update_win_alpha, get_string(it->value, "update_win_alpha")),
                std::pair(urls::update_win_beta, get_string(it->value, "update_win_beta")),
                std::pair(urls::update_win_release, get_string(it->value, "update_win_release")),
                std::pair(urls::update_mac_alpha, get_string(it->value, "update_mac_alpha")),
                std::pair(urls::update_mac_beta, get_string(it->value, "update_mac_beta")),
                std::pair(urls::update_mac_release, get_string(it->value, "update_mac_release")),
                std::pair(urls::update_linux_alpha_32, get_string(it->value, "update_linux_alpha_32")),
                std::pair(urls::update_linux_alpha_64, get_string(it->value, "update_linux_alpha_64")),
                std::pair(urls::update_linux_beta_32, get_string(it->value, "update_linux_beta_32")),
                std::pair(urls::update_linux_beta_64, get_string(it->value, "update_linux_beta_64")),
                std::pair(urls::update_linux_release_32, get_string(it->value, "update_linux_release_32")),
                std::pair(urls::update_linux_release_64, get_string(it->value, "update_linux_release_64")),
                std::pair(urls::omicron, get_string(it->value, "omicron")),
                std::pair(urls::stat_base, get_string(it->value, "stat_base")),
                std::pair(urls::feedback, get_string(it->value, "feedback")),
                std::pair(urls::legal_terms, get_string(it->value, "legal_terms")),
                std::pair(urls::legal_privacy_policy, get_string(it->value, "legal_privacy_policy")),
                std::pair(urls::installer_help, get_string(it->value, "installer_help")),
                std::pair(urls::data_visibility, get_string(it->value, "data_visibility")),
                std::pair(urls::password_recovery, get_string(it->value, "password_recovery")),
                std::pair(urls::zstd_request_dict, get_string(it->value, "zstd_request_dict")),
                std::pair(urls::zstd_response_dict, get_string(it->value, "zstd_response_dict")),
                std::pair(urls::attach_phone, get_string(it->value, "attach_phone_url")),
                std::pair(urls::update_app_url, get_string(it->value, "update_app_url")),
                std::pair(urls::vcs_room, get_string(it->value, "vcs_room")),
                std::pair(urls::dns_cache, get_string(it->value, "dns_cache")),
                std::pair(urls::external_emoji, get_string(it->value, "external_emoji")),
            };

            if (std::is_sorted(std::cbegin(res), std::cend(res), is_less_by_first))
                return std::make_optional(std::move(res));
            assert(false);
        }
        return {};
    }

    static std::optional<translations_array> parse_translations(const rapidjson::Value& _node)
    {
        if (const auto it = _node.FindMember("translations"); it != _node.MemberEnd())
        {
            translations_array res =
            {
                std::pair(translations::installer_title_win, get_string(it->value, "installer_title_win")),
                std::pair(translations::installer_failed_win, get_string(it->value, "installer_failed_win")),
                std::pair(translations::installer_welcome_win, get_string(it->value, "installer_welcome_win")),
                std::pair(translations::app_title, get_string(it->value, "app_title")),
                std::pair(translations::app_install_mobile, get_string(it->value, "app_install_mobile")),
                std::pair(translations::gdpr_welcome, get_string(it->value, "gdpr_welcome")),
            };

            if (std::is_sorted(std::cbegin(res), std::cend(res), is_less_by_first))
                return std::make_optional(std::move(res));
            assert(false);
        }
        return {};
    }

    static std::optional<features_array> parse_features(const rapidjson::Value& _node)
    {
        if (const auto it = _node.FindMember("features"); it != _node.MemberEnd())
        {
            features_array res =
            {
                std::pair(features::feedback_selected, get_bool(it->value, "feedback_selected")),
                std::pair(features::new_avatar_rapi, get_bool(it->value, "new_avatar_rapi")),
                std::pair(features::ptt_recognition, get_bool(it->value, "ptt_recognition")),
                std::pair(features::snippet_in_chat, get_bool(it->value, "snippet_in_chat")),
                std::pair(features::add_contact, get_bool(it->value, "add_contact")),
                std::pair(features::remove_contact, get_bool(it->value, "remove_contact")),
                std::pair(features::force_avatar_update, get_bool(it->value, "force_avatar_update")),
                std::pair(features::call_quality_stat, get_bool(it->value, "call_quality_stat")),
                std::pair(features::show_data_visibility_link, get_bool(it->value, "show_data_visibility_link")),
                std::pair(features::show_security_call_link, get_bool(it->value, "show_security_call_link")),
                std::pair(features::contact_us_via_mail_default, get_bool(it->value, "contact_us_via_mail_default")),
                std::pair(features::searchable_recents_placeholder, get_bool(it->value, "searchable_recents_placeholder")),
                std::pair(features::auto_accepted_gdpr, get_bool(it->value, "auto_accepted_gdpr")),
                std::pair(features::phone_allowed, get_bool(it->value, "phone_allowed")),
                std::pair(features::show_attach_phone_number_popup, get_bool(it->value, "show_attach_phone_number_popup")),
                std::pair(features::attach_phone_number_popup_modal, get_bool(it->value, "attach_phone_number_popup_modal")),
                std::pair(features::login_by_phone_allowed, get_bool(it->value, "login_by_phone_allowed")),
                std::pair(features::login_by_mail_default, get_bool(it->value, "login_by_mail_default")),
                std::pair(features::login_by_uin_allowed, get_bool(it->value, "login_by_uin_allowed")),
                std::pair(features::login_by_oauth2_allowed, get_bool(it->value, "login_by_oauth2_allowed")),
                std::pair(features::forgot_password, get_bool(it->value, "forgot_password")),
                std::pair(features::explained_forgot_password, get_bool(it->value, "explained_forgot_password")),
                std::pair(features::unknown_contacts, get_bool(it->value, "unknown_contacts")),
                std::pair(features::stranger_contacts, get_bool(it->value, "stranger_contacts")),
                std::pair(features::otp_login, get_bool(it->value, "otp_login")),
                std::pair(features::show_notification_text, get_bool(it->value, "show_notification_text")),
                std::pair(features::changeable_name, get_bool(it->value, "changeable_name")),
                std::pair(features::avatar_change_allowed, get_bool(it->value, "avatar_change_allowed")),
                std::pair(features::beta_update, get_bool(it->value, "beta_update")),
                std::pair(features::ssl_verify, get_bool(it->value, "ssl_verify")),
                std::pair(features::profile_agent_as_domain_url, get_bool(it->value, "profile_agent_as_domain_url")),
                std::pair(features::need_gdpr_window, get_bool(it->value, "need_gdpr_window")),
                std::pair(features::need_introduce_window, get_bool(it->value, "need_introduce_window")),
                std::pair(features::has_nicknames, get_bool(it->value, "has_nicknames")),
                std::pair(features::zstd_request_enabled, get_bool(it->value, "zstd_request_enabled")),
                std::pair(features::zstd_response_enabled, get_bool(it->value, "zstd_response_enabled")),
                std::pair(features::external_phone_attachment, get_bool(it->value, "external_phone_attachment")),
                std::pair(features::external_url_config, get_bool(it->value, "external_url_config")),
                std::pair(features::omicron_enabled, get_bool(it->value, "omicron_enabled")),
                std::pair(features::sticker_suggests, get_bool(it->value, "sticker_suggests")),
                std::pair(features::sticker_suggests_server, get_bool(it->value, "sticker_suggests_server")),
                std::pair(features::smartreplies, get_bool(it->value, "smartreplies")),
                std::pair(features::spell_check, get_bool(it->value, "spell_check")),
                std::pair(features::favorites_message_onpremise, get_bool(it->value, "favorites_message_onpremise")),
                std::pair(features::info_change_allowed, get_bool(it->value, "info_change_allowed")),
                std::pair(features::vcs_call_by_link_enabled, get_bool(it->value, "vcs_call_by_link_enabled")),
                std::pair(features::vcs_webinar_enabled, get_bool(it->value, "vcs_webinar_enabled")),
                std::pair(features::statuses_enabled, get_bool(it->value, "statuses_enabled")),
                std::pair(features::global_contact_search_allowed, get_bool(it->value, "global_contact_search_allowed")),
                std::pair(features::show_reactions, get_bool(it->value, "show_reactions")),
                std::pair(features::open_icqcom_link, get_bool(it->value, "open_icqcom_link")),
                std::pair(features::statistics, get_bool(it->value, "statistics")),
                std::pair(features::statistics_mytracker, get_bool(it->value, "statistics_mytracker")),
                std::pair(features::force_update_check_allowed, get_bool(it->value, "force_update_check_allowed")),
                std::pair(features::call_room_info_enabled, get_bool(it->value, "call_room_info_enabled")),
                std::pair(features::external_config_use_preset_url, get_bool(it->value, "external_config_use_preset_url")),
                std::pair(features::store_version, get_bool(it->value, "store_version")),
                std::pair(features::otp_login_open_mail_link, get_bool(it->value, "otp_login_open_mail_link")),
                std::pair(features::dns_workaround, get_bool(it->value, "dns_workaround_enabled")),
                std::pair(features::external_emoji, get_bool(it->value, "external_emoji")),
                std::pair(features::show_your_invites_to_group_enabled, get_bool(it->value, "show_your_invites_to_group_enabled")),
                std::pair(features::group_invite_blacklist_enabled, get_bool(it->value, "group_invite_blacklist_enabled")),
                std::pair(features::contact_us_via_backend, get_bool(it->value, "contact_us_via_backend")),
                std::pair(features::update_from_backend, get_bool(it->value, "update_from_backend")),
                std::pair(features::invite_by_sms, get_bool(it->value, "invite_by_sms")),
                std::pair(features::show_sms_notify_setting, get_bool(it->value, "show_sms_notify_setting")),
                std::pair(features::silent_message_delete, get_bool(it->value, "silent_message_delete")),
                std::pair(features::remove_deleted_from_notifications, get_bool(it->value, "remove_deleted_from_notifications")),
                std::pair(features::long_path_tooltip_enabled, get_bool(it->value, "long_path_tooltip_enabled")),
                std::pair(features::installer_crash_send, get_bool(it->value, "installer_crash_send")),
                std::pair(features::custom_statuses_enabled, get_bool(it->value, "custom_statuses_enabled")),
                std::pair(features::formatting_in_bubbles, get_bool(it->value, "formatting_in_bubbles")),
                std::pair(features::formatting_in_input, get_bool(it->value, "formatting_in_input")),
                std::pair(features::apps_bar_enabled, get_bool(it->value, "apps_bar_enabled")),
                std::pair(features::status_in_apps_bar, get_bool(it->value, "status_in_apps_bar")),
                std::pair(features::scheduled_messages_enabled, get_bool(it->value, "scheduled_messages_enabled")),
                std::pair(features::threads_enabled, get_bool(it->value, "threads_enabled")),
                std::pair(features::reminders_enabled, get_bool(it->value, "reminders_enabled")),
                std::pair(features::support_shared_federation_stickerpacks, get_bool(it->value, "support_shared_federation_stickerpacks")),
                std::pair(features::url_ftp_protocols_allowed, get_bool(it->value, "url_ftp_protocols_allowed")),
                std::pair(features::organization_structure_enabled, get_bool(it->value, "organization_structure_enabled")),
                std::pair(features::tasks_enabled, get_bool(it->value, "tasks_enabled")),
                std::pair(features::draft_enabled, get_bool(it->value, "draft_enabled")),
                std::pair(features::message_corner_menu, get_bool(it->value, "message_corner_menu")),
                std::pair(features::task_creation_in_chat_enabled, get_bool(it->value, "task_creation_in_chat_enabled")),
                std::pair(features::smartreply_suggests_feature_enabled, get_bool(it->value, "smartreply_suggests_feature_enabled")),
                std::pair(features::smartreply_suggests_text, get_bool(it->value, "smartreply_suggests_text")),
                std::pair(features::smartreply_suggests_stickers, get_bool(it->value, "smartreply_suggests_stickers")),
                std::pair(features::smartreply_suggests_for_quotes, get_bool(it->value, "smartreply_suggests_for_quotes")),
                std::pair(features::compact_mode_by_default, get_bool(it->value, "compact_mode_by_default")),
                std::pair(features::expanded_gallery, get_bool(it->value, "expanded_gallery")),
                std::pair(features::restricted_files_enabled, get_bool(it->value, "restricted_files_enabled")),
                std::pair(features::antivirus_check_enabled, get_bool(it->value, "antivirus_check_enabled")),
                std::pair(features::antivirus_check_progress_visible, get_bool(it->value, "antivirus_check_progress_visible")),
                std::pair(features::calendar_enabled, get_bool(it->value, "calendar_enabled")),
            };

            if (std::is_sorted(std::cbegin(res), std::cend(res), is_less_by_first))
                return std::make_optional(std::move(res));
            assert(false);
        }
        return {};
    }

    static std::optional<values_array> parse_values(const rapidjson::Value& _node)
    {
        if (const auto it = _node.FindMember("values"); it != _node.MemberEnd())
        {
            values_array res =
            {
                std::pair(values::product_path, get_string(it->value, "product_path")),
                std::pair(values::product_path_mac, get_string(it->value, "product_path_mac")),
                std::pair(values::app_name_win, get_string(it->value, "app_name_win")),
                std::pair(values::app_name_mac, get_string(it->value, "app_name_mac")),
                std::pair(values::app_name_linux, get_string(it->value, "app_name_linux")),
                std::pair(values::user_agent_app_name, get_string(it->value, "user_agent_app_name")),
                std::pair(values::client_b64, get_string(it->value, "client_b64")),
                std::pair(values::client_id, get_string(it->value, "client_id")),
                std::pair(values::client_rapi, get_string(it->value, "client_rapi")),
                std::pair(values::product_name, get_string(it->value, "product_name")),
                std::pair(values::product_name_short, get_string(it->value, "product_name_short")),
                std::pair(values::product_name_full, get_string(it->value, "product_name_full")),
                std::pair(values::main_instance_mutex_linux, get_string(it->value, "main_instance_mutex_linux")),
                std::pair(values::main_instance_mutex_win, get_string(it->value, "main_instance_mutex_win")),
                std::pair(values::crossprocess_pipe, get_string(it->value, "crossprocess_pipe")),
                std::pair(values::register_url_scheme_csv, get_string(it->value, "register_url_scheme_csv")),
                std::pair(values::installer_shortcut_win, get_string(it->value, "installer_shortcut_win")),
                std::pair(values::installer_menu_folder_win, get_string(it->value, "installer_menu_folder_win")),
                std::pair(values::installer_product_exe_win, get_string(it->value, "installer_product_exe_win")),
                std::pair(values::installer_exe_win, get_string(it->value, "installer_exe_win")),
                std::pair(values::installer_hkey_class_win, get_string(it->value, "installer_hkey_class_win")),
                std::pair(values::installer_main_instance_mutex_win, get_string(it->value, "installer_main_instance_mutex_win")),
                std::pair(values::company_name, get_string(it->value, "company_name")),
                std::pair(values::app_user_model_win, get_string(it->value, "app_user_model_win")),
                std::pair(values::feedback_version_id, get_string(it->value, "feedback_version_id")),
                std::pair(values::feedback_platform_id, get_string(it->value, "feedback_platform_id")),
                std::pair(values::feedback_aimid_id, get_string(it->value, "feedback_aimid_id")),
                std::pair(values::feedback_selected_id, get_string(it->value, "feedback_selected_id")),
                std::pair(values::omicron_dev_id_win, get_string(it->value, "omicron_dev_id_win")),
                std::pair(values::omicron_dev_id_mac, get_string(it->value, "omicron_dev_id_mac")),
                std::pair(values::omicron_dev_id_linux, get_string(it->value, "omicron_dev_id_linux")),
                std::pair(values::dev_id_win, get_string(it->value, "dev_id_win")),
                std::pair(values::dev_id_mac, get_string(it->value, "dev_id_mac")),
                std::pair(values::dev_id_linux, get_string(it->value, "dev_id_linux")),
                std::pair(values::additional_fs_parser_urls_csv, get_string(it->value, "additional_fs_parser_urls_csv")),
                std::pair(values::uins_for_send_log_csv, get_string(it->value, "uins_for_send_log_csv")),
                std::pair(values::zstd_compression_level, get_int64(it->value, "zstd_compression_level")),
                std::pair(values::server_search_messages_min_symbols, get_int64(it->value, "server_search_messages_min_symbols")),
                std::pair(values::server_search_contacts_min_symbols, get_int64(it->value, "server_search_contacts_min_symbols")),
                std::pair(values::voip_call_user_limit, get_int64(it->value, "voip_call_user_limit")),
                std::pair(values::voip_video_user_limit, get_int64(it->value, "voip_video_user_limit")),
                std::pair(values::voip_big_conference_boundary, get_int64(it->value, "voip_big_conference_boundary")),
                std::pair(values::external_config_preset_url, get_string(it->value, "external_config_preset_url")),
                std::pair(values::server_api_version, get_int64(it->value, "server_api_version")),
                std::pair(values::server_mention_timeout, get_int64(it->value, "server_mention_timeout")),
                std::pair(values::support_uin, get_string(it->value, "support_uin")),
                std::pair(values::mytracker_app_id_win, get_string(it->value, "mytracker_app_id_win")),
                std::pair(values::mytracker_app_id_mac, get_string(it->value, "mytracker_app_id_mac")),
                std::pair(values::mytracker_app_id_linux, get_string(it->value, "mytracker_app_id_linux")),
                std::pair(values::status_banner_emoji_csv, get_string(it->value, "status_banner_emoji_csv")),
                std::pair(values::draft_timeout_sec, get_int64(it->value, "draft_timeout")),
                std::pair(values::draft_max_len, get_int64(it->value, "draft_max_len")),
                std::pair(values::smartreply_suggests_click_hide_timeout, get_int64(it->value, "smartreply_suggests_click_hide_timeout")),
                std::pair(values::smartreply_suggests_msgid_cache_size, get_int64(it->value, "smartreply_suggests_msgid_cache_size")),
                std::pair(values::base_retry_interval_sec, get_int64(it->value, "base_retry_interval_sec")),
            };

            if (std::is_sorted(std::cbegin(res), std::cend(res), is_less_by_first))
                return std::make_optional(std::move(res));
            assert(false);
        }
        return {};
    }

    configuration::configuration(std::string_view json, bool _is_debug)
        : is_debug_(_is_debug)
    {
        spin_lock_ = std::make_unique<common::tools::spin_lock>();
        if (rapidjson::Document doc; !doc.Parse(json.data(), json.size()).HasParseError())
        {
            auto urls = parse_urls(doc);
            if (!urls)
                return;
            c_.urls = std::move(*urls);

            auto values = parse_values(doc);
            if (!values)
                return;
            c_.values = std::move(*values);

            auto features = parse_features(doc);
            if (!features)
                return;
            c_.features = std::move(*features);

            auto translations = parse_translations(doc);
            if (!translations)
                return;
            c_.translations = std::move(*translations);

            is_valid_ = true;

            if (is_on(config::features::external_url_config))
                e_ = std::make_shared<external_configuration>();
        }
    }

    configuration::configuration() = default;

    bool configuration::is_external_config_enabled() const noexcept
    {
        return c_.features[static_cast<size_t>(config::features::external_url_config)].second;
    }

    std::shared_ptr<external_configuration> configuration::get_external() const
    {
        std::scoped_lock lock(*spin_lock_);
        return e_;
    }

    void configuration::set_external(std::shared_ptr<external_configuration> _e)
    {
        std::scoped_lock lock(*spin_lock_);
        e_ = std::move(_e);
    }

    configuration::~configuration() = default;

    bool configuration::is_valid() const noexcept
    {
        return is_valid_;
    }

    const value_type& configuration::value(values _v) const noexcept
    {
        if (is_external_config_enabled())
        {
            if (const auto external = get_external(); external)
            {
                const auto& values = external->values;
                const auto it = std::find_if(values.begin(), values.end(), [_v](auto x) { return x.first == _v; });
                if (it != values.end())
                    return it->second;
            }
        }

        return c_.values[static_cast<size_t>(_v)].second;
    }

    std::string_view configuration::string(values _v) const noexcept
    {
        if (const auto& v = value(_v); auto ptr = std::get_if<std::string>(&v))
            return std::string_view(*ptr);

        return {};
    }

    std::string_view configuration::url(urls _v) const noexcept
    {
        return c_.urls[static_cast<size_t>(_v)].second;
    }

    std::string_view configuration::translation(translations _v) const noexcept
    {
        return c_.translations[static_cast<size_t>(_v)].second;
    }

    bool configuration::is_on(features _v) const noexcept
    {
        auto default_value = c_.features[static_cast<size_t>(_v)].second;
        if (!is_external_config_enabled() || config::features::external_url_config == _v)
            return default_value;

        if (const auto external = get_external(); external)
        {
            const auto& features = external->features;
            const auto it = std::find_if(features.begin(), features.end(), [_v](auto x) { return x.first == _v; });
            if (it != features.end())
                return it->second;
        }

        return default_value;
    }

    bool configuration::is_debug() const noexcept
    {
        return is_debug_;
    }

    bool configuration::is_overridden(features _v) const noexcept
    {
        if (!is_external_config_enabled() || config::features::external_url_config == _v)
            return false;

        if (const auto external = get_external(); external)
        {
            const auto& features = external->features;
            return std::any_of(features.begin(), features.end(), [_v](auto x) { return x.first == _v; });
        }

        return false;
    }

    bool configuration::is_overridden(values _v) const noexcept
    {
        if (!is_external_config_enabled())
            return false;

        if (const auto external = get_external(); external)
        {
            const auto& values = external->values;
            return std::any_of(values.begin(), values.end(), [_v](auto x) { return x.first == _v; });
        }
        return false;
    }

    static configuration make_config()
    {
        auto local_config = configuration(config_json(), false);

#ifdef SUPPORT_EXTERNAL_CONFIG
        if (!environment::is_release())
        {
            if (const auto v = local_config.value(platform::is_apple() ? values::product_path_mac : values::product_path); const auto path = std::get_if<std::string>(&v))
            {
                const auto debug_config_path = core::utils::get_product_data_path(core::tools::from_utf8(*path));

                boost::system::error_code error_code;
                const auto extrenal_config_file_name = boost::filesystem::canonical(debug_config_path, Out error_code) / L"config.json";

                if (boost::system::errc::success == error_code)
                {
                    if (core::tools::binary_stream bstream; bstream.load_from_file(extrenal_config_file_name.wstring()))
                    {
                        const auto size = bstream.available();
                        if (auto extrernal_config = configuration(std::string_view(bstream.read(size), size_t(size)), true); extrernal_config.is_valid())
                            return extrernal_config;
                    }
                }
            }
        }
#endif // SUPPORT_EXTERNAL_CONFIG

        return local_config;
    }
}

static config::configuration& get_impl()
{
    static auto c = config::make_config();
    return c;
}

const config::configuration& config::get()
{
    return get_impl();
}

bool config::is_overridden(features _v)
{
    return config::get().is_overridden(_v);
}

bool config::is_overridden(values _v)
{
    return config::get().is_overridden(_v);
}

void config::reset_external()
{
    set_external({});
}

void config::set_external(std::shared_ptr<external_configuration> _f)
{
    get_impl().set_external(std::move(_f));
}

max_stars_repo_name: mail-ru-im/im-desktop

max_issues_repo_name: mail-ru-im/im-desktop

max_forks_repo_name: mail-ru-im/im-desktop


text:
/*=======================================================================
Ratel is a application framework, which provides some convenient librarys
for for those c++ developers pursuing fast-developement.
Copyright (c) scofieldzhu. All rights reserved.

Project: ratel.kernel
Module: xsignal.hxx
CreateTime: 2019-7-7 21:11
=======================================================================*/
#ifndef __xsignal_hxx__
#define __xsignal_hxx__

#include "kernelpublic.h"
#include <boost/signals2.hpp>

RATEL_NAMESPACE_BEGIN

typedef boost::signals2::connection SignalCon;

template <typename EvtCls>
struct XSignal
{
    typedef EvtCls MyEvtCls;
    typedef XSignal<EvtCls> Self;
    typedef boost::signals2::signal<void(const EvtCls&)> BSig2Type;
    typedef typename BSig2Type::slot_type SigSlot;
    static Self& Inst()
    {
        static Self s;
        return s;
    }
    enum PosType
    {
        kBack,
        kFront,
    };
    SignalCon connect(const SigSlot& subscriber, PosType postype = kBack)
    {
        return sigsource_.connect(subscriber, (boost::signals2::connect_position)postype);
    }
    SignalCon connect(const SigSlot& subscriber, int group, PosType postype = kBack)
    {
        return sigsource_.connect(group, subscriber, (boost::signals2::connect_position)postype);
    }
    void trigger(const EvtCls& event)
    {
        sigsource_(event);
    }
    void disconnectAll()
    {
        sigsource_.disconnect_all_slots();
    }
    bool empty()const
    {
        return sigsource_.empty();
    }
private:
    BSig2Type sigsource_;
};

RATEL_NAMESPACE_END

#endif

ext: hxx

max_stars_repo_name: scofieldzhu/jigsawpuzzle

max_issues_repo_name: scofieldzhu/jigsawpuzzle

max_forks_repo_name: scofieldzhu/jigsawpuzzle


text:
#ifndef CALENDAR_HPP_
#define CALENDAR_HPP_
//============================================================================
// Name        :
// Author      : Avi
// Revision    : $Revision: #48 $
//
// Copyright 2009- ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//
// Description : The calendar object is initialised when the suite begins.
//               The calendar encapsulates date and time. The date is derived from the time.
//
// After each update the calendar will store the time_duration between the init() function
// call and the update() function call.
// The calendar is to be used for all reference to time and date
// This will stop different time functionality from getting out of step.
//
// Examples of Use of calendar are:
//    o Generated time variables
//    o Time dependent attributes: TimeAttr,TodaySeries,CronAttr,DateAttr,DayAttr
//      ****************************************************************************
//      ** A time attribute can have a +, which means time relative to suite start
//      ** This is stored on the TimeSeries, as it isNode/Attribute specific.
//      ** i.e repeated families will have its own relative start time.
//      *****************************************************************************
//
// DESIGN CONSIDERATIONS:
//   Real and Hybrid:
//   Real
//      calendar is like a normal calendar where time and date are related
//      and day/date changes at midnight.
//   Hybrid:
//      There is currently confusion about how this is supposed to work.
//      The date is not supposed to change. (According to John date updates at suite restart?)
//      This has important implications, i.e does the day change ?
//      If the day does not change, then many of suites will never complete.
//      	i.e if we use repeat, with a single time series,  "time 10:00"
//      *** This relies on a day change to reset time attribute at midnight. ****
//   Conclusion: Will support day change for both REAL and HYBRID (date does not change)
//
// Calendar Updates:
// 	 How and when should we update the calendar?
//   In both the approaches below we need to make a distinction/separation
//   between the server poll and calendar update. This is required for testing
//
//	o Poll/Job submission interval in server is used to update calendar .
//     +: No time slots will be missed. even if server is suspended/restarted.
//        since suspending the server, also suspends the calendar updates
//     +: Suite relative times will continue to work even after server stopped/started
//     +: Avoids additional system call.
//     +: Lead's to more deterministic behaviour
//     -: If server is suspended and restarted the calendar will NOT be in
//        phase with system clock. (Its not clear to me why this should be an issue?)
//     ?: If the server is run for several days is there a possibility for the poll
//        update to get out of skew with real time. This is only possible if
//        job dependencies take more the 60 seconds to resolve.
//      *** THIS FUNCTIONALITY NEEDS TO BE ADVERTISED, SO THAT USERS ARE AWARE OF IT
//      *** THIS FUNCTIONALITY IS AVAILABLE VIA -s flag on the clock attribute .i.e
//      *** the -s stand's for stop start clock in line with the server
// 	        clock real 20.1.2007 +01:00 -s
// 			clock hybrid -s
//
//	o Poll/Job submission interval in server is used Initiate an update of calendar via a system call.
//     +: calendar is always in phase with system clock.
//        Many task job dependencies depend on ordering based on real time.
//     -: Requires additional system call for each poll in the server
//     -: Time slots can be missed. (i.e if server suspended/restarted).
//        There is no catch up. (?? See TimeDependencies.ddoc)
//     -: Relative times will not be adhered too, when server stopped/started.
//     -: Will require more manual intervention ?
//
//  Conclusion:: The clock attribute will be changed to add both capabilities
//
//  Resolution: Will support 1 minute resolution:
//============================================================================

#include <boost/date_time/posix_time/posix_time.hpp>
namespace cereal { class access; }

namespace ecf {

class CalendarUpdateParams; // forward declare

class Calendar  {
public:
	enum Clock_t {
		REAL,       // like a normal clock
		HYBRID      // date does not change, but will support day change. See Above.
	};

	/// Defaults to the REAL clock
	Calendar();
	Calendar(const Calendar&);
	Calendar& operator=( const Calendar&);
	bool operator==( const Calendar&) const;

	/// Initialise the Calendar.
  	void init(Clock_t clock);

   // for test init and begin calendar
   void init(const boost::posix_time::ptime& time, Clock_t clock = Calendar::REAL);

   /// Start the Calendar.  Parameter time can include gain.
   void begin(const boost::posix_time::ptime&);

	/// Update the calendar using the input. Will Store internally the time duration
	/// between the init() function call and the last update.
 	/// The for_test parameter is *ONLY* used if we are using real time calendar
  	void update(const ecf::CalendarUpdateParams &);

  	/// This is used to improve resolution of state change time. ECFLOW-1512
   void update_duration_only(boost::posix_time::ptime& time_now);

  	// Used for test only, will call the function above
  	void update(const boost::posix_time::time_duration&);
  	void update(const boost::posix_time::ptime& time_now);

	// The following were added as a performance optimisation
   // Represent a day within a week (range 0==Sun to 6==Sat)
	int day_of_week() const;  // same as suiteTime().date().day_of_week().as_number()
	int day_of_year() const;  // same as suiteTime().date().day_of_year()
	int day_of_month() const; // same as suiteTime().date().day()
	int month() const;        // same as suiteTime().date().month()
	int year() const;         // same as suiteTime().date().year()

	/// returns true if the day changed, this will update for REAL and HYBRID .
  	bool dayChanged() const { return dayChanged_;}

  	/// returns the last calendar increment
	const boost::posix_time::time_duration& calendarIncrement() const { return increment_;}

 	/// return the init() time + the accumulated duration from calls to update(...)
  	/// This should only be used when this calendar is real.
 	const boost::posix_time::ptime& suiteTime() const { return suiteTime_;}
	std::string suite_time_str() const;

 	// duration since last call to init, essentially suite duration
	const boost::posix_time::time_duration& duration() const { return duration_;}

	/// return real time, when the calendar was begun/initialised.
	/// This is used to update the duration_, which is recorded for each state change in the node
	/// Hence to when we can compute when a state change occurred by using:
	///   boost::posix_time::ptime time_of_state_change = begin_time() + node->get_state().second(duration)
   const boost::posix_time::ptime& begin_time() const { return initLocalTime_;}

 	/// return the date, for real calendar this corresponds to the date on suiteTime_
 	/// for hybrid,  the date does not change, and hence we return date for initTime_
	boost::gregorian::date date() const;

 	/// The calendar type. For hybrid clocks the date does not update.
	bool hybrid() const { return (ctype_ == Calendar::HYBRID) ?  true : false; }

	/// for debug,  must link with boost date and time library
	void dump(const std::string& title) const;

	/// for debug,  must link with boost date and time library
	std::string toString() const;

	void write_state(std::string&) const;
   void read_state(const std::string& line,const std::vector<std::string>& lineTokens);

	bool checkInvariants(std::string& errorMsg) const;

	// allow Suite memento to update calendar type
	void set_clock_type( Clock_t  ct) { ctype_ = ct;}

	/// Will return either second_clock::universal_time()/UTC ( the other alternative is second_clock::local_time() )
	/// This is because boost deadline timer is based on UTC clock
	/// >>> The deadline_timer typedef is based on a UTC clock, and all operations (expires_at, expires_from_now) work in UTC time.
	/// >>> If you want it to use a different clock (such as the local time clock), you can use basic_deadline_timer<> with your own traits class.
	/// >>> Please see the "Timers" example.
	/// Taken from boost date/time doc
  	/// If you want exact agreement with wall-clock time, you must use either UTC or local time. If you compute a duration
	//	by subtracting one UTC time from another and you want an answer accurate to the second, the two times must not be
	//	too far in the future because leap seconds affect the count but are only determined about 6 months in advance. With
	//	local times a future duration calculation could be off by an entire hour, since legislatures can and do change DST
	//	rules at will.
	//	If you want to handle wall-clock times in the future, you won't be able (in the general case) to calculate exact durations,
	//	for the same reasons described above.
	//	If you want accurate calculations with future times, you will have to use TAI or an equivalent, but the mapping from
	//	TAI to UTC or local time depends on leap seconds, so you will not have exact agreement with wall-clock time.
	static boost::posix_time::ptime second_clock_time();

	bool is_special() const { return initTime_.is_special(); }
private:
	void assign( const Calendar& rhs);

 	boost::posix_time::ptime         initTime_;   // When calendar was started, suite time(could be in the past OR real time)
 	boost::posix_time::ptime         suiteTime_;  // The suite time for hybrid DATE does not change.
  	boost::posix_time::ptime         initLocalTime_;        // Real Time: When calendar was started, used to work out duration_
 	boost::posix_time::ptime         lastTime_;             // Real Time: Used to calculate calendarIncrement
	boost::posix_time::time_duration duration_;   // duration since last call to init/begin, used on Node for late and autocancel
	boost::posix_time::time_duration increment_{0,1,0,0};

private:
   void update_cache() const;
   mutable int day_of_week_{-1};  // Cache
   mutable int day_of_year_{-1};  // Cache
   mutable int day_of_month_{-1}; // Cache
   mutable int month_{-1};        // Cache
   mutable int year_{-1};         // Cache

   Clock_t                          ctype_{Calendar::REAL};// *NOT* persisted: can be derived from suite clock attribute
   bool                             dayChanged_{false};

private:
	// Note: The *only* reason to serialise the calendar is so that we can support
	// why() command on the client side. By default calendar is initialised in the *server*
	// at begin time, from the clock attribute
   friend class cereal::access;
	template<class Archive>
	void serialize(Archive & ar, std::uint32_t const /*version*/);
};
}

#endif

max_stars_repo_name: mpartio/ecflow

max_issues_repo_name: mpartio/ecflow

max_forks_repo_name: mpartio/ecflow


text:
#ifndef BOOST_MPL_TAG_HPP_INCLUDED
#define BOOST_MPL_TAG_HPP_INCLUDED

// Copyright Aleksey Gurtovoy 2004
//
// 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)
//
// See http://www.boost.org/libs/mpl for documentation.

// $Id$
// $Date$
// $Revision$

#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/void.hpp>
#include <boost/mpl/aux_/has_tag.hpp>
#include <boost/mpl/aux_/config/eti.hpp>

namespace bx { namespace mpl {

namespace aux {
template< typename T > struct tag_impl
{
    typedef typename T::tag type;
};
}

template< typename T, typename Default = void_ > struct tag
#if !defined(BOOST_MPL_CFG_MSVC_ETI_BUG)
    : if_<
          aux::has_tag<T>
        , aux::tag_impl<T>
        , Default
        >::type
{
#else
{
    typedef typename eval_if<
          aux::has_tag<T>
        , aux::tag_impl<T>
        , Default
        >::type type;

#endif
};

}}

#endif // BOOST_MPL_TAG_HPP_INCLUDED


text:
#pragma once
#include <Eigen/Sparse>

#include "mtao/eigen/type_info.hpp"

namespace mtao::eigen {
template <typename Derived>
auto mat_to_triplets(const Derived& V, typename Derived::Scalar thresh) {
    using Scalar = typename Derived::Scalar;
    std::vector<Eigen::Triplet<Scalar>> ret;

    ret.reserve(V.nonZeros());
    if constexpr (is_sparse(V)) {
        for (int k = 0; k < V.outerSize(); ++k) {
            for (typename Derived::InnerIterator it(V, k); it; ++it) {
                if (std::abs(it.value()) >= thresh) {
                    ret.emplace_back(it.row(), it.col(), it.value());
                }
            }
        }
    } else {
        constexpr bool RM = is_row_major(V);
        const int iCount = RM ? V.rows() : V.cols();
        const int jCount = RM ? V.cols() : V.rows();
        for (int i = 0; i < iCount; ++i) {
            for (int j = 0; j < jCount; ++j) {
                auto&& value = RM ? V(i, j) : V(j, i);
                if (std::abs(value) > thresh) {
                    if constexpr (RM) {
                        ret.emplace_back(i, j, value);
                    } else {
                        ret.emplace_back(j, i, value);
                    }
                }
            }
        }
    }
    return ret;
}
template <typename Derived>
auto mat_to_triplets(const Derived& V) {
    using Scalar = typename Derived::Scalar;
    std::vector<Eigen::Triplet<Scalar>> ret;

    ret.reserve(V.nonZeros());
    if constexpr (is_sparse(V)) {
        for (int k = 0; k < V.outerSize(); ++k) {
            for (typename Derived::InnerIterator it(V, k); it; ++it) {
                ret.emplace_back(it.row(), it.col(), it.value());
            }
        }
    } else {
        constexpr bool RM = is_row_major(V);
        const int iCount = RM ? V.rows() : V.cols();
        const int jCount = RM ? V.cols() : V.rows();
        for (int i = 0; i < iCount; ++i) {
            for (int j = 0; j < jCount; ++j) {
                auto&& value = RM ? V(i, j) : V(j, i);
                if (value != 0) {
                    if constexpr (RM) {
                        ret.emplace_back(i, j, value);
                    } else {
                        ret.emplace_back(j, i, value);
                    }
                }
            }
        }
    }
    return ret;
}
}  // namespace mtao::eigen

max_stars_repo_name: mtao/core

max_issues_repo_name: mtao/core

max_forks_repo_name: mtao/core


text: #include <boost/msm/mpl_graph/depth_first_search.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino