text:
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE KtlLoggerTest
#include <boost/test/unit_test.hpp>
#include "boost-taef.h"

#include "Stdafx.h"

#include <ktl.h>
#include <ktrace.h>
#include <ktllogger.h>

#include "KtlLoggerTests.h"

#define ALLOCATION_TAG 'LLT'

namespace KtlPhysicalLogTest
{
    // All tests run in User mode

    //
    // Kernel mode only tests
    //
    class KtlLoggerTests
    {
    public:
        KtlLoggerTests()
        {
            Setup();
        }

        ~KtlLoggerTests()
        {
            Cleanup();
        }

        NTSTATUS FindDiskIdForDriveLetter(
                UCHAR& DriveLetter,
                GUID& DiskIdGuid
        )
        {
            return(::FindDiskIdForDriveLetter(DriveLetter, DiskIdGuid));
        }

        bool Setup()
        {
            ::SetupTests(_diskId,
                         _driveLetter,
                         _LogManagerCount,
                         _logManagers,
                         _startingAllocs,
                         _system);

            return true;
        }

        bool Cleanup()
        {
            ::CleanupTests(_diskId,
                           _LogManagerCount,
                           _logManagers,
                           _startingAllocs,
                           _system);

            return true;
        }

    public:
        const static int _LogManagerCount = 16;

        KGuid _diskId;
        UCHAR _driveLetter;
        KtlLogManager::SPtr _logManagers[_LogManagerCount];
        ULONGLONG _startingAllocs;
        KtlSystem* _system;
    };

    BOOST_FIXTURE_TEST_SUITE(KtlLoggerTestsSuite, KtlLoggerTests)

    BOOST_AUTO_TEST_CASE(CorruptedLCMBInfoTest)
    {
        ::CorruptedLCMBInfoTest(_driveLetter, _logManagers[0]);
    }

    BOOST_AUTO_TEST_CASE(PartialContainerCreateTest)
    {
        ::PartialContainerCreateTest(_driveLetter, _logManagers[0]);
    }

#if 0  // TODO: Re-enable when this can be made more reliable
    BOOST_AUTO_TEST_CASE(VerifySparseTruncateTest)
    {
        ::VerifySparseTruncateTest(_driveLetter, _logManagers[0]);
    }
#endif

    BOOST_AUTO_TEST_CASE(DeletedDedicatedLogTest)
    {
        ::DeletedDedicatedLogTest(_diskId, _logManagers[0]);
    }

    BOOST_AUTO_TEST_CASE(EnumContainersTest)
    {
        ::EnumContainersTest(_diskId, _logManagers[0]);
    }

    BOOST_AUTO_TEST_CASE(StreamMetadataTest)
    {
        ::StreamMetadataTest(_diskId, _logManagers[0]);
    }

    BOOST_AUTO_TEST_CASE(CloseOpenRaceTest)
    {
        ::CloseOpenRaceTest(_diskId, _logManagers[0]);
    }

    BOOST_AUTO_TEST_CASE(OpenRightAfterCloseTest)
    {
        ::OpenRightAfterCloseTest(_diskId, _logManagers[0]);
    }

    BOOST_AUTO_TEST_CASE(QueryRecordsTest)
    {
        ::QueryRecordsTest(_diskId, _logManagers[0]);
    }

#if defined(UDRIVER) || defined(UPASSTHROUGH)
    BOOST_AUTO_TEST_CASE(OpenWriteCloseTest)
    {
        ::OpenWriteCloseTest(_diskId, _logManagers[0]);
    }
#endif
#ifdef UDRIVER
    BOOST_AUTO_TEST_CASE(FailCoalesceFlushTest)
    {
        ::FailCoalesceFlushTest(_diskId, _logManagers[0]);
    }
#endif

    BOOST_AUTO_TEST_CASE(ManyKIoBufferElementsTest)
    {
        ::ManyKIoBufferElementsTest(_diskId, _logManagers[0]);
    }

    BOOST_AUTO_TEST_CASE(CloseTest)
    {
        ::CloseTest(_diskId, _logManagers[0]);
    }

    BOOST_AUTO_TEST_CASE(ThresholdTest)
    {
        ::ThresholdTest(_diskId, _logManagers[0]);
    }

    BOOST_AUTO_TEST_CASE(CancelStressTest)
    {
        ::CancelStressTest(2,       // Number loops
                           64,      // Number Asyncs
                           _diskId, _logManagers[0]);
    }

    BOOST_AUTO_TEST_CASE(DeleteOpenStreamTest)
    {
        ::DeleteOpenStreamTest(_diskId, _logManagers[0]);
    }

    BOOST_AUTO_TEST_CASE(DLogReservationTest)
    {
        ::DLogReservationTest(_diskId, _logManagers[0]);
    }

    BOOST_AUTO_TEST_SUITE_END()

#if defined(UDRIVER) || defined(UPASSTHROUGH)
    class MetadataBlockInfoTests
    {
    public:
        MetadataBlockInfoTests()
        {
            Setup();
        }

        ~MetadataBlockInfoTests()
        {
            Cleanup();
        }

        bool Setup()
        {
            ::SetupMBInfoTests(_diskId,
                               _startingAllocs,
                               _system);

            return true;
        }

        bool Cleanup()
        {
            ::CleanupMBInfoTests(_diskId,
                               _startingAllocs,
                                 _system);

            return true;
        }

    public:
        KGuid _diskId;
        KtlSystem* _system;
        ULONGLONG _startingAllocs;
    };

    BOOST_FIXTURE_TEST_SUITE(MetadataBlockInfoTestsSuite, MetadataBlockInfoTests)

    BOOST_AUTO_TEST_CASE(BasicMBInfoTest)
    {
        ::BasicMBInfoTest(_diskId,
                          1,              // Loops
                          16,             // Number blocks
                          0x4000);        // Block Size
    }

    BOOST_AUTO_TEST_CASE(BasicMBInfoDataIntegrityTest)
    {
        ::BasicMBInfoDataIntegrityTest(_diskId);
    }

    BOOST_AUTO_TEST_CASE(FailOpenCorruptedMBInfoTest)
    {
        ::FailOpenCorruptedMBInfoTest(_diskId);
    }

    BOOST_AUTO_TEST_CASE(SharedLCMBInfoTest)
    {
        ::SharedLCMBInfoTest(_diskId,
                          1,              // Loops
                          0x800);         // Number entries
    }

    BOOST_AUTO_TEST_CASE(DedicatedLCMBInfoTest)
    {
        ::DedicatedLCMBInfoTest(_diskId,
                                1);              // Loops
    }

    BOOST_AUTO_TEST_SUITE_END()
#endif  // UDRIVER

#if defined(UDRIVER) || defined(UPASSTHROUGH)
    //
    // RAW Core logger tests
    //
    class RawCoreLoggerTests
    {
    public:
        KGuid _diskId;
        ULONGLONG _startingAllocs;
        KtlSystem* _system;

    public:
        RawCoreLoggerTests()
        {
            Setup();
        }

        ~RawCoreLoggerTests()
        {
            Cleanup();
        }

        bool Setup()
        {
            ::SetupRawCoreLoggerTests(_diskId,
                                      _startingAllocs,
                                      _system);

            return true;
        }

        bool Cleanup()
        {
            ::CleanupRawCoreLoggerTests(_diskId,
                                        _startingAllocs,
                                        _system);

            return true;
        }
    };

    BOOST_FIXTURE_TEST_SUITE(RawCoreLoggerTestsSuite, RawCoreLoggerTests)

    BOOST_AUTO_TEST_CASE(TruncateToBadLogLowLsnTest)
    {
        ::TruncateToBadLogLowLsnTest(_diskId);
    }

    BOOST_AUTO_TEST_CASE(StreamCheckpointBoundaryTest)
    {
        ::StreamCheckpointBoundaryTest(_diskId);
    }

    BOOST_AUTO_TEST_CASE(QueryLogTypeTest)
    {
        ::QueryLogTypeTest(_diskId);
    }

    BOOST_AUTO_TEST_CASE(DeleteRecordsTest)
    {
        ::DeleteRecordsTest(_diskId);
    }

    BOOST_AUTO_TEST_CASE(StreamCheckpointAtEndOfLogTest)
    {
        ::StreamCheckpointAtEndOfLogTest(_diskId);
    }

    BOOST_AUTO_TEST_SUITE_END()
#endif // UDRIVER

#if defined(UDRIVER) || defined(UPASSTHROUGH)
    class OverlayLogTests
    {
    public:
        OverlayLogTests()
        {
            Setup();
        }

        ~OverlayLogTests()
        {
            Cleanup();
        }

        bool Setup()
        {
            ::SetupOverlayLogTests(_diskId,
                                   _startingAllocs,
                                   _system);

            return true;
        }

        bool Cleanup()
        {
            ::CleanupOverlayLogTests(_diskId,
                                     _startingAllocs,
                                     _system);

            return true;
        }

    public:
        //
        // Disable these for now as the implementation of
        // MultiRecordRead has changed and these scenarios will not be
        // hit. At some point we may want to delete them, but not yet.
        //
        KGuid _diskId;
        ULONGLONG _startingAllocs;
        KtlSystem* _system;

    };

    BOOST_FIXTURE_TEST_SUITE(OverlayLogTestsSuite, OverlayLogTests)

    BOOST_AUTO_TEST_CASE(PeriodicTimerCloseRaceTest)
    {
        ::PeriodicTimerCloseRaceTest(_diskId);
    }

    BOOST_AUTO_TEST_CASE(RecoveryPartlyCreatedStreamTest)
    {
        ::RecoveryPartlyCreatedStreamTest(_diskId);

    }

    BOOST_AUTO_TEST_CASE(StreamQuotaTest)
    {
        ::StreamQuotaTest(_diskId);
    }

    BOOST_AUTO_TEST_CASE(RetryOnSharedLogFullTest)
    {
        ::StreamQuotaTest(_diskId);
    }

    BOOST_AUTO_TEST_CASE(ThrottledAllocatorTest)
    {
        ::ThrottledAllocatorTest(_diskId);
    }

    BOOST_AUTO_TEST_CASE(VerifySharedTruncateOnDedicatedFailureTest)
    {
        ::VerifySharedTruncateOnDedicatedFailureTest(_diskId);
    }

    BOOST_AUTO_TEST_CASE(FlushAllRecordsForCloseWaitTest)
    {
        ::FlushAllRecordsForCloseWaitTest(_diskId);
    }

    BOOST_AUTO_TEST_CASE(WriteStuckConditionsTest)
    {
        ::WriteStuckConditionsTest(_diskId);
    }

    BOOST_AUTO_TEST_CASE(WriteThrottleUnitTest)
    {
        ::WriteThrottleUnitTest(_diskId);
    }

    BOOST_AUTO_TEST_CASE(ReadFromCoalesceBuffersCornerCase1Test)
    {
        ::ReadFromCoalesceBuffersCornerCase1Test(_diskId);
    }

    BOOST_AUTO_TEST_CASE(ReadFromCoalesceBuffersTruncateTailTest)
    {
        ::ReadFromCoalesceBuffersTruncateTailTest(_diskId);
    }

#if 0   // Enable when ktl package 23 is checked in
    BOOST_AUTO_TEST_CASE(ReadWriteRaceTest)
    {
        ::ReadWriteRaceTest(_diskId);
    }
#endif
    BOOST_AUTO_TEST_SUITE_END()

#endif // UDRIVER

#ifdef UDRIVER
    //
    // NOTE: This MUST be the last test in the list as the test does not cleanup properly, by design
    //
    class KtlLoggerMiscTests
    {
    public:
        KtlLoggerMiscTests()
        {
            Setup();
        }

        ~KtlLoggerMiscTests()
        {
            Cleanup();
        }

        bool Setup()
        {
            ::SetupMiscTests(_diskId,
                             _driveLetter,
                             _startingAllocs,
                             _system);

            return true;
        }

        bool Cleanup()
        {
            ::CleanupMiscTests(_diskId,
                               _startingAllocs,
                               _system);

            return true;
        }

