text:
#pragma once

#include <array>
#include <tuple>
#include <mtao/geometry/cyclic_order.hpp>
#include <map>
#include <set>
#include <vector>
#include <spdlog/spdlog.h>
#include <mtao/data_structures/disjoint_set.hpp>
#include <mtao/geometry/mesh/triangle_fan.hpp>
#include <mtao/geometry/trigonometry.hpp>
#include "mandoline/cutface.hpp"
#include <mtao/logging/logger.hpp>
#include <mtao/logging/profiler.hpp>
#include <Eigen/Eigenvalues>

namespace mandoline::construction {
struct CellCollapser {
  public:
    using Edge = std::array<int, 2>;
    using HalfFace = std::tuple<int, Edge>;
    using coord_type = std::array<int, 3>;
    //CellCollapser(const mtao::map<int,std::set<std::vector<int>>>& faces);
    CellCollapser(const mtao::map<int, CutFace<3>> &faces);
    std::tuple<std::set<std::vector<int>>, std::set<Edge>> clean_unmanifold(const std::vector<int> &);
    // for each edge, list off all of the ordered halffaces that use it
    mtao::map<Edge, std::set<const HalfFace *>> collect_halffaces() const;

    int dual_cell(const HalfFace &hf) const;
    int cell(const HalfFace &hf) const;

    void fill_cell_boundaries();
    // merge_open_faces makes both sides of a triangle part of the same cell if it has an unshared edge
    template<typename Derived>
    void merge(const Eigen::MatrixBase<Derived> &V, bool merge_open_faces = true);
    template<typename Derived>
    void merge_around_edge(const Eigen::MatrixBase<Derived> &V, const Edge& e, const std::set<const HalfFace *>& halffaces);
    template<typename Derived>
    void bake(const Eigen::MatrixBase<Derived> &V);

    std::vector<std::set<int>> cell_faces() const;
    const auto &faces() const { return m_faces; }
    const auto &face(int idx) const { return m_faces.at(idx); }

    const auto &cell_boundaries() const { return m_cell_boundaries; }
    void remove_boundary_cells();
    void remove_grid_boundary_cells(const std::array<int, 3> &shape);
    void remove_boundary_cells_by_volume(const std::map<int, double> &face_vols);
    void remove_boundary_cells_from_vertices(const std::set<int> &boundary_vertices);
    void remove_boundary_cells_from_faces(const std::set<int> &boundary_faces);
    std::set<int> folded_faces() const;//faces that have their duals as well
    //private:
    // stores a halfface (edge + face index) and maps it to a cell (the sign maintains the chirality wrt the original face)
    mtao::map<HalfFace, std::tuple<int, bool>> m_halfface_to_cell;
    mtao::map<int, CutFace<3>> m_faces;
    std::map<int, std::set<Edge>> flap_edges;
    mtao::map<int, std::set<coord_type>> face_cell_possibilities;
    std::vector<mtao::map<int, bool>> m_cell_boundaries;
    std::set<Edge> invalid_edges;
    mtao::data_structures::DisjointSet<int> cell_ds;

};

template<typename Derived>
void CellCollapser::bake(const Eigen::MatrixBase<Derived> &V) {
    merge(V);
}

template<typename Derived>
void CellCollapser::merge_around_edge(const Eigen::MatrixBase<Derived> &V, const Edge& e, const std::set<const HalfFace *>& halffaces) {
    //auto t3 = mtao::logging::profiler("cell collapser edge fan processessing",false,"profiler");
    if (halffaces.empty()) {
        return;
    }
    auto [a, b] = e;
    auto va = V.col(a);
    auto vb = V.col(b);
    auto vba = va - vb;

    int maxcoeff;
    // if the edge is really small then we use eigen analysis of the face to compute a normal
    {
        if (vba.norm() < 1e-8) {
            mtao::Mat3d A = mtao::Mat3d::Zero();

            for (auto &&hfp : halffaces) {
                auto [fidx, e] = *hfp;

                bool sign = std::get<1>(m_halfface_to_cell.at(*hfp));
                if (sign) {
                    auto &&F = m_faces.at(fidx);
                    auto &&N = F.N;
                    A += N * N.transpose();
                }
            }
            Eigen::SelfAdjointEigenSolver<mtao::Mat3d> eigensolver(A);
            if (eigensolver.info() != Eigen::Success) {
                vba.cwiseAbs().maxCoeff(&maxcoeff);
            } else {
                eigensolver.eigenvectors().col(0).cwiseAbs().maxCoeff(&maxcoeff);
            }
        } else {
            vba.cwiseAbs().maxCoeff(&maxcoeff);
        }
    }
    const bool flip_axes = vba(maxcoeff) < 0;

    std::vector<int> faces(halffaces.size());
    mtao::ColVecs2d A(2,halffaces.size());

    for (auto && [idx,fidx,hfp] : mtao::iterator::enumerate(faces,halffaces)) {
        auto [fidx_, e] = *hfp;

        fidx = fidx_;

        auto &&F = m_faces.at(fidx);
        const bool sign = std::get<1>(m_halfface_to_cell.at(*hfp));
        mtao::Vec3d N = (sign ? 1 : -1) * F.N.normalized();

        auto a = A.col(idx);
        if(flip_axes) {
            a(0) = N((maxcoeff+1)%3);
            a(1) = N((maxcoeff+2)%3);
        } else {
            a(1) = N((maxcoeff+1)%3);
            a(0) = N((maxcoeff+2)%3);
        }

    }
    auto order = mtao::geometry::cyclic_order(A);
    std::vector<int> ordered_faces(halffaces.size());
    // dereference the indices of indices
    std::transform(order.begin(), order.end(), ordered_faces.begin(), [&](int idx) { return faces[idx]; });
    auto it = ordered_faces.begin();
    auto it1 = it;
    it1++;
    for (; it != ordered_faces.end(); ++it, ++it1) {
        if (it1 == ordered_faces.end()) {
            it1 = ordered_faces.begin();
        }
        int idx = cell({*it,e});
        int idx1 = dual_cell({*it1,e});
        cell_ds.join(idx,idx1);
    }
}
template<typename Derived>
void CellCollapser::merge(const Eigen::MatrixBase<Derived> &V, bool merge_open_faces) {
    auto t2 = mtao::logging::profiler("cell collapser merge", false, "profiler");
    auto&& hfs = collect_halffaces();
    for (auto [e, halffaces] : hfs) {
        if (e[0] < e[1]) { // only need to process each edge once
            if(merge_open_faces || halffaces.size() > 1) {
                merge_around_edge(V,e,halffaces);
            }
        }
    }
    fill_cell_boundaries();
}
}// namespace mandoline::construction

ext: hpp

max_stars_repo_name: mtao/mandoline

max_issues_repo_name: mtao/mandoline

max_forks_repo_name: mtao/mandoline


text:
#include <string>
#include <unordered_map>
#include <Eigen/Dense>
#include <cmath>
#include "../include/optimizer.h"

namespace MyDL
{

    // ------------------------------------------------------------
    //                  SGD
    // ------------------------------------------------------------
    SGD::SGD(double learning_rate): _learning_rate(learning_rate)
    {
    }

    void SGD::update(unordered_map<string, MatrixXd>& params, unordered_map<string, MatrixXd>& grads)
    {
        for (auto grad : grads)
        {
            params[grad.first] -= _learning_rate * grad.second;
        }
    }

    void SGD::update(unordered_map<string, shared_ptr<MatrixXd>> & params, unordered_map<string, MatrixXd> &grads)
    {
        for (auto grad : grads)
        {
            *(params[grad.first]) -= _learning_rate * grad.second;
        }
    }

    // ------------------------------------------------------------
    //                  Momentum
    // ------------------------------------------------------------
    Momentum::Momentum(double learning_rate, double momentum) : _learning_rate(learning_rate), _momentum(momentum)
    {
    }

    void Momentum::update(unordered_map<string, MatrixXd>& params, unordered_map<string, MatrixXd>& grads)
    {
        if (_v.empty())
        {
            for (auto param : params)
            {
                _v[param.first] = MatrixXd::Zero(param.second.rows(), param.second.cols());
            }
        }

        for (auto param : params)
        {
            string key = param.first;
            _v[key] = _momentum * _v[key] - _learning_rate * grads[key];
            params[key] += _v[key];
        }
    }

    void Momentum::update(unordered_map<string, shared_ptr<MatrixXd>> &params, unordered_map<string, MatrixXd> &grads)
    {
        if (_v.empty())
        {
            for (auto param : params)
            {
                MatrixXd tmp_mat = *(param.second);
                _v[param.first] = MatrixXd::Zero(tmp_mat.rows(), tmp_mat.cols());
            }
        }

        for (auto param : params)
        {
            string key = param.first;
            _v[key] = _momentum * _v[key] - _learning_rate * grads[key];
            *(params[key]) += _v[key];
        }
    }

    // ------------------------------------------------------------
    //                  AdaGrad
    // ------------------------------------------------------------
    AdaGrad::AdaGrad(double learning_rate) : _learning_rate(learning_rate)
    {
    }

    void AdaGrad::update(unordered_map<string, MatrixXd> &params, unordered_map<string, MatrixXd> & grads)
    {
        if (_h.empty())
        {
            for (auto param : params)
            {
                _h[param.first] = MatrixXd::Zero(param.second.rows(), param.second.cols());
            }
        }

        for (auto param : params)
        {
            string key = param.first;
            // 勾配変化の大きかったパラメータの二乗平方根で割る → 要は勾配の絶対値が大きかったパラメータの更新幅を小さくするということ
            // ※ 厳密には勾配の絶対値で割っているわけではない(直前の内部状態に加算して平方根を取っている)
            _h[key].array() += grads[key].array() * grads[key].array();
            params[key].array() -= _learning_rate * _h[key].unaryExpr([](double p){return 1/(sqrt(p)+1e-7);}).array() * grads[key].array();
        }
    }

    void AdaGrad::update(unordered_map<string, shared_ptr<MatrixXd>> &params, unordered_map<string, MatrixXd> &grads)
    {
        if (_h.empty())
        {
            for (auto param : params)
            {
                MatrixXd tmp_mat = *(param.second);
                _h[param.first] = MatrixXd::Zero(tmp_mat.rows(), tmp_mat.cols());
            }
        }

        for (auto param : params)
        {
            string key = param.first;
            // 勾配変化の大きかったパラメータの二乗平方根で割る → 要は勾配の絶対値が大きかったパラメータの更新幅を小さくするということ
            // ※ 厳密には勾配の絶対値で割っているわけではない(直前の内部状態に加算して平方根を取っている)
            _h[key].array() += grads[key].array() * grads[key].array();
            params[key]->array() -= _learning_rate * _h[key].unaryExpr([](double p) { return 1 / (sqrt(p) + 1e-7); }).array() * grads[key].array();
        }
    }

    // ------------------------------------------------------------
    //                  RMSProp
    // ------------------------------------------------------------
    RMSprop::RMSprop(double learning_rate, double decay_rate): _learning_rate(learning_rate), _decay_rate(decay_rate)
    {
    }

    void RMSprop::update(unordered_map<string, MatrixXd>& params, unordered_map<string, MatrixXd>& grads)
    {
        if (_h.empty())
        {
            for (auto param : params)
            {
                _h[param.first] = MatrixXd::Zero(param.second.rows(), param.second.cols());
            }
        }

        for (auto param : params)
        {
            string key = param.first;
            // AdaGradの内部状態hを指数移動平均に置き換えたものがRMSprop -> 指数移動平均の減衰率(平滑化係数)がdecay_rate
            _h[key].array() *= _decay_rate;
            _h[key].array() += (1 - _decay_rate) * grads[key].array() * grads[key].array();
            params[key].array() -= _learning_rate * _h[key].unaryExpr([](double p) { return 1 / (sqrt(p) + 1e-7); }).array() * grads[key].array();
        }
    }

