text:
// sorted_data_interface_test_insert.cpp

/**
 *    Copyright (C) 2014 MongoDB 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.
 */

#include "mongo/db/storage/sorted_data_interface_test_harness.h"

#include <boost/scoped_ptr.hpp>

#include "mongo/db/storage/sorted_data_interface.h"
#include "mongo/unittest/unittest.h"

namespace mongo {

    using boost::scoped_ptr;

    // Insert a key and verify that the number of entries in the index equals 1.
    TEST( SortedDataInterface, Insert ) {
        scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() );
        scoped_ptr<SortedDataInterface> sorted( harnessHelper->newSortedDataInterface( false ) );

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            ASSERT( sorted->isEmpty( opCtx.get() ) );
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                WriteUnitOfWork uow( opCtx.get() );
                ASSERT_OK( sorted->insert( opCtx.get(), key1, loc1, true ) );
                uow.commit();
            }
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            ASSERT_EQUALS( 1, sorted->numEntries( opCtx.get() ) );
        }
    }

    // Insert a compound key and verify that the number of entries in the index equals 1.
    TEST( SortedDataInterface, InsertCompoundKey ) {
        scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() );
        scoped_ptr<SortedDataInterface> sorted( harnessHelper->newSortedDataInterface( false ) );

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            ASSERT( sorted->isEmpty( opCtx.get() ) );
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                WriteUnitOfWork uow( opCtx.get() );
                ASSERT_OK( sorted->insert( opCtx.get(), compoundKey1a, loc1, true ) );
                uow.commit();
            }
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            ASSERT_EQUALS( 1, sorted->numEntries( opCtx.get() ) );
        }
    }

    // Insert multiple, distinct keys at the same RecordId and verify that the
    // number of entries in the index equals the number that were inserted, even
    // when duplicates are not allowed.
    TEST( SortedDataInterface, InsertSameDiskLoc ) {
        scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() );
        scoped_ptr<SortedDataInterface> sorted( harnessHelper->newSortedDataInterface( false ) );

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            ASSERT( sorted->isEmpty( opCtx.get() ) );
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                WriteUnitOfWork uow( opCtx.get() );
                ASSERT_OK( sorted->insert( opCtx.get(), key1, loc1, true ) );
                ASSERT_OK( sorted->insert( opCtx.get(), key2, loc1, true ) );
                uow.commit();
            }
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            ASSERT_EQUALS( 2, sorted->numEntries( opCtx.get() ) );
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                WriteUnitOfWork uow( opCtx.get() );
                ASSERT_OK( sorted->insert( opCtx.get(), key3, loc1, true ) );
                uow.commit();
            }
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            ASSERT_EQUALS( 3, sorted->numEntries( opCtx.get() ) );
        }
    }

    // Insert multiple, distinct keys at the same RecordId and verify that the
    // number of entries in the index equals the number that were inserted, even
    // when duplicates are allowed.
    TEST( SortedDataInterface, InsertSameDiskLocWithDupsAllowed ) {
        scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() );
        scoped_ptr<SortedDataInterface> sorted( harnessHelper->newSortedDataInterface( true ) );

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            ASSERT( sorted->isEmpty( opCtx.get() ) );
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                WriteUnitOfWork uow( opCtx.get() );
                ASSERT_OK( sorted->insert( opCtx.get(), key1, loc1, false ) );
                ASSERT_OK( sorted->insert( opCtx.get(), key2, loc1, true /* allow duplicates */ ) );
                uow.commit();
            }
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            ASSERT_EQUALS( 2, sorted->numEntries( opCtx.get() ) );
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                WriteUnitOfWork uow( opCtx.get() );
                ASSERT_OK( sorted->insert( opCtx.get(), key3, loc1, true /* allow duplicates */ ) );
                uow.commit();
            }
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            ASSERT_EQUALS( 3, sorted->numEntries( opCtx.get() ) );
        }
    }

    // Insert the same key multiple times and verify that only 1 entry exists
    // in the index when duplicates are not allowed.
    TEST( SortedDataInterface, InsertSameKey ) {
        scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() );
        scoped_ptr<SortedDataInterface> sorted( harnessHelper->newSortedDataInterface( true ) );

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            ASSERT( sorted->isEmpty( opCtx.get() ) );
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                WriteUnitOfWork uow( opCtx.get() );
                ASSERT_OK( sorted->insert( opCtx.get(), key1, loc1, false ) );
                ASSERT_NOT_OK( sorted->insert( opCtx.get(), key1, loc2, false ) );
                uow.commit();
            }
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            ASSERT_EQUALS( 1, sorted->numEntries( opCtx.get() ) );
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                WriteUnitOfWork uow( opCtx.get() );
                ASSERT_NOT_OK( sorted->insert( opCtx.get(), key1, loc2, false ) );
                uow.commit();
            }
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            ASSERT_EQUALS( 1, sorted->numEntries( opCtx.get() ) );
        }
    }

namespace {

    // Insert the same key multiple times and verify that all entries exists
    // in the index when duplicates are allowed. Since it is illegal to open a cursor to an unique
    // index while the unique constraint is violated, this is tested by running the test 3 times,
    // removing all but one loc each time and verifying the correct loc remains.
    void _testInsertSameKeyWithDupsAllowed(const RecordId locs[3]) {
        for (int keeper = 0; keeper < 3; keeper++) {
            scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() );
            scoped_ptr<SortedDataInterface> sorted( harnessHelper->newSortedDataInterface( true ) );

            {
                scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
                ASSERT( sorted->isEmpty( opCtx.get() ) );
            }

            {
                scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
                {
                    WriteUnitOfWork uow( opCtx.get() );
                    ASSERT_OK(sorted->insert(opCtx.get(), key1, locs[0], false));
                    ASSERT_OK(sorted->insert(opCtx.get(), key1, locs[1], true));
                    ASSERT_OK(sorted->insert(opCtx.get(), key1, locs[2], true));
                    uow.commit();
                }
            }

            {
                scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
                {
                    WriteUnitOfWork uow( opCtx.get() );
                    for (int i = 0; i < 3; i++) {
                        if (i != keeper) {
                            sorted->unindex(opCtx.get(), key1, locs[i], true);
                        }
                    }
                    uow.commit();
                }
            }

            {
                scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
                ASSERT_EQUALS( 1, sorted->numEntries( opCtx.get() ) );

                scoped_ptr<SortedDataInterface::Cursor> cursor(sorted->newCursor(opCtx.get(), 1));
                cursor->locate(key1, RecordId::min());
                ASSERT_EQUALS(key1, cursor->getKey());
                ASSERT_EQUALS(locs[keeper], cursor->getRecordId());
            }
        }
    }

}  // namespace

    TEST( SortedDataInterface, InsertSameKeyWithDupsAllowedLocsAscending ) {
        const RecordId locs[3] = {loc1, loc2, loc3};
        _testInsertSameKeyWithDupsAllowed(locs);
    }

    TEST( SortedDataInterface, InsertSameKeyWithDupsAllowedLocsDescending ) {
        const RecordId locs[3] = {loc3, loc2, loc1};
        _testInsertSameKeyWithDupsAllowed(locs);
    }

    // Insert multiple keys and verify that the number of entries
    // in the index equals the number that were inserted.
    TEST( SortedDataInterface, InsertMultiple ) {
        scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() );
        scoped_ptr<SortedDataInterface> sorted( harnessHelper->newSortedDataInterface( true ) );

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            ASSERT( sorted->isEmpty( opCtx.get() ) );
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                WriteUnitOfWork uow( opCtx.get() );
                ASSERT_OK( sorted->insert( opCtx.get(), key1, loc1, false ) );
                ASSERT_OK( sorted->insert( opCtx.get(), key2, loc2, false ) );
                uow.commit();
            }
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            ASSERT_EQUALS( 2, sorted->numEntries( opCtx.get() ) );
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                WriteUnitOfWork uow( opCtx.get() );
                ASSERT_OK( sorted->insert( opCtx.get(), key3, loc3, false ) );
                uow.commit();
            }
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            ASSERT_EQUALS( 3, sorted->numEntries( opCtx.get() ) );
        }
    }

    // Insert multiple compound keys and verify that the number of entries
    // in the index equals the number that were inserted.
    TEST( SortedDataInterface, InsertMultipleCompoundKeys ) {
        scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() );
        scoped_ptr<SortedDataInterface> sorted( harnessHelper->newSortedDataInterface( true ) );

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            ASSERT( sorted->isEmpty( opCtx.get() ) );
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                WriteUnitOfWork uow( opCtx.get() );
                ASSERT_OK( sorted->insert( opCtx.get(), compoundKey1a, loc1, false ) );
                ASSERT_OK( sorted->insert( opCtx.get(), compoundKey1b, loc2, false ) );
                ASSERT_OK( sorted->insert( opCtx.get(), compoundKey2b, loc3, false ) );
                uow.commit();
            }
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            ASSERT_EQUALS( 3, sorted->numEntries( opCtx.get() ) );
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            {
                WriteUnitOfWork uow( opCtx.get() );
                ASSERT_OK( sorted->insert( opCtx.get(), compoundKey1c, loc4, false ) );
                ASSERT_OK( sorted->insert( opCtx.get(), compoundKey3a, loc5, false ) );
                uow.commit();
            }
        }

        {
            scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
            ASSERT_EQUALS( 5, sorted->numEntries( opCtx.get() ) );
        }
    }

} // namespace mongo

max_stars_repo_name: leifwalsh/mongo

max_issues_repo_name: leifwalsh/mongo

max_forks_repo_name: leifwalsh/mongo


text:
//
// Copyright (c) 2019 Vinnie Falco (vinnie.falco@gmail.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/vinniefalco/json
//

// Test that header file is self-contained.
#include <boost/json/basic_parser.hpp>

#include <boost/beast/_experimental/unit_test/suite.hpp>
#include <string>

#include "test.hpp"
#include "parse-vectors.hpp"

namespace boost {
namespace json {

class basic_parser_test : public beast::unit_test::suite
{
public:
    void
    split_grind(
        string_view s,
        error_code ex = {})
    {
        // make sure all split inputs
        // produce the same result.
        for(std::size_t i = 1;
            i < s.size(); ++i)
        {
            if(! BEAST_EXPECT(i < 100000))
                break;
            error_code ec;
            fail_parser p;
            auto const n =
                p.write_some(s.data(), i, ec);
            if(ec)
            {
                BEAST_EXPECTS(ec == ex,
                    ec.message());
                continue;
            }
            p.write(
                s.data() + n,
                s.size() - n, ec);
            if(! ec)
                p.finish(ec);
            if(! BEAST_EXPECTS(ec == ex,
                ec.message()))
                log << "should be " << ex.message() << std::endl;
        }
    }