    public:
        KGuid _diskId;
        UCHAR _driveLetter;
        ULONGLONG _startingAllocs;
        KtlSystem* _system;
    };

    BOOST_FIXTURE_TEST_SUITE(KtlLoggerMiscTestsSuite, KtlLoggerMiscTests)

    BOOST_AUTO_TEST_CASE(ForceCloseTest)
    {
        ::ForceCloseTest(_diskId);
    }

    BOOST_AUTO_TEST_CASE(ForceCloseOnDeleteContainerWaitTest)
    {
        ::ForceCloseOnDeleteContainerWaitTest(_diskId);
    }
    BOOST_AUTO_TEST_SUITE_END()
#endif
}

max_stars_repo_name: AnthonyM/service-fabric

max_issues_repo_name: AnthonyM/service-fabric

max_forks_repo_name: AnthonyM/service-fabric


text:
////////////////////////////////////////////////////////////////////////////////
// distribution::toolkit::distributions::exponential::log_unnormalized_pdf.hpp //
//                                                                            //
//  (C) Copyright 2009 Erwann Rogard                                          //
//  Use, modification and distribution are subject to the                     //
//  Boost Software License, Version 1.0. (See accompanying file               //
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)          //
////////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_EXPONENTIAL_LOG_UNNORMALIZED_PDF_HPP_ER_2009
#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_EXPONENTIAL_LOG_UNNORMALIZED_PDF_HPP_ER_2009
#include <string>
#include <boost/math/distributions/exponential.hpp>
#include <boost/math/policies/policy.hpp>

namespace boost{
namespace math{

    template<typename T,typename P>
    T
    log_unnormalized_pdf(
        const boost::math::exponential_distribution<T,P>& d,
        const T& x
    ){

        typedef std::string str_;
        BOOST_MATH_STD_USING // for ADL of std functions
        static const char* function =
            (str_("log_unnormalized_pdf(")+
            "const exponential_distribution<%1%>&,%1%)").c_str();

        T lambda = d.lambda();
        T result;

        if(0 == boost::math::detail::verify_lambda(
            function, lambda, &result, P()))
            return result;
        if(0 == boost::math::detail::verify_exp_x(
            function, x, &result, P()))
            return result;
        result = (-lambda * x);
        return result;
    }

}// math
}// boost

#endif

ext: hpp


text:
// It is extremely important to use this header
// if you are using the numpy_eigen interface
#include <numpy_eigen/boost_python_headers.hpp>
#include <boost/shared_ptr.hpp>

#include <aslam/backend/ScalarDesignVariable.hpp>
#include <aslam/backend/ErrorTermObservation.hpp>
#include <aslam/backend/ErrorTermMotion.hpp>
#include <aslam/backend/ErrorTermPrior.hpp>

// The title of this library must match exactly the title of the produced library
BOOST_PYTHON_MODULE(libaslam_backend_tutorial_python)
{
  // Here we have to export the design variables and error terms used in this problem.
  // The aslam_python library exports the interface of the base classes so we
  // leverage this work by pointing the boost::python wrapper at these base classes.

  using namespace boost::python;
  using namespace aslam::backend;

  class_<
    // The first template argument is the class we are wrapping.
    ScalarDesignVariable,
    // This tells boost::python so wrap this class as a boost shared
    // pointer. While this is not strictly required, it does help as
    // it will allow us to pass objects from python to the OptimizationProblem
    // as boost shared pointers.
    boost::shared_ptr<ScalarDesignVariable>,
    // This template argument tells boost::python to inherit the interface of
    // DesignVariable.
    bases<DesignVariable>
    >("ScalarDesignVariable", // <-- this sets the name of the class in Python
      init<double>("ScalarDesignVariable( initialValue )")) // <-- Here we tell python that the default constructor takes a double. The string is for documentation.
    .def("value", &ScalarDesignVariable::value) // <-- And here we export methods specific to this class.
    ;

class_<ErrorTermObservation, boost::shared_ptr<ErrorTermObservation>, bases<ErrorTerm> >
("ErrorTermObservation",
 init<ScalarDesignVariable *,ScalarDesignVariable *,double,double>("ErrorTermObservation(ScalarDesignVariable x_k, ScalarDesignVariable w, double y, double sigma2_n)"))
;

class_<ErrorTermMotion, boost::shared_ptr<ErrorTermMotion>, bases<ErrorTerm> >
("ErrorTermMotion",
 init<ScalarDesignVariable *,ScalarDesignVariable *,double,double>("ErrorTermMotion(ScalarDesignVariable x_k, ScalarDesignVariable x_kp1, double u, double sigma2_u)"))
;

class_<ErrorTermPrior, boost::shared_ptr<ErrorTermPrior>, bases<ErrorTerm> >
("ErrorTermPrior",
 init<ScalarDesignVariable *,double,double>("ErrorTermPrior(ScalarDesignVariable * x, double hat_x, double sigma2_x)"))
;

}

ext: cpp


text:
//
// Config.cpp
//

#include "Config.hpp"
#include <boost/filesystem.hpp>
#include <stdint.h>

using namespace boost::filesystem;

const char* Config::CONFIG_JSON = "./config.json";

namespace {
    using boost::property_tree::ptree;

	void MergePtree(ptree* dst,
		const ptree& source,
		const ptree::path_type& current_path = ptree::path_type(""))
	{
		BOOST_FOREACH(const auto& tree, source) {
			if (!tree.first.empty()) {
				auto new_path = current_path;
				new_path /= tree.first;
				if (tree.second.empty() || tree.second.front().first.empty()) {
					if (!dst->get_child_optional(new_path)) {
						dst->put_child(new_path, tree.second);
					}
				} else {
					MergePtree(dst, tree.second, new_path);
				}
			}
		}
	}
};

Config::Config()
{
	Load();
}

void Config::Load()
{

	try {
		std::ifstream ifs;
		ifs.open(CONFIG_JSON);
		read_json(ifs, pt_);
	} catch(std::exception& e) {
		Logger::Error(unicode::ToTString(e.what()));
	}

    port_ =             pt_.get<uint16_t>("port", 39390);
    server_name_ =		pt_.get<std::string>("server_name", "MMO Server");
    server_note_ =		pt_.get<std::string>("server_note", "");
	stage_ =			pt_.get<std::string>("stage", unicode::ToString(_T("stage:ケロリン町")));
    capacity_ =			pt_.get<int>("capacity", 20);

	public_ =			pt_.get<bool>("public", false);

	receive_limit_1_ =	pt_.get<int>("receive_limit_1", 60);
	receive_limit_2_ =	pt_.get<int>("receive_limit_2", 100);

	auto patterns =		pt_.get_child("blocking_address_patterns", ptree());
	BOOST_FOREACH(const auto& item, patterns) {
		blocking_address_patterns_.push_back(item.second.get_value<std::string>());
	}

	auto lobby_servers = pt_.get_child("lobby_servers", ptree());
	BOOST_FOREACH(const auto& item, lobby_servers) {
		lobby_servers_.push_back(item.second.get_value<std::string>());
	}

	if (exists(CONFIG_JSON)) {
		timestamp_ = last_write_time(CONFIG_JSON);
	}
}

void Config::Reload()
{
	if (exists(CONFIG_JSON) &&
		timestamp_ < last_write_time(CONFIG_JSON)) {
		Config::Load();
		Logger::Info(_T("Configuration reloaded."));
	}
}

//
// アクセサ
//

uint16_t Config::port() const
{
	return port_;
}

const std::string& Config::server_name() const
{
    return server_name_;
}

const std::string& Config::server_note() const
{
    return server_note_;
}

bool Config::is_public() const
{
	return public_;
}

const std::string& Config::stage() const
{
    return stage_;
}

int Config::capacity() const
{
	return capacity_;
}

int Config::receive_limit_1() const
{
	return receive_limit_1_;
}

int Config::receive_limit_2() const
{
	return receive_limit_2_;
}

const std::list<std::string>& Config::blocking_address_patterns() const
{
	return blocking_address_patterns_;
}

const std::list<std::string>& Config::lobby_servers() const
{
	return lobby_servers_;
}

const boost::property_tree::ptree& Config::pt() const
{
	return pt_;
}


text:
// @file threadedtests.cpp - Tests for threaded code
//

/**
 *    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/>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the GNU Affero General Public License in all respects
 *    for all of the code used other than as permitted herein. If you modify
 *    file(s) with this exception, you may extend this exception to your
 *    version of the file(s), but you are not obligated to do so. If you do not
 *    wish to do so, delete this exception statement from your version. If you
 *    delete this exception statement from all source files in the program,
 *    then also delete it in the license file.
 */

#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kCommand

#include "mongo/platform/basic.h"

#include <boost/thread/barrier.hpp>
#include <boost/version.hpp>
#include <iostream>

#include "mongo/config.h"
#include "mongo/db/client.h"
#include "mongo/dbtests/dbtests.h"
#include "mongo/platform/atomic_word.h"
#include "mongo/platform/bits.h"
#include "mongo/stdx/functional.h"
#include "mongo/stdx/thread.h"
#include "mongo/util/concurrency/old_thread_pool.h"
#include "mongo/util/concurrency/ticketholder.h"
#include "mongo/util/log.h"
#include "mongo/util/timer.h"

namespace ThreadedTests {

using std::unique_ptr;
using std::cout;
using std::endl;
using std::string;

template <int nthreads_param = 10>
class ThreadedTest {
public:
    virtual void setup() {}                     // optional
    virtual void subthread(int remaining) = 0;  // each thread whatever test work you want done
    virtual void validate() = 0;                // after work is done

    static const int nthreads = nthreads_param;

    void run() {
        setup();
        launch_subthreads(nthreads);
        validate();
    }

    virtual ~ThreadedTest(){};  // not necessary, but makes compilers happy

private:
    void launch_subthreads(int remaining) {
        if (!remaining)
            return;

        stdx::thread athread(stdx::bind(&ThreadedTest::subthread, this, remaining));
        launch_subthreads(remaining - 1);
        athread.join();
    }
};

template <typename _AtomicUInt>
class IsAtomicWordAtomic : public ThreadedTest<> {
    static const int iterations = 1000000;
    typedef typename _AtomicUInt::WordType WordType;
    _AtomicUInt target;

    void subthread(int) {
        for (int i = 0; i < iterations; i++) {
            target.fetchAndAdd(WordType(1));
        }
    }
    void validate() {
        ASSERT_EQUALS(target.load(), unsigned(nthreads * iterations));

        _AtomicUInt u;
        ASSERT_EQUALS(0u, u.load());
        ASSERT_EQUALS(0u, u.fetchAndAdd(WordType(1)));
        ASSERT_EQUALS(2u, u.addAndFetch(WordType(1)));
        ASSERT_EQUALS(2u, u.fetchAndSubtract(WordType(1)));
        ASSERT_EQUALS(0u, u.subtractAndFetch(WordType(1)));
        ASSERT_EQUALS(0u, u.load());

        u.fetchAndAdd(WordType(1));
        ASSERT_GREATER_THAN(u.load(), WordType(0));

        u.fetchAndSubtract(WordType(1));
        ASSERT_NOT_GREATER_THAN(u.load(), WordType(0));
    }
};

class ThreadPoolTest {
    static const unsigned iterations = 10000;
    static const unsigned nThreads = 8;

    AtomicUInt32 counter;
    void increment(unsigned n) {
        for (unsigned i = 0; i < n; i++) {
            counter.fetchAndAdd(1);
        }
    }

public:
    void run() {
        OldThreadPool tp(nThreads);

        for (unsigned i = 0; i < iterations; i++) {
            tp.schedule(&ThreadPoolTest::increment, this, 2);
        }

        tp.join();

        ASSERT_EQUALS(counter.load(), iterations * 2);
    }
};

void sleepalittle() {
    Timer t;
    while (1) {
        stdx::this_thread::yield();
        if (t.micros() > 8)
            break;
    }
}

int once;

/* This test is to see how long it takes to get a lock after there has been contention -- the OS
   will need to reschedule us. if a spinlock, it will be fast of course, but these aren't spin
   locks. Experimenting with different # of threads would be a good idea.
*/
template <class whichmutex, class scoped>
class Slack : public ThreadedTest<17> {
public:
    Slack() {
        k.store(0);
        done.store(false);
        a = b = 0;
        locks = 0;
    }

private:
    whichmutex m;
    char pad1[128];
    unsigned a, b;
    char pad2[128];
    unsigned locks;
    char pad3[128];
    AtomicInt32 k;