    void RMSprop::update(unordered_map<string, shared_ptr<MatrixXd>> &params, unordered_map<string, MatrixXd> &grads)
    {
        if (_h.empty())
        {
            for (auto param : params)
            {
                _h[param.first] = MatrixXd::Zero(param.second->rows(), param.second->cols());
            }
        }

        for (auto param : params)
        {
            string key = param.first;
            // AdaGradの内部状態hを指数移動平均に置き換えたものがRMSprop -> 指数移動平均の減衰率(平滑化係数)がdecay_rate
            _h[key].array() *= _decay_rate;
            _h[key].array() += (1 - _decay_rate) * grads[key].array() * grads[key].array();
            params[key]->array() -= _learning_rate * _h[key].unaryExpr([](double p) { return 1 / (sqrt(p) + 1e-7); }).array() * grads[key].array();
        }

    }

    // ------------------------------------------------------------
    //                  Adam
    // ------------------------------------------------------------
    Adam::Adam(double learning_rate, double beta1, double beta2): _learning_rate(learning_rate), _beta1(beta1), _beta2(beta2)
    {
        _iter = 0;
    }

    void Adam::update(unordered_map<string, MatrixXd>& params, unordered_map<string, MatrixXd>& grads)
    {
        if (_m.empty())
        {
            for (auto param : params)
            {
                _m[param.first] = MatrixXd::Zero(param.second.rows(), param.second.cols());
                _v[param.first] = MatrixXd::Zero(param.second.rows(), param.second.cols());
            }
        }

        _iter++;
        double lr_t = _learning_rate * sqrt(1.0 - std::pow(_beta2, _iter)) / (1.0 - std::pow(_beta1, _iter));

        for (auto param : params)
        {
            string key = param.first;
            _m[key] += (1 - _beta1) * (grads[key] - _m[key]);
            _v[key] += (1 - _beta2) * (grads[key].unaryExpr([](double p){return p*p;}) - _v[key]);

            params[key].array() -= lr_t * _m[key].array() * _v[key].unaryExpr([](double p){return 1 / (sqrt(p) + 1e-7);}).array();
        }
    }

    void Adam::update(unordered_map<string, shared_ptr<MatrixXd>>& params, unordered_map<string, MatrixXd>& grads)
    {
        if (_m.empty())
        {
            for (auto param : params)
            {
                _m[param.first] = MatrixXd::Zero(param.second->rows(), param.second->cols());
                _v[param.first] = MatrixXd::Zero(param.second->rows(), param.second->cols());
            }
        }

        _iter++;
        double lr_t = _learning_rate * sqrt(1.0 - std::pow(_beta2, _iter)) / (1.0 - std::pow(_beta1, _iter));

        for (auto param : params)
        {
            string key = param.first;
            _m[key] += (1 - _beta1) * (grads[key] - _m[key]);
            _v[key] += (1 - _beta2) * (grads[key].unaryExpr([](double p) { return p * p; }) - _v[key]);

            params[key]->array() -= lr_t * _m[key].array() * _v[key].unaryExpr([](double p) { return 1 / (sqrt(p) + 1e-7); }).array();
        }

    }

}

ext: cpp


text:
// restore.cpp

/**
*    Copyright (C) 2008 10gen Inc.
*
*    This program is free software: you can redistribute it and/or  modify
*    it under the terms of the GNU Affero General Public License, version 3,
*    as published by the Free Software Foundation.
*
*    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 Affero General Public License for more details.
*
*    You should have received a copy of the GNU Affero General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "../pch.h"
#include "../client/dbclient.h"
#include "../util/mmap.h"
#include "../util/text.h"
#include "tool.h"

#include <boost/program_options.hpp>

#include <fcntl.h>

using namespace mongo;

namespace po = boost::program_options;

class BSONDump : public BSONTool {

    enum OutputType { JSON , DEBUG } _type;

public:

    BSONDump() : BSONTool( "bsondump", NONE ){
        add_options()
            ("type" , po::value<string>()->default_value("json") , "type of output: json,debug" )
            ;
        add_hidden_options()
            ("file" , po::value<string>() , ".bson file" )
            ;
        addPositionArg( "file" , 1 );
        _noconnection = true;
    }

    virtual void printExtraHelp(ostream& out) {
        out << "usage: " << _name << " [options] <bson filename>" << endl;
    }

    virtual int doRun(){
        {
            string t = getParam( "type" );
            if ( t == "json" )
                _type = JSON;
            else if ( t == "debug" )
                _type = DEBUG;
            else {
                cerr << "bad type: " << t << endl;
                return 1;
            }
        }

        path root = getParam( "file" );
        if ( root == "" ) {
            printExtraHelp(cout);
            return 1;
        }

        processFile( root );
        return 0;
    }

    bool debug( const BSONObj& o , int depth=0){
        string prefix = "";
        for ( int i=0; i<depth; i++ ){
            prefix += "\t\t\t";
        }

        int read = 4;

        try {
            cout << prefix << "--- new object ---\n";
            cout << prefix << "\t size : " << o.objsize() << "\n";
            BSONObjIterator i(o);
            while ( i.more() ){
                BSONElement e = i.next();
                cout << prefix << "\t\t " << e.fieldName() << "\n" << prefix << "\t\t\t type:" << setw(3) << e.type() << " size: " << e.size() << endl;
                if ( ( read + e.size() ) > o.objsize() ){
                    cout << prefix << " SIZE DOES NOT WORK" << endl;
                    return false;
                }
                read += e.size();
                try {
                    e.validate();
                    if ( e.isABSONObj() ){
                        if ( ! debug( e.Obj() , depth + 1 ) )
                            return false;
                    }
                    else if ( e.type() == String && ! isValidUTF8( e.valuestr() ) ){
                        cout << prefix << "\t\t\t" << "bad utf8 String!" << endl;
                    }
                    else if ( logLevel > 0 ){
                        cout << prefix << "\t\t\t" << e << endl;
                    }

                }
                catch ( std::exception& e ){
                    cout << prefix << "\t\t\t bad value: " << e.what() << endl;
                }
            }
        }
        catch ( std::exception& e ){
            cout << prefix << "\t" << e.what() << endl;
        }
        return true;
    }

    virtual void gotObject( const BSONObj& o ){
        switch ( _type ){
        case JSON:
            cout << o.jsonString( TenGen ) << endl;
            break;
        case DEBUG:
            debug(o);
            break;
        default:
            cerr << "bad type? : " << _type << endl;
        }
    }
};

int main( int argc , char ** argv ) {
    BSONDump dump;
    return dump.main( argc , argv );
}

max_stars_repo_name: rauchg/mongo

max_issues_repo_name: kharayo/mongo

max_forks_repo_name: kharayo/mongo


text:
// (C) 2016 Marvin Sielenkemper

#pragma once

#include "Config.hpp"

#include <mysql.h>

#include <boost/noncopyable.hpp>

namespace db {
  class MySql : boost::noncopyable {
  public:
    MySql(Config const& config);
    ~MySql();

    operator MYSQL*() const;

  private:
    MYSQL* const m_mysqlPtr;
  };
}

max_stars_repo_name: sielenk/furnace

max_issues_repo_name: sielenk/furnace

max_forks_repo_name: sielenk/furnace


text:
/////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga  2006-2013
//
// 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/intrusive for documentation.
//
/////////////////////////////////////////////////////////////////////////////

#ifndef BOOST_CONFIG_HPP
#include <boost/config.hpp>
#endif

#ifdef BOOST_MSVC

   #pragma warning (push)
   #pragma warning (disable : 4275) // non DLL-interface classkey "identifier" used as base for DLL-interface classkey "identifier"
   #pragma warning (disable : 4251) // "identifier" : class "type" needs to have dll-interface to be used by clients of class "type2"
   #pragma warning (disable : 4675) // "method" should be declared "static" and have exactly one parameter
   #pragma warning (disable : 4996) // "function": was declared deprecated
   #pragma warning (disable : 4503) // "identifier" : decorated name length exceeded, name was truncated
   #pragma warning (disable : 4284) // odd return type for operator->
   #pragma warning (disable : 4244) // possible loss of data
   #pragma warning (disable : 4521) ////Disable "multiple copy constructors specified"
   #pragma warning (disable : 4127) //conditional expression is constant
   #pragma warning (disable : 4146) // unary minus operator applied to unsigned type, result still unsigned
   #pragma warning (disable : 4267) //conversion from 'X' to 'Y', possible loss of data
   #pragma warning (disable : 4541) //'typeid' used on polymorphic type 'lslboost::exception' with /GR-
   #pragma warning (disable : 4512) //'typeid' used on polymorphic type 'lslboost::exception' with /GR-
   #pragma warning (disable : 4522) // "class" : multiple assignment operators specified
   #pragma warning (disable : 4706) //assignment within conditional expression
   #pragma warning (disable : 4710) // function not inlined
   #pragma warning (disable : 4714) // "function": marked as __forceinline not inlined
   #pragma warning (disable : 4711) // function selected for automatic inline expansion
   #pragma warning (disable : 4786) // identifier truncated in debug info
   #pragma warning (disable : 4996) // "function": was declared deprecated
#endif

//#define BOOST_INTRUSIVE_USE_ITERATOR_FACADE
//#define BOOST_INTRUSIVE_USE_ITERATOR_ENABLE_IF_CONVERTIBLE

max_stars_repo_name: samuelpowell/liblsl

max_issues_repo_name: samuelpowell/liblsl

max_forks_repo_name: samuelpowell/liblsl


text:
// Copyright (C) 2013 Alain Miniussi <alain.miniussi@oca.eu>

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

// test threading::level operations

#include <boost/mpicxx/environment.hpp>
#include "check_test.hpp"
#include <iostream>
#include <sstream>

namespace mpi = boost::mpicxx;

void
test_threading_level_io(mpi::communicator const& comm,
                        mpi::threading::level orig) {
  std::ostringstream out;
  namespace mt = boost::mpicxx::threading;
  mt::level printed = mt::level(-1);

  out << orig;
  check_test(comm, out.good());
  std::string orig_str(out.str());
  std::cout << "orig string:" << orig_str << '\n';
  std::istringstream in(orig_str);
  in >> printed;
  check_test(comm, !in.bad());
  std::cout << "orig: " << orig << ", printed: " << printed << std::endl;
  check_test(comm, orig == printed);
}

void
test_threading_levels_io(mpi::communicator const& comm) {
  namespace mt = boost::mpicxx::threading;
  test_threading_level_io(comm, mt::single);
  test_threading_level_io(comm, mt::funneled);
  test_threading_level_io(comm, mt::serialized);
  test_threading_level_io(comm, mt::multiple);
}

void
test_threading_level_cmp(mpi::communicator const& comm) {
  namespace mt = boost::mpicxx::threading;
  check_test(comm, mt::single == mt::single);
  check_test(comm, mt::funneled == mt::funneled);
  check_test(comm, mt::serialized == mt::serialized);
  check_test(comm, mt::multiple == mt::multiple);

  check_test(comm, mt::single != mt::funneled);
  check_test(comm, mt::single != mt::serialized);
  check_test(comm, mt::single != mt::multiple);

  check_test(comm, mt::funneled != mt::single);
  check_test(comm, mt::funneled != mt::serialized);
  check_test(comm, mt::funneled != mt::multiple);

  check_test(comm, mt::serialized != mt::single);
  check_test(comm, mt::serialized != mt::funneled);
  check_test(comm, mt::serialized != mt::multiple);

  check_test(comm, mt::multiple != mt::single);
  check_test(comm, mt::multiple != mt::funneled);
  check_test(comm, mt::multiple != mt::serialized);

  check_test(comm, mt::single < mt::funneled);
  check_test(comm, mt::funneled > mt::single);
  check_test(comm, mt::single < mt::serialized);
  check_test(comm, mt::serialized > mt::single);
  check_test(comm, mt::single < mt::multiple);
  check_test(comm, mt::multiple > mt::single);

  check_test(comm, mt::funneled < mt::serialized);
  check_test(comm, mt::serialized > mt::funneled);
  check_test(comm, mt::funneled < mt::multiple);
  check_test(comm, mt::multiple > mt::funneled);

  check_test(comm, mt::serialized < mt::multiple);
  check_test(comm, mt::multiple > mt::serialized);

  check_test(comm, mt::single <= mt::single);
  check_test(comm, mt::single <= mt::funneled);
  check_test(comm, mt::funneled >= mt::single);
  check_test(comm, mt::single <= mt::serialized);
  check_test(comm, mt::serialized >= mt::single);
  check_test(comm, mt::single <= mt::multiple);
  check_test(comm, mt::multiple >= mt::single);

  check_test(comm, mt::funneled <= mt::funneled);
  check_test(comm, mt::funneled <= mt::serialized);
  check_test(comm, mt::serialized >= mt::funneled);
  check_test(comm, mt::funneled <= mt::multiple);
  check_test(comm, mt::multiple >= mt::funneled);

  check_test(comm, mt::serialized <= mt::serialized);
  check_test(comm, mt::serialized <= mt::multiple);
  check_test(comm, mt::multiple >= mt::serialized);

  check_test(comm, mt::multiple <= mt::multiple);
}

int
main(int argc, char* argv[]) {
  mpi::environment env;
  mpi::communicator world;
  test_threading_levels_io(world);
  test_threading_level_cmp(world);
  return 0;
}

max_stars_repo_name: aminiussi/mpicxx

max_issues_repo_name: aminiussi/mpicxx

max_forks_repo_name: aminiussi/mpicxx


text:
/**
 *  @copyright Copyright 2018 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  @file JPetGeantEventInformationTest.cpp
 */

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetGeantEventInformationTest
#include <boost/test/unit_test.hpp>