    void
    fail_grind(
        string_view s,
        error_code ex = {})
    {
        // exercise all error paths
        for(std::size_t j = 1;;++j)
        {
            if(! BEAST_EXPECT(j < 100000))
                break;
            error_code ec;
            fail_parser p(j);
            p.write(
                s.data(), s.size(), ec);
            if(! ec)
                p.finish(ec);
            if(ec == error::test_failure)
                continue;
            BEAST_EXPECTS(ec == ex,
                ec.message());
            break;
        }
    }

    void
    throw_grind(
        string_view s,
        error_code ex = {})
    {
        // exercise all exception paths
        for(std::size_t j = 1;;++j)
        {
            if(! BEAST_EXPECT(j < 100000))
                break;
            error_code ec;
            throw_parser p(j);
            try
            {
                p.write(
                    s.data(), s.size(), ec);
                if(! ec)
                    p.finish(ec);
                BEAST_EXPECTS(ec == ex,
                    ec.message());
                break;
            }
            catch(test_exception const&)
            {
                continue;
            }
            catch(std::exception const& e)
            {
                BEAST_FAIL();
                log << "  " <<
                    e.what() << std::endl;
            }
        }
    }

    void
    grind(string_view s, bool good)
    {
        error_code ex;
        {
            fail_parser p;
            p.write(
                s.data(),
                s.size(),
                ex);
            if(! ex)
                p.finish(ex);
            if(good)
            {
                if(! BEAST_EXPECTS(
                    ! ex, ex.message()))
                    return;
            }
            else
            {
                if(! BEAST_EXPECT(ex))
                    return;
            }
        }

        split_grind(s, ex);
        throw_grind(s, ex);
        fail_grind(s, ex);
    }

    void
    good(string_view s)
    {
        grind(s, true);
    }

    void
    bad(string_view s)
    {
        grind(s, false);
    }

    void
    testObject()
    {
        good("{}");
        good("{ }");
        good("{ \t }");
        good("{\"x\":null}");
        good("{ \"x\":null}");
        good("{\"x\" :null}");
        good("{\"x\": null}");
        good("{\"x\":null }");
        good("{ \"x\" : null }");
        good("{ \"x\" : {} }");
        good("{ \"x\" : [] }");
        good("{ \"x\" : { \"y\" : null } }");
        good("{ \"x\" : [{}] }");
        good("{ \"x\":1, \"y\":null}");
        good("{\"x\":1,\"y\":2,\"z\":3}");
        good(" {\"x\":1,\"y\":2,\"z\":3}");
        good("{\"x\":1,\"y\":2,\"z\":3} ");
        good(" {\"x\":1,\"y\":2,\"z\":3} ");
        good("{ \"x\":1,\"y\":2,\"z\":3}");
        good("{\"x\" :1,\"y\":2,\"z\":3}");
        good("{\"x\":1 ,\"y\":2,\"z\":3}");
        good("{\"x\":1,\"y\" :2,\"z\":3}");
        good("{\"x\":1,\"y\": 2,\"z\":3}");
        good("{\"x\":1,\"y\":2 ,\"z\":3}");
        good("{\"x\":1,\"y\":2, \"z\":3}");
        good("{\"x\":1,\"y\":2, \"z\" :3}");
        good("{\"x\":1,\"y\":2, \"z\": 3}");
        good("{\"x\":1,\"y\":2, \"z\":3 }");
        good(" \t { \"x\" \n  :   1, \"y\" :2, \"z\" : 3} \n");

        good("[{\"x\":[{\"y\":null}]}]");

        bad ("{");
        bad (" {");
        bad (" {}}");
        bad ("{{}}");
        bad ("{[]}");
    }

    void
    testArray()
    {
        good("[]");
        good("[ ]");
        good("[ \t ]");
        good("[ \"\" ]");
        good("[ \" \" ]");
        good("[ \"x\" ]");
        good("[ \"x\", \"y\" ]");
        good("[1,2,3]");
        good(" [1,2,3]");
        good("[1,2,3] ");
        good(" [1,2,3] ");
        good("[1,2,3]");
        good("[ 1,2,3]");
        good("[1 ,2,3]");
        good("[1, 2,3]");
        good("[1,2 ,3]");
        good("[1,2, 3]");
        good("[1,2,3 ]");
        good(" [  1 , 2 \t\n ,  \n3]");

        bad ("[");
        bad (" [");
        bad (" []]");
        bad ("[{]");
        bad ("[ \"x\", ]");
    }

    void
    testString()
    {
        good("\""   "x"         "\"");
        good("\""   "xy"        "\"");
        good("\""   "x y"       "\"");

        bad ("\""   "\t"        "\"");

        // control after escape
        bad ("\"\\\\\n\"");
    }

    void
    testNumber()
    {
        good("0");
        good("0.0");
        good("0.10");
        good("0.01");
        good("1");
        good("10");
        good("1.5");
        good("10.5");
        good("10.25");
        good("10.25e0");
        good("1e1");
        good("1e10");
        good("1e+0");
        good("1e+1");
        good("0e+10");
        good("0e-0");
        good("0e-1");
        good("0e-10");
        good("1E+1");
        good("-0");
        good("-1");
        good("-1e1");
        good("1.1e309");
        good(   "9223372036854775807");
        good(  "-9223372036854775807");
        good(  "18446744073709551615");
        good( "-18446744073709551615");
        good(  "[9223372036854775807]");
        good( "[-9223372036854775807]");
        good( "[18446744073709551615]");
        good("[-18446744073709551615]");

        bad ("");
        bad ("-");
        bad ("00");
        bad ("00.");
        bad ("00.0");
        bad ("1a");
        bad (".");
        bad ("1.");
        bad ("1+");
        bad ("0.0+");
        bad ("0.0e+");
        bad ("0.0e-");
        bad ("0.0e0-");
        bad ("0.0e");
    }

    void
    testBoolean()
    {
        good("true");
        good(" true");
        good("true ");
        good("\ttrue");
        good("true\t");
        good("\r\n\t true\r\n\t ");

        bad ("TRUE");
        bad ("tRUE");
        bad ("trUE");
        bad ("truE");
        bad ("truex");
        bad ("tru");
        bad ("tr");
        bad ("t");

        good("false");
        good(" false");
        good("false ");
        good("\tfalse");
        good("false\t");
        good("\r\n\t false\r\n\t ");

        bad ("FALSE");
        bad ("fALSE");
        bad ("faLSE");
        bad ("falSE");
        bad ("falsE");
        bad ("falsex");
        bad ("fals");
        bad ("fal");
        bad ("fa");
        bad ("f");
    }

    void
    testNull()
    {
        good("null");
        good(" null");
        good("null ");
        good("\tnull");
        good("null\t");
        good("\r\n\t null\r\n\t ");

        bad ("NULL");
        bad ("nULL");
        bad ("nuLL");
        bad ("nulL");
        bad ("nullx");
        bad ("nul");
        bad ("nu");
        bad ("n");
    }

    void
    testParser()
    {
        auto const check =
        []( string_view s,
            bool is_done)
        {
            fail_parser p;
            error_code ec;
            p.write_some(
                s.data(), s.size(),
                ec);
            if(! BEAST_EXPECTS(! ec,
                ec.message()))
                return;
            BEAST_EXPECT(is_done ==
                p.is_done());
        };

        // is_done()

        check("{}", false);
        check("{} ", false);
        check("{}x", true);
        check("{} x", true);

        check("[]", false);
        check("[] ", false);
        check("[]x", true);
        check("[] x", true);

        check("\"a\"", false);
        check("\"a\" ", false);
        check("\"a\"x", true);
        check("\"a\" x", true);

        check("0", false);
        check("0 ", false);
        check("0x", true);
        check("0 x", true);
        check("00", true);
        check("0.", false);
        check("0.0", false);
        check("0.0 ", false);
        check("0.0 x", true);

        check("true", false);
        check("true ", false);
        check("truex", true);
        check("true x", true);

        check("false", false);
        check("false ", false);
        check("falsex", true);
        check("false x", true);

        check("null", false);
        check("null ", false);
        check("nullx", true);
        check("null x", true);

        // depth(), max_depth(), is_done()
        {
            {
                error_code ec;
                fail_parser p;
                BEAST_EXPECT(
                    p.depth() == 0);
                BEAST_EXPECT(
                    p.max_depth() > 0);
                p.max_depth(1);
                p.write("[{}]", 4, ec);
                BEAST_EXPECTS(
                    ec == error::too_deep,
                    ec.message());
                BEAST_EXPECT(! p.is_done());
            }
            {
                error_code ec;
                fail_parser p;
                BEAST_EXPECT(
                    p.max_depth() > 0);
                p.max_depth(1);
                p.write_some("[", 1, ec);
                BEAST_EXPECT(p.depth() == 1);
                if(BEAST_EXPECTS(! ec,
                    ec.message()))
                {
                    p.write_some("{", 1, ec);
                    BEAST_EXPECTS(
                        ec == error::too_deep,
                        ec.message());
                }
                BEAST_EXPECT(! p.is_done());
                ec = {};
                p.write_some("{}", 2, ec);
                BEAST_EXPECT(ec);
                p.reset();
                p.write("{}", 2, ec);
                if(! ec)
                    p.finish(ec);
                BEAST_EXPECTS(! ec, ec.message());
                BEAST_EXPECT(p.is_done());
            }
        }

        // maybe_flush
        {
            // VFALCO This must be equal to the size
            // of the temp buffer used in write_some.
            //
            int constexpr BUFFER_SIZE = 2048;

            {
                for(auto esc :
                    { "\\\"", "\\\\", "\\/", "\\b",
                      "\\f", "\\n", "\\r", "\\t", "\\u0000" })
                {
                    std::string big;
                    big = "\\\"" + std::string(BUFFER_SIZE-4, '*') + esc;
                    std::string s;
                    s = "{\"" + big + "\":\"" + big + "\"}";
                    fail_grind(s);
                }
            }

            {
                std::string big;
                big = "\\\"" +
                    std::string(BUFFER_SIZE + 1, '*');
                std::string s;
                s = "{\"" + big + "\":\"" + big + "\"}";
                fail_grind(s);
            }
        }

        // no input
        {
            error_code ec;
            fail_parser p;
            p.finish(ec);
            BEAST_EXPECT(ec);
        }
    }