    virtual void validate() {
        if (once++ == 0) {
            // <= 1.35 we use a different rwmutex impl so worth noting
            cout << "Boost version : " << BOOST_VERSION << endl;
        }
        cout << typeid(whichmutex).name() << " Slack useful work fraction: " << ((double)a) / b
             << " locks:" << locks << endl;
    }
    void watch() {
        while (1) {
            b++;
            //__sync_synchronize();
            if (k.load()) {
                a++;
            }
            sleepmillis(0);
            if (done.load())
                break;
        }
    }
    AtomicBool done;
    virtual void subthread(int x) {
        if (x == 1) {
            watch();
            return;
        }
        Timer t;
        unsigned lks = 0;
        while (1) {
            scoped lk(m);
            k.store(1);
            // not very long, we'd like to simulate about 100K locks per second
            sleepalittle();
            lks++;
            if (done.load() || t.millis() > 1500) {
                locks += lks;
                k.store(0);
                break;
            }
            k.store(0);
            //__sync_synchronize();
        }
        done.store(true);
    }
};

// Tests waiting on the TicketHolder by running many more threads than can fit into the "hotel", but
// only max _nRooms threads should ever get in at once
class TicketHolderWaits : public ThreadedTest<10> {
    static const int checkIns = 1000;
    static const int rooms = 3;

public:
    TicketHolderWaits() : _hotel(rooms), _tickets(_hotel._nRooms) {}

private:
    class Hotel {
    public:
        Hotel(int nRooms) : _nRooms(nRooms), _checkedIn(0), _maxRooms(0) {}

        void checkIn() {
            stdx::lock_guard<stdx::mutex> lk(_frontDesk);
            _checkedIn++;
            verify(_checkedIn <= _nRooms);
            if (_checkedIn > _maxRooms)
                _maxRooms = _checkedIn;
        }

        void checkOut() {
            stdx::lock_guard<stdx::mutex> lk(_frontDesk);
            _checkedIn--;
            verify(_checkedIn >= 0);
        }

        stdx::mutex _frontDesk;
        int _nRooms;
        int _checkedIn;
        int _maxRooms;
    };

    Hotel _hotel;
    TicketHolder _tickets;

    virtual void subthread(int x) {
        string threadName = (str::stream() << "ticketHolder" << x);
        Client::initThread(threadName.c_str());

        for (int i = 0; i < checkIns; i++) {
            _tickets.waitForTicket();
            TicketHolderReleaser whenDone(&_tickets);

            _hotel.checkIn();

            sleepalittle();
            if (i == checkIns - 1)
                sleepsecs(2);

            _hotel.checkOut();

            if ((i % (checkIns / 10)) == 0)
                mongo::unittest::log() << "checked in " << i << " times..." << endl;
        }
    }

    virtual void validate() {
        // This should always be true, assuming that it takes < 1 sec for the hardware to process a
        // check-out/check-in Time for test is then ~ #threads / _nRooms * 2 seconds
        verify(_hotel._maxRooms == _hotel._nRooms);
    }
};

class All : public Suite {
public:
    All() : Suite("threading") {}

    void setupTests() {
        // Slack is a test to see how long it takes for another thread to pick up
        // and begin work after another relinquishes the lock.  e.g. a spin lock
        // would have very little slack.
        add<Slack<SimpleMutex, stdx::lock_guard<SimpleMutex>>>();

        add<IsAtomicWordAtomic<AtomicUInt32>>();
        add<IsAtomicWordAtomic<AtomicUInt64>>();
        add<ThreadPoolTest>();

        add<TicketHolderWaits>();
    }
};

SuiteInstance<All> myall;
}  // namespace ThreadedTests

max_stars_repo_name: mwhudson/mongo

max_issues_repo_name: mwhudson/mongo

max_forks_repo_name: mwhudson/mongo


text:
/*
	This file is part of solidity.

	solidity is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	solidity is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with solidity.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file JSON.cpp
 * @author Alexander Arlt <alexander.arlt@arlt-labs.com>
 * @date 2018
 */

#include <libsolutil/JSON.h>

#include <libsolutil/CommonIO.h>

#include <boost/algorithm/string/replace.hpp>

#include <sstream>
#include <map>
#include <memory>

using namespace std;

static_assert(
	(JSONCPP_VERSION_MAJOR == 1) && (JSONCPP_VERSION_MINOR == 9) && (JSONCPP_VERSION_PATCH == 2),
	"Unexpected jsoncpp version: " JSONCPP_VERSION_STRING ". Expecting 1.9.2."
);

namespace solidity::util
{

namespace
{

/// StreamWriterBuilder that can be constructed with specific settings
class StreamWriterBuilder: public Json::StreamWriterBuilder
{
public:
	explicit StreamWriterBuilder(map<string, Json::Value> const& _settings)
	{
		for (auto const& iter: _settings)
			this->settings_[iter.first] = iter.second;
	}
};

/// CharReaderBuilder with strict-mode settings
class StrictModeCharReaderBuilder: public Json::CharReaderBuilder
{
public:
	StrictModeCharReaderBuilder()
	{
		Json::CharReaderBuilder::strictMode(&this->settings_);
	}
};

/// Serialise the JSON object (@a _input) with specific builder (@a _builder)
/// \param _input JSON input string
/// \param _builder StreamWriterBuilder that is used to create new Json::StreamWriter
/// \return serialized json object
string print(Json::Value const& _input, Json::StreamWriterBuilder const& _builder)
{
	stringstream stream;
	unique_ptr<Json::StreamWriter> writer(_builder.newStreamWriter());
	writer->write(_input, &stream);
	return stream.str();
}

/// Parse a JSON string (@a _input) with specified builder (@ _builder) and writes resulting JSON object to (@a _json)
/// \param _builder CharReaderBuilder that is used to create new Json::CharReaders
/// \param _input JSON input string
/// \param _json [out] resulting JSON object
/// \param _errs [out] Formatted error messages
/// \return \c true if the document was successfully parsed, \c false if an error occurred.
bool parse(Json::CharReaderBuilder& _builder, string const& _input, Json::Value& _json, string* _errs)
{
	unique_ptr<Json::CharReader> reader(_builder.newCharReader());
	return reader->parse(_input.c_str(), _input.c_str() + _input.length(), &_json, _errs);
}

} // end anonymous namespace

string jsonPrettyPrint(Json::Value const& _input)
{
	static map<string, Json::Value> settings{{"indentation", "  "}, {"enableYAMLCompatibility", true}};
	static StreamWriterBuilder writerBuilder(settings);
	string result = print(_input, writerBuilder);
	boost::replace_all(result, " \n", "\n");
	return result;
}

string jsonCompactPrint(Json::Value const& _input)
{
	static map<string, Json::Value> settings{{"indentation", ""}};
	static StreamWriterBuilder writerBuilder(settings);
	return print(_input, writerBuilder);
}

bool jsonParseStrict(string const& _input, Json::Value& _json, string* _errs /* = nullptr */)
{
	static StrictModeCharReaderBuilder readerBuilder;
	return parse(readerBuilder, _input, _json, _errs);
}

} // namespace solidity::util

max_stars_repo_name: MrChico/solidity

max_issues_repo_name: MrChico/solidity


text:
/* -*-c++-*--------------------------------------------------------------------
 * 2018 Bernd Pfrommer bernd.pfrommer@gmail.com
 */

#include "tagslam/camera.h"
#include "tagslam/xml.h"
#include "tagslam/logging.h"

#include <ros/console.h>
#include <boost/range/irange.hpp>
#include <XmlRpcException.h>

namespace tagslam {
  using boost::irange;
  using std::string;

  CameraPtr
  Camera::parse_camera(const string &name, XmlRpc::XmlRpcValue config) {
    CameraPtr camPtr(new Camera());
    Camera &cam = *camPtr; // short hand
    cam.name_ = name;
    cam.intrinsics_ = CameraIntrinsics::parse(config);
    cam.imageTopic_ = xml::parse<string>(config, "rostopic");
    cam.tagTopic_   = xml::parse<string>(config, "tagtopic", "");
    cam.rigName_    = xml::parse<string>(config, "rig_body");
    cam.frameId_    = xml::parse<string>(config, "frameId", cam.name_);
    double wiggleR  = xml::parse<double>(config, "wiggle_rotation",   0.00001);
    double wiggleT  = xml::parse<double>(config, "wiggle_translation",0.00001);
    cam.wiggle_    = PoseNoise::make(wiggleR, wiggleT);
    return (camPtr);
  }

  CameraVec
  Camera::parse_cameras(XmlRpc::XmlRpcValue config) {
    CameraVec cdv;
    int cam_idx = 0;
    for (const auto cam_num: irange(0, 100)) {
      string name = "cam" + std::to_string(cam_num);
      if (!config.hasMember(name)) {
        name = "camera_" + std::to_string(cam_num);
        if (!config.hasMember(name)) {
        continue;
        }
      }
      try {
        CameraPtr camera = parse_camera(name, config[name]);
        camera->index_ = cam_idx++;
        cdv.push_back(camera);
      } catch (const XmlRpc::XmlRpcException &e) {
        ROS_ERROR_STREAM("got xmlrpc exception: " <<
                         e.getCode() << " " << e.getMessage());
        BOMB_OUT("error reading camera: " << name);
      }
    }
    return (cdv);
  }

}

max_stars_repo_name: Shuhei-YOSHIDA/tagslam

max_issues_repo_name: Shuhei-YOSHIDA/tagslam

max_forks_repo_name: Shuhei-YOSHIDA/tagslam


text:
///
/// @file
/// @copyright Copyright (C) 2017-2018, Jonathan Bryan Schmalhofer
///
/// @brief Node to cyclically publish buffered PNG images
///
#include <string>
#include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <boost/filesystem.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <algorithm>

// Source for GetFileList(): https://gist.github.com/vivithemage/9517678
std::vector<std::string> GetFileList(const std::string& path)
{
    std::vector<std::string> file_list;
    if (!path.empty())
    {
        boost::filesystem::path apk_path(path);
        boost::filesystem::recursive_directory_iterator end;

        for (boost::filesystem::recursive_directory_iterator i(apk_path); i != end; ++i)
        {
            const boost::filesystem::path cp = (*i);
            if (".png" == boost::filesystem::extension(cp.string()))
            {
                file_list.push_back(cp.string());
            }
        }
    }
    std::sort(file_list.begin(), file_list.end());
    return file_list;
}