#include "JPetGeantEventInformation/JPetGeantEventInformation.h"

BOOST_AUTO_TEST_SUITE(FirstSuite)

BOOST_AUTO_TEST_CASE(default_constructor)
{
  JPetGeantEventInformation info;

  BOOST_REQUIRE_EQUAL(info.GetThreeGammaGen(), 0);
  BOOST_REQUIRE_EQUAL(info.GetTwoGammaGen(), 0);
  BOOST_REQUIRE_EQUAL(info.GetPromptGammaGen(), 0);
  BOOST_REQUIRE_EQUAL(info.GetRunNr(), 0);

  double epsilon = 0.0001;

  BOOST_REQUIRE_CLOSE(info.GetVtxPositionX(), 0.0f, epsilon);
  BOOST_REQUIRE_CLOSE(info.GetVtxPositionY(), 0.0f, epsilon);
  BOOST_REQUIRE_CLOSE(info.GetVtxPositionZ(), 0.0f, epsilon);

  BOOST_REQUIRE_CLOSE(info.GetVtxPromptPositionX(), 0.0f, epsilon);
  BOOST_REQUIRE_CLOSE(info.GetVtxPromptPositionY(), 0.0f, epsilon);
  BOOST_REQUIRE_CLOSE(info.GetVtxPromptPositionZ(), 0.0f, epsilon);

  BOOST_REQUIRE_CLOSE(info.GetLifetime(), 0.0f, epsilon);
  BOOST_REQUIRE_CLOSE(info.GetPromptLifetime(), 0.0f, epsilon);
}

BOOST_AUTO_TEST_CASE(check_setters)
{
  JPetGeantEventInformation info;

  bool gammaGen = true;

  info.SetThreeGammaGen(gammaGen);
  info.SetTwoGammaGen(gammaGen);
  info.SetPromptGammaGen(gammaGen);

  int runNR = 45;
  info.SetRunNr(runNR);

  BOOST_REQUIRE_EQUAL(info.GetThreeGammaGen(), gammaGen);
  BOOST_REQUIRE_EQUAL(info.GetTwoGammaGen(), gammaGen);
  BOOST_REQUIRE_EQUAL(info.GetPromptGammaGen(), gammaGen);
  BOOST_REQUIRE_EQUAL(info.GetRunNr(), runNR);

  float vtx_x = 35;
  float vtx_y = 25;
  float vtx_z = 33;
  float lifetime = 432;
  info.SetVtxPosition(vtx_x, vtx_y, vtx_z);
  info.SetLifetime(lifetime);

  float prompt_vtx_x = 335;
  float prompt_vtx_y = 325;
  float prompt_vtx_z = 333;
  float prompt_lifetime = 43.342;
  info.SetVtxPromptPosition(prompt_vtx_x, prompt_vtx_y, prompt_vtx_z);
  info.SetPromptLifetime(prompt_lifetime);

  BOOST_REQUIRE_EQUAL(info.GetVtxPositionX(), vtx_x);
  BOOST_REQUIRE_EQUAL(info.GetVtxPositionY(), vtx_y);
  BOOST_REQUIRE_EQUAL(info.GetVtxPositionZ(), vtx_z);
  BOOST_REQUIRE_EQUAL(info.GetLifetime(), lifetime);

  BOOST_REQUIRE_EQUAL(info.GetVtxPromptPositionX(), prompt_vtx_x);
  BOOST_REQUIRE_EQUAL(info.GetVtxPromptPositionY(), prompt_vtx_y);
  BOOST_REQUIRE_EQUAL(info.GetVtxPromptPositionZ(), prompt_vtx_z);
  BOOST_REQUIRE_EQUAL(info.GetPromptLifetime(), prompt_lifetime);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: BlurredChoise/j-pet-framework

max_issues_repo_name: BlurredChoise/j-pet-framework

max_forks_repo_name: BlurredChoise/j-pet-framework


text:
/*
(c) 2014 Glen Joseph Fernandes
glenjofe at gmail dot com

Distributed under the Boost Software
License, Version 1.0.
http://boost.org/LICENSE_1_0.txt
*/
#ifndef BOOST_ALIGN_DETAIL_MAX_ALIGN_HPP
#define BOOST_ALIGN_DETAIL_MAX_ALIGN_HPP

#include <boost/align/detail/integral_constant.hpp>
#include <cstddef>

namespace boost {
namespace alignment {
namespace detail {

template<std::size_t A, std::size_t B>
struct max_align
    : integral_constant<std::size_t, (A > B) ? A : B> {
};

} /* :detail */
} /* :alignment */
} /* :boost */

#endif

max_stars_repo_name: BruceNUAA/gaze-detection-android-app

max_issues_repo_name: BruceNUAA/gaze-detection-android-app

max_forks_repo_name: BruceNUAA/gaze-detection-android-app


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

#include <boost/optional.hpp>

#include "yb/client/yb_table_name.h"

#include "yb/yql/pggate/pggate.h"
#include "yb/yql/pggate/pggate_flags.h"
#include "yb/yql/pggate/pg_ddl.h"
#include "yb/yql/pggate/pg_insert.h"
#include "yb/yql/pggate/pg_update.h"
#include "yb/yql/pggate/pg_delete.h"
#include "yb/yql/pggate/pg_truncate_colocated.h"
#include "yb/yql/pggate/pg_select.h"
#include "yb/yql/pggate/pg_txn_manager.h"
#include "yb/yql/pggate/ybc_pggate.h"

#include "yb/util/flag_tags.h"
#include "yb/client/client_fwd.h"
#include "yb/client/client_utils.h"
#include "yb/rpc/messenger.h"
#include "yb/rpc/secure_stream.h"
#include "yb/server/secure.h"

#include "yb/tserver/tserver_shared_mem.h"

DECLARE_string(rpc_bind_addresses);
DECLARE_bool(use_node_to_node_encryption);
DECLARE_string(certs_dir);

namespace yb {
namespace pggate {

namespace {

CHECKED_STATUS AddColumn(PgCreateTable* pg_stmt, const char *attr_name, int attr_num,
                         const YBCPgTypeEntity *attr_type, bool is_hash, bool is_range,
                         bool is_desc, bool is_nulls_first) {
  using SortingType = ColumnSchema::SortingType;
  SortingType sorting_type = SortingType::kNotSpecified;

  if (!is_hash && is_range) {
    if (is_desc) {
      sorting_type = is_nulls_first ? SortingType::kDescending : SortingType::kDescendingNullsLast;
    } else {
      sorting_type = is_nulls_first ? SortingType::kAscending : SortingType::kAscendingNullsLast;
    }
  }

  return pg_stmt->AddColumn(attr_name, attr_num, attr_type, is_hash, is_range, sorting_type);
}

Result<PgApiImpl::MessengerHolder> BuildMessenger(
    const string& client_name,
    int32_t num_reactors,
    const scoped_refptr<MetricEntity>& metric_entity,
    const std::shared_ptr<MemTracker>& parent_mem_tracker) {
  std::unique_ptr<rpc::SecureContext> secure_context;
  if (FLAGS_use_node_to_node_encryption) {
    secure_context = VERIFY_RESULT(server::CreateSecureContext(FLAGS_certs_dir));
  }
  auto messenger = VERIFY_RESULT(client::CreateClientMessenger(
      client_name, num_reactors, metric_entity, parent_mem_tracker, secure_context.get()));
  return PgApiImpl::MessengerHolder{std::move(secure_context), std::move(messenger)};
}

std::unique_ptr<tserver::TServerSharedObject> InitTServerSharedObject() {
  // Do not use shared memory in initdb or if explicity set to be ignored.
  if (YBCIsInitDbModeEnvVarSet() || FLAGS_pggate_ignore_tserver_shm ||
      FLAGS_pggate_tserver_shm_fd == -1) {
    return nullptr;
  }
  return std::make_unique<tserver::TServerSharedObject>(CHECK_RESULT(
      tserver::TServerSharedObject::OpenReadOnly(FLAGS_pggate_tserver_shm_fd)));
}

} // namespace

using std::make_shared;
using client::YBSession;

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

PggateOptions::PggateOptions() {
  server_type = "tserver";
  rpc_opts.default_port = kDefaultPort;
  rpc_opts.connection_keepalive_time_ms = FLAGS_pgsql_rpc_keepalive_time_ms;

  if (FLAGS_pggate_proxy_bind_address.empty()) {
    HostPort host_port;
    CHECK_OK(host_port.ParseString(FLAGS_rpc_bind_addresses, 0));
    host_port.set_port(PggateOptions::kDefaultPort);
    FLAGS_pggate_proxy_bind_address = host_port.ToString();
    LOG(INFO) << "Reset YSQL bind address to " << FLAGS_pggate_proxy_bind_address;
  }
  rpc_opts.rpc_bind_addresses = FLAGS_pggate_proxy_bind_address;
  master_addresses_flag = FLAGS_pggate_master_addresses;

  server::MasterAddresses master_addresses;
  // TODO: we might have to allow setting master_replication_factor similarly to how it is done
  // in tserver to support master auto-discovery on Kubernetes.
  CHECK_OK(server::DetermineMasterAddresses(
      "pggate_master_addresses", master_addresses_flag, /* master_replication_factor */ 0,
      &master_addresses, &master_addresses_flag));
  SetMasterAddresses(make_shared<server::MasterAddresses>(std::move(master_addresses)));
}

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

PgApiImpl::PgApiImpl(const YBCPgTypeEntity *YBCDataTypeArray, int count, YBCPgCallbacks callbacks)
    : metric_registry_(new MetricRegistry()),
      metric_entity_(METRIC_ENTITY_server.Instantiate(metric_registry_.get(), "yb.pggate")),
      mem_tracker_(MemTracker::CreateTracker("PostgreSQL")),
      messenger_holder_(CHECK_RESULT(BuildMessenger("pggate_ybclient",
                                                    FLAGS_pggate_ybclient_reactor_threads,
                                                    metric_entity_,
                                                    mem_tracker_))),
      async_client_init_(messenger_holder_.messenger.get()->name(),
                         FLAGS_pggate_ybclient_reactor_threads,
                         FLAGS_pggate_rpc_timeout_secs,
                         "" /* tserver_uuid */,
                         &pggate_options_,
                         metric_entity_,
                         mem_tracker_,
                         messenger_holder_.messenger.get()),
      clock_(new server::HybridClock()),
      tserver_shared_object_(InitTServerSharedObject()),
      pg_txn_manager_(new PgTxnManager(&async_client_init_, clock_, tserver_shared_object_.get())),
      pg_callbacks_(callbacks) {
  CHECK_OK(clock_->Init());

  // Setup type mapping.
  for (int idx = 0; idx < count; idx++) {
    const YBCPgTypeEntity *type_entity = &YBCDataTypeArray[idx];
    type_map_[type_entity->type_oid] = type_entity;
  }

  async_client_init_.Start();
}

PgApiImpl::~PgApiImpl() {
  messenger_holder_.messenger->Shutdown();
}

const YBCPgTypeEntity *PgApiImpl::FindTypeEntity(int type_oid) {
  const auto iter = type_map_.find(type_oid);
  if (iter != type_map_.end()) {
    return iter->second;
  }
  return nullptr;
}

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

Status PgApiImpl::CreateEnv(PgEnv **pg_env) {
  *pg_env = pg_env_.get();
  return Status::OK();
}

Status PgApiImpl::DestroyEnv(PgEnv *pg_env) {
  pg_env_ = nullptr;
  return Status::OK();
}

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

Status PgApiImpl::InitSession(const PgEnv *pg_env,
                              const string& database_name) {
  CHECK(!pg_session_);
  auto session = make_scoped_refptr<PgSession>(client(),
                                               database_name,
                                               pg_txn_manager_,
                                               clock_,
                                               tserver_shared_object_.get(),
                                               pg_callbacks_);
  if (!database_name.empty()) {
    RETURN_NOT_OK(session->ConnectDatabase(database_name));
  }

  pg_session_.swap(session);
  return Status::OK();
}

Status PgApiImpl::InvalidateCache() {
  pg_session_->InvalidateCache();
  return Status::OK();
}

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

Status PgApiImpl::CreateSequencesDataTable() {
  return pg_session_->CreateSequencesDataTable();
}

Status PgApiImpl::InsertSequenceTuple(int64_t db_oid,
                                      int64_t seq_oid,
                                      uint64_t ysql_catalog_version,
                                      int64_t last_val,
                                      bool is_called) {
  return pg_session_->InsertSequenceTuple(
      db_oid, seq_oid, ysql_catalog_version, last_val, is_called);
}

Status PgApiImpl::UpdateSequenceTupleConditionally(int64_t db_oid,
                                                   int64_t seq_oid,
                                                   uint64_t ysql_catalog_version,
                                                   int64_t last_val,
                                                   bool is_called,
                                                   int64_t expected_last_val,
                                                   bool expected_is_called,
                                                   bool *skipped) {
  return pg_session_->UpdateSequenceTuple(
      db_oid, seq_oid, ysql_catalog_version, last_val, is_called,
      expected_last_val, expected_is_called, skipped);
}

Status PgApiImpl::UpdateSequenceTuple(int64_t db_oid,
                                      int64_t seq_oid,
                                      uint64_t ysql_catalog_version,
                                      int64_t last_val,
                                      bool is_called,
                                      bool* skipped) {
  return pg_session_->UpdateSequenceTuple(
      db_oid, seq_oid, ysql_catalog_version, last_val,
      is_called, boost::none, boost::none, skipped);
}

Status PgApiImpl::ReadSequenceTuple(int64_t db_oid,
                                    int64_t seq_oid,
                                    uint64_t ysql_catalog_version,
                                    int64_t *last_val,
                                    bool *is_called) {
  return pg_session_->ReadSequenceTuple(db_oid, seq_oid, ysql_catalog_version, last_val, is_called);
}

Status PgApiImpl::DeleteSequenceTuple(int64_t db_oid, int64_t seq_oid) {
  return pg_session_->DeleteSequenceTuple(db_oid, seq_oid);
}

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

Status PgApiImpl::DeleteStatement(PgStatement *handle) {
  if (handle) {
    handle->Release();
  }
  return Status::OK();
}

Status PgApiImpl::ClearBinds(PgStatement *handle) {
  return handle->ClearBinds();
}

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

Status PgApiImpl::ConnectDatabase(const char *database_name) {
  return pg_session_->ConnectDatabase(database_name);
}

Status PgApiImpl::NewCreateDatabase(const char *database_name,
                                    const PgOid database_oid,
                                    const PgOid source_database_oid,
                                    const PgOid next_oid,
                                    const bool colocated,
                                    PgStatement **handle) {
  auto stmt = make_scoped_refptr<PgCreateDatabase>(pg_session_, database_name, database_oid,
                                                   source_database_oid, next_oid, colocated);
  *handle = stmt.detach();
  return Status::OK();
}

Status PgApiImpl::ExecCreateDatabase(PgStatement *handle) {
  if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_CREATE_DATABASE)) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }

  return down_cast<PgCreateDatabase*>(handle)->Exec();
}