    void
    testMembers()
    {
        // write_some(char const*, size_t, error_code&)
        {
            {
                error_code ec;
                fail_parser p;
                p.write_some("0", 1, ec);
                BEAST_EXPECTS(! ec, ec.message());
            }

            // partial write
            {
                error_code ec;
                fail_parser p;
                auto const n =
                    p.write_some("null x", 6, ec);
                BEAST_EXPECTS(! ec, ec.message());
                BEAST_EXPECT(n < 6);
            }
        }

        // write_some(char const*, size_t)
        {
            fail_parser p;
            BEAST_THROWS(
                p.write_some("x", 1),
                system_error);
        }

        // write(char const*, size_t, error_code&)
        {
            error_code ec;
            fail_parser p;
            p.write("0x", 2, ec);
            BEAST_EXPECTS(
                ec == error::extra_data,
                ec.message());
        }

        // write(char const*, size_t)
        {
            {
                fail_parser p;
                p.write("0", 1);
            }

            {
                fail_parser p;
                BEAST_THROWS(
                    p.write("0x", 2),
                    system_error);
            }
        }

        // finish(char const*, size_t, error_code&)
        {
            error_code ec;
            fail_parser p;
            p.finish("{", 1, ec);
            BEAST_EXPECTS(
                ec == error::incomplete,
                ec.message());
        }

        // finish(char const*, size_t)
        {
            {
                fail_parser p;
                p.finish("{}", 2);
            }

            {
                fail_parser p;
                BEAST_THROWS(
                    p.finish("{", 1),
                    system_error);
            }
        }

        // finish()
        {
            {
                fail_parser p;
                p.write("{}", 2);
                BEAST_EXPECT(! p.is_done());
                p.finish();
                BEAST_EXPECT(p.is_done());
            }

            {
                fail_parser p;
                p.write("{", 1);
                BEAST_EXPECT(! p.is_done());
                BEAST_THROWS(
                    p.finish(),
                    system_error);
            }
        }
    }

    void
    testParseVectors()
    {
        parse_vectors pv;
        for(auto const& v : pv)
        {
            if(v.result == 'i')
            {
                error_code ec;
                fail_parser p;
                p.write(
                    v.text.data(),
                    v.text.size(),
                    ec);
                grind(v.text,
                    ec ? false : true);
                continue;
            }
            if(v.result == 'y')
                grind(v.text, true);
            else
                grind(v.text, false);
        }
    }

    void
    run() override
    {
        testObject();
        testArray();
        testString();
        testNumber();
        testBoolean();
        testNull();
        testParser();
        testMembers();
        testParseVectors();
    }
};

BEAST_DEFINE_TESTSUITE(boost,json,basic_parser);

} // json
} // boost

ext: cpp

max_stars_repo_name: Vicfred/json

max_issues_repo_name: Vicfred/json

max_forks_repo_name: Vicfred/json


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

#include <pmp/algorithms/SurfaceParameterization.h>
#include <pmp/algorithms/DifferentialGeometry.h>
#include <cmath>
#include <Eigen/Dense>
#include <Eigen/Sparse>

//=============================================================================

namespace pmp {

//=============================================================================

SurfaceParameterization::SurfaceParameterization(SurfaceMesh& mesh)
    : m_mesh(mesh)
{
}

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

bool SurfaceParameterization::setupBoundaryConstraints()
{
    // get properties
    auto points = m_mesh.vertexProperty<Point>("v:point");
    auto tex = m_mesh.vertexProperty<TextureCoordinate>("v:tex");

    SurfaceMesh::VertexIterator vit, vend = m_mesh.verticesEnd();
    SurfaceMesh::Vertex vh;
    SurfaceMesh::Halfedge hh;
    std::vector<SurfaceMesh::Vertex> loop;

    // Initialize all texture coordinates to the origin.
    for (auto v : m_mesh.vertices())
        tex[v] = TextureCoordinate(0.5, 0.5);

    // find 1st boundary vertex
    for (vit = m_mesh.verticesBegin(); vit != vend; ++vit)
        if (m_mesh.isSurfaceBoundary(*vit))
            break;

    // no boundary found ?
    if (vit == vend)
    {
        std::cerr << "Mesh has no boundary." << std::endl;
        return false;
    }

    // collect boundary loop
    vh = *vit;
    hh = m_mesh.halfedge(vh);
    do
    {
        loop.push_back(m_mesh.toVertex(hh));
        hh = m_mesh.nextHalfedge(hh);
    } while (hh != m_mesh.halfedge(vh));

    // map boundary loop to unit circle in texture domain
    unsigned int i, n = loop.size();
    Scalar angle, l, length;
    TextureCoordinate t;

    // compute length of boundary loop
    for (i = 0, length = 0.0; i < n; ++i)
        length += distance(points[loop[i]], points[loop[(i + 1) % n]]);

    // map length intervalls to unit circle intervals
    for (i = 0, l = 0.0; i < n;)
    {
        // go from 2pi to 0 to preserve orientation
        angle = 2.0 * M_PI * (1.0 - l / length);

        t[0] = 0.5 + 0.5 * cosf(angle);
        t[1] = 0.5 + 0.5 * sinf(angle);

        tex[loop[i]] = t;

        ++i;
        if (i < n)
        {
            l += distance(points[loop[i]], points[loop[(i + 1) % n]]);
        }
    }

    return true;
}

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

void SurfaceParameterization::harmonic(bool useUniformWeights)
{
    // map boundary to circle
    if (!setupBoundaryConstraints())
    {
        std::cerr << "Could not perform setup of boundary constraints.\n";
        return;
    }

    // get properties
    auto tex = m_mesh.vertexProperty<TextureCoordinate>("v:tex");
    auto eweight = m_mesh.addEdgeProperty<Scalar>("e:param");
    auto idx = m_mesh.addVertexProperty<int>("v:idx", -1);

    // compute Laplace weight per edge: cotan or uniform
    for (auto e : m_mesh.edges())
    {
        eweight[e] =
            useUniformWeights ? 1.0 : std::max(0.0, cotanWeight(m_mesh, e));
    }

    // collect free (non-boundary) vertices in array free_vertices[]
    // assign indices such that idx[ free_vertices[i] ] == i
    unsigned i = 0;
    std::vector<SurfaceMesh::Vertex> free_vertices;
    free_vertices.reserve(m_mesh.nVertices());
    for (auto v : m_mesh.vertices())
    {
        if (!m_mesh.isSurfaceBoundary(v))
        {
            idx[v] = i++;
            free_vertices.push_back(v);
        }
    }

    // setup matrix A and rhs B
    const unsigned int n = free_vertices.size();
    Eigen::SparseMatrix<double> A(n, n);
    Eigen::MatrixXd B(n, 2);
    std::vector<Eigen::Triplet<double>> triplets;
    double w, ww;
    SurfaceMesh::Vertex v, vv;
    SurfaceMesh::Edge e;
    for (i = 0; i < n; ++i)
    {
        v = free_vertices[i];

        // rhs row
        B(i, 0) = 0.0;
        B(i, 1) = 0.0;

        // lhs row
        ww = 0.0;
        for (auto h : m_mesh.halfedges(v))
        {
            vv = m_mesh.toVertex(h);
            e = m_mesh.edge(h);
            w = eweight[e];
            ww += w;

            if (m_mesh.isSurfaceBoundary(vv))
            {
                B(i, 0) -= -w * tex[vv][0];
                B(i, 1) -= -w * tex[vv][1];
            }
            else
            {
                triplets.emplace_back(i, idx[vv], -w);
            }
        }
        triplets.emplace_back(i, i, ww);
    }

    // build sparse matrix from triplets
    A.setFromTriplets(triplets.begin(), triplets.end());

    // solve A*X = B
    Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> solver(A);
    Eigen::MatrixXd X = solver.solve(B);
    if (solver.info() != Eigen::Success)
    {
        std::cerr << "SurfaceParameterization: Could not solve linear system\n";
    }
    else
    {
        // copy solution
        for (i = 0; i < n; ++i)
        {
            v = free_vertices[i];
            tex[v][0] = X(i, 0);
            tex[v][1] = X(i, 1);
        }
    }

    // clean-up
    m_mesh.removeVertexProperty(idx);
    m_mesh.removeEdgeProperty(eweight);
}

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

bool SurfaceParameterization::setupLSCMBoundary()
{
    // constrain the two boundary vertices farthest from each other to fix
    // the translation and rotation of the resulting parameterization

    // vertex properties
    auto pos = m_mesh.vertexProperty<Point>("v:point");
    auto tex = m_mesh.vertexProperty<TexCoord>("v:tex");
    auto locked = m_mesh.addVertexProperty<bool>("v:locked", false);

    // find boundary vertices and store handles in vector
    std::vector<SurfaceMesh::Vertex> boundary;
    for (auto v : m_mesh.vertices())
        if (m_mesh.isSurfaceBoundary(v))
            boundary.push_back(v);

    // no boundary?
    if (boundary.empty())
    {
        return false;
    }

    // find boundary vertices with largest distance
    Scalar diam(0.0), d;
    SurfaceMesh::Vertex v1, v2;
    for (auto vv1 : boundary)
    {
        for (auto vv2 : boundary)
        {
            d = distance(pos[vv1], pos[vv2]);
            if (d > diam)
            {
                diam = d;
                v1 = vv1;
                v2 = vv2;
            }
        }
    }

    // pin these two boundary vertices
    for (auto v : m_mesh.vertices())
    {
        tex[v] = TexCoord(0.5, 0.5);
        locked[v] = false;
    }
    tex[v1] = TexCoord(0.0, 0.0);
    tex[v2] = TexCoord(1.0, 1.0);
    locked[v1] = true;
    locked[v2] = true;

    return true;
}

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

void SurfaceParameterization::lscm()
{
    // boundary constraints
    if (!setupLSCMBoundary())
        return;

    // properties
    auto pos = m_mesh.vertexProperty<Point>("v:point");
    auto tex = m_mesh.vertexProperty<TexCoord>("v:tex");
    auto idx = m_mesh.addVertexProperty<int>("v:idx", -1);
    auto weight = m_mesh.addHalfedgeProperty<dvec2>("h:lscm");
    auto locked = m_mesh.getVertexProperty<bool>("v:locked");
    assert(locked);

    // compute weights/gradients per face/halfedge
    for (auto f : m_mesh.faces())
    {
        // collect face halfedge
        auto fh_it = m_mesh.halfedges(f);
        auto ha = *fh_it;
        ++fh_it;
        auto hb = *fh_it;
        ++fh_it;
        auto hc = *fh_it;

        // collect face vertices
        dvec3 a = (dvec3)pos[m_mesh.toVertex(ha)];
        dvec3 b = (dvec3)pos[m_mesh.toVertex(hb)];
        dvec3 c = (dvec3)pos[m_mesh.toVertex(hc)];

        // calculate local coordinate system
        dvec3 z = cross(c - b, a - b);
        dvec3 x = normalize(b - a);
        dvec3 y = normalize(cross(z, x));

        // calculate local vertex coordinates
        dvec2 a2D(0.0, 0.0);
        dvec2 b2D(norm(b - a), 0.0);
        dvec2 c2D(dot(c - a, x), dot(c - a, y));

        // calculate double triangle area
        double area = norm(z);
        if (area)
            area = 1.0 / area;

        // calculate W_j,Ti (index by corner a,b,c and real/imaginary)
        double War = c2D[0] - b2D[0];
        double Wbr = a2D[0] - c2D[0];
        double Wcr = b2D[0] - a2D[0];
        double Wai = c2D[1] - b2D[1];
        double Wbi = a2D[1] - c2D[1];
        double Wci = b2D[1] - a2D[1];

        // store matrix information per halfedge
        weight[ha] = dvec2(War * area, Wai * area);
        weight[hb] = dvec2(Wbr * area, Wbi * area);
        weight[hc] = dvec2(Wcr * area, Wci * area);
    }

    // collect free (non-boundary) vertices in array free_vertices[]
    // assign indices such that idx[ free_vertices[i] ] == i
    unsigned i = 0;
    std::vector<SurfaceMesh::Vertex> free_vertices;
    free_vertices.reserve(m_mesh.nVertices());
    for (auto v : m_mesh.vertices())
    {
        if (!locked[v])
        {
            idx[v] = i++;
            free_vertices.push_back(v);
        }
    }

    // build matrix and rhs
    const unsigned int nV2 = 2 * m_mesh.nVertices();
    const unsigned int nV = m_mesh.nVertices();
    const unsigned int N = free_vertices.size();
    SurfaceMesh::Vertex vi, vj;
    SurfaceMesh::Halfedge hh;
    double si, sj0, sj1, sign;
    int row(0), c0, c1;

    Eigen::SparseMatrix<double> A(2 * N, 2 * N);
    Eigen::VectorXd b = Eigen::VectorXd::Zero(2 * N);
    std::vector<Eigen::Triplet<double>> triplets;

    for (unsigned int i = 0; i < nV2; ++i)
    {
        vi = SurfaceMesh::Vertex(i % nV);

        if (i < nV)
        {
            sign = 1.0;
            c0 = 0;
            c1 = 1;
        }
        else
        {
            sign = -1.0;
            c0 = 1;
            c1 = 0;
        }

        if (!locked[vi])
        {
            si = 0;

            for (auto h : m_mesh.halfedges(vi))
            {
                vj = m_mesh.toVertex(h);
                sj0 = sj1 = 0;

                if (!m_mesh.isSurfaceBoundary(h))
                {
                    const dvec2& wj = weight[h];
                    const dvec2& wi = weight[m_mesh.prevHalfedge(h)];

                    sj0 += sign * wi[c0] * wj[0] + wi[c1] * wj[1];
                    sj1 += -sign * wi[c0] * wj[1] + wi[c1] * wj[0];
                    si += wi[0] * wi[0] + wi[1] * wi[1];
                }

                h = m_mesh.oppositeHalfedge(h);
                if (!m_mesh.isSurfaceBoundary(h))
                {
                    const dvec2& wi = weight[h];
                    const dvec2& wj = weight[m_mesh.prevHalfedge(h)];

                    sj0 += sign * wi[c0] * wj[0] + wi[c1] * wj[1];
                    sj1 += -sign * wi[c0] * wj[1] + wi[c1] * wj[0];
                    si += wi[0] * wi[0] + wi[1] * wi[1];
                }

                if (!locked[vj])
                {
                    triplets.emplace_back(row, idx[vj], sj0);
                    triplets.emplace_back(row, idx[vj] + N, sj1);
                }
                else
                {
                    b[row] -= sj0 * tex[vj][0];
                    b[row] -= sj1 * tex[vj][1];
                }
            }

            triplets.emplace_back(row, idx[vi] + (i < nV ? 0 : N), 0.5 * si);

            ++row;
        }
    }

    // build sparse matrix from triplets
    A.setFromTriplets(triplets.begin(), triplets.end());

    // solve A*X = B
    Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> solver(A);
    Eigen::VectorXd x = solver.solve(b);
    if (solver.info() != Eigen::Success)
    {
        std::cerr << "SurfaceParameterization: Could not solve linear system\n";
    }
    else
    {
        // copy solution
        for (i = 0; i < N; ++i)
        {
            tex[free_vertices[i]] = TexCoord(x[i], x[i + N]);
        }
    }

    // scale tex coordiantes to unit square
    TexCoord bbmin(1, 1), bbmax(0, 0);
    for (auto v : m_mesh.vertices())
    {
        bbmin = min(bbmin, tex[v]);
        bbmax = max(bbmax, tex[v]);
    }
    bbmax -= bbmin;
    Scalar s = std::max(bbmax[0], bbmax[1]);
    for (auto v : m_mesh.vertices())
    {
        tex[v] -= bbmin;
        tex[v] /= s;
    }

    // clean-up
    m_mesh.removeVertexProperty(idx);
    m_mesh.removeVertexProperty(locked);
    m_mesh.removeHalfedgeProperty(weight);
}

//=============================================================================
} // namespace pmp
//=============================================================================