int main(int argc, char **argv)
{
    ros::init(argc, argv, "airsim_to_ros_image_publisher_node");
    ros::NodeHandle node_handle;

    ROS_INFO("Starting node");

    image_transport::ImageTransport image_transport(node_handle);
    image_transport::Publisher left_stereoimage_chatter = image_transport.advertise("/airsim/left/image_raw", 1);
    image_transport::Publisher right_stereoimage_chatter = image_transport.advertise("/airsim/right/image_raw", 1);

    std::vector<std::string> left_file_list = GetFileList("/home/johnny/camera_calibration/left");
    std::vector<std::string> right_file_list = GetFileList("/home/johnny/camera_calibration/right");

    std::vector<sensor_msgs::Image> left_image_messages;
    std::vector<sensor_msgs::Image> right_image_messages;

    // Buffer left images
    for (auto image_path : left_file_list)
    {
        ROS_INFO("Reading left file %s: ", image_path.c_str());

        cv_bridge::CvImage cv_image;
        cv_image.image = cv::imread(image_path.c_str(), CV_LOAD_IMAGE_COLOR);
        cv_image.encoding = "bgr8";
        sensor_msgs::Image ros_image;
        cv_image.toImageMsg(ros_image);
        left_image_messages.push_back(ros_image);
    }

    // Buffer right images
    for (auto image_path : right_file_list)
    {
        ROS_INFO("Reading right file %s: ", image_path.c_str());

        cv_bridge::CvImage cv_image;
        cv_image.image = cv::imread(image_path.c_str(), CV_LOAD_IMAGE_COLOR);
        cv_image.encoding = "bgr8";
        sensor_msgs::Image ros_image;
        cv_image.toImageMsg(ros_image);
        right_image_messages.push_back(ros_image);
    }

    ros::Rate r(2.0); // 2.0 hz
    std::int32_t loop_counter = 0;
    std::int32_t loop_direction = +1;
    while (ros::ok())
    {
        if (loop_counter >= std::min(left_image_messages.size(), right_image_messages.size())-1)
        {
            ROS_INFO("Reverse direction");
            loop_direction = -1;
        }
        if (loop_counter <= 0)
        {
            ROS_INFO("Forward direction");
            loop_direction = +1;
        }

        ROS_INFO("Publishing %d: ", loop_counter);

        left_stereoimage_chatter.publish(left_image_messages.at(loop_counter));
        right_stereoimage_chatter.publish(right_image_messages.at(loop_counter));
        loop_counter += loop_direction;
        ros::spinOnce();
        r.sleep();
    }

    return 0;
}

max_stars_repo_name: JonathanSchmalhofer/RecursiveStereoUAV

max_issues_repo_name: JonathanSchmalhofer/RecursiveStereoUAV

max_forks_repo_name: JonathanSchmalhofer/RecursiveStereoUAV


text:
/*
 files.cpp

 Copyright (c) 2014 Terumasa Tadano

 This file is distributed under the terms of the MIT license.
 Please see the file 'LICENCE.txt' in the root directory
 or http://opensource.org/licenses/mit-license.php for information.
*/

#include <iostream>
#include "files.h"
#include "error.h"
#include "memory.h"
#include "interaction.h"
#include <boost/lexical_cast.hpp>

using namespace ALM_NS;

Files::Files(ALM *alm): Pointers(alm) {}
Files::~Files() {
    if (alm->mode == "fitting" || alm->mode == "lasso") {
//        closefiles();
    } else if (alm->mode == "suggest") {
        memory->deallocate(file_disp_pattern);
    }
}

void Files::setfilenames()
{
    int i;

    file_fcs = job_title + ".fcs";
    file_info = job_title + ".info";

    if (alm->mode == "suggest") {

        memory->allocate(file_disp_pattern, interaction->maxorder);

        for (i = 0; i < interaction->maxorder; ++i) {
            if (i == 0) {
                file_disp_pattern[i] = job_title + ".pattern_HARMONIC";
            } else {
                file_disp_pattern[i] = job_title + ".pattern_ANHARM" + boost::lexical_cast<std::string>(i+2);
            }
        }
    }
}

void Files::openfiles()
{
    ifs_disp.open(file_disp.c_str(), std::ios::in);
    if (!ifs_disp) error->exit("openfiles", "cannot open disp file");
    ifs_force.open(file_force.c_str(), std::ios::in);
    if (!ifs_force) error->exit("openfiles", "cannot open force file");
}

void Files::closefiles()
{
    ifs_disp.close();
    ifs_force.close();
}

void Files::init()
{
    setfilenames();
}

max_stars_repo_name: dlnguyen/alamode

max_issues_repo_name: dlnguyen/alamode

max_forks_repo_name: dlnguyen/alamode


text:
//
// Copyright (c) 2018 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//

#ifndef BOOST_BEAST_TEST_TEST_EXECUTOR_HPP
#define BOOST_BEAST_TEST_TEST_EXECUTOR_HPP

#include <boost/beast/core/detail/config.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/io_context.hpp>
#include <memory>

namespace boost {
namespace beast {

template<class Executor = net::io_context::executor_type>
class test_executor
{
public:
    // VFALCO These need to be atomic or something
    struct info
    {
        int dispatch = 0;
        int post = 0;
        int defer = 0;
        int work = 0;
        int total = 0;
    };

private:
    struct state
    {
        Executor ex;
        info info_;

        state(Executor const& ex_)
            : ex(ex_)
        {
        }
    };

    std::shared_ptr<state> sp_;

public:
    test_executor(test_executor const&) = default;
    test_executor& operator=(test_executor const&) = default;

    explicit
    test_executor(Executor const& ex)
        : sp_(std::make_shared<state>(ex))
    {
    }

    decltype(sp_->ex.context())
    context() const noexcept
    {
        return sp_->ex.context();
    }

    info&
    operator*() noexcept
    {
        return sp_->info_;
    }

    info*
    operator->() noexcept
    {
        return &sp_->info_;
    }

    void
    on_work_started() const noexcept
    {
        ++sp_->info_.work;
    }

    void
    on_work_finished() const noexcept
    {
    }

    template<class F, class A>
    void
    dispatch(F&& f, A const& a) const
    {
        ++sp_->info_.dispatch;
        ++sp_->info_.total;
        sp_->ex.dispatch(
            std::forward<F>(f), a);
    }

    template<class F, class A>
    void
    post(F&& f, A const& a) const
    {
        ++sp_->info_.post;
        ++sp_->info_.total;
        sp_->ex.post(
            std::forward<F>(f), a);
    }

    template<class F, class A>
    void
    defer(F&& f, A const& a) const
    {
        ++sp_->info_.defer;
        ++sp_->info_.total;
        sp_->ex.defer(
            std::forward<F>(f), a);
    }
};

} // beast
} // boost

#endif


text:
#include <boost/test/unit_test.hpp>

#include <smtrat-common/smtrat-common.h>
#include <smtrat-mcsat/explanations/icp/IntervalPropagation.h>

using namespace smtrat;

BOOST_AUTO_TEST_SUITE(Test_Explanation_ICP);

BOOST_AUTO_TEST_CASE(Test_Basic) {
	carl::Variable x = carl::freshRealVariable("x");
	carl::Variable y = carl::freshRealVariable("y");
	carl::Variable z = carl::freshRealVariable("z");

	Model model;
	model.emplace(x, Rational(4)/10);
	model.emplace(y, Rational(15)/100);

	ConstraintT c1(Poly(x)-Poly(z), carl::Relation::EQ);
	ConstraintT c2(Poly(x)*x-Poly(z), carl::Relation::EQ);
	ConstraintT c3(Poly(y)-Poly(x)*x, carl::Relation::LESS);
	ConstraintT c4(Poly(y)-Poly(1)/10, carl::Relation::GREATER);

	mcsat::icp::IntervalPropagation ip({x, y, z}, { FormulaT(c1), FormulaT(c2), FormulaT(c3), FormulaT(c4) }, model);
	auto res = ip.execute();
	if (res) {
		std::cout << *res << std::endl;
	}
}

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: minemebarsha/smtrat

max_issues_repo_name: minemebarsha/smtrat

max_forks_repo_name: minemebarsha/smtrat


text:
///
/// Copyright (c) 2009-2014 Nous Xiong (348944179 at qq dot com)
///
/// Distributed under the Boost Software License, Version 1.0. (See accompanying
/// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
///
/// See https://github.com/nousxiong/gce for latest version.
///

#include "conn.hpp"
#include <gce/detail/scope.hpp>
#include <boost/make_shared.hpp>
#include <boost/foreach.hpp>

///----------------------------------------------------------------------------
conn::conn(socket_ptr skt, gce::aid_t group_aid, app_ctxid_list_t game_list)
  : skt_(skt)
  , group_aid_(group_aid)
  , game_list_(game_list)
  , rcv_(skt_, game_list_)
{
}
///----------------------------------------------------------------------------
conn::~conn()
{
}
///----------------------------------------------------------------------------
gce::aid_t conn::spawn(
  gce::actor<gce::stackful>& sire, socket_ptr skt,
  gce::aid_t group_aid, app_ctxid_list_t game_list
  )
{
  ptr_t c(boost::make_shared<conn>(skt, group_aid, game_list));
  return
    gce::spawn<gce::stackless>(
      sire,
      boost::bind(&conn::run, c, _1)
      );
}
///----------------------------------------------------------------------------
void quit_callback(gce::actor<gce::stackless>& self, gce::aid_t group_aid)
{
  gce::send(self, group_aid, gce::atom("rmv_conn"));
}
///----------------------------------------------------------------------------
void conn::run(gce::actor<gce::stackless>& self)
{
  try
  {
    GCE_REENTER (self)
    {
      GCE_YIELD
      {
        gce::response_t res =
          gce::request(
            self, group_aid_,
            gce::atom("add_conn")
            );

        self.recv(res, sender_, msg_);
      }

      if (msg_.get_type() != gce::atom("ok"))
      {
        throw std::runtime_error("add_conn error");
      }

      GCE_YIELD
      {
        gce::spawn(
          self,
          boost::bind(&conn::timeout::run, &tmo_, _1),
          tmo_aid_,
          gce::monitored
          );
      }

      GCE_YIELD
      {
        gce::spawn(
          self,
          boost::bind(
            &conn::recv::run, &rcv_, _1,
            tmo_aid_, self.get_aid()
            ),
          rcv_aid_,
          gce::monitored,
          true
          );
      }

      running_ = true;
      exit_num_ = 0;
      while (running_)
      {
        msg_ = gce::message();
        sender_ = gce::aid_t();
        GCE_YIELD self.recv(sender_, msg_);
        type_ = msg_.get_type();
        if (type_ == gce::exit)
        {
          ++exit_num_;
          if (exit_num_ < 2)
          {
            gce::send(self, tmo_aid_, gce::exit);
          skt_->close();
          }
          else
          {
            running_ = false;
          }
        }
        else if (type_ == gce::atom("stop"))
        {
          gce::send(self, tmo_aid_, gce::exit);
          skt_->close();
        }
        else if (type_ == gce::atom("fwd_msg"))
        {
          GCE_YIELD
          {
            gce::message m;
            msg_ >> m;
            std::printf("fwd msg to client: %s\n", gce::atom(m.get_type()).c_str());
            ec_.clear();
            skt_->send(m, gce::adaptor(self, ec_, bytes_transferred_));
          }

          if (ec_)
          {
            throw std::runtime_error("socket send error");
          }
        }
        else
        {
          std::string errmsg("conn::run unexpected message, type: ");
          errmsg += gce::atom(type_);
          throw std::runtime_error(errmsg);
        }
      }
    }
  }
  catch (std::exception& ex)
  {
    std::printf("conn::run except: %s\n", ex.what());
    quit_callback(self, group_aid_);
  }
}
///----------------------------------------------------------------------------
void conn::timeout::run(gce::actor<gce::stackless>& self)
{
  try
  {
    GCE_REENTER (self)
    {
      curr_tmo_ = boost::chrono::seconds(60);
      max_count_ = 1;
      curr_count_ = 1;

      running_ = true;
      while (running_)
      {
        msg_ = gce::message();
        sender_ = gce::aid_t();
        GCE_YIELD self.recv(sender_, msg_, gce::match(curr_tmo_));
        gce::match_t type = msg_.get_type();
        if (sender_)
        {
          if (type == gce::exit)
          {
            running_ = false;
          }
          else if (type == gce::atom("reset"))
          {
            curr_count_ = max_count_;
          }
          else if (type == gce::atom("online"))
          {
            curr_tmo_ = boost::chrono::seconds(30);
            curr_count_ = 3;
          }
          else
          {
            std::string errmsg("conn::timeout unexpected message, type: ");
            errmsg += gce::atom(type);
            throw std::runtime_error(errmsg);
          }
        }
        else
        {
          --curr_count_;
          if (curr_count_ == 0)
          {
            running_ = false;
          }
        }
      }
    }
  }
  catch (std::exception& ex)
  {
    std::printf("conn::timeout except: %s\n", ex.what());
  }
}
///----------------------------------------------------------------------------
conn::recv::recv(socket_ptr skt, app_ctxid_list_t game_list)
  : skt_(skt)
  , game_list_(game_list)
{
}
///----------------------------------------------------------------------------
void conn::recv::run(
  gce::actor<gce::stackless>& self,
  gce::aid_t tmo_aid, gce::aid_t conn_aid
  )
{
  try
  {
    GCE_REENTER (self)
    {
      tmo_aid_ = tmo_aid;
      conn_aid_ = conn_aid;
      stat_ = conned;

      while (true)
      {
        ec_.clear();
        msg_ = gce::message();
        GCE_YIELD skt_->recv(msg_, gce::adaptor(self, ec_, bytes_transferred_));

        if (!ec_)
        {
          gce::send(self, tmo_aid_, gce::atom("reset"));
          type_ = msg_.get_type();
          if (type_ == gce::atom("cln_login"))
          {
            if (stat_ != conned)
            {
              throw std::runtime_error("conn status error, must be conned");
            }

            msg_ >> username_;
            game_svcid_ = select_game_app(game_list_, username_);

            msg_ << conn_aid_;
            GCE_YIELD
            {
              gce::response_t res = self.request(game_svcid_, msg_);
              msg_ = gce::message();
              usr_aid_ = gce::aid_t();
              self.recv(res, usr_aid_, msg_, gce::seconds_t(5));
            }

            if (!usr_aid_)
            {
              throw std::runtime_error("client login failed");
            }
            else
            {
              std::string errmsg;
              msg_ >> errmsg;
              if (!errmsg.empty())
              {
                throw std::runtime_error(errmsg);
              }
            }

            stat_ = online;
            gce::message m(gce::atom("cln_login_ret"));
            std::printf("fwd msg: %s\n", gce::atom(m.get_type()).c_str());
            m << std::string();
            gce::send(self, conn_aid_, gce::atom("fwd_msg"), m);
            gce::send(self, tmo_aid_, gce::atom("online"));
          }
          else if (type_ == gce::atom("chat"))
          {
            if (stat_ != online)
            {
              throw std::runtime_error("conn status error, must be online");
            }

            BOOST_FOREACH(gce::svcid_t svc, game_list_)
            {
              self.send(svc, msg_);
            }
          }
          else
          {
            if (stat_ != online)
            {
              throw std::runtime_error("conn status error, must be online");
            }

            /// forward to user
            self.send(usr_aid_, msg_);
          }
        }
        else
        {
          std::printf("conn::recv::run, socket err: %s\n", ec_.message().c_str());
          break;
        }
      }
    }
  }
  catch (std::exception& ex)
  {
    std::printf("conn::recv::run except: %s\n", ex.what());
    std::string errstr = boost::diagnostic_information(ex);
    std::printf("kick, err: %s\n", errstr.c_str());

    gce::message m(gce::atom("kick"));
    m << errstr;
    gce::send(self, conn_aid_, gce::atom("fwd_msg"), m);
  }
}
///----------------------------------------------------------------------------