Status PgApiImpl::NewDropDatabase(const char *database_name,
                                  PgOid database_oid,
                                  PgStatement **handle) {
  auto stmt = make_scoped_refptr<PgDropDatabase>(pg_session_, database_name, database_oid);
  *handle = stmt.detach();
  return Status::OK();
}

Status PgApiImpl::ExecDropDatabase(PgStatement *handle) {
  if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_DROP_DATABASE)) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }
  return down_cast<PgDropDatabase*>(handle)->Exec();
}

Status PgApiImpl::NewAlterDatabase(const char *database_name,
                                  PgOid database_oid,
                                  PgStatement **handle) {
  auto stmt = make_scoped_refptr<PgAlterDatabase>(pg_session_, database_name, database_oid);
  *handle = stmt.detach();
  return Status::OK();
}

Status PgApiImpl::AlterDatabaseRenameDatabase(PgStatement *handle, const char *newname) {
  if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_ALTER_DATABASE)) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }
  return down_cast<PgAlterDatabase*>(handle)->RenameDatabase(newname);
}

Status PgApiImpl::ExecAlterDatabase(PgStatement *handle) {
  if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_ALTER_DATABASE)) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }
  return down_cast<PgAlterDatabase*>(handle)->Exec();
}

Status PgApiImpl::ReserveOids(const PgOid database_oid,
                              const PgOid next_oid,
                              const uint32_t count,
                              PgOid *begin_oid,
                              PgOid *end_oid) {
  return pg_session_->ReserveOids(database_oid, next_oid, count, begin_oid, end_oid);
}

Status PgApiImpl::GetCatalogMasterVersion(uint64_t *version) {
  return pg_session_->GetCatalogMasterVersion(version);
}

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

Status PgApiImpl::NewCreateTable(const char *database_name,
                                 const char *schema_name,
                                 const char *table_name,
                                 const PgObjectId& table_id,
                                 bool is_shared_table,
                                 bool if_not_exist,
                                 bool add_primary_key,
                                 PgStatement **handle) {
  auto stmt = make_scoped_refptr<PgCreateTable>(
      pg_session_, database_name, schema_name, table_name,
      table_id, is_shared_table, if_not_exist, add_primary_key);
  *handle = stmt.detach();
  return Status::OK();
}

Status PgApiImpl::CreateTableAddColumn(PgStatement *handle, const char *attr_name, int attr_num,
                                       const YBCPgTypeEntity *attr_type,
                                       bool is_hash, bool is_range,
                                       bool is_desc, bool is_nulls_first) {
  if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_CREATE_TABLE)) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }
  return AddColumn(down_cast<PgCreateTable*>(handle), attr_name, attr_num, attr_type,
      is_hash, is_range, is_desc, is_nulls_first);
}

Status PgApiImpl::CreateTableSetNumTablets(PgStatement *handle, int32_t num_tablets) {
  if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_CREATE_TABLE)) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }
  return down_cast<PgCreateTable*>(handle)->SetNumTablets(num_tablets);
}

Status PgApiImpl::CreateTableSetColocated(PgStatement *handle, bool colocated) {
  if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_CREATE_TABLE)) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }
  down_cast<PgCreateTable*>(handle)->SetColocated(colocated);
  return Status::OK();
}

Status PgApiImpl::ExecCreateTable(PgStatement *handle) {
  if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_CREATE_TABLE)) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }
  return down_cast<PgCreateTable*>(handle)->Exec();
}

Status PgApiImpl::NewAlterTable(const PgObjectId& table_id,
                                PgStatement **handle) {
  auto stmt = make_scoped_refptr<PgAlterTable>(pg_session_, table_id);
  *handle = stmt.detach();
  return Status::OK();
}

Status PgApiImpl::AlterTableAddColumn(PgStatement *handle, const char *name,
                                      int order, const YBCPgTypeEntity *attr_type,
                                      bool is_not_null) {
  if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_ALTER_TABLE)) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }

  PgAlterTable *pg_stmt = down_cast<PgAlterTable*>(handle);
  return pg_stmt->AddColumn(name, attr_type, order, is_not_null);
}

Status PgApiImpl::AlterTableRenameColumn(PgStatement *handle, const char *oldname,
                                         const char *newname) {
  if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_ALTER_TABLE)) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }

  PgAlterTable *pg_stmt = down_cast<PgAlterTable*>(handle);
  return pg_stmt->RenameColumn(oldname, newname);
}

Status PgApiImpl::AlterTableDropColumn(PgStatement *handle, const char *name) {
  if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_ALTER_TABLE)) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }

  PgAlterTable *pg_stmt = down_cast<PgAlterTable*>(handle);
  return pg_stmt->DropColumn(name);
}

Status PgApiImpl::AlterTableRenameTable(PgStatement *handle, const char *db_name,
                                        const char *newname) {
  if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_ALTER_TABLE)) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }

  PgAlterTable *pg_stmt = down_cast<PgAlterTable*>(handle);
  return pg_stmt->RenameTable(db_name, newname);
}

Status PgApiImpl::ExecAlterTable(PgStatement *handle) {
  if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_ALTER_TABLE)) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }
  PgAlterTable *pg_stmt = down_cast<PgAlterTable*>(handle);
  return pg_stmt->Exec();
}

Status PgApiImpl::NewDropTable(const PgObjectId& table_id,
                               bool if_exist,
                               PgStatement **handle) {
  auto stmt = make_scoped_refptr<PgDropTable>(pg_session_, table_id, if_exist);
  *handle = stmt.detach();
  return Status::OK();
}

Status PgApiImpl::ExecDropTable(PgStatement *handle) {
  if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_DROP_TABLE)) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }
  return down_cast<PgDropTable*>(handle)->Exec();
}

Status PgApiImpl::NewTruncateTable(const PgObjectId& table_id,
                                   PgStatement **handle) {
  auto stmt = make_scoped_refptr<PgTruncateTable>(pg_session_, table_id);
  *handle = stmt.detach();
  return Status::OK();
}

Status PgApiImpl::ExecTruncateTable(PgStatement *handle) {
  if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_TRUNCATE_TABLE)) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }
  return down_cast<PgTruncateTable*>(handle)->Exec();
}

Status PgApiImpl::GetTableDesc(const PgObjectId& table_id,
                               PgTableDesc **handle) {
  PgTableDesc::ScopedRefPtr table;
  auto result = pg_session_->LoadTable(table_id);
  RETURN_NOT_OK(result);
  *handle = (*result).detach();
  return Status::OK();
}

Status PgApiImpl::DeleteTableDesc(PgTableDesc *handle) {
  if (handle) {
    handle->Release();
  }
  return Status::OK();
}

Status PgApiImpl::GetColumnInfo(YBCPgTableDesc table_desc,
                                int16_t attr_number,
                                bool *is_primary,
                                bool *is_hash) {
  return table_desc->GetColumnInfo(attr_number, is_primary, is_hash);
}

Status PgApiImpl::DmlModifiesRow(PgStatement *handle, bool *modifies_row) {
  if (!handle) {
    return STATUS(InvalidArgument, "Invalid statement handle");
  }

  *modifies_row = false;

  switch (handle->stmt_op()) {
    case StmtOp::STMT_UPDATE:
    case StmtOp::STMT_DELETE:
      *modifies_row = true;
      break;
    default:
      break;
  }

  return Status::OK();
}

Status PgApiImpl::SetIsSysCatalogVersionChange(PgStatement *handle) {
  if (!handle) {
    return STATUS(InvalidArgument, "Invalid statement handle");
  }

  switch (handle->stmt_op()) {
    case StmtOp::STMT_UPDATE:
    case StmtOp::STMT_DELETE:
    case StmtOp::STMT_INSERT:
      down_cast<PgDmlWrite *>(handle)->SetIsSystemCatalogChange();
      return Status::OK();
    default:
      break;
  }

  return STATUS(InvalidArgument, "Invalid statement handle");
}