max_stars_repo_name: choyfung/pmp-library

max_issues_repo_name: choyfung/pmp-library

max_forks_repo_name: choyfung/pmp-library


text:
#ifndef __LEXER_HPP__
#define __LEXER_HPP__

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>

typedef struct{
    std::vector<std::vector<int>> CNF;
    int numVar;
    int numLiteral;
}clauses;

class lexer{
private:
    std::ifstream readfile;
    clauses cnf;
public:
    void lex(std::string filename);
    void parse_line(std::string line);
    clauses getClauses();
};

#endif

ext: hpp

max_stars_repo_name: acerols/SATSolver

max_issues_repo_name: acerols/SATSolver

max_forks_repo_name: acerols/SATSolver


text:
//          Copyright Carl Philipp Reh 2009 - 2016.
// 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 <fcppt/make_cref.hpp>
#include <fcppt/make_ref.hpp>
#include <fcppt/optional/reference.hpp>
#include <fcppt/preprocessor/disable_gcc_warning.hpp>
#include <fcppt/preprocessor/pop_warning.hpp>
#include <fcppt/preprocessor/push_warning.hpp>
#include <fcppt/config/external_begin.hpp>
#include <boost/test/unit_test.hpp>
#include <fcppt/config/external_end.hpp>

FCPPT_PP_PUSH_WARNING
FCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)

BOOST_AUTO_TEST_CASE(
	optional_ref
)
{
FCPPT_PP_POP_WARNING

	typedef
	fcppt::optional::reference<
		int
	>
	optional_int_ref;

	optional_int_ref const test1{};

	BOOST_CHECK(
		!test1.has_value()
	);

	int val{
		42
	};

	optional_int_ref test2(
		fcppt::make_ref(
			val
		)
	);

	BOOST_CHECK(
		test2.has_value()
	);

	BOOST_CHECK_EQUAL(
		test2.get_unsafe().get(),
		42
	);

	test2 =
		test1;

	BOOST_CHECK(
		!test2.has_value()
	);
}

FCPPT_PP_PUSH_WARNING
FCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)

BOOST_AUTO_TEST_CASE(
	optional_ref_const
)
{
FCPPT_PP_POP_WARNING

	typedef
	fcppt::optional::reference<
		int const
	>
	optional_int_ref_const;

	optional_int_ref_const const test1{};

	BOOST_CHECK(
		!test1.has_value()
	);

	int const val1{
		42
	};

	optional_int_ref_const test2(
		fcppt::make_cref(
			val1
		)
	);

	BOOST_CHECK(
		test2.has_value()
	);

	BOOST_CHECK_EQUAL(
		test2.get_unsafe().get(),
		42
	);

	int val2{
		50
	};

	optional_int_ref_const test3(
		fcppt::make_cref(
			val2
		)
	);

	BOOST_CHECK(
		test3.has_value()
	);

	BOOST_CHECK_EQUAL(
		test3.get_unsafe().get(),
		50
	);

	test3 = test1;

	BOOST_CHECK(
		!test3.has_value()
	);
}

max_stars_repo_name: vinzenz/fcppt

max_issues_repo_name: vinzenz/fcppt

max_forks_repo_name: vinzenz/fcppt


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

#include "runtime/data-stream-mgr.h"

#include <iostream>
#include <boost/functional/hash.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/thread.hpp>

#include "runtime/row-batch.h"
#include "runtime/data-stream-recvr.h"
#include "runtime/raw-value.h"
#include "runtime/runtime-state.h"
#include "util/debug-util.h"
#include "util/periodic-counter-updater.h"
#include "util/uid-util.h"

#include "gen-cpp/ImpalaInternalService.h"
#include "gen-cpp/ImpalaInternalService_types.h"

#include "common/names.h"

using namespace apache::thrift;
using std::boolalpha;

DEFINE_int32(datastream_sender_timeout_ms, 120000, "(Advanced) The time, in ms, that can "
    "elapse  before a plan fragment will time-out trying to send the initial row batch.");

/// This parameter controls the minimum amount of time a closed stream ID will stay in
/// closed_stream_cache_ before it is evicted. It needs to be set sufficiently high that
/// it will outlive all the calls to FindRecvrOrWait() for that stream ID, to distinguish
/// between was-here-but-now-gone and never-here states for the receiver. If the stream ID
/// expires before a call to FindRecvrOrWait(), the sender will see an error which will
/// lead to query cancellation. Setting this value higher will increase the size of the
/// stream cache (which is roughly 48 bytes per receiver).
/// TODO: We don't need millisecond precision here.
const int32_t STREAM_EXPIRATION_TIME_MS = 300 * 1000;