max_stars_repo_name: nousxiong/gce

max_issues_repo_name: txwdyzcb/gce

max_forks_repo_name: txwdyzcb/gce


text:
#include <iostream>

#include <mmt/sentence.h>
#include <sapt/PhraseTable.h>
#include <suffixarray/UpdateBatch.h>
#include <suffixarray/SuffixArray.h>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <thread>
#include <util/BilingualCorpus.h>
#include <util/chrono.h>
#ifdef _OPENMP
#include <thread>
#include <omp.h>
#endif

using namespace std;
using namespace mmt;
using namespace mmt::sapt;

namespace {
    const size_t ERROR_IN_COMMAND_LINE = 1;
    const size_t GENERIC_ERROR = 2;
    const size_t SUCCESS = 0;

    struct args_t {
        string model_path;
        string input_path;
        string source_lang;
        string target_lang;

        size_t buffer_size = 100000;
    };
} // namespace

namespace po = boost::program_options;
namespace fs = boost::filesystem;

bool ParseArgs(int argc, const char *argv[], args_t *args) {
    po::options_description desc("Train a SuffixArray Phrase Table from scratch");
    desc.add_options()
            ("help,h", "print this help message")
            ("model,m", po::value<string>()->required(), "output model path")
            ("source,s", po::value<string>()->required(), "source language")
            ("target,t", po::value<string>()->required(), "target language")
            ("input,i", po::value<string>()->required(), "input folder with input corpora")
            ("buffer,b", po::value<size_t>(), "size of the buffer");

    po::variables_map vm;
    try {
        po::store(po::parse_command_line(argc, argv, desc), vm);

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

        po::notify(vm);

        args->model_path = vm["model"].as<string>();
        args->input_path = vm["input"].as<string>();
        args->source_lang = vm["source"].as<string>();
        args->target_lang = vm["target"].as<string>();

        if (vm.count("buffer"))
            args->buffer_size = vm["buffer"].as<size_t>();
    } catch (po::error &e) {
        std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
        std::cerr << desc << std::endl;
        return false;
    }

    return true;
}

void LoadCorpus(const BilingualCorpus &corpus, SuffixArray &index, size_t buffer_size) {
    domain_t domain = corpus.GetDomain();

    CorpusReader reader(corpus);
    UpdateBatch batch(buffer_size, vector<seqid_t>());

    vector<wid_t> source;
    vector<wid_t> target;
    alignment_t alignment;

    while(reader.Read(source, target, alignment)) {
        if (!batch.Add(domain, source, target, alignment)) {
            index.PutBatch(batch);

            batch.Clear();
            batch.Add(domain, source, target, alignment);
        }
    }

    if (!batch.IsEmpty()) {
        index.PutBatch(batch);
        batch.Clear();
    }
}

int main(int argc, const char *argv[]) {
#ifdef _OPENMP
    int threads = std::min((thread::hardware_concurrency() * 2) / 3, 8U);

    omp_set_dynamic(0);
    omp_set_num_threads(threads);
#endif

    args_t args;

    if (!ParseArgs(argc, argv, &args))
        return ERROR_IN_COMMAND_LINE;

    if (!fs::exists(args.input_path) || !fs::is_directory(args.input_path)) {
        cerr << "ERROR: input path is not a valid directory" << endl;
        return GENERIC_ERROR;
    }

    if (!fs::is_directory(args.model_path))
        fs::create_directories(args.model_path);

    Options options;
    SuffixArray index(args.model_path, options.prefix_length, options.gc_timeout, options.gc_buffer_size, true);

    vector<BilingualCorpus> corpora;
    BilingualCorpus::List(args.input_path, args.source_lang, args.target_lang, corpora);

#pragma omp parallel for schedule(dynamic)
    for (size_t i = 0; i < corpora.size(); ++i) {
        BilingualCorpus &corpus = corpora[i];

        double begin = GetTime();
        LoadCorpus(corpus, index, args.buffer_size);
        double elapsed = GetElapsedTime(begin);
        cout << "Corpus " << corpus.GetDomain() << " DONE in " << elapsed << "s" << endl;
    }

    index.ForceCompaction();

    return SUCCESS;
}

max_stars_repo_name: ugermann/MMT

max_issues_repo_name: ugermann/MMT

max_forks_repo_name: ugermann/MMT


text:
// Boost.Range library
//
//  Copyright Neil Groves 2009. 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)
//
//
// For more information, see http://www.boost.org/libs/range/
//
#ifndef BOOST_RANGE_DETAIL_DEMOTE_ITERATOR_TRAVERSAL_TAG_HPP_INCLUDED
#define BOOST_RANGE_DETAIL_DEMOTE_ITERATOR_TRAVERSAL_TAG_HPP_INCLUDED

#include <boost/iterator/iterator_categories.hpp>

namespace boost
{
	namespace range_detail
	{

template<class IteratorTraversalTag1, class IteratorTraversalTag2>
struct demote_iterator_traversal_tag
{
};

#define BOOST_DEMOTE_TRAVERSAL_TAG( Tag1, Tag2, ResultTag ) \
template<> struct demote_iterator_traversal_tag< Tag1 , Tag2 > \
{ \
	typedef ResultTag type; \
};

BOOST_DEMOTE_TRAVERSAL_TAG( no_traversal_tag, no_traversal_tag,            no_traversal_tag )
BOOST_DEMOTE_TRAVERSAL_TAG( no_traversal_tag, incrementable_traversal_tag, no_traversal_tag )
BOOST_DEMOTE_TRAVERSAL_TAG( no_traversal_tag, single_pass_traversal_tag,   no_traversal_tag )
BOOST_DEMOTE_TRAVERSAL_TAG( no_traversal_tag, forward_traversal_tag,       no_traversal_tag )
BOOST_DEMOTE_TRAVERSAL_TAG( no_traversal_tag, bidirectional_traversal_tag, no_traversal_tag )
BOOST_DEMOTE_TRAVERSAL_TAG( no_traversal_tag, random_access_traversal_tag, no_traversal_tag )

BOOST_DEMOTE_TRAVERSAL_TAG( incrementable_traversal_tag, no_traversal_tag,            no_traversal_tag            )
BOOST_DEMOTE_TRAVERSAL_TAG( incrementable_traversal_tag, incrementable_traversal_tag, incrementable_traversal_tag )
BOOST_DEMOTE_TRAVERSAL_TAG( incrementable_traversal_tag, single_pass_traversal_tag,   incrementable_traversal_tag )
BOOST_DEMOTE_TRAVERSAL_TAG( incrementable_traversal_tag, forward_traversal_tag,       incrementable_traversal_tag )
BOOST_DEMOTE_TRAVERSAL_TAG( incrementable_traversal_tag, bidirectional_traversal_tag, incrementable_traversal_tag )
BOOST_DEMOTE_TRAVERSAL_TAG( incrementable_traversal_tag, random_access_traversal_tag, incrementable_traversal_tag )

BOOST_DEMOTE_TRAVERSAL_TAG( single_pass_traversal_tag, no_traversal_tag,            no_traversal_tag            )
BOOST_DEMOTE_TRAVERSAL_TAG( single_pass_traversal_tag, incrementable_traversal_tag, incrementable_traversal_tag )
BOOST_DEMOTE_TRAVERSAL_TAG( single_pass_traversal_tag, single_pass_traversal_tag,   single_pass_traversal_tag   )
BOOST_DEMOTE_TRAVERSAL_TAG( single_pass_traversal_tag, forward_traversal_tag,       single_pass_traversal_tag   )
BOOST_DEMOTE_TRAVERSAL_TAG( single_pass_traversal_tag, bidirectional_traversal_tag, single_pass_traversal_tag   )
BOOST_DEMOTE_TRAVERSAL_TAG( single_pass_traversal_tag, random_access_traversal_tag, single_pass_traversal_tag   )

BOOST_DEMOTE_TRAVERSAL_TAG( forward_traversal_tag, no_traversal_tag,            no_traversal_tag            )
BOOST_DEMOTE_TRAVERSAL_TAG( forward_traversal_tag, incrementable_traversal_tag, incrementable_traversal_tag )
BOOST_DEMOTE_TRAVERSAL_TAG( forward_traversal_tag, single_pass_traversal_tag,   single_pass_traversal_tag   )
BOOST_DEMOTE_TRAVERSAL_TAG( forward_traversal_tag, forward_traversal_tag,       forward_traversal_tag       )
BOOST_DEMOTE_TRAVERSAL_TAG( forward_traversal_tag, bidirectional_traversal_tag, forward_traversal_tag       )
BOOST_DEMOTE_TRAVERSAL_TAG( forward_traversal_tag, random_access_traversal_tag, forward_traversal_tag       )

BOOST_DEMOTE_TRAVERSAL_TAG( bidirectional_traversal_tag, no_traversal_tag,            no_traversal_tag            )
BOOST_DEMOTE_TRAVERSAL_TAG( bidirectional_traversal_tag, incrementable_traversal_tag, incrementable_traversal_tag )
BOOST_DEMOTE_TRAVERSAL_TAG( bidirectional_traversal_tag, single_pass_traversal_tag,   single_pass_traversal_tag   )
BOOST_DEMOTE_TRAVERSAL_TAG( bidirectional_traversal_tag, forward_traversal_tag,       forward_traversal_tag       )
BOOST_DEMOTE_TRAVERSAL_TAG( bidirectional_traversal_tag, bidirectional_traversal_tag, bidirectional_traversal_tag )
BOOST_DEMOTE_TRAVERSAL_TAG( bidirectional_traversal_tag, random_access_traversal_tag, bidirectional_traversal_tag )

BOOST_DEMOTE_TRAVERSAL_TAG( random_access_traversal_tag, no_traversal_tag,            no_traversal_tag            )
BOOST_DEMOTE_TRAVERSAL_TAG( random_access_traversal_tag, incrementable_traversal_tag, incrementable_traversal_tag )
BOOST_DEMOTE_TRAVERSAL_TAG( random_access_traversal_tag, single_pass_traversal_tag,   single_pass_traversal_tag   )
BOOST_DEMOTE_TRAVERSAL_TAG( random_access_traversal_tag, forward_traversal_tag,       forward_traversal_tag       )
BOOST_DEMOTE_TRAVERSAL_TAG( random_access_traversal_tag, bidirectional_traversal_tag, bidirectional_traversal_tag )
BOOST_DEMOTE_TRAVERSAL_TAG( random_access_traversal_tag, random_access_traversal_tag, random_access_traversal_tag )

#undef BOOST_DEMOTE_TRAVERSAL_TAG

	} // namespace range_detail
} // namespace boost