Status PgApiImpl::SetCatalogCacheVersion(PgStatement *handle, uint64_t catalog_cache_version) {
  if (!handle) {
    return STATUS(InvalidArgument, "Invalid statement handle");
  }

  switch (handle->stmt_op()) {
    case StmtOp::STMT_SELECT:
    case StmtOp::STMT_INSERT:
    case StmtOp::STMT_UPDATE:
    case StmtOp::STMT_DELETE:
      down_cast<PgDml *>(handle)->SetCatalogCacheVersion(catalog_cache_version);
      return Status::OK();
    default:
      break;
  }

  return STATUS(InvalidArgument, "Invalid statement handle");
}

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

Status PgApiImpl::NewCreateIndex(const char *database_name,
                                 const char *schema_name,
                                 const char *index_name,
                                 const PgObjectId& index_id,
                                 const PgObjectId& base_table_id,
                                 bool is_shared_index,
                                 bool is_unique_index,
                                 bool if_not_exist,
                                 PgStatement **handle) {
  auto stmt = make_scoped_refptr<PgCreateIndex>(
      pg_session_, database_name, schema_name, index_name, index_id, base_table_id,
      is_shared_index, is_unique_index, if_not_exist);
  *handle = stmt.detach();
  return Status::OK();
}

Status PgApiImpl::CreateIndexAddColumn(PgStatement *handle, const char *attr_name, int attr_num,
                                       const YBCPgTypeEntity *attr_type,
                                       bool is_hash, bool is_range,
                                       bool is_desc, bool is_nulls_first) {
  if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_CREATE_INDEX)) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }

  return AddColumn(down_cast<PgCreateIndex*>(handle), attr_name, attr_num, attr_type,
      is_hash, is_range, is_desc, is_nulls_first);
}

Status PgApiImpl::ExecCreateIndex(PgStatement *handle) {
  if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_CREATE_INDEX)) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }
  return down_cast<PgCreateIndex*>(handle)->Exec();
}

Status PgApiImpl::NewDropIndex(const PgObjectId& index_id,
                               bool if_exist,
                               PgStatement **handle) {
  auto stmt = make_scoped_refptr<PgDropIndex>(pg_session_, index_id, if_exist);
  *handle = stmt.detach();
  return Status::OK();
}

Status PgApiImpl::ExecDropIndex(PgStatement *handle) {
  if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_DROP_INDEX)) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }
  return down_cast<PgDropIndex*>(handle)->Exec();
}

//--------------------------------------------------------------------------------------------------
// DML Statment Support.
//--------------------------------------------------------------------------------------------------

// Binding -----------------------------------------------------------------------------------------

Status PgApiImpl::DmlAppendTarget(PgStatement *handle, PgExpr *target) {
  return down_cast<PgDml*>(handle)->AppendTarget(target);
}

Status PgApiImpl::DmlBindColumn(PgStatement *handle, int attr_num, PgExpr *attr_value) {
  return down_cast<PgDml*>(handle)->BindColumn(attr_num, attr_value);
}

Status PgApiImpl::DmlBindColumnCondEq(PgStatement *handle, int attr_num, PgExpr *attr_value) {
  return down_cast<PgSelect*>(handle)->BindColumnCondEq(attr_num, attr_value);
}

Status PgApiImpl::DmlBindColumnCondBetween(PgStatement *handle, int attr_num, PgExpr *attr_value,
    PgExpr *attr_value_end) {
  return down_cast<PgSelect*>(handle)->BindColumnCondBetween(attr_num, attr_value, attr_value_end);
}

Status PgApiImpl::DmlBindColumnCondIn(PgStatement *handle, int attr_num, int n_attr_values,
    PgExpr **attr_values) {
  return down_cast<PgSelect*>(handle)->BindColumnCondIn(attr_num, n_attr_values, attr_values);
}

Status PgApiImpl::DmlBindIndexColumn(PgStatement *handle, int attr_num, PgExpr *attr_value) {
  if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_SELECT)) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }
  return down_cast<PgSelect*>(handle)->BindIndexColumn(attr_num, attr_value);
}

Status PgApiImpl::DmlBindTable(PgStatement *handle) {
  return down_cast<PgDml*>(handle)->BindTable();
}

CHECKED_STATUS PgApiImpl::DmlAssignColumn(PgStatement *handle, int attr_num, PgExpr *attr_value) {
  return down_cast<PgDml*>(handle)->AssignColumn(attr_num, attr_value);
}

Status PgApiImpl::DmlFetch(PgStatement *handle, int32_t natts, uint64_t *values, bool *isnulls,
                           PgSysColumns *syscols, bool *has_data) {
  return down_cast<PgDml*>(handle)->Fetch(natts, values, isnulls, syscols, has_data);
}

Status PgApiImpl::DmlBuildYBTupleId(PgStatement *handle, const PgAttrValueDescriptor *attrs,
                                    int32_t nattrs, uint64_t *ybctid) {
  const string id = VERIFY_RESULT(down_cast<PgDml*>(handle)->BuildYBTupleId(attrs, nattrs));
  const YBCPgTypeEntity *type_entity = FindTypeEntity(kPgByteArrayOid);
  *ybctid = type_entity->yb_to_datum(id.data(), id.size(), nullptr /* type_attrs */);
  return Status::OK();
}

Status PgApiImpl::StartOperationsBuffering() {
  return pg_session_->StartOperationsBuffering();
}

Status PgApiImpl::FlushBufferedOperations() {
  return pg_session_->FlushBufferedOperations();
}

Status PgApiImpl::DmlExecWriteOp(PgStatement *handle, int32_t *rows_affected_count) {
  switch (handle->stmt_op()) {
    case StmtOp::STMT_INSERT:
    case StmtOp::STMT_UPDATE:
    case StmtOp::STMT_DELETE:
    case StmtOp::STMT_TRUNCATE:
      {
        auto dml_write = down_cast<PgDmlWrite *>(handle);
        RETURN_NOT_OK(dml_write->Exec(rows_affected_count != nullptr /* force_non_bufferable */));
        if (rows_affected_count) {
          *rows_affected_count = dml_write->GetRowsAffectedCount();
        }
        return Status::OK();
      }
    default:
      break;
  }
  return STATUS(InvalidArgument, "Invalid statement handle");
}

// Insert ------------------------------------------------------------------------------------------

Status PgApiImpl::NewInsert(const PgObjectId& table_id,
                            const bool is_single_row_txn,
                            PgStatement **handle) {
  *handle = nullptr;
  auto stmt = make_scoped_refptr<PgInsert>(pg_session_, table_id, is_single_row_txn);
  RETURN_NOT_OK(stmt->Prepare());
  *handle = stmt.detach();
  return Status::OK();
}

Status PgApiImpl::ExecInsert(PgStatement *handle) {
  if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_INSERT)) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }
  return down_cast<PgInsert*>(handle)->Exec();
}

// Update ------------------------------------------------------------------------------------------

Status PgApiImpl::NewUpdate(const PgObjectId& table_id,
                            const bool is_single_row_txn,
                            PgStatement **handle) {
  *handle = nullptr;
  auto stmt = make_scoped_refptr<PgUpdate>(pg_session_, table_id, is_single_row_txn);
  RETURN_NOT_OK(stmt->Prepare());
  *handle = stmt.detach();
  return Status::OK();
}

Status PgApiImpl::ExecUpdate(PgStatement *handle) {
  if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_UPDATE)) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }
  return down_cast<PgUpdate*>(handle)->Exec();
}

// Delete ------------------------------------------------------------------------------------------

Status PgApiImpl::NewDelete(const PgObjectId& table_id,
                            const bool is_single_row_txn,
                            PgStatement **handle) {
  *handle = nullptr;
  auto stmt = make_scoped_refptr<PgDelete>(pg_session_, table_id, is_single_row_txn);
  RETURN_NOT_OK(stmt->Prepare());
  *handle = stmt.detach();
  return Status::OK();
}

Status PgApiImpl::ExecDelete(PgStatement *handle) {
  if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_DELETE)) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }
  return down_cast<PgDelete*>(handle)->Exec();
}

// Colocated Truncate ------------------------------------------------------------------------------

Status PgApiImpl::NewTruncateColocated(const PgObjectId& table_id,
                                       const bool is_single_row_txn,
                                       PgStatement **handle) {
  *handle = nullptr;
  auto stmt = make_scoped_refptr<PgTruncateColocated>(pg_session_, table_id, is_single_row_txn);
  RETURN_NOT_OK(stmt->Prepare());
  *handle = stmt.detach();
  return Status::OK();
}

Status PgApiImpl::ExecTruncateColocated(PgStatement *handle) {
  if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_TRUNCATE)) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }
  return down_cast<PgTruncateColocated*>(handle)->Exec();
}

// Select ------------------------------------------------------------------------------------------

Status PgApiImpl::NewSelect(const PgObjectId& table_id,
                            const PgObjectId& index_id,
                            const PgPrepareParameters *prepare_params,
                            PgStatement **handle) {
  *handle = nullptr;
  if (prepare_params && prepare_params->index_only_scan && !index_id.IsValid()) {
    return STATUS(InvalidArgument, "Cannot run query with invalid index ID");
  }
  auto stmt = make_scoped_refptr<PgSelect>(pg_session_, table_id, index_id, prepare_params);

  RETURN_NOT_OK(stmt->Prepare());
  *handle = stmt.detach();
  return Status::OK();
}

Status PgApiImpl::SetForwardScan(PgStatement *handle, bool is_forward_scan) {
  if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_SELECT)) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }
  down_cast<PgSelect*>(handle)->SetForwardScan(is_forward_scan);
  return Status::OK();
}

Status PgApiImpl::ExecSelect(PgStatement *handle, const PgExecParameters *exec_params) {
  if (!PgStatement::IsValidStmt(handle, StmtOp::STMT_SELECT)) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }
  return down_cast<PgSelect*>(handle)->Exec(exec_params);
}

//--------------------------------------------------------------------------------------------------
// Expressions.
//--------------------------------------------------------------------------------------------------

// Column references -------------------------------------------------------------------------------

Status PgApiImpl::NewColumnRef(PgStatement *stmt, int attr_num, const PgTypeEntity *type_entity,
                               const PgTypeAttrs *type_attrs, PgExpr **expr_handle) {
  if (!stmt) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }
  PgColumnRef::SharedPtr colref = make_shared<PgColumnRef>(attr_num, type_entity, type_attrs);
  stmt->AddExpr(colref);

  *expr_handle = colref.get();
  return Status::OK();
}

// Constant ----------------------------------------------------------------------------------------
Status PgApiImpl::NewConstant(YBCPgStatement stmt, const YBCPgTypeEntity *type_entity,
                              uint64_t datum, bool is_null, YBCPgExpr *expr_handle) {
  if (!stmt) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }
  PgExpr::SharedPtr pg_const = make_shared<PgConstant>(type_entity, datum, is_null);
  stmt->AddExpr(pg_const);

  *expr_handle = pg_const.get();
  return Status::OK();
}

Status PgApiImpl::NewConstantOp(YBCPgStatement stmt, const YBCPgTypeEntity *type_entity,
                              uint64_t datum, bool is_null, YBCPgExpr *expr_handle, bool is_gt) {
  if (!stmt) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }
  PgExpr::SharedPtr pg_const = make_shared<PgConstant>(type_entity, datum, is_null,
      is_gt ? PgExpr::Opcode::PG_EXPR_GT : PgExpr::Opcode::PG_EXPR_LT);
  stmt->AddExpr(pg_const);

  *expr_handle = pg_const.get();
  return Status::OK();
}

// Text constant -----------------------------------------------------------------------------------

Status PgApiImpl::UpdateConstant(PgExpr *expr, const char *value, bool is_null) {
  if (expr->opcode() != PgExpr::Opcode::PG_EXPR_CONSTANT) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid expression handle for constant");
  }
  down_cast<PgConstant*>(expr)->UpdateConstant(value, is_null);
  return Status::OK();
}