namespace impala {

DataStreamMgr::DataStreamMgr(MetricGroup* metrics) {
  metrics_ = metrics->GetChildGroup("datastream-manager");
  num_senders_waiting_ =
      metrics_->AddGauge<int64_t>("senders-blocked-on-recvr-creation", 0L);
  total_senders_waited_ =
      metrics_->AddCounter<int64_t>("total-senders-blocked-on-recvr-creation", 0L);
  num_senders_timedout_ = metrics_->AddCounter<int64_t>(
      "total-senders-timedout-waiting-for-recvr-creation", 0L);
}

inline uint32_t DataStreamMgr::GetHashValue(
    const TUniqueId& fragment_instance_id, PlanNodeId node_id) {
  uint32_t value = RawValue::GetHashValue(&fragment_instance_id.lo, TYPE_BIGINT, 0);
  value = RawValue::GetHashValue(&fragment_instance_id.hi, TYPE_BIGINT, value);
  value = RawValue::GetHashValue(&node_id, TYPE_INT, value);
  return value;
}

shared_ptr<DataStreamRecvr> DataStreamMgr::CreateRecvr(RuntimeState* state,
    const RowDescriptor& row_desc, const TUniqueId& fragment_instance_id,
    PlanNodeId dest_node_id, int num_senders, int buffer_size, RuntimeProfile* profile,
    bool is_merging) {
  DCHECK(profile != NULL);
  VLOG_FILE << "creating receiver for fragment="
            << fragment_instance_id << ", node=" << dest_node_id;
  shared_ptr<DataStreamRecvr> recvr(
      new DataStreamRecvr(this, state->instance_mem_tracker(), row_desc,
          fragment_instance_id, dest_node_id, num_senders, is_merging, buffer_size,
          profile));
  size_t hash_value = GetHashValue(fragment_instance_id, dest_node_id);
  lock_guard<SpinLock> l(lock_);
  fragment_recvr_set_.insert(make_pair(fragment_instance_id, dest_node_id));
  receiver_map_.insert(make_pair(hash_value, recvr));

  RendezvousMap::iterator it =
      pending_rendezvous_.find(make_pair(fragment_instance_id, dest_node_id));
  if (it != pending_rendezvous_.end()) it->second.promise->Set(recvr);

  return recvr;
}

shared_ptr<DataStreamRecvr> DataStreamMgr::FindRecvrOrWait(
    const TUniqueId& fragment_instance_id, PlanNodeId node_id,
    bool* already_unregistered) {
  RendezvousPromise* promise = NULL;
  RecvrId promise_key = make_pair(fragment_instance_id, node_id);
  *already_unregistered = false;
  {
    lock_guard<SpinLock> l(lock_);
    if (closed_stream_cache_.find(promise_key) != closed_stream_cache_.end()) {
      *already_unregistered = true;
      return shared_ptr<DataStreamRecvr>();
    }
    shared_ptr<DataStreamRecvr> rcvr = FindRecvr(fragment_instance_id, node_id, false);
    if (rcvr.get() != NULL) return rcvr;
    // Find the rendezvous, creating a new one if one does not already exist.
    RefCountedPromise* ref_counted_promise = &pending_rendezvous_[promise_key];
    promise = ref_counted_promise->promise;
    ref_counted_promise->IncRefCount();
  }
  bool timed_out = false;
  MonotonicStopWatch sw;
  sw.Start();
  num_senders_waiting_->Increment(1L);
  total_senders_waited_->Increment(1L);
  shared_ptr<DataStreamRecvr> rcvr =
      promise->Get(FLAGS_datastream_sender_timeout_ms, &timed_out);
  num_senders_waiting_->Increment(-1L);
  const string& time_taken = PrettyPrinter::Print(sw.ElapsedTime(), TUnit::TIME_NS);
  if (timed_out) {
    LOG(INFO) << "Datastream sender timed-out waiting for recvr for fragment instance: "
              << fragment_instance_id << " (time-out was: " << time_taken << "). ";
  } else {
    VLOG_RPC << "Datastream sender waited for " << time_taken
             << ", and did not time-out.";
  }
  if (timed_out) num_senders_timedout_->Increment(1L);
  {
    lock_guard<SpinLock> l(lock_);
    // If we are the last to leave, remove the rendezvous from the pending map. Any new
    // incoming senders will add a new entry to the map themselves.
    if (pending_rendezvous_[promise_key].DecRefCount() == 0) {
      pending_rendezvous_.erase(promise_key);
    }
  }
  return rcvr;
}

shared_ptr<DataStreamRecvr> DataStreamMgr::FindRecvr(
    const TUniqueId& fragment_instance_id, PlanNodeId node_id, bool acquire_lock) {
  VLOG_ROW << "looking up fragment_instance_id=" << fragment_instance_id
           << ", node=" << node_id;
  size_t hash_value = GetHashValue(fragment_instance_id, node_id);
  if (acquire_lock) lock_.lock();
  pair<RecvrMap::iterator, RecvrMap::iterator> range =
      receiver_map_.equal_range(hash_value);
  while (range.first != range.second) {
    shared_ptr<DataStreamRecvr> recvr = range.first->second;
    if (recvr->fragment_instance_id() == fragment_instance_id
        && recvr->dest_node_id() == node_id) {
      if (acquire_lock) lock_.unlock();
      return recvr;
    }
    ++range.first;
  }
  if (acquire_lock) lock_.unlock();
  return shared_ptr<DataStreamRecvr>();
}

Status DataStreamMgr::AddData(const TUniqueId& fragment_instance_id,
    PlanNodeId dest_node_id, const TRowBatch& thrift_batch, int sender_id) {
  VLOG_ROW << "AddData(): fragment_instance_id=" << fragment_instance_id
           << " node=" << dest_node_id
           << " size=" << RowBatch::GetBatchSize(thrift_batch);
  bool already_unregistered;
  shared_ptr<DataStreamRecvr> recvr = FindRecvrOrWait(fragment_instance_id, dest_node_id,
      &already_unregistered);
  if (recvr.get() == NULL) {
    // The receiver may remove itself from the receiver map via DeregisterRecvr() at any
    // time without considering the remaining number of senders.  As a consequence,
    // FindRecvrOrWait() may return NULL if a thread calling DeregisterRecvr() beat the
    // thread calling FindRecvr() in acquiring lock_. We detect this case by checking
    // already_unregistered - if true then the receiver was already closed deliberately,
    // and there's no unexpected error here. If already_unregistered is false,
    // FindRecvrOrWait() timed out, which is unexpected and suggests a query setup error;
    // we return DATASTREAM_SENDER_TIMEOUT to trigger tear-down of the query.
    return already_unregistered ? Status::OK() :
        Status(TErrorCode::DATASTREAM_SENDER_TIMEOUT, PrintId(fragment_instance_id));
  }
  DCHECK(!already_unregistered);
  recvr->AddBatch(thrift_batch, sender_id);
  return Status::OK();
}

Status DataStreamMgr::CloseSender(const TUniqueId& fragment_instance_id,
    PlanNodeId dest_node_id, int sender_id) {
  VLOG_FILE << "CloseSender(): fragment_instance_id=" << fragment_instance_id
            << ", node=" << dest_node_id;
  bool unused;
  shared_ptr<DataStreamRecvr> recvr = FindRecvrOrWait(fragment_instance_id, dest_node_id,
      &unused);
  if (recvr.get() != NULL) recvr->RemoveSender(sender_id);

  {
    // Remove any closed streams that have been in the cache for more than
    // STREAM_EXPIRATION_TIME_MS.
    lock_guard<SpinLock> l(lock_);
    ClosedStreamMap::iterator it = closed_stream_expirations_.begin();
    int64_t now = MonotonicMillis();
    int32_t before = closed_stream_cache_.size();
    while (it != closed_stream_expirations_.end() && it->first < now) {
      closed_stream_cache_.erase(it->second);
      closed_stream_expirations_.erase(it++);
    }
    DCHECK_EQ(closed_stream_cache_.size(), closed_stream_expirations_.size());
    int32_t after = closed_stream_cache_.size();
    if (before != after) {
      VLOG_QUERY << "Reduced stream ID cache from " << before << " items, to " << after
                 << ", eviction took: "
                 << PrettyPrinter::Print(MonotonicMillis() - now, TUnit::TIME_MS);
    }
  }
  return Status::OK();
}

Status DataStreamMgr::DeregisterRecvr(
    const TUniqueId& fragment_instance_id, PlanNodeId node_id) {
  VLOG_QUERY << "DeregisterRecvr(): fragment_instance_id=" << fragment_instance_id
             << ", node=" << node_id;
  size_t hash_value = GetHashValue(fragment_instance_id, node_id);
  lock_guard<SpinLock> l(lock_);
  pair<RecvrMap::iterator, RecvrMap::iterator> range =
      receiver_map_.equal_range(hash_value);
  while (range.first != range.second) {
    const shared_ptr<DataStreamRecvr>& recvr = range.first->second;
    if (recvr->fragment_instance_id() == fragment_instance_id
        && recvr->dest_node_id() == node_id) {
      // Notify concurrent AddData() requests that the stream has been terminated.
      recvr->CancelStream();
      RecvrId recvr_id =
          make_pair(recvr->fragment_instance_id(), recvr->dest_node_id());
      fragment_recvr_set_.erase(recvr_id);
      receiver_map_.erase(range.first);
      closed_stream_expirations_.insert(
          make_pair(MonotonicMillis() + STREAM_EXPIRATION_TIME_MS, recvr_id));
      closed_stream_cache_.insert(recvr_id);
      return Status::OK();
    }
    ++range.first;
  }

  stringstream err;
  err << "unknown row receiver id: fragment_instance_id=" << fragment_instance_id
      << " node_id=" << node_id;
  LOG(ERROR) << err.str();
  return Status(err.str());
}

void DataStreamMgr::Cancel(const TUniqueId& fragment_instance_id) {
  VLOG_QUERY << "cancelling all streams for fragment=" << fragment_instance_id;
  lock_guard<SpinLock> l(lock_);
  FragmentRecvrSet::iterator i =
      fragment_recvr_set_.lower_bound(make_pair(fragment_instance_id, 0));
  while (i != fragment_recvr_set_.end() && i->first == fragment_instance_id) {
    shared_ptr<DataStreamRecvr> recvr = FindRecvr(i->first, i->second, false);
    if (recvr.get() == NULL) {
      // keep going but at least log it
      stringstream err;
      err << "Cancel(): missing in stream_map: fragment=" << i->first
          << " node=" << i->second;
      LOG(ERROR) << err.str();
    } else {
      recvr->CancelStream();
    }
    ++i;
  }
}

}

ext: cc

max_stars_repo_name: henryr/minimised-impala

max_issues_repo_name: henryr/minimised-impala

max_forks_repo_name: henryr/minimised-impala


text:
//=======================================================================
// Copyright 2009 Trustees of Indiana University.
// Authors: Michael Hansen, Andrew Lumsdaine
//
// 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/graph/graph_archetypes.hpp>
#include <boost/graph/graph_concepts.hpp>
#include <boost/graph/grid_graph.hpp>
#include <boost/concept/assert.hpp>

#define DIMENSIONS 3
using namespace boost;

int main (int, char*[]) {

  typedef grid_graph<DIMENSIONS> Graph;
  typedef graph_traits<Graph>::vertex_descriptor Vertex;
  typedef graph_traits<Graph>::edge_descriptor Edge;

  BOOST_CONCEPT_ASSERT((BidirectionalGraphConcept<Graph> ));
  BOOST_CONCEPT_ASSERT((VertexListGraphConcept<Graph> ));
  BOOST_CONCEPT_ASSERT((EdgeListGraphConcept<Graph> ));
  BOOST_CONCEPT_ASSERT((IncidenceGraphConcept<Graph> ));
  BOOST_CONCEPT_ASSERT((AdjacencyGraphConcept<Graph> ));
  BOOST_CONCEPT_ASSERT((AdjacencyMatrixConcept<Graph> ));
  BOOST_CONCEPT_ASSERT((ReadablePropertyGraphConcept<Graph, Vertex, vertex_index_t> ));
  BOOST_CONCEPT_ASSERT((ReadablePropertyGraphConcept<Graph, Edge, edge_index_t> ));

  return (0);
}


text:
#ifndef __VSIM_LIGHT_HPP__
#define __VSIM_LIGHT_HPP__

#include <string>
#include <vector>
#include <memory>
#include <map>

#include <vsim/util/variant.hpp>
#include <vsim/env/base_element.hpp>

#include <Eigen/Core>