#endif // include guard

max_stars_repo_name: jonstewart/boost-svn

max_issues_repo_name: jonstewart/boost-svn

max_forks_repo_name: jonstewart/boost-svn


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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 <memory>
#include <boost/bind.hpp>

#include "exec/base-sequence-scanner.h"

#include "exec/hdfs-scan-node-base.h"
#include "exec/hdfs-scan-node.h"
#include "exec/scanner-context.inline.h"
#include "runtime/runtime-state.h"
#include "runtime/string-search.h"
#include "util/codec.h"
#include "util/runtime-profile-counters.h"
#include "util/test-info.h"

#include "common/names.h"

using namespace impala;
using namespace impala::io;

const int BaseSequenceScanner::HEADER_SIZE = 1024;
const int BaseSequenceScanner::SYNC_MARKER = -1;

// Constants used in ReadPastSize()
static const double BLOCK_SIZE_PADDING_PERCENT = 0.1;
static const int MIN_SYNC_READ_SIZE = 64 * 1024; // bytes

// Macro to convert between SerdeUtil errors to Status returns.
#define RETURN_IF_FALSE(x) if (UNLIKELY(!(x))) return parse_status_

Status BaseSequenceScanner::IssueInitialRanges(HdfsScanNodeBase* scan_node,
    const vector<HdfsFileDesc*>& files) {
  // Issue just the header range for each file.  When the header is complete,
  // we'll issue the splits for that file.  Splits cannot be processed until the
  // header is parsed (the header object is then shared across splits for that file).
  vector<ScanRange*> header_ranges;
  for (int i = 0; i < files.size(); ++i) {
    ScanRangeMetadata* metadata =
        static_cast<ScanRangeMetadata*>(files[i]->splits[0]->meta_data());
    ScanRangeMetadata* header_metadata =
        scan_node->runtime_state()->obj_pool()->Add(new ScanRangeMetadata(*metadata));
    header_metadata->is_sequence_header = true;
    int64_t header_size = min<int64_t>(HEADER_SIZE, files[i]->file_length);
    // The header is almost always a remote read. Set the disk id to -1 and indicate
    // it is not cached.
    // TODO: add remote disk id and plumb that through to the io mgr.  It should have
    // 1 queue for each NIC as well?
    ScanRange* header_range = scan_node->AllocateScanRange(files[i]->fs,
        files[i]->filename.c_str(), header_size, 0, header_metadata, -1, false,
        BufferOpts::Uncached());
    header_ranges.push_back(header_range);
  }
  // Issue the header ranges only. GetNextInternal() will issue the files' scan ranges
  // and those ranges will need scanner threads, so no files are marked completed yet.
  RETURN_IF_ERROR(scan_node->AddDiskIoRanges(header_ranges, 0));
  return Status::OK();
}

bool BaseSequenceScanner::FileFormatIsSequenceBased(THdfsFileFormat::type format) {
  return format == THdfsFileFormat::SEQUENCE_FILE ||
         format == THdfsFileFormat::RC_FILE ||
         format == THdfsFileFormat::AVRO;
}

BaseSequenceScanner::BaseSequenceScanner(HdfsScanNodeBase* node, RuntimeState* state)
  : HdfsScanner(node, state) {
}

BaseSequenceScanner::BaseSequenceScanner() : HdfsScanner() {
  DCHECK(TestInfo::is_test());
}

BaseSequenceScanner::~BaseSequenceScanner() {
}

Status BaseSequenceScanner::Open(ScannerContext* context) {
  RETURN_IF_ERROR(HdfsScanner::Open(context));
  stream_->set_read_past_size_cb(bind(&BaseSequenceScanner::ReadPastSize, this, _1));
  bytes_skipped_counter_ = ADD_COUNTER(
      scan_node_->runtime_profile(), "BytesSkipped", TUnit::BYTES);

  header_ = reinterpret_cast<FileHeader*>(
      scan_node_->GetFileMetadata(
          context->partition_descriptor()->id(), stream_->filename()));
  if (header_ == nullptr) {
    only_parsing_header_ = true;
    return Status::OK();
  }
  RETURN_IF_ERROR(InitNewRange());

  // Skip to the first record
  if (stream_->file_offset() < header_->header_size) {
    // If the scan range starts within the header, skip to the end of the header so we
    // don't accidentally skip to an extra sync within the header
    RETURN_IF_FALSE(stream_->SkipBytes(
        header_->header_size - stream_->file_offset(), &parse_status_));
  }
  RETURN_IF_ERROR(SkipToSync(header_->sync, SYNC_HASH_SIZE));
  return Status::OK();
}

void BaseSequenceScanner::Close(RowBatch* row_batch) {
  DCHECK(!is_closed_);
  VLOG_FILE << "Bytes read past scan range: " << -stream_->bytes_left();
  VLOG_FILE << "Average block size: "
            << (num_syncs_ > 1 ? total_block_size_ / (num_syncs_ - 1) : 0);
  // Need to close the decompressor before releasing the resources at AddFinalRowBatch(),
  // because in some cases there is memory allocated in decompressor_'s temp_memory_pool_.
  if (decompressor_.get() != nullptr) {
    decompressor_->Close();
    decompressor_.reset();
  }
  if (row_batch != nullptr) {
    row_batch->tuple_data_pool()->AcquireData(data_buffer_pool_.get(), false);
    row_batch->tuple_data_pool()->AcquireData(template_tuple_pool_.get(), false);
    if (scan_node_->HasRowBatchQueue()) {
      static_cast<HdfsScanNode*>(scan_node_)->AddMaterializedRowBatch(
        unique_ptr<RowBatch>(row_batch));
    }
  } else {
    data_buffer_pool_->FreeAll();
    template_tuple_pool_->FreeAll();
  }
  context_->ReleaseCompletedResources(true);

  // Verify all resources (if any) have been transferred.
  DCHECK_EQ(template_tuple_pool_.get()->total_allocated_bytes(), 0);
  DCHECK_EQ(data_buffer_pool_.get()->total_allocated_bytes(), 0);
  // 'header_' can be nullptr if HdfsScanNodeBase::CreateAndOpenScanner() failed.
  if (!only_parsing_header_ && header_ != nullptr) {
    scan_node_->RangeComplete(file_format(), header_->compression_type);
  }
  CloseInternal();
}

Status BaseSequenceScanner::GetNextInternal(RowBatch* row_batch) {
  if (only_parsing_header_) {
    DCHECK(header_ == nullptr);
    eos_ = true;
    header_ = state_->obj_pool()->Add(AllocateFileHeader());
    Status status = ReadFileHeader();
    if (!status.ok()) {
      RETURN_IF_ERROR(state_->LogOrReturnError(status.msg()));
      // We need to complete the ranges for this file.
      CloseFileRanges(stream_->filename());
      return Status::OK();
    }
    // Header is parsed, set the metadata in the scan node and issue more ranges.
    static_cast<HdfsScanNodeBase*>(scan_node_)->SetFileMetadata(
        context_->partition_descriptor()->id(), stream_->filename(), header_);
    HdfsFileDesc* desc = scan_node_->GetFileDesc(
        context_->partition_descriptor()->id(), stream_->filename());
    RETURN_IF_ERROR(scan_node_->AddDiskIoRanges(desc));
    return Status::OK();
  }
  if (eos_) return Status::OK();

  int64_t tuple_buffer_size;
  RETURN_IF_ERROR(
      row_batch->ResizeAndAllocateTupleBuffer(state_, &tuple_buffer_size, &tuple_mem_));
  tuple_ = reinterpret_cast<Tuple*>(tuple_mem_);
  DCHECK_GT(row_batch->capacity(), 0);

  Status status = ProcessRange(row_batch);
  if (!status.ok()) {
    // Log error from file format parsing.
    // TODO(IMPALA-5922): Include the file and offset in errors inside the scanners.
    if (!status.IsCancelled() &&
        !status.IsMemLimitExceeded() &&
        !status.IsInternalError() &&
        !status.IsDiskIoError()) {
      state_->LogError(ErrorMsg(TErrorCode::SEQUENCE_SCANNER_PARSE_ERROR,
          stream_->filename(), stream_->file_offset(),
          (stream_->eof() ? "(EOF)" : "")));
    }

    // This checks for abort_on_error.
    RETURN_IF_ERROR(state_->LogOrReturnError(status.msg()));

    // Recover by skipping to the next sync.
    parse_status_ = Status::OK();
    int64_t error_offset = stream_->file_offset();
    status = SkipToSync(header_->sync, SYNC_HASH_SIZE);
    COUNTER_ADD(bytes_skipped_counter_, stream_->file_offset() - error_offset);
    RETURN_IF_ERROR(status);
    DCHECK(parse_status_.ok());
  }
  return Status::OK();
}

Status BaseSequenceScanner::ReadSync() {
  uint8_t* hash;
  int64_t out_len;
  bool success = stream_->GetBytes(SYNC_HASH_SIZE, &hash, &out_len, &parse_status_);
  // We are done when we read a sync marker occurring completely in the next scan range.
  eos_ = stream_->eosr() || stream_->eof();
  if (!success) return parse_status_;
  if (out_len != SYNC_HASH_SIZE) {
    return Status(Substitute("Hit end of stream after reading $0 bytes of $1-byte "
        "synchronization marker", out_len, SYNC_HASH_SIZE));
  } else if (memcmp(hash, header_->sync, SYNC_HASH_SIZE) != 0) {
    stringstream ss;
    ss  << "Bad synchronization marker" << endl
        << "  Expected: '"
        << ReadWriteUtil::HexDump(header_->sync, SYNC_HASH_SIZE) << "'" << endl
        << "  Actual:   '"
        << ReadWriteUtil::HexDump(hash, SYNC_HASH_SIZE) << "'";
    return Status(ss.str());
  }
  total_block_size_ += stream_->file_offset() - block_start_;
  block_start_ = stream_->file_offset();
  ++num_syncs_;
  return Status::OK();
}

int BaseSequenceScanner::FindSyncBlock(const uint8_t* buffer, int buffer_len,
                                       const uint8_t* sync, int sync_len) {
  char* sync_str = reinterpret_cast<char*>(const_cast<uint8_t*>(sync));
  StringValue needle = StringValue(sync_str, sync_len);

  StringValue haystack(
      const_cast<char*>(reinterpret_cast<const char*>(buffer)), buffer_len);

  StringSearch search(&needle);
  int offset = search.Search(&haystack);

  if (offset != -1) {
    // Advance offset past sync
    offset += sync_len;
  }
  return offset;
}