Status PgApiImpl::UpdateConstant(PgExpr *expr, const void *value, int64_t bytes, bool is_null) {
  if (expr->opcode() != PgExpr::Opcode::PG_EXPR_CONSTANT) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid expression handle for constant");
  }
  down_cast<PgConstant*>(expr)->UpdateConstant(value, bytes, is_null);
  return Status::OK();
}

// Text constant -----------------------------------------------------------------------------------

Status PgApiImpl::NewOperator(PgStatement *stmt, const char *opname,
                              const YBCPgTypeEntity *type_entity,
                              PgExpr **op_handle) {
  if (!stmt) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid statement handle");
  }
  RETURN_NOT_OK(PgExpr::CheckOperatorName(opname));

  // Create operator.
  PgExpr::SharedPtr pg_op = make_shared<PgOperator>(opname, type_entity);
  stmt->AddExpr(pg_op);

  *op_handle = pg_op.get();
  return Status::OK();
}

Status PgApiImpl::OperatorAppendArg(PgExpr *op_handle, PgExpr *arg) {
  if (!op_handle || !arg) {
    // Invalid handle.
    return STATUS(InvalidArgument, "Invalid expression handle");
  }
  down_cast<PgOperator*>(op_handle)->AppendArg(arg);
  return Status::OK();
}

Result<bool> PgApiImpl::IsInitDbDone() {
  return pg_session_->IsInitDbDone();
}

Result<uint64_t> PgApiImpl::GetSharedCatalogVersion() {
  return pg_session_->GetSharedCatalogVersion();
}

// Transaction Control -----------------------------------------------------------------------------
Status PgApiImpl::BeginTransaction() {
  pg_session_->InvalidateForeignKeyReferenceCache();
  return pg_txn_manager_->BeginTransaction();
}

Status PgApiImpl::RestartTransaction() {
  pg_session_->InvalidateForeignKeyReferenceCache();
  return pg_txn_manager_->RestartTransaction();
}

Status PgApiImpl::CommitTransaction() {
  pg_session_->InvalidateForeignKeyReferenceCache();
  return pg_txn_manager_->CommitTransaction();
}

Status PgApiImpl::AbortTransaction() {
  pg_session_->InvalidateForeignKeyReferenceCache();
  return pg_txn_manager_->AbortTransaction();
}

Status PgApiImpl::SetTransactionIsolationLevel(int isolation) {
  return pg_txn_manager_->SetIsolationLevel(isolation);
}

Status PgApiImpl::SetTransactionReadOnly(bool read_only) {
  return pg_txn_manager_->SetReadOnly(read_only);
}

Status PgApiImpl::SetTransactionDeferrable(bool deferrable) {
  return pg_txn_manager_->SetDeferrable(deferrable);
}

Status PgApiImpl::EnterSeparateDdlTxnMode() {
  return pg_txn_manager_->EnterSeparateDdlTxnMode();
}

Status PgApiImpl::ExitSeparateDdlTxnMode(bool success) {
  return pg_txn_manager_->ExitSeparateDdlTxnMode(success);
}

bool PgApiImpl::ForeignKeyReferenceExists(YBCPgOid table_id, std::string&& ybctid) {
  return pg_session_->ForeignKeyReferenceExists(table_id, std::move(ybctid));
}

Status PgApiImpl::CacheForeignKeyReference(YBCPgOid table_id, std::string&& ybctid) {
  return pg_session_->CacheForeignKeyReference(table_id, std::move(ybctid));
}

Status PgApiImpl::DeleteForeignKeyReference(YBCPgOid table_id, std::string&& ybctid) {
  return pg_session_->DeleteForeignKeyReference(table_id, std::move(ybctid));
}

void PgApiImpl::ClearForeignKeyReferenceCache() {
  pg_session_->InvalidateForeignKeyReferenceCache();
}

} // namespace pggate
} // namespace yb

ext: cc

max_stars_repo_name: svanellewee/yugabyte-db

max_issues_repo_name: svanellewee/yugabyte-db

max_forks_repo_name: svanellewee/yugabyte-db