namespace vsim {

// Abstract light

struct Light: public BaseElement {
    enum Type { AMBIENT, POINT, DIRECTIONAL, SPOT } ;
    Light(Type t): type_(t) {}

    Type type_ ;
};

struct AmbientLight: public Light {
    AmbientLight(): Light(AMBIENT) {}
    AmbientLight(const Eigen::Vector3f &clr): Light(AMBIENT), color_(clr) {}

    Eigen::Vector3f color_ ;
};

struct PointLight: public Light {
    PointLight(): Light(POINT), constant_attenuation_(1.0), linear_attenuation_(0.0) {}
    PointLight(const Eigen::Vector3f &pos, const Eigen::Vector3f &clr): Light(POINT), position_(pos), color_(clr), constant_attenuation_(1.0), linear_attenuation_(0.0) {}

    Eigen::Vector3f position_ ;
    Eigen::Vector3f color_ ;
    float constant_attenuation_ ;
    float linear_attenuation_ ;
    float quadratic_attenuation_ ;
};

struct DirectionalLight: public Light {
    DirectionalLight(): Light(DIRECTIONAL) {}
    DirectionalLight(const Eigen::Vector3f &dir, const Eigen::Vector3f &clr): Light(DIRECTIONAL), direction_(dir), color_(clr) {}

    Eigen::Vector3f color_, direction_ ;
};

struct SpotLight: public Light {
    SpotLight(): Light(SPOT), constant_attenuation_(1.0),
    linear_attenuation_(0.0), quadratic_attenuation_(0.0),
    falloff_angle_(M_PI), falloff_exponent_(0){}

    Eigen::Vector3f color_, direction_, position_ ;
    float constant_attenuation_ ;
    float linear_attenuation_ ;
    float quadratic_attenuation_ ;
    float falloff_angle_, falloff_exponent_ ;
};

}
#endif

max_stars_repo_name: malasiot/vsim

max_issues_repo_name: malasiot/vsim

max_forks_repo_name: malasiot/vsim


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

 /*
  * A test for idset template class query.
  *
  * Author: Omid Mashayekhi <omidm@stanford.edu>
  */

#include <boost/unordered_set.hpp>
#include <iostream>  // NOLINT
#include <sstream>  // NOLINT
#include <string>
#include <map>
#include <set>
#include "shared/nimbus.h"
#include "shared/log.h"
#include "../../application/job_spawner/app.h"

#define START_ 100000

using namespace nimbus; // NOLINT

int main(int argc, const char *argv[]) {
  if (argc < 2) {
    std::cout << "ERROR: provide an integer!" << std::endl;
    exit(-1);
  }

  int elem_num;
  std::string s(argv[1]);
  std::stringstream ss(s);
  ss >> elem_num;
  if (ss.fail()) {
    std::cout << "ERROR: provide an integer!" << std::endl;
    exit(-1);
  }

  nimbus_initialize();
  Log log;

  log.StartTimer();
  // IDSet<job_id_t> set;
  // std::set<job_id_t> set;
  boost::unordered_set<job_id_t> set;
  for (int i = 0; i < elem_num; ++i) {
    set.insert(START_ + i);
  }
  log.StopTimer();
  std::cout << "Time elapsed idset insertion: " << log.timer() << std::endl;

  // IDSet<job_id_t> set_copy;
  // std::set<job_id_t> set_copy;
  boost::unordered_set<job_id_t> set_copy;
  log.StartTimer();
  set_copy = set;
  log.StopTimer();
  std::cout << "Time elapsed idset copy: " << log.timer() << std::endl;

//   log.StartTimer();
//   if (set.contains(START_ + 1)) {
//     log.StopTimer();
//     std::cout << "Time elapsed idset query: " << log.timer() << std::endl;
//   }

  log.StartTimer();
  std::map<int, int> map;
  for (int i = 0; i < elem_num; ++i) {
    map[START_ + i] = START_ + i;
  }
  log.StopTimer();
  std::cout << "Time elapsed map insertion: " << log.timer() << std::endl;

  std::map<int, int> map_copy;
  log.StartTimer();
  map_copy = map;
  log.StopTimer();
  std::cout << "Time elapsed map copy: " << log.timer() << std::endl;

  log.StartTimer();
  if (map.count(START_ + 1)) {
    log.StopTimer();
    std::cout << "Time elapsed map query: " << log.timer() << std::endl;
  }
}

max_stars_repo_name: schinmayee/nimbus

max_issues_repo_name: schinmayee/nimbus

max_forks_repo_name: schinmayee/nimbus


text:
// Copyright (c) 2020 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//
// Based on the xversion (renamed to extversion) subsystem from Bitcoin Unlimited
// Copyright (c) 2015-2020 The Bitcoin Unlimited developers
// License: MIT

#include <compat/endian.h>
#include <extversion.h>
#include <serialize.h>
#include <streams.h>
#include <test/setup_common.h>
#include <util/strencodings.h>
#include <version.h>

#include <boost/test/unit_test.hpp>

#include <cassert>
#include <cstdint>
#include <limits>
#include <map>
#include <random>
#include <tuple>
#include <utility>
#include <vector>

//! We will use a deterministic rng in this test, seeded with this value
static constexpr uint64_t seed = 0xfeed'f00d'1235'abcd;

BOOST_FIXTURE_TEST_SUITE(extversion_tests, BasicTestingSetup)

using extversion::VersionTuple;
using extversion::Message;

std::mt19937_64 g{seed};

auto gen(const uint64_t minimum, const uint64_t maximum) {
    assert(maximum >= minimum);
    return std::uniform_int_distribution<uint64_t>{minimum, maximum}(g);
}

BOOST_AUTO_TEST_CASE(version_tuple_basic) {
    using VT = VersionTuple;

    std::tuple<uint32_t, uint8_t, uint8_t, uint64_t> test_and_expected[] = {
        {       123,  12, 37,          1231237 },
        {         0,   0, 1,                 1 },
        {         0,   1, 0,               100 },
        {         1,   1, 1,             10101 },
        { 212345678,  99, 66, 2123456789966ULL },
    };
    for (const auto &tup : test_and_expected) {
        const auto maj = std::get<0>(tup);
        const auto min = std::get<1>(tup);
        const auto rev = std::get<2>(tup);
        const auto u64 = std::get<3>(tup);
        const VT vt{maj, min, rev};
        BOOST_CHECK_EQUAL(vt.Major(), maj);
        BOOST_CHECK_EQUAL(vt.Minor(), min);
        BOOST_CHECK_EQUAL(vt.Revision(), rev);
        BOOST_CHECK_EQUAL(vt.ToU64(), u64);
    }
}

using MajT = decltype(VersionTuple{}.Major());
using MinT = decltype(VersionTuple{}.Minor());
using RevT = decltype(VersionTuple{}.Revision());

BOOST_AUTO_TEST_CASE(version_tuple_u64_round_trip) {
    // Test to ensure that as long as we aren't using out-of-range minor/revision values,
    // everything is sane
    for (int i = 0; i < 4096; ++i) {
        constexpr auto lastNumberInRange = VersionTuple::MinorRevisionRange() - 1;
        const MajT maj = gen(0, std::numeric_limits<MajT>::max());
        const MinT min = gen(0, lastNumberInRange);
        const RevT rev = gen(0, lastNumberInRange);
        const auto vt = VersionTuple{maj, min, rev},
                   vt2 = VersionTuple::FromU64(vt.ToU64());
        BOOST_CHECK(vt == vt2);
        BOOST_CHECK_EQUAL(vt.ToU64(), vt2.ToU64());
        BOOST_CHECK_EQUAL(vt.Major(), maj);
        BOOST_CHECK_EQUAL(vt.Minor(), min);
        BOOST_CHECK_EQUAL(vt.Revision(), rev);
    }
}

BOOST_AUTO_TEST_CASE(version_tuple_out_of_range) {
    // Test to ensure that some out-of-range minor/revision values may lose information
    // (as is expected by the spec)
    for (int i = 0; i < 10000; ++i) {
        constexpr auto outOfRangeBegin = VersionTuple::MinorRevisionRange();
        const MajT maj = gen(0, std::numeric_limits<MajT>::max());
        const MinT min = gen(outOfRangeBegin, std::numeric_limits<MinT>::max());
        const RevT rev = gen(outOfRangeBegin, std::numeric_limits<RevT>::max());
        const auto vt = VersionTuple{maj, min, rev},
                   vt2 = VersionTuple::FromU64(vt.ToU64());
        BOOST_CHECK(vt != vt2);
    }
}