Status BaseSequenceScanner::SkipToSync(const uint8_t* sync, int sync_size) {
  // offset into current buffer of end of sync (once found, -1 until then)
  int offset = -1;
  uint8_t* buffer;
  int64_t buffer_len;
  Status status;

  // Read buffers until we find a sync or reach the end of the scan range. If we read all
  // the buffers remaining in the scan range and none of them contain a sync (including a
  // sync that starts at the end of this scan range and continues into the next one), then
  // there are no more syncs in this scan range and we're finished.
  while (!stream_->eosr()) {
    // Check if there's a sync fully contained in the current buffer
    RETURN_IF_ERROR(stream_->GetBuffer(true, &buffer, &buffer_len));
    offset = FindSyncBlock(buffer, buffer_len, sync, sync_size);
    DCHECK_LE(offset, buffer_len);
    if (offset != -1) break;

    // No sync found in the current buffer, so check if there's a sync spanning the
    // current buffer and the next. First we skip so there are sync_size - 1 bytes left,
    // then we read these bytes plus the first sync_size - 1 bytes of the next buffer.
    // This guarantees that we find any syncs that start in the current buffer and end in
    // the next buffer.
    int64_t to_skip = max<int64_t>(0, buffer_len - (sync_size - 1));
    RETURN_IF_FALSE(stream_->SkipBytes(to_skip, &parse_status_));
    // Peek so we don't advance stream_ into the next buffer. If we don't find a sync here
    // then we'll need to check all of the next buffer, including the first sync_size -1
    // bytes.
    RETURN_IF_FALSE(stream_->GetBytes(
        (sync_size - 1) * 2, &buffer, &buffer_len, &parse_status_, true));
    offset = FindSyncBlock(buffer, buffer_len, sync, sync_size);
    DCHECK_LE(offset, buffer_len);
    if (offset != -1) break;

    // No sync starting in this buffer, so advance stream_ to the beginning of the next
    // buffer.
    RETURN_IF_ERROR(stream_->GetBuffer(false, &buffer, &buffer_len));
  }

  if (offset == -1) {
    // No more syncs in this scan range
    DCHECK(stream_->eosr());
    eos_ = true;
    return Status::OK();
  }
  DCHECK_GE(offset, sync_size);

  // Make sure sync starts in our scan range
  if (offset - sync_size >= stream_->bytes_left()) {
    eos_ = true;
    return Status::OK();
  }

  RETURN_IF_FALSE(stream_->SkipBytes(offset, &parse_status_));
  VLOG_FILE << "Found sync for: " << stream_->filename()
            << " at " << stream_->file_offset() - sync_size;
  if (stream_->eof()) eos_ = true;
  block_start_ = stream_->file_offset();
  ++num_syncs_;
  return Status::OK();
}

void BaseSequenceScanner::CloseFileRanges(const char* filename) {
  DCHECK(only_parsing_header_);
  HdfsFileDesc* desc = scan_node_->GetFileDesc(
      context_->partition_descriptor()->id(), filename);
  const vector<ScanRange*>& splits = desc->splits;
  for (int i = 0; i < splits.size(); ++i) {
    COUNTER_ADD(bytes_skipped_counter_, splits[i]->len());
    scan_node_->RangeComplete(file_format(), THdfsCompression::NONE);
  }
}

int BaseSequenceScanner::ReadPastSize(int64_t file_offset) {
  DCHECK_GE(total_block_size_, 0);
  // This scan range didn't include a complete block, so we have no idea how many bytes
  // remain in the block. Let ScannerContext use its default strategy.
  if (total_block_size_ == 0) return 0;
  DCHECK_GE(num_syncs_, 2);
  int average_block_size = total_block_size_ / (num_syncs_ - 1);

  // Number of bytes read in the current block
  int block_bytes_read = file_offset - block_start_;
  DCHECK_GE(block_bytes_read, 0);
  int bytes_left = max(average_block_size - block_bytes_read, 0);
  // Include some padding
  bytes_left += average_block_size * BLOCK_SIZE_PADDING_PERCENT;
  return max(bytes_left, MIN_SYNC_READ_SIZE);
}

ext: cc

max_stars_repo_name: kexianda/impala

max_issues_repo_name: kexianda/impala

max_forks_repo_name: kexianda/impala


text:
#include <cstdio>
#include <boost/asio.hpp>
#include <thread>
#include <queue>
#include <string>
#include <random>
#include <nlohmann/json.hpp>
//#include <mutex>
#include "server.h"

// comment this to disable debugging info
#define DEBUG

using boost::asio::ip::tcp;

std::map<int, std::thread *> threads;
std::map<int, tcp::socket *> sockets;
std::map<int, std::string> nicknames;

std::mutex client_maps_mutex;

std::vector<int> discarded_keys;
std::mutex discarded_keys_mutex;

void delete_threads() {
	while(1) {
		std::lock_guard<std::mutex> g1(discarded_keys_mutex);
		std::lock_guard<std::mutex> g2(client_maps_mutex);
		for (auto key : discarded_keys) {
			threads[key]->join();

			delete sockets[key];
			sockets.erase(key);

			delete threads[key];
			threads.erase(key);
			nicknames.erase(key);
		}
		discarded_keys.clear();
	}
}

void send_data(const std::string &data, tcp::socket *socket) {
	std::string len(4, 0);

	for (size_t i = 0; i < 4; i++) {
		len[i] = (data.size() >> (i * 8)) & 0xFF;
	}

	std::string full = len + data;

	boost::system::error_code ignored_error;
	boost::asio::write(*socket, boost::asio::buffer(full), ignored_error);
	if (ignored_error) {
		throw boost::system::system_error(ignored_error);
	}
}

// sends message to all connected clients
void broadcast_data(const std::string &data) {
	for (auto &c : sockets)
		send_data(data, c.second);
}

void recv_worker(tcp::socket *socket, int key) {
	boost::system::error_code err;
	std::ostringstream tmp_str;
	std::array<char, 128> buf;
	std::array<uint8_t, 4> size_buf{0,0,0,0};
	uint32_t size;
	char tmp[129];
	while(1) {
		tmp_str.str("");
		size_t len = socket->read_some(boost::asio::buffer(size_buf), err);
		if (err == boost::asio::error::broken_pipe ||
			err == boost::asio::error::eof || err == boost::asio::error::connection_aborted ||
			err == boost::asio::error::connection_reset) {
			std::lock_guard<std::mutex> g(discarded_keys_mutex);
			discarded_keys.push_back(key);
			return;
		}

		if (len != 4) throw std::runtime_error("didn't receive 4 size bytes");
		size = 0;
		for(size_t i = 0; i < 4; i++) {
			size |= ((uint32_t)size_buf[i]) << (i * 8);
		}

		#ifdef DEBUG
		printf("Expecting to receive %zu bytes\n", size);
		#endif

		size_t recv_len = 0;
		while(1) {
			if (!size) break;
			buf.fill(0);
			memset(tmp, 0, 129);

			size_t len = socket->read_some(boost::asio::buffer(buf), err);
			if (err == boost::asio::error::broken_pipe || err == boost::asio::error::eof ||
			err == boost::asio::error::connection_aborted || err == boost::asio::error::connection_reset) {
				std::lock_guard<std::mutex> g(discarded_keys_mutex);
				discarded_keys.push_back(key);
			}
			else if (err)
				throw boost::system::system_error(err);

			recv_len += len;
			std::copy(std::begin(buf), std::begin(buf) + len, std::begin(tmp));
			tmp_str << tmp;
			#ifdef DEBUG
			printf("Received %zu bytes from client, content: '%s'\n", len, tmp);
			#endif
			if (recv_len == size) break;
		}

		std::string msg = tmp_str.str();

		nlohmann::json j = nlohmann::json::parse(msg);
		if (j.find("type") == j.end()) {
			continue; // no type, discard
		}

		message_type t = (message_type)j["type"].get<int>();

		if (t == message_type::username) {
			std::string username = j["username"].get<std::string>();
			nicknames.emplace(key, username);
		}

		if (t == message_type::message_in) {
			// send message to other users, append client's name
			nlohmann::json in = nlohmann::json::parse(msg);

			nlohmann::json jmsg = {
				{"type", (int)message_type::message_out},
				{"username", nicknames[key]},
				{"content", in["content"]}
			};
			#ifdef DEBUG
			printf("[!] broadcasting %s\n", jmsg.dump().c_str());
			#endif
			broadcast_data(jmsg.dump());
		}
	}
}

int main() {
	printf("Chat protocol - server\n\n");

	int port;
	port = 6660;

	boost::asio::io_context io_context;
	tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), port));

	std::random_device rd;
	std::mt19937 rnd(rd());

	printf("Created socket on port %d \n", port);

	std::thread discard_worker(delete_threads);

	while(1) {
		tcp::socket *sock = new tcp::socket(io_context);
		acceptor.accept(*sock);

		int key = rnd();

		std::thread *tr = new std::thread(recv_worker, sock, key);

		sockets.emplace(key, sock);
		threads.emplace(key, tr);

		printf("New client connected.\n");
	}

	for (auto t : threads) delete t.second;
	for (auto s : sockets) delete s.second;

	return 0;
}

max_stars_repo_name: kasesag/generic-chat-protocol

max_issues_repo_name: kasesag/generic-chat-protocol

max_forks_repo_name: kasesag/generic-chat-protocol


text:
// Copyright (c) 2017 Pieter Wuille
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <key_io.h>
#include <bech32.h>
#include <test/util/setup_common.h>
#include <test/util/str.h>

#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(bech32_tests, GraviocoinBasicTestingSetup)

std::vector<std::pair<std::string, std::string> > testsPass = {
    std::make_pair("GKYgnLKnvevLeUyeYgm2DnjT1FGsgVNzYE", "gh1z2kuclaye2ktkndy7mdpw3zk0nck78a7ftag2u"),
    std::make_pair("RJAPhgckEgRGVPZa9WoGSWW24spskSfLTQ", "gr1v9h7c4k0e3axk7jlejzyh8tnc5eryx6eq46g39"),
    std::make_pair("SPGxiYZ1Q5dhAJxJNMk56ZbxcsUBYqTCsdEPPHsJJ96Vcns889gHTqSrTZoyrCd5E9NSe9XxLivK6izETniNp1Gu1DtrhVwv3VuZ3e", "gs1qqpvvvphd2zkphxxckzef2lgag67gzpz85alcemkxzvpl5tkgc8p34qpqwg58jx532dpkk0qtysnyudzg4ajk0vvqp8w9zlgjamxxz2l9cpt7qqqyd80pl"),
    std::make_pair("PPARTKMMf4AUDYzRSBcXSJZALbUXgWKHi6qdpy95yBmABuznU3keHFyNHfjaMT33ehuYwjx3RXort1j8d9AYnqyhAvdN168J4GBsM2ZHuTb91rsj", "gep1qqqqqqqqqqqqqqqcpjvcv9trdnv8t2nscuw056mm74cps7jkmrrdq48xpdjy6ylf6vpru36q6zax883gjclngas40d7097mudl05y48ewzvulpnsk5z75kgufmdvt"),
};

std::vector<std::string> testsFail = {
    "gh1z2kuclaye2kthndy7mdpw3zk0nck78a7u6h8hm",
    "grIv9h7c4k0e3axk7jlejzyh8tnc5eryx6e4ys8vz",
    "gs1qqpvvvphd2zkphxxckzef2lgag67gzpz85alcemkxzvpl5tkgc7p34qpqwg58jx532dpkk0qtysnyudzg4ajk0vvqp8w9zlgjamxxz2l9cpt7qqqflt7zu",
    "gep1qqqqqqqqqqqqqqcpjvcv9trdnv8t2nscuw056mm74cps7jkmrrdq48xpdjy6ylf6vpru36q6zax883gjclngas40d7097mudl05y48ewzvulpnsk5z75kg24d5nf",
};