text:
/*==============================================================================
  Copyright (c) 2017, 2018, 2019 Matt Calabrese

  Distributed under the Boost Software License, Version 1.0. (See accompanying
  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/

#ifndef ARGOT_CONCEPTS_PERSISTENT_FORGETFUL_THENABLE_DETAIL_BOOST_SHARED_FUTURE_HPP_
#define ARGOT_CONCEPTS_PERSISTENT_FORGETFUL_THENABLE_DETAIL_BOOST_SHARED_FUTURE_HPP_

#include <argot/fut_traits/config.hpp>

#ifndef ARGOT_HAS_BOOST_FUTURE_WITH_CONTINUATION
#error Included boost::shared_future concept map header without continuations enabled.
#else

#include <argot/concepts/copy_constructible.hpp>
#include <argot/concepts/decay_sinkable.hpp>
#include <argot/concepts/future.hpp>
#include <argot/concepts/future/detail/immediate_boost_executor.hpp>
#include <argot/concepts/invocable_object_with.hpp>
#include <argot/concepts/persistent_forgetful_thenable.hpp>
#include <argot/detail/conditional.hpp>
#include <argot/detail/constexpr_invoke.hpp>
#include <argot/detail/sink.hpp>
#include <argot/executor/immediate.hpp>
#include <argot/detail/forward.hpp>
#include <argot/gen/make_concept_map.hpp>
#include <argot/gen/requires.hpp>
#include <argot/detail/move.hpp>
#include <argot/detail/remove_cvref.hpp>
#include <argot/void_.hpp>

#include <boost/thread/future.hpp>

#include <type_traits>

namespace argot {
namespace detail_persistent_future_boost_shared_future {

template< class T, class Fun >
static constexpr auto
intrinsic_persistent_then( boost::shared_future< T > const& self, Fun&& fun )
{
  return self.then
  ( [ fun = ARGOT_MOVE( fun ) ]
    ( boost::shared_future< T > const& self_arg ) mutable -> decltype( auto )
    {
      if constexpr( std::is_void_v< T > )
      {
        void_to_regular_void_t< T > result{};

        self_arg.get();
        return ARGOT_MOVE( fun )( result );  // TODO(mattcalabrese) as const?
      }
      else
        ARGOT_MOVE( fun )( self_arg.get() );
    }
  );
}

} // namespace argot(::detail_persistent_future_boost_shared_future)

template< class T >
struct make_concept_map
< PersistentForgetfulThenable
  < boost::shared_future< T >, executor::immediate_t >
>
{
  template< class Fun >
  static constexpr void forgetful_then
  ( boost::shared_future< T > const& self, executor::immediate_t, Fun&& fun )
  {
    (void)detail_persistent_future_boost_shared_future
    ::intrinsic_persistent_then( self, ARGOT_MOVE( fun ) );
  }
};

} // namespace argot

#endif  // ARGOT_HAS_BOOST_FUTURE_WITH_CONTINUATION

#endif  // ARGOT_CONCEPTS_PERSISTENT_FORGETFUL_THENABLE_DETAIL_BOOST_SHARED_FUTURE_HPP_

max_stars_repo_name: mattcalabrese/argot

max_issues_repo_name: mattcalabrese/argot

max_forks_repo_name: mattcalabrese/argot


text:
#include <gtest/gtest.h>
#include <boost/math/distributions.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <stan/math/prim/mat.hpp>
#include <math/prim/mat/prob/vector_rng_test_helper.hpp>
#include <math/prim/mat/prob/VectorIntRNGTestRig.hpp>
#include <limits>
#include <vector>

class NegativeBinomialTestRig : public VectorIntRNGTestRig {
 public:
  NegativeBinomialTestRig()
      : VectorIntRNGTestRig(10000, 10, {0, 1, 2, 3, 4, 5, 6}, {0.1, 1.7, 3.99},
                            {1, 2, 3}, {-2.1, -0.5, 0.0}, {-3, -1, 0},
                            {0.1, 1.1, 4.99}, {1, 2, 3}, {-3.0, -2.0, 0.0},
                            {-3, -1, 0}) {}

  template <typename T1, typename T2, typename T3, typename T_rng>
  auto generate_samples(const T1& alpha, const T2& beta, const T3&,
                        T_rng& rng) const {
    return stan::math::neg_binomial_rng(alpha, beta, rng);
  }

  template <typename T1>
  double pmf(int y, T1 alpha, double beta, double) const {
    return std::exp(stan::math::neg_binomial_lpmf(y, alpha, beta));
  }
};

TEST(ProbDistributionsNegativeBinomial, errorCheck) {
  check_dist_throws_all_types(NegativeBinomialTestRig());
}

TEST(ProbDistributionsNegativeBinomial, distributionCheck) {
  check_counts_real_real(NegativeBinomialTestRig());
}

max_stars_repo_name: alashworth/stan-monorepo

max_issues_repo_name: alashworth/stan-monorepo

max_forks_repo_name: alashworth/stan-monorepo


text:
// Copyright 2013 The CARFAC Authors. All Rights Reserved.
// Author: Ron Weiss <ronw@google.com>
//
// This file is part of an implementation of Lyon's cochlear model:
// "Cascade of Asymmetric Resonators with Fast-Acting Compression"
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "sai.h"

#include <math.h>
#include <iostream>
#include <string>

#include <Eigen/Core>

#include "gtest/gtest.h"

#include "agc.h"
#include "car.h"
#include "carfac.h"
#include "common.h"
#include "ihc.h"
#include "test_util.h"

using testing::Values;

class SAIPeriodicInputTest
    : public SAITestBase,
      public ::testing::WithParamInterface< ::testing::tuple<int, int> > {
 protected:
  void SetUp() {
    period_ = ::testing::get<0>(GetParam());
    num_channels_ = ::testing::get<1>(GetParam());
  }

  int period_;
  int num_channels_;
};

TEST_P(SAIPeriodicInputTest, MultiChannelPulseTrain) {
  const int kInputSegmentWidth = 38;
  ArrayXX segment =
      CreatePulseTrain(num_channels_, kInputSegmentWidth, period_);

  const int kSAIWidth = 15;
  const int kTriggerWindowWidth = kInputSegmentWidth;
  SAIParams sai_params = CreateSAIParams(num_channels_, kInputSegmentWidth,
                                         kTriggerWindowWidth, kSAIWidth);
  sai_params.future_lags = 0;  // Only compute past lags.

  SAI sai(sai_params);
  ArrayXX sai_frame;
  sai.RunSegment(segment, &sai_frame);

  // The output should have peaks at the same positions, regardless of
  // input phase.
  for (int i = 0; i < num_channels_; ++i) {
    const ArrayX& sai_channel = sai_frame.row(i);
    for (int j = sai_channel.size() - 1; j >= 0; j -= period_) {
      EXPECT_TRUE(HasPeakAt(sai_channel, j));
    }
  }

  std::cout << "Input:" << std::endl << segment << std::endl
            << "Output:" << std::endl << sai_frame << std::endl;
}

INSTANTIATE_TEST_SUITE_P(PeriodicInputVariations, SAIPeriodicInputTest,
                         testing::Combine(Values(25, 10, 5, 2),  // periods.
                                          Values(1, 2, 15)));  // num_channels.

class SAITest : public SAITestBase {};

TEST_F(SAITest, DiesIfInputSegmentWidthIsLargerThanBuffer) {
  const int kNumChannels = 2;
  const int kSAIWidth = 10;
  const int kInputSegmentWidth = 200;
  SAIParams valid_params = CreateSAIParams(kNumChannels, kInputSegmentWidth,
                                           kInputSegmentWidth, kSAIWidth);
  SAI sai(valid_params);

  const int kTriggerWindowWidth = kInputSegmentWidth / 10;
  SAIParams params = CreateSAIParams(kNumChannels, kInputSegmentWidth,
                                     kTriggerWindowWidth, kSAIWidth);
  ASSERT_GT(kInputSegmentWidth,
            params.num_triggers_per_frame * params.trigger_window_width);
  ASSERT_DEATH(sai.Redesign(params), "Too few triggers");
}

TEST_F(SAITest, DiesIfInputWidthDoesntMatchInputSegmentWidth) {
  const int kNumChannels = 2;
  const int kInputSegmentWidth = 10;
  const int kPeriod = 4;
  ArrayXX segment = CreatePulseTrain(kNumChannels, kInputSegmentWidth, kPeriod);

  const int kSAIWidth = 20;
  const int kExpectedInputSegmentWidth = kInputSegmentWidth - 1;
  const int kTriggerWindowWidth = kSAIWidth + 1;
  SAIParams sai_params = CreateSAIParams(
      kNumChannels, kExpectedInputSegmentWidth, kTriggerWindowWidth, kSAIWidth);
  ASSERT_NE(sai_params.input_segment_width, kInputSegmentWidth);
  SAI sai(sai_params);
  ArrayXX sai_frame;
  ASSERT_DEATH(sai.RunSegment(segment, &sai_frame), "input samples");
}

TEST_F(SAITest, InputSegmentWidthSmallerThanTriggerWindow) {  // I.e. small hop.
  const int kNumChannels = 1;
  const int kTotalInputSamples = 20;
  const int kPeriod = 5;
  ArrayXX input = CreatePulseTrain(kNumChannels, kTotalInputSamples, kPeriod);

  const int kNumFrames = 4;
  const int kInputSegmentWidth = kTotalInputSamples / kNumFrames;
  const int kTriggerWindowWidth = kTotalInputSamples;
  const int kSAIWidth = 15;
  SAIParams sai_params = CreateSAIParams(kNumChannels, kInputSegmentWidth,
                                         kTriggerWindowWidth, kSAIWidth);
  ASSERT_LT(sai_params.input_segment_width, sai_params.trigger_window_width);
  sai_params.future_lags = 0;  // Only compute past lags.

  ASSERT_GE(kPeriod, kInputSegmentWidth);

  SAI sai(sai_params);
  ArrayXX sai_frame;
  for (int i = 0; i < kNumFrames; ++i) {
    ArrayXX segment =
        input.row(0).segment(i * kInputSegmentWidth, kInputSegmentWidth);
    sai.RunSegment(segment, &sai_frame);

    std::cout << "Frame " << i << std::endl
              << "Input:" << std::endl << segment << std::endl
              << "Output:" << std::endl << sai_frame << std::endl;

    EXPECT_NE(segment.cwiseAbs().sum(), 0);
    // Since the input segment is never all zero, there should always
    // be a peak at zero lag.
    ArrayX sai_channel = sai_frame.row(0);
    EXPECT_TRUE(HasPeakAt(sai_channel, sai_channel.size() - 1));

    if (i == 0) {
      // Since the pulse train period is larger than the input segment
      // size, the first input segment will only see a single impulse,
      // most of the SAI will be zero.
      AssertArrayNear(sai_channel.head(sai_channel.size() - 1),
                      ArrayX::Zero(sai_channel.size() - 1), 1e-9);
    }

    if (i == kNumFrames - 1) {
      // By the last frame, the SAI's internal buffer will have
      // accumulated the full input signal, so the resulting image
      // should contain kPeriod peaks.
      for (int j = sai_channel.size() - 1; j >= 0; j -= kPeriod) {
        EXPECT_TRUE(HasPeakAt(sai_channel, j));
      }
    }
  }
}

TEST_F(SAITest, MatchesMatlabOnBinauralData) {
  const std::string kTestName = "binaural_test";
  const int kInputSegmentWidth = 882;
  const int kNumChannels = 71;
  // The Matlab CARFAC output is transposed compared to the C++.
  ArrayXX input_segment =
      LoadMatrix(kTestName + "-matlab-nap1.txt", kInputSegmentWidth,
                 kNumChannels).transpose();

  const int kTriggerWindowWidth = kInputSegmentWidth;
  const int kSAIWidth = 500;
  SAIParams sai_params = CreateSAIParams(kNumChannels, kInputSegmentWidth,
                                         kTriggerWindowWidth, kSAIWidth);
  SAI sai(sai_params);
  ArrayXX sai_frame;
  sai.RunSegment(input_segment, &sai_frame);
  ArrayXX expected_sai_frame = LoadMatrix(kTestName + "-matlab-sai1.txt",
                                          kNumChannels, sai_params.sai_width);
  AssertArrayNear(expected_sai_frame, sai_frame, kTestPrecision);

  WriteMatrix(kTestName + "-cpp-sai1.txt", sai_frame);
}

TEST_F(SAITest, CARFACIntegration) {
  const int kNumEars = 1;
  const int kInputSegmentWidth = 300;
  ArrayXX segment(kNumEars, kInputSegmentWidth);

  // Sinusoid input.
  const float kFrequency = 10.0;
  segment.row(0) =
      ArrayX::LinSpaced(kInputSegmentWidth, 0.0, 2 * kFrequency * M_PI).sin();

  CARParams car_params;
  IHCParams ihc_params;
  AGCParams agc_params;
  CARFAC carfac(kNumEars, 8000, car_params, ihc_params, agc_params);
  CARFACOutput output(true, false, false, false);
  const bool kOpenLoop = false;
  carfac.RunSegment(segment, kOpenLoop, &output);

  const int kSAIWidth = 20;
  const int kTriggerWindowWidth = kInputSegmentWidth;
  SAIParams sai_params =
      CreateSAIParams(carfac.num_channels(), kInputSegmentWidth,
                      kTriggerWindowWidth, kSAIWidth);
  SAI sai(sai_params);
  ArrayXX sai_frame;
  sai.RunSegment(output.nap()[0], &sai_frame);

  // TODO(ronw): Test something about the output.
}


text:
// Copyright (c) 2019-2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//
#include <test/util/setup_common.h>
#include <util/system.h>
#include <univalue.h>

#ifdef ENABLE_EXTERNAL_SIGNER
#if defined(WIN32) && !defined(__kernel_entry)
// A workaround for boost 1.71 incompatibility with mingw-w64 compiler.
// For details see https://github.com/bitcoin/bitcoin/pull/22348.
#define __kernel_entry
#endif
#include <boost/process.hpp>
#endif // ENABLE_EXTERNAL_SIGNER

#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(system_tests, BasicTestingSetup)

// At least one test is required (in case ENABLE_EXTERNAL_SIGNER is not defined).
// Workaround for https://github.com/bitcoin/bitcoin/issues/19128
BOOST_AUTO_TEST_CASE(dummy)
{
    BOOST_CHECK(true);
}

#ifdef ENABLE_EXTERNAL_SIGNER

BOOST_AUTO_TEST_CASE(run_command)
{
    {
        const UniValue result = RunCommandParseJSON("");
        BOOST_CHECK(result.isNull());
    }
    {
#ifdef WIN32
        const UniValue result = RunCommandParseJSON("cmd.exe /c echo {\"success\": true}");
#else
        const UniValue result = RunCommandParseJSON("echo \"{\"success\": true}\"");
#endif
        BOOST_CHECK(result.isObject());
        const UniValue& success = find_value(result, "success");
        BOOST_CHECK(!success.isNull());
        BOOST_CHECK_EQUAL(success.getBool(), true);
    }
    {
        // An invalid command is handled by Boost
#ifdef WIN32
        const std::string expected{"The system cannot find the file specified."};
#else
        const std::string expected{"No such file or directory"};
#endif
        BOOST_CHECK_EXCEPTION(RunCommandParseJSON("invalid_command"), boost::process::process_error, [&](const boost::process::process_error& e) {
            const std::string what(e.what());
            BOOST_CHECK(what.find("RunCommandParseJSON error:") == std::string::npos);
            BOOST_CHECK(what.find(expected) != std::string::npos);
            return true;
        });
    }
    {
        // Return non-zero exit code, no output to stderr
#ifdef WIN32
        const std::string command{"cmd.exe /c call"};
#else
        const std::string command{"false"};
#endif
        BOOST_CHECK_EXCEPTION(RunCommandParseJSON(command), std::runtime_error, [&](const std::runtime_error& e) {
            BOOST_CHECK(std::string(e.what()).find(strprintf("RunCommandParseJSON error: process(%s) returned 1: \n", command)) != std::string::npos);
            return true;
        });
    }
    {
        // Return non-zero exit code, with error message for stderr
#ifdef WIN32
        const std::string command{"cmd.exe /c dir nosuchfile"};
        const std::string expected{"File Not Found"};
#else
        const std::string command{"ls nosuchfile"};
        const std::string expected{"No such file or directory"};
#endif
        BOOST_CHECK_EXCEPTION(RunCommandParseJSON(command), std::runtime_error, [&](const std::runtime_error& e) {
            const std::string what(e.what());
            BOOST_CHECK(what.find(strprintf("RunCommandParseJSON error: process(%s) returned", command)) != std::string::npos);
            BOOST_CHECK(what.find(expected) != std::string::npos);
            return true;
        });
    }
    {
        BOOST_REQUIRE_THROW(RunCommandParseJSON("echo \"{\""), std::runtime_error); // Unable to parse JSON
    }
    // Test std::in, except for Windows
#ifndef WIN32
    {
        const UniValue result = RunCommandParseJSON("cat", "{\"success\": true}");
        BOOST_CHECK(result.isObject());
        const UniValue& success = find_value(result, "success");
        BOOST_CHECK(!success.isNull());
        BOOST_CHECK_EQUAL(success.getBool(), true);
    }
#endif
}
#endif // ENABLE_EXTERNAL_SIGNER

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: apokalyzr/bitcoin

max_issues_repo_name: apokalyzr/bitcoin

max_forks_repo_name: apokalyzr/bitcoin


text:
//  Copyright (c) 2007-2015 Hartmut Kaiser
//
//  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)

/// \file parallel/executors/service_executors.hpp

#if !defined(HPX_PARALLEL_EXECUTORS_SERVICE_EXECUTORS_MAY_15_2015_0548PM)
#define HPX_PARALLEL_EXECUTORS_SERVICE_EXECUTORS_MAY_15_2015_0548PM

#include <hpx/config.hpp>
#include <hpx/parallel/config/inline_namespace.hpp>
#include <hpx/parallel/executors/executor_traits.hpp>
#include <hpx/parallel/executors/detail/thread_executor.hpp>
#include <hpx/runtime/threads/executors/service_executors.hpp>
#include <hpx/util/move.hpp>

#include <type_traits>

#include <boost/detail/scoped_enum_emulation.hpp>

namespace hpx { namespace parallel { HPX_INLINE_NAMESPACE(v3)
{
    ///////////////////////////////////////////////////////////////////////////
    /// \brief The type of the HPX thread pool to use for a given service_executor
    ///
    /// This enum type allows to specify the kind of the HPX thread pool to use
    /// for a given \a service_executor.
    BOOST_SCOPED_ENUM_START(service_executor_type)
    {
        io_thread_pool,        ///< Selects creating a service executor using the I/O pool of threads
        parcel_thread_pool,    ///< Selects creating a service executor using the parcel pool of threads
        timer_thread_pool,     ///< Selects creating a service executor using the timer pool of threads
        main_thread            ///< Selects creating a service executor using the main thread
    };
    BOOST_SCOPED_ENUM_END

    namespace detail
    {
        /// \cond NOINTERNAL
        inline threads::executor
        get_service_executor(BOOST_SCOPED_ENUM(service_executor_type) t)
        {
            switch(t)
            {
            case service_executor_type::io_thread_pool:
                return threads::executors::io_pool_executor();

            case service_executor_type::parcel_thread_pool:
                return threads::executors::parcel_pool_executor();

            case service_executor_type::timer_thread_pool:
                return threads::executors::timer_pool_executor();

            case service_executor_type::main_thread:
                return threads::executors::main_pool_executor();

            default:
                break;
            }

            HPX_THROW_EXCEPTION(bad_parameter,
                "hpx::parallel::v3::detail::get_service_executor",
                "unknown pool executor type");
        }
        /// \endcond
    }

    /// A \a service_executor exposes one of the predefined HPX thread pools
    /// through an executor interface.
    ///
    /// \note All tasks executed by one of these executors will run on
    ///       one of the OS-threads dedicated for the given thread pool. The
    ///       tasks will not run a HPX-threads.
    ///
    struct service_executor
#if !defined(DOXYGEN)
      : detail::threads_executor
#endif
    {
        /// Create a new service executor for the given HPX thread pool
        ///
        /// \param t    [in] Specifies the HPX thread pool to encapsulate
        ///
        service_executor(BOOST_SCOPED_ENUM(service_executor_type) t)
          : threads_executor(detail::get_service_executor(t))
        {}
    };

    namespace detail
    {
        /// \cond NOINTERNAL
        template <>
        struct is_executor<service_executor>
          : std::true_type
        {};
        /// \endcond
    }
}}}

#endif

max_stars_repo_name: kempj/hpx

max_issues_repo_name: kempj/hpx

max_forks_repo_name: kempj/hpx


text:
#include <ConfigurationReader.h>
#include <IConfiguration.h>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/log/trivial.hpp>
#include <fstream>
#include <iostream>
#include <vector>

namespace pt = boost::property_tree;
using namespace neneta::conf;

struct ConfigurationReader::ConfigImpl
{
    pt::ptree m_configCache;
};

ConfigurationReader::ConfigurationReader()
    : m_configImpl(std::make_shared<ConfigurationReader::ConfigImpl>())
{
}

ConfigurationReader::ConfigurationReader(const IConfiguration& conf)
    : m_configImpl(std::make_shared<ConfigurationReader::ConfigImpl>())
{
    pt::read_xml(conf.getConfigurationFilename(), m_configImpl->m_configCache, pt::xml_parser::trim_whitespace);
}

ConfigurationReader::ConfigurationReader(const std::string& configuration)
    : m_configImpl(std::make_shared<ConfigurationReader::ConfigImpl>())
{
    std::stringstream ss;
    ss << configuration;
    pt::read_xml(ss, m_configImpl->m_configCache,  pt::xml_parser::trim_whitespace);
}

ConfigurationReader& ConfigurationReader::operator=(const std::string& configuration)
{
    std::stringstream ss;
    ss << configuration;
    pt::read_xml(ss, m_configImpl->m_configCache,  pt::xml_parser::trim_whitespace);
    return *this;
}

double ConfigurationReader::getDoubleParameter(const std::string& parameterName) const
{
    double rv = 0.0;
    try
    {
        rv = m_configImpl->m_configCache.get<double>(parameterName);
    }
    catch(...)
    {

    }
    return rv;
}

std::int32_t ConfigurationReader::getInt32Parameter(const std::string& parameterName) const
{
    std::int32_t rv = -1;
    try
    {
        rv = m_configImpl->m_configCache.get<std::int32_t>(parameterName);
    }
    catch(...)
    {

    }
    return rv;
}

std::string ConfigurationReader::getStringParameter(const std::string& parameterName) const
{
    std::string rv;
    try
    {
        rv = m_configImpl->m_configCache.get<std::string>(parameterName);
    }
    catch(...)
    {

    }
    return rv;
}

std::string ConfigurationReader::getStringAttribute(const std::string& parameterName, const std::string& attributeName) const
{
    std::string rv;
    try
    {
        rv = m_configImpl->m_configCache.get<std::string>(parameterName+".<xmlattr>."+attributeName);
    }
    catch(...)
    {

    }
    return rv;
}

bool ConfigurationReader::getBooleanParameter(const std::string &parameterName) const
{
    bool rv;
    try
    {
        rv = m_configImpl->m_configCache.get<bool>(parameterName);
    }
    catch(...)
    {

    }
    return rv;
}

std::vector<ConfigurationReader> ConfigurationReader::getSiblingsConfiguration(const std::string& siblingsPath, const std::string& siblingName) const
{
    std::vector<ConfigurationReader> result;
    try
    {
        pt::ptree siblings = m_configImpl->m_configCache.get_child(siblingsPath);

        for(const auto& sibling : siblings)
        {
            if(sibling.first == siblingName)
            {
                pt::ptree kconf;
                kconf.add_child(siblingName, sibling.second);
                std::ostringstream oss;
                pt::write_xml(oss, kconf);
                result.emplace_back(oss.str());
            }
        }
    }
    catch(...)
    {

    }
    return result;
}

std::vector<ConfigurationReader> ConfigurationReader::getSiblingsConfiguration(const std::string& siblingsPath, const std::string& siblingName,
                                                                               const std::string& attributeName, const std::string& attributeValue) const
{
    std::vector<ConfigurationReader> result;
    try
    {
        pt::ptree siblings = m_configImpl->m_configCache.get_child(siblingsPath);

        for(const auto& sibling : siblings)
        {
            if(sibling.first == siblingName)
            {
                pt::ptree kconf;
                kconf.add_child(siblingName, sibling.second);
                std::ostringstream oss;
                pt::write_xml(oss, kconf);
                if(kconf.get<std::string>(siblingName+".<xmlattr>."+attributeName) == attributeValue)
                {
                    result.emplace_back(oss.str());
                }
            }
        }
    }
    catch(...)
    {

    }
    return result;
}

ConfigurationReader ConfigurationReader::getSiblingConfiguration(const std::string& siblingsPath, const std::string& siblingName,
                                                                 const std::string& attributeName, const std::string& attributeValue) const
{
    ConfigurationReader result;
    try
    {
        pt::ptree siblings = m_configImpl->m_configCache.get_child(siblingsPath);

        for(const auto& sibling : siblings)
        {
            if(sibling.first == siblingName)
            {
                pt::ptree kconf;
                kconf.add_child(siblingName, sibling.second);
                std::ostringstream oss;
                pt::write_xml(oss, kconf);
                if(kconf.get<std::string>(siblingName+".<xmlattr>."+attributeName) == attributeValue)
                {
                    result = oss.str();
                    break;
                }
            }
        }
    }
    catch(...)
    {

    }
    return result;
}

ConfigurationReader ConfigurationReader::getSiblingConfiguration(const std::string& siblingsPath, const std::string& siblingName,
                                                                 const std::string& attribute1Name, const std::string& attribute1Value,
                                                                 const std::string& attribute2Name, const std::string& attribute2Value) const
{
    ConfigurationReader result;
    try
    {
        pt::ptree siblings = m_configImpl->m_configCache.get_child(siblingsPath);

        for(const auto& sibling : siblings)
        {
            if(sibling.first == siblingName)
            {
                pt::ptree kconf;
                kconf.add_child(siblingName, sibling.second);
                std::ostringstream oss;
                pt::write_xml(oss, kconf);
                if(kconf.get<std::string>(siblingName+".<xmlattr>."+attribute1Name) == attribute1Value &&
                   kconf.get<std::string>(siblingName+".<xmlattr>."+attribute2Name) == attribute2Value)
                {
                    result = oss.str();
                    break;
                }
            }
        }
    }
    catch(...)
    {

    }
    return result;
}

max_stars_repo_name: lekic-ai/neneta

max_issues_repo_name: lekic-ai/neneta

max_forks_repo_name: lekic-ai/neneta


text:
/**
 * Test suite for the `IncrementableIterator` concept.
 */