BOOST_AUTO_TEST_CASE(message_tests) {
    using Vec = std::vector<uint8_t>;
    using Map = std::map<uint8_t, Vec>;
    using MMap = std::multimap<uint8_t, Vec>;

    // Check that a ser/unser round-trip of Message works
    Vec vtmp;
    Message msg, msg2;
    msg.SetVersion({1, 2, 3});
    CVectorWriter(SER_NETWORK, PROTOCOL_VERSION, vtmp, 0) << msg;
    VectorReader(SER_NETWORK, PROTOCOL_VERSION, vtmp, 0) >> msg2;
    BOOST_CHECK(msg.GetVersion() && msg2.GetVersion() && *msg.GetVersion() == *msg2.GetVersion());

    // Check that serializing a map -> unserializing as Message works
    // Note that we lack the compact map serializer so we use a map with
    // uint8_t keys to ensure it serializes like the BU compact map.
    static_assert (uint8_t(extversion::Key::Version) == uint64_t(extversion::Key::Version),
                   "Assumption is that Version key fits inside an 8-bit integer");
    Map m1{{
        { uint8_t(extversion::Key::Version), {100} },
    }};
    Vec v1;
    CVectorWriter(SER_NETWORK, PROTOCOL_VERSION, v1, 0) << m1;
    BOOST_CHECK(v1.size() > 0);
    msg = Message();
    VectorReader(SER_NETWORK, PROTOCOL_VERSION, v1, 0) >> msg;

    BOOST_CHECK(bool(msg.GetVersion()));
    if (auto ver = msg.GetVersion())
        BOOST_CHECK(*ver == VersionTuple(0, 1, 0));

    // Check that serialize again is equal
    vtmp.clear();
    CVectorWriter(SER_NETWORK, PROTOCOL_VERSION, vtmp, 0) << msg;
    BOOST_CHECK(vtmp == v1);

    // Next, check the requirement that subsequent duplicate keys
    // in the map overwrite previous keys.
    const auto SerializeMMap = [](CVectorWriter &&vw, const MMap &m) {
        WriteCompactSize(vw, m.size());
        for (const auto &entry : m)
            Serialize(vw, entry);
    };
    MMap m2{{
        { uint8_t(extversion::Key::Version), {012} },
        { uint8_t(extversion::Key::Version), {123} },
        { uint8_t(extversion::Key::Version), {234} },
    }};
    Vec v2;
    SerializeMMap(CVectorWriter{SER_NETWORK, PROTOCOL_VERSION, v2, 0}, m2);
    BOOST_CHECK(v2.size() > 0);
    msg = Message();
    VectorReader(SER_NETWORK, PROTOCOL_VERSION, v2, 0) >> msg;

    BOOST_CHECK(bool(msg.GetVersion()));
    if (auto ver = msg.GetVersion())
        BOOST_CHECK(*ver == VersionTuple(0, 2, 34));

    // Next, try a map with below the key limit, at the key limit, and beyond the key limit
    // the first two should not throw, and the last should.
    using P = std::pair<uint16_t, bool>; // nKeys, shouldThrow
    BOOST_CHECK(Message::MaxNumKeys() < std::numeric_limits<uint16_t>::max());
    const P tests[] = {
        { Message::MaxNumKeys() - 1, false },
        { Message::MaxNumKeys(), false },
        { Message::MaxNumKeys() + 1, true },
    };
    for (auto & pair : tests) {
        const uint16_t nKeys = pair.first;
        const bool shouldThrow = pair.second;
        const uint16_t le16 = htole16(nKeys);
        const uint8_t *le8 = reinterpret_cast<const uint8_t *>(&le16);
        vtmp = {
            // Compact size (16-bit) for number of keys
            253, le8[0], le8[1],
        };
        static_assert (uint64_t(extversion::Key::Version) != 1, "This code assumes Version key is != 1");
        vtmp.resize(vtmp.size() + nKeys*3, 1); // each entry has minimum 3 bytes
        msg = Message();
        // IF shouldThrow == true, then this should throw, with "size too long" in the message
        try {
            VectorReader(SER_NETWORK, PROTOCOL_VERSION, vtmp, 0) >> msg;
            if (shouldThrow)
                throw std::runtime_error("Test failed -- expected Message deserialization to throw but it didn't");
            // shouldThrow == false case: all the keys didn't match Version, so Version should still be unset
            BOOST_CHECK(!msg.GetVersion());
        } catch (const std::ios_base::failure &e) {
            if (!shouldThrow || std::string(e.what()).find("size too large") == std::string::npos)
                throw;
        }
    }
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: EyeOfPython/bitcoin-cash-node


text:
#include <assert.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#include <NTL/GF2X.h>
#include <NTL/GF2XFactoring.h>
#include <NTL/GF2E.h>
#include <NTL/GF2EX.h>
#include <NTL/GF2EXFactoring.h>

#include "gcm.h"

using namespace std;
using namespace NTL;

int main(int argc, char **argv)
{
    struct slice a1, c1, t1, a2, c2, t2;
    struct slice *sp[] = {&a1, &c1, &t1, &a2, &c2, &t2};
    int i;
    GF2EX p, p1, p2;
    vec_pair_GF2EX_long factors;
    char out[33];

    argc -= 1;
    argv += 1;

    assert(argc == 6);

    for (i = 0; i < argc; i += 1) {
        hex2bytes(sp[i], argv[i]);
    }

    initfield();
    buildpoly(p1, &a1, &c1, &t1);
    buildpoly(p2, &a2, &c2, &t2);
    p = p1 + p2;
    MakeMonic(p);
    CanZass(factors, p);

    for (i = 0; i < factors.length(); i += 1) {
        if (deg(factors[i].a) == 1) {
            felem2hex(out, factors[i].a[0]);
            printf("%s\n", out);
        }
    }

    return 0;
}

max_stars_repo_name: nonce-disrespect/nonce-disrespect

max_issues_repo_name: nonce-disrespect/nonce-disrespect

max_forks_repo_name: nonce-disrespect/nonce-disrespect


text:
#include <vector>
#include <type_traits>

#include <gtest/gtest.h>

#include <boost/pfr.hpp>

#include "mystruct.h"

TEST(unittest, bundle_dereference) {

  dummy::mystruct s = {10, "bar", true};
  auto t = boost::pfr::get<0>(s);
  EXPECT_EQ(t, 10);
}

TEST(unittest, bundle_getsize) {

  dummy::mystruct s = {10, "bar", true};
  constexpr std::size_t t = boost::pfr::detail::fields_count<decltype(s)>();
  EXPECT_EQ(t, 3);
}

TEST(unittest, bundle_gettype) {

  dummy::mystruct s = {10, "bar", true};
  static_assert(std::is_same<decltype(boost::pfr::get<0>(s)), int&>::value, "type mismatch");

  using deref_t = std::remove_reference<decltype(boost::pfr::get<0>(s))>::type;
  static_assert(std::is_same<deref_t, int>::value, "type mismatch");
}

TEST(unittest, bundle_gettype2) {

  // only with the type
  using ref_t = decltype(boost::pfr::get<0>(std::declval<dummy::mystruct>()));
  using obj_t = std::remove_reference<ref_t>::type;
  static_assert(std::is_same<obj_t, int>::value, "type mismatch");
}

#include <meta/bundles/aos.h>

TEST(unittest, bundle_aos) {

  using bundle_t = meta::bundle<dummy::mystruct, meta::bundles::layout::aos>;

  bundle_t b;
  b.push_back({10, "bar", true});
}

#include <meta/bundles/soa.h>
TEST(unittest, bundle_soa) {

  using bundle_t = meta::bundle<dummy::mystruct, meta::bundles::layout::soa>;

  bundle_t b;
  b.push_back({10, "bar", true});
}

int main(int argc, char* argv[]) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

max_stars_repo_name: vermosen/meta

max_issues_repo_name: vermosen/meta

max_forks_repo_name: vermosen/meta


text:
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
//    names, trademarks, service marks, or product names of the Licensor
//    and its affiliates, except as required to comply with Section 4(c) of
//    the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "pxr/pxr.h"
#include "usdMaya/editUtil.h"

#include "usdMaya/util.h"

#include <boost/python/args.hpp>
#include <boost/python/def.hpp>
#include <boost/python.hpp>

#include "pxr/base/tf/pyResultConversions.h"
#include "pxr/base/tf/pyEnum.h"

#include <maya/MFnAssembly.h>
#include <maya/MObject.h>
#include <maya/MStatus.h>
#include <maya/MString.h>

#include <string>

using namespace std;
using namespace boost::python;
using namespace boost;

#define BOOST_PYTHON_NONE boost::python::object()

PXR_NAMESPACE_USING_DIRECTIVE

namespace {

static
boost::python::object
_GetEditFromString(
        const std::string& assemblyPath,
        const std::string& editString)
{
    MObject assemblyObj;
    MStatus status = UsdMayaUtil::GetMObjectByName(assemblyPath,
                                                      assemblyObj);
    if (status != MS::kSuccess) {
        TF_CODING_ERROR("EditUtil.GetEditFromString: "
                        "assembly dag path expected, not found!");
        return BOOST_PYTHON_NONE;
    }

    MFnAssembly assemblyFn(assemblyObj, &status);
    if (status != MS::kSuccess) {
        TF_CODING_ERROR("EditUtil.GetEditFromString: "
                        "assembly dag path expected, not found!");
        return BOOST_PYTHON_NONE;
    }

    SdfPath editPath;
    UsdMayaEditUtil::RefEdit refEdit;
    if (!UsdMayaEditUtil::GetEditFromString(assemblyFn,
                                               editString,
                                               &editPath,
                                               &refEdit)) {
        TF_CODING_ERROR("EditUtil.GetEditFromString: invalid edit");
        return BOOST_PYTHON_NONE;
    }

    return boost::python::make_tuple(editPath, refEdit);
}

static
boost::python::object
_GetEditsForAssembly(
        const std::string& assemblyPath)
{
    UsdMayaEditUtil::PathEditMap refEdits;
    std::vector< std::string > invalidEdits;

    MObject assemblyObj;
    MStatus status = UsdMayaUtil::GetMObjectByName(assemblyPath,
                                                      assemblyObj);
    if (status != MS::kSuccess) {
        TF_CODING_ERROR("EditUtil.GetEditsForAssembly: "
                        "assembly dag path expected, not found!");
        return BOOST_PYTHON_NONE;
    }

    UsdMayaEditUtil::GetEditsForAssembly(assemblyObj,
                                            &refEdits,
                                            &invalidEdits);

    boost::python::dict editDict;
    TF_FOR_ALL( pathEdits, refEdits )
    {
        boost::python::list editList;
        TF_FOR_ALL( edit, pathEdits->second )
        {
            editList.append( *edit );
        }

        editDict[ pathEdits->first ] = editList;
    }

    return boost::python::make_tuple(editDict,invalidEdits);
}

static bool
_GetRefEditsFromDict(
    boost::python::dict &refEditDict,
    UsdMayaEditUtil::PathEditMap *refEdits )
{
    boost::python::list keys = refEditDict.keys();
    for( int i=0; i<len(keys); i++ )
    {
        boost::python::extract<SdfPath> extractedKey(keys[i]);
        if( !extractedKey.check() )
        {
            TF_CODING_ERROR( "EditUtil.ApplyEditsToProxy:"
                             " SdfPath key expected, not found!" );
            return false;
        }
        else
        {
            SdfPath path = extractedKey;

            UsdMayaEditUtil::RefEditVec pathEdits;

            boost::python::extract<boost::python::list>
                    extractedList( refEditDict[path] );

            if( !extractedList.check() )
            {
                TF_CODING_ERROR( "EditUtil.ApplyEditsToProxy:"
                                 " list value expected, not found!" );
                return false;
            }
            else
            {
                boost::python::list editList = extractedList;
                for( int j=0; j<len(extractedList); j++ )
                {
                    boost::python::extract<UsdMayaEditUtil::RefEdit>
                            extractedEdit(editList[j]);

                    if( !extractedEdit.check() )
                    {
                        TF_CODING_ERROR( "EditUtil.ApplyEditsToProxy:"
                                         " RefEdit expected in list, not found!");
                        return false;
                    }
                    else
                    {
                        pathEdits.push_back( extractedEdit );
                    }
                }
            }

            (*refEdits)[path] = pathEdits;
        }
    }

    return true;
}

static boost::python::object
_ApplyEditsToProxy(
    boost::python::dict &refEditDict,
    const UsdStagePtr &stage,
    const UsdPrim &proxyRootPrim )
{
    UsdMayaEditUtil::PathEditMap refEdits;
    if( !_GetRefEditsFromDict( refEditDict, &refEdits ) )
        return BOOST_PYTHON_NONE;

    std::vector< std::string > failedEdits;

    UsdMayaEditUtil::ApplyEditsToProxy(
            refEdits,stage,proxyRootPrim,&failedEdits);

    return boost::python::make_tuple(failedEdits.empty(),failedEdits);
}

static boost::python::object
_GetAvarEdits(
    boost::python::dict &refEditDict )
{
    UsdMayaEditUtil::PathEditMap refEdits;
    if( !_GetRefEditsFromDict( refEditDict, &refEdits ) )
        return BOOST_PYTHON_NONE;

    UsdMayaEditUtil::PathAvarMap avarMap;
    UsdMayaEditUtil::GetAvarEdits( refEdits, &avarMap );

    boost::python::dict pathDict;
    TF_FOR_ALL( pathEdits, avarMap )
    {
        boost::python::dict valueMap;
        TF_FOR_ALL( avarEdit, pathEdits->second )
        {
            valueMap[avarEdit->first] = avarEdit->second;
        }

        pathDict[ pathEdits->first ] = valueMap;
    }

    return pathDict;
}

} // anonymous namespace

void wrapEditUtil()
{
    {
        scope EditUtil =
            class_< UsdMayaEditUtil,
                    boost::noncopyable>("EditUtil", "UsdMaya edit utilities")
            .def("GetEditFromString",
                 &_GetEditFromString)
            .staticmethod("GetEditFromString")
            .def("GetEditsForAssembly",
                 &_GetEditsForAssembly)
            .staticmethod("GetEditsForAssembly")
            .def("ApplyEditsToProxy",
                 &_ApplyEditsToProxy)
            .staticmethod("ApplyEditsToProxy")
            .def("GetAvarEdits",
                 &_GetAvarEdits)
            .staticmethod("GetAvarEdits")
        ;

        enum_<UsdMayaEditUtil::EditOp>("EditOp")
            .value("OP_TRANSLATE", UsdMayaEditUtil::OP_TRANSLATE)
            .value("OP_ROTATE", UsdMayaEditUtil::OP_ROTATE)
            .value("OP_SCALE", UsdMayaEditUtil::OP_SCALE)
        ;

        enum_<UsdMayaEditUtil::EditSet>("EditSet")
            .value("SET_ALL", UsdMayaEditUtil::SET_ALL)
            .value("SET_X", UsdMayaEditUtil::SET_X)
            .value("SET_Y", UsdMayaEditUtil::SET_Y)
            .value("SET_Z", UsdMayaEditUtil::SET_Z)
        ;

        typedef UsdMayaEditUtil::RefEdit RefEdit;
        class_<RefEdit>("RefEdit", "Assembly edit")
            .def_readwrite("editString", &RefEdit::editString)
            .def_readwrite("op", &RefEdit::op)
            .def_readwrite("set", &RefEdit::set)
            .add_property("value",
                make_getter(&RefEdit::value,
                    return_value_policy<return_by_value>()),
                make_setter(&RefEdit::value))
        ;
    }
}

max_stars_repo_name: octarrow/USD

max_issues_repo_name: octarrow/USD

max_forks_repo_name: octarrow/USD


text:
/*
Copyright (C) 2016 Thomas Hauth. All Rights Reserved.
* Written by Thomas Hauth (Thomas.Hauth@web.de)

This file is part of Kung Foo Barracuda.

Kung Foo Barracuda 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.

Kung Foo Barracuda 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 Kung Foo Barracuda.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <iostream>
#include <vector>
#include <boost/program_options.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>

#include <DescentLogic/src/DescentFramework.h>

//#include "CommandLineOptions.h"

// set via the build system, if a profile is needed
#ifdef USE_PROFILER
#include <gperftools/profiler.h>
#endif

namespace po = boost::program_options;

// use ./DescentGame --fullscreen --resolution 1366x768
// on the notebook for the total fun

int main(int argc, const char* argv[]) {
	SDLInterfaceInitData sdlInitData;

	std::vector < std::string > opts;

	for (int i = 0; i < argc; i++) {
		opts.push_back(std::string(argv[i]));
	}

	// running fullscreen is default
	sdlInitData.Fullscreen = false;
	bool runDemoMode = false;
	bool muted = false;
	bool forwardScroll = false;
	bool withIntro = false;
/*
	if (commandline::handleCommandLine(sdlInitData, opts, runDemoMode, muted, forwardScroll, withIntro)
			== false)
		return 0;*/

	DescentFramework f(false, runDemoMode, muted, forwardScroll, withIntro, true);

	f.initRenderEngine(sdlInitData);

	// todo: make this a lot nicer, by templating the FW class
#ifdef USE_PROFILER
	ProfilerStart("GameLoop.perf");
#endif

	f.execute();

#ifdef USE_PROFILER
	ProfilerStop();
#endif

	// done globally here for all used SDL systems;
	SDL_Quit();

	return 0;
}