std::vector<std::pair<CChainParams::Base58Type, std::string>> testsType = {
    std::make_pair(CChainParams::PUBKEY_ADDRESS, "gh1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqn06f76"),
    std::make_pair(CChainParams::SCRIPT_ADDRESS, "gr1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqmsspcj"),
    std::make_pair(CChainParams::PUBKEY_ADDRESS_256, "gl1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqkv5vrl"),
    std::make_pair(CChainParams::SCRIPT_ADDRESS_256, "gj1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq96alyv"),
    std::make_pair(CChainParams::SECRET_KEY, "gx1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq8rta3w"),
    std::make_pair(CChainParams::EXT_PUBLIC_KEY, "gep1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqz0r4sv"),
    std::make_pair(CChainParams::EXT_SECRET_KEY, "gex1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqgfllrx"),
    std::make_pair(CChainParams::STEALTH_ADDRESS, "gs1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqsw824e"),
    std::make_pair(CChainParams::EXT_KEY_HASH, "gek1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqpw7km0"),
    std::make_pair(CChainParams::EXT_ACC_HASH, "gea1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqaa92jn"),
};

BOOST_AUTO_TEST_CASE(bech32_test)
{
    CBitcoinAddress addr_base58;
    CBitcoinAddress addr_bech32;

    for (auto &v : testsPass)
    {
        addr_base58.SetString(v.first);
        CTxDestination dest = addr_base58.Get();
        BOOST_CHECK(addr_bech32.Set(dest, true));
        BOOST_CHECK(addr_bech32.ToString() == v.second);

        CTxDestination dest2 = addr_bech32.Get();
        BOOST_CHECK(dest == dest2);
        CBitcoinAddress t58_back(dest2);
        BOOST_CHECK(t58_back.ToString() == v.first);

        CBitcoinAddress addr_bech32_2(v.second);
        BOOST_CHECK(addr_bech32_2.IsValid());
        CTxDestination dest3 = addr_bech32_2.Get();
        BOOST_CHECK(dest == dest3);
    };

    for (auto &v : testsFail)
    {
        BOOST_CHECK(!addr_bech32.SetString(v));
    };

    CKeyID knull;
    for (auto &v : testsType)
    {
        CBitcoinAddress addr;
        addr.Set(knull, v.first, true);
        BOOST_CHECK(addr.ToString() == v.second);
    };
}

BOOST_AUTO_TEST_CASE(bip173_testvectors_valid)
{
    static const std::string CASES[] = {
        "A12UEL5L",
        "a12uel5l",
        "an83characterlonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1tt5tgs",
        "abcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lmqqqxw",
        "11qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqc8247j",
        "split1checkupstagehandshakeupstreamerranterredcaperred2y9e3w",
        "?1ezyfcl",
    };
    for (const std::string& str : CASES) {
        auto ret = bech32::Decode(str);
        BOOST_CHECK(!ret.first.empty());
        std::string recode = bech32::Encode(ret.first, ret.second);
        BOOST_CHECK(!recode.empty());
        BOOST_CHECK(CaseInsensitiveEqual(str, recode));
    }
}

BOOST_AUTO_TEST_CASE(bip173_testvectors_invalid)
{
    static const std::string CASES[] = {
        " 1nwldj5",
        "\x7f""1axkwrx",
        "\x80""1eym55h",
        "an84characterslonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1569pvx",
        "pzry9x0s0muk",
        "1pzry9x0s0muk",
        "x1b4n0q5v",
        "li1dgmt3",
        "de1lg7wt\xff",
        "A1G7SGD8",
        "10a06t8",
        "1qzzfhee",
        "a12UEL5L",
        "A12uEL5L",
    };
    for (const std::string& str : CASES) {
        auto ret = bech32::Decode(str);
        BOOST_CHECK(ret.first.empty());
    }
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: gravio-net/graviocoin-pos

max_issues_repo_name: gravio-net/graviocoin-pos

max_forks_repo_name: gravio-net/graviocoin-pos


text:
#include <boost/program_options.hpp>
//#include "boost/program_options/options_description.hpp"

#include <iostream>
#include <fstream>
#include <string>

#include "ClpbProblem.hpp"

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

int main(int argc, char* argv[])
{
	if(argc==1){
		printVersionInfo();
		printHelpInfo();
		return 0;
	}
	if(strcmp(argv[1],"--version")==0){
		printVersionInfo();
		return 0;
	}
	if(strcmp(argv[1],"--help")==0){
		printHelpInfo();
		return 0;
	}
	if(strcmp(argv[1],"--formats")==0){
		printFileFormatOptions();
		return 0;
	}
	if(strcmp(argv[1],"--problem")==0){
		printProblemOptions();
		return 0;
	}

	ClpbProblem problem;
	problem.parseParams(argc, argv);

	problem.solve();

	return 0;
}

max_stars_repo_name: xixicat/argmat-clpb

max_issues_repo_name: xixicat/argmat-clpb

max_forks_repo_name: xixicat/argmat-clpb


text:
// Copyright David Abrahams 2003.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/python/detail/copy_ctor_mutates_rhs.hpp>
#include <boost/static_assert.hpp>
#include <memory>
#include <string>

struct foo
{
    operator std::auto_ptr<int>&() const;
};

int main()
{
    using namespace boost::python::detail;
    BOOST_STATIC_ASSERT(!copy_ctor_mutates_rhs<int>::value);
    BOOST_STATIC_ASSERT(copy_ctor_mutates_rhs<std::auto_ptr<int> >::value);
    BOOST_STATIC_ASSERT(!copy_ctor_mutates_rhs<std::string>::value);
    BOOST_STATIC_ASSERT(!copy_ctor_mutates_rhs<foo>::value);
    return 0;
}

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
//[ VirtualMember
//  Copyright 2012 Eric Niebler. 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)
//
// This example demonstrates how to use BOOST_PROTO_EXTENDS_MEMBERS()
// to add "virtual" data members to expressions within a domain. For
// instance, with Phoenix you can create a lambda expression such as
//
//    if_(_1 > 0)[ std::cout << _2 ].else_[ std::cout << _3 ]
//
// In the above expression, "else_" is a so-called virtual data member
// of the expression "if_(_1 > 0)[ std::cout << _2 ]". This example
// shows how to implement the ".else_" syntax with Proto.
//
// ****WARNING****WARNING****WARNING****WARNING****WARNING****WARNING****
// * The virtual data member feature is experimental and can change at  *
// * any time. Use it at your own risk.                                 *
// **********************************************************************

#include <iostream>
#include <type_traits>
#include <boost/proto/v5/proto.hpp>
#include <boost/proto/v5/debug.hpp>

namespace proto = boost::proto;
using proto::_;

namespace std
{
    // For debugging purposes only. Don't do this in production code.
    std::ostream & operator<<(std::ostream & s, std::ostream &)
    {
        return s << "std::cout";
    }
}

namespace mini_lambda
{
    // An MPL IntegralConstant
    template<class N>
    struct placeholder
      : proto::env_tag<placeholder<N>>
    {
        using proto::env_tag<placeholder>::operator=;

        // So placeholder terminals can be pretty-printed with display_expr
        friend std::ostream & operator << (std::ostream & s, placeholder)
        {
            return s << "_" << N::value + 1;
        }
    };

    template<std::size_t N>
    using placeholder_c = placeholder<std::integral_constant<std::size_t, N>>;

    // Some keyword types for our lambda EDSL
    namespace keyword
    {
        struct if_ {};
        struct else_ {};
        struct do_ {};
        struct while_ {};
        struct try_ {};
        struct catch_ {};
    }

    // Forward declaration for the mini-lambda grammar
    struct grammar;
    struct eval_if_else;

    // The grammar for mini-lambda expressions with actions for
    // evaluating the lambda expression.
    struct grammar
      : proto::def<
            proto::match(
                // When evaluating a placeholder, use the placeholder
                // fetch a value from the environment parameter, which
                // is a key/value store set up before calling grammar.
                proto::case_(
                    proto::terminal(placeholder<_>)
                  , proto::get_env(proto::_value)
                )
                // When evaluating if/then/else expressions of the form
                // "if_( E0 )[ E1 ].else_[ E2 ]", pass E0, E1 and E2 to
                // eval_if_else along with the "data" parameter. Note the
                // use of proto::member to match binary expressions like
                // "X.Y" where "Y" is a virtual data member.
              , proto::case_(
                    proto::subscript(
                        proto::member(
                            proto::subscript(
                                proto::function(
                                    proto::terminal(keyword::if_)
                                  , grammar
                                )
                              , grammar
                            )
                          , proto::terminal(keyword::else_)
                        )
                      , grammar
                    )
                  , eval_if_else(
                        proto::_right(proto::_left(proto::_left(proto::_left)))
                      , proto::_right(proto::_left(proto::_left))
                      , proto::_right
                      , proto::_env
                    )
                )
              , proto::default_(
                    proto::eval_with(grammar)
                )
            )
        >
    {};

    // A callable PolymorphicFunctionObject that evaluates
    // if/then/else expressions.
    struct eval_if_else
    {
        template<typename If, typename Then, typename Else, typename Args>
        void operator()(If const &if_, Then const &then_, Else const &else_, Args const &args) const
        {
            if(grammar()(if_, args))
            {
                grammar()(then_, args);
            }
            else
            {
                grammar()(else_, args);
            }
        }
    };

    // Here is the mini-lambda expression wrapper. It serves two purposes:
    // 1) To define operator() overloads that evaluate the lambda expression, and
    // 2) To define virtual data members like "else_" so that we can write
    //    expressions like "if_(X)[Y].else_[Z]".
    template<class ExprDesc>
    struct expression
      : proto::basic_expr<expression<ExprDesc>>
      , proto::expr_assign<expression<ExprDesc>>
      , proto::expr_subscript<expression<ExprDesc>>
    {
    private:
        template<std::size_t ...I, typename ...A>
        auto eval(proto::utility::indices<I...>, A &&...a) const
        BOOST_PROTO_AUTO_RETURN(
            grammar()(*this, proto::make_env(placeholder_c<I>() = std::forward<A>(a)...))
        )

    public:
        using proto::basic_expr<expression<ExprDesc>>::basic_expr;
        using proto::expr_assign<expression>::operator=;

        // Use BOOST_PROTO_EXTENDS_MEMBERS() to define "virtual"
        // data members that all expressions in the mini-lambda
        // domain will have. They can be used to create expressions
        // like "if_(x)[y].else_[z]" and "do_[y].while_(z)".
        BOOST_PROTO_EXTENDS_MEMBERS(
            expression,
            ((keyword::else_,   else_))
            ((keyword::while_,  while_))
            ((keyword::catch_,  catch_))
        );

        template<typename ...A>
        auto operator()(A &&... a) const
        BOOST_PROTO_AUTO_RETURN(
            this->eval(proto::utility::make_indices<sizeof...(A)>(), std::forward<A>(a)...)
        )
    };

    template<typename T>
    using var = proto::custom<expression<_>>::terminal<T>;

    using domain = proto::result_of::domain_of<var<placeholder_c<0>>>::type;

    namespace placeholders
    {
        // Define some placeholders
        namespace
        {
            constexpr auto const & _1 = proto::utility::static_const<var<placeholder_c<0>>>::value;
            constexpr auto const & _2 = proto::utility::static_const<var<placeholder_c<1>>>::value;
            constexpr auto const & _3 = proto::utility::static_const<var<placeholder_c<2>>>::value;
        }

        BOOST_PROTO_IGNORE_UNUSED(_1, _2, _3);

        // Define the if_() statement
        template<typename E>
        auto if_(E && e)
        BOOST_PROTO_AUTO_RETURN(
            proto::make_expr<proto::function, domain>(
                keyword::if_()
              , std::forward<E>(e)
            )
        )
    }

    using placeholders::if_;
}

int main()
{
    using namespace mini_lambda::placeholders;

    // OK, we can create if/then/else lambda expressions
    // and evaluate them.
    auto fun =
        if_(_1 > 0)
        [
            std::cout << _2 << '\n'
        ]
        .else_
        [
            std::cout << _3 << '\n'
        ];

    proto::display_expr(fun);
    fun(42, "positive", "non-positive");
    fun(-42, "positive", "non-positive");

    // Even though all expressions in the mini-lambda
    // domain have members named else_, while_, and catch_,
    // they all occupy the same byte in the expression.
    static_assert(sizeof(_1) == 3, "_1 should be only 3 bytes");
}
//]