#include <duck/incrementable_iterator.hpp>

#include <boost/mpl/assert.hpp>
#include <vector>

#define ASSERT_II(T) BOOST_MPL_ASSERT((duck::is_incrementable_iterator<T>))
#define ASSERT_NOT_II(T) \
    BOOST_MPL_ASSERT_NOT((duck::is_incrementable_iterator<T>))

// Test with primitive types.
ASSERT_II(int);
ASSERT_II(int&);
ASSERT_II(int*);
ASSERT_II(int const*);
ASSERT_NOT_II(int const);
ASSERT_NOT_II(int const&);
ASSERT_NOT_II(int* const);
ASSERT_NOT_II(int&&);
ASSERT_NOT_II(int const&&);

// Test with a sample iterator.
ASSERT_II(std::vector<int>::iterator);

max_stars_repo_name: ldionne/duck

max_issues_repo_name: ldionne/duck

max_forks_repo_name: ldionne/duck


text:
#include <iostream>

#include "gtest/gtest.h"

#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/filesystem.hpp>

TEST(BoostTidbitsTests, simpleDateConstruction) {
    boost::gregorian::date d{ 1986, 9, 15 };

    EXPECT_EQ(1986, d.year());
}

TEST(BoostTidbitsTests, currentPath) {
    boost::filesystem::path path = boost::filesystem::current_path();
    std::string cwd = path.string();
    int index = cwd.find("test");
    EXPECT_GT(index, 0);
}

max_stars_repo_name: ctarrington/try-c

max_issues_repo_name: ctarrington/try-c

max_forks_repo_name: ctarrington/try-c


text:
/**
 * This file is part of the twosome package.
 *
 * (c) Azat Khuzhin <a3at.mail@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#include "chatclient.h"
#include "util/log.h"

#include <functional>
#include <boost/asio/ip/basic_resolver.hpp>
#include <boost/asio/write.hpp>
#include <boost/asio/read.hpp>
#include <boost/asio/read_until.hpp>

namespace PlaceHolders = std::placeholders;
namespace Ip = boost::asio::ip;
namespace Sctp = boost::asio_sctp;

ChatClient::ChatClient(const Options &options, boost::asio::io_service &ioService)
    : m_options(options)
    , m_messageBuffer(Session::MAX_BUFFER_LENGTH)
    , m_inputBuffer(Session::MAX_BUFFER_LENGTH)
    , m_input(ioService, ::dup(STDIN_FILENO))
    , m_output(ioService, ::dup(STDOUT_FILENO))
    , m_ioService(ioService)
    , m_socket(ioService)
{
    memset(m_buffer, 0, Session::MAX_BUFFER_LENGTH);

    Sctp::ip::sctp::resolver resolver(ioService);
    Sctp::ip::sctp::resolver_query query(options.ip, options.port);

    connectAsyncNext(resolver.resolve(query));
}

void ChatClient::send(const std::string& message)
{
    m_ioService.post(std::bind(&ChatClient::asyncWrite, this, message));
}

void ChatClient::close()
{
    LOG(info) << "Leaving";
    m_socket.close();
    m_input.close();
    m_output.close();
}

void ChatClient::handleConnect(const boost::system::error_code& error,
                               Sctp::ip::sctp::resolver_iterator iterator)
{
    if (error) {
        LOG(info) << "Connect error";
        close();
        connectAsyncNext(iterator);
        return;
    }

    asyncRead();
    asyncReadFromStdin();
}

void ChatClient::connectAsyncNext(Sctp::ip::sctp::resolver_iterator iterator)
{
    m_socket.async_connect(*iterator,
                           std::bind(&ChatClient::handleConnect, this,
                                      PlaceHolders::_1, ++iterator));
}

void ChatClient::handleRead(const boost::system::error_code& error,
                            size_t length)
{
    if (error) {
        LOG(info) << "Read error";
        close();
        return;
    }

    m_messageBuffer.sgetn(m_buffer, length);
    writeOutputPrompt();
    std::cout << m_buffer << std::flush;
    writeInputPrompt();

    asyncRead();
}

void ChatClient::handleReadInput(const boost::system::error_code& error,
                                 size_t length)
{
    if (error) {
        close();
        return;
    }

    m_inputBuffer.sgetn(m_buffer, length);
    asyncWrite(m_buffer);
}

void ChatClient::handleWrite(const boost::system::error_code& error)
{
    if (error) {
        LOG(info) << "Write error";
        close();
        return;
    }

    asyncReadFromStdin();
}

void ChatClient::asyncRead()
{
    boost::asio::async_read_until(m_socket, m_messageBuffer, '\n',
                                  std::bind(&ChatClient::handleRead, this,
                                            PlaceHolders::_1, PlaceHolders::_2));
}

void ChatClient::asyncReadFromStdin()
{
    writeInputPrompt();
    boost::asio::async_read_until(m_input, m_inputBuffer, '\n',
                                  std::bind(&ChatClient::handleReadInput, this,
                                            PlaceHolders::_1, PlaceHolders::_2));
}

void ChatClient::asyncWrite(const std::string& message)
{
    boost::asio::async_write(m_socket,
                             boost::asio::buffer(message.c_str(), message.size()),
                             std::bind(&ChatClient::handleWrite, this,
                                       PlaceHolders::_1));
}

max_stars_repo_name: shadansari/twosome

max_issues_repo_name: shadansari/twosome

max_forks_repo_name: shadansari/twosome