max_stars_repo_name: poseidn/KungFoo

max_issues_repo_name: poseidn/KungFoo

max_forks_repo_name: poseidn/KungFoo


text: #include <boost/mpl/aux_/preprocessed/mwcw/set.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/**               _______   _______   _  ____  _____
 *               / ___/ /  / __/ _ | / |/ / / / / _ \
 *              / /__/ /__/ _// __ |/    / /_/ / ___/
 *              \___/____/___/_/ |_/_/|_/\____/_/
 *
 *   Copyright (C) 2016  Fabian Thuering (fabian_thuering@hotmail.com)
 *
 * This file is distributed under the MIT Open Source License. See
 * LICENSE.TXT for details.
 */

#include <cleanup/CommandLine.h>
#include <cleanup/Error.h>
#include <boost/filesystem.hpp>
#include <boost/version.hpp>
#include <tbb/tbb_stddef.h>
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <initializer_list>
#include <string>
#include <vector>

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

CLEANUP_NAMESPACE_BEGIN

CommandLine::CommandLine() : desc_("Options")
{
    desc_.add_options()
        // --help
        ("help", "Display this information.")
        // --version
        ("version", "Display version information.")
        // --cache, -c
        ("cache,c", "Print the found files but don't delete them.")
        // --quiet
        ("quiet", "Be quit (no output to terminal).")
        // --single
        ("single", "Run single threaded version.")
        // --dir, -d
        ("dir,d", po::value<std::vector<std::string>>(),
         "Specify the directories at which the recursive search shall start. "
         "These directories will be merged with the directories found in the "
         "configuration file.")
        // --config-file
        ("config-file", po::value<std::vector<std::string>>(),
         "Absolute path to the configuration file. If nothing is specified, "
         "the program will use:"
#ifdef CLEANUP_PLATFORM_WINDOWS
         "\n %HOMEPATH%\\.cleanup\\config.xml")
#else
         "\n $HOME/.cleanup/config.xml")
#endif
        // --add-dir
        ("add-dir", po::value<std::vector<std::string>>(),
         "Add a directory to the config file.")
        // --remove-dir
        ("remove-dir", po::value<std::vector<std::string>>(),
         "Remove a directory from the config file.");

    // Associate positional arguments to options
    posDesc_.add("dir", -1);
}

CommandLine::CommandLine(int argc, const char* const argv[]) : CommandLine()
{
    parse(argc, argv);
}

/// Check if the value of arg is in the list
template <class T, class VarMap>
inline void validate(const std::string& arg,
                     const VarMap& varMap,
                     std::initializer_list<T> list)
{
    if(varMap.count(arg)
       && std::count(list.begin(), list.end(), varMap[arg].template as<T>())
              == 0)
        throw po::validation_error(po::validation_error::invalid_option_value,
                                   arg, varMap[arg].template as<T>());
}

void CommandLine::parse(int argc, const char* const argv[])
{
    try
    {
        po::store(po::command_line_parser(argc, argv)
                      .options(desc_)
                      .positional(posDesc_)
                      .run(),
                  variableMap_);
        po::notify(variableMap_);
    }
    catch(const std::exception& e)
    {
        Error::fatal({e.what(), ", for help type '",
                      fs::path(argv[0]).filename().string(), " --help'"});
    }
}

NORETURN void CommandLine::printHelp() const NOEXCEPT
{
    std::cout << "Usage: cleanup [options] directories...\n\n";
    std::cout << desc_ << std::endl;
    std::exit(EXIT_SUCCESS);
}

void CommandLine::printVersion() NOEXCEPT
{
    std::cout << "cleanup - " << CLEANUP_VERSION_STRING
        << "\nCopyright (C) 2016 Fabian Thuering. All rights reserved."
        << " There is NO warranty; \nnot even for MERCHANTABILITY or FITNESS "
        << "FOR A PARTICULAR PURPOSE.\n";

    // Tag compiler
#if defined(CLEANUP_COMPILER_MSVC)
    std::cout << " - Compiler: Microsoft(R) Visual C/C++ " << _MSC_VER << "\n";
#elif defined(CLEANUP_COMPILER_INTEL)
    std::cout << " - Compiler: " << __VERSION__ << "\n";
#elif defined(CLEANUP_COMPILER_CLANG)
    std::cout << " - Compiler: LLVM Clang " << __clang_version__ << "\n";
#elif defined(CLEANUP_COMPILER_GNU)
    std::cout << " - Compiler: GNU GCC/G++ " << __VERSION__ << "\n";
#endif

    // Boost version
    std::cout << " - Boost version: " << BOOST_LIB_VERSION << "\n";

    // Boost version
    std::cout << " - TBB version: " << TBB_VERSION_MAJOR << "."
              << TBB_VERSION_MINOR << "\n";

    std::exit(EXIT_SUCCESS);
}

CLEANUP_NAMESPACE_END

max_stars_repo_name: thfabian/cleanup

max_issues_repo_name: thfabian/cleanup

max_forks_repo_name: thfabian/cleanup


text:
// Andrew Naplavkov

#ifndef BARK_ANY_HASHABLE_HPP
#define BARK_ANY_HASHABLE_HPP

#include <any>
#include <boost/functional/hash.hpp>
#include <type_traits>

namespace bark {

class any_hashable {
public:
    any_hashable() = delete;

    template <class T,
              std::enable_if_t<!std::is_same_v<any_hashable, std::decay_t<T>>,
                               void*> = nullptr>
    explicit any_hashable(T&& val)
        : any_{std::forward<T>(val)}
        , hash_{[](const std::any& that) {
            using boost::hash_value;
            return hash_value(std::any_cast<const T&>(that));
        }}
        , equal_{[](const std::any& lhs, const std::any& rhs) {
            return std::any_cast<const T&>(lhs) == std::any_cast<const T&>(rhs);
        }}
    {
    }

    friend size_t hash_value(const any_hashable& that)
    {
        size_t res = 0;
        boost::hash_combine(res, that.any_.type().hash_code());
        boost::hash_combine(res, that.hash_(that.any_));
        return res;
    }

    friend bool operator==(const any_hashable& lhs, const any_hashable& rhs)
    {
        return lhs.any_.type() == rhs.any_.type() &&
               lhs.equal_(lhs.any_, rhs.any_);
    }

private:
    std::any any_;
    size_t (*hash_)(const std::any&);
    bool (*equal_)(const std::any&, const std::any&);
};

}  // namespace bark

#endif  // BARK_ANY_HASHABLE_HPP

max_stars_repo_name: storm-ptr/bark

max_issues_repo_name: storm-ptr/bark

max_forks_repo_name: storm-ptr/bark