text:
//==================================================================================================
/*!
  @file

  Gather informations for PowerPC SIMD extensions

  @copyright 2012 - 2015 NumScale SAS

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

**/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_POWER_SPEC_HPP_INCLUDED
#define BOOST_SIMD_ARCH_POWER_SPEC_HPP_INCLUDED

#include <boost/predef/architecture.h>
#include <boost/simd/detail/predef.hpp>

#include <boost/simd/arch/power/qpx/spec.hpp>
#include <boost/simd/arch/power/vsx/spec.hpp>
#include <boost/simd/arch/power/vmx/spec.hpp>

// Defines register count macros for POWERPC CPUs
#if BOOST_HW_SIMD_PPC
  #if BOOST_HW_SIMD_PPC == BOOST_HW_SIMD_PPC_VSX_VERSION
    #if !defined(BOOST_SIMD_VR_COUNT)
    #define BOOST_SIMD_VR_COUNT 64u
    #endif
  #else
    #if !defined(BOOST_SIMD_VR_COUNT)
    #define BOOST_SIMD_VR_COUNT 32u
    #endif
  #endif

  #if BOOST_HW_SIMD_PPC != BOOST_HW_SIMD_PPC_VSX_VERSION
    #if !defined(BOOST_SIMD_GPR_COUNT)
    #define BOOST_SIMD_GPR_COUNT  32u
    #endif
  #endif
#endif

#endif

ext: hpp


text:
// Copyright (c) 2016-2017 Antony Polukhin
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_PFR_PRECISE_IO_HPP
#define BOOST_PFR_PRECISE_IO_HPP
#pragma once

#include <boost/pfr/detail/config.hpp>

#include <type_traits>
#include <utility>      // metaprogramming stuff

#include <boost/pfr/detail/sequence_tuple.hpp>
#include <boost/pfr/detail/io.hpp>
#include <boost/pfr/precise/tuple_size.hpp>

#if BOOST_PFR_USE_CPP17
#   include <boost/pfr/detail/core17.hpp>
#else
#   include <boost/pfr/detail/core14.hpp>
#endif

namespace boost { namespace pfr {

/// \brief Writes aggregate `value` to `out`
///
/// \b Requires: C++17 or \constexprinit{C++14 constexpr aggregate intializable type}.
///
/// \rcast14
///
/// \b Example:
/// \code
///     struct my_struct { int i, short s; };
///     my_struct s{12, 13};
///     write(std::cout, s); // outputs '{12, 13}'
/// \endcode
template <class Char, class Traits, class T>
void write(std::basic_ostream<Char, Traits>& out, const T& value) {
    constexpr std::size_t fields_count_val = boost::pfr::detail::fields_count<std::remove_reference_t<T>>();
    out << '{';
#if BOOST_PFR_USE_CPP17
    detail::print_impl<0, fields_count_val>::print(out, detail::tie_as_tuple(value));
#else
    ::boost::pfr::detail::for_each_field_dispatcher(
        value,
        [&out, &fields_count_val](const auto& val) {
            detail::print_impl<0, fields_count_val>::print(out, val);
        },
        std::make_index_sequence<fields_count_val>{}
    );
#endif
    out << '}';
}

/// Reads aggregate `value` from stream `in`
///
/// \b Requires: C++17 or \constexprinit{C++14 constexpr aggregate intializable type}.
///
/// \rcast14
///
/// \b Example:
/// \code
///     struct my_struct { int i, short s; };
///     my_struct s;
///     std::stringstream ss;
///     ss << "{ 12, 13 }";
///     ss >> s;
///     assert(s.i == 12);
///     assert(s.i == 13);
/// \endcode
template <class Char, class Traits, class T>
void read(std::basic_istream<Char, Traits>& in, T& value) {
    constexpr std::size_t fields_count_val = boost::pfr::detail::fields_count<std::remove_reference_t<T>>();

    const auto prev_exceptions = in.exceptions();
    in.exceptions( typename std::basic_istream<Char, Traits>::iostate(0) );
    const auto prev_flags = in.flags( typename std::basic_istream<Char, Traits>::fmtflags(0) );

    char parenthis = {};
    in >> parenthis;
    if (parenthis != '{') in.setstate(std::basic_istream<Char, Traits>::failbit);

#if BOOST_PFR_USE_CPP17
    detail::read_impl<0, fields_count_val>::read(in, detail::tie_as_tuple(value));
#else
    ::boost::pfr::detail::for_each_field_dispatcher(
        value,
        [&in, &fields_count_val](const auto& val) {
            detail::read_impl<0, fields_count_val>::read(in, val);
        },
        std::make_index_sequence<fields_count_val>{}
    );
#endif

    in >> parenthis;
    if (parenthis != '}') in.setstate(std::basic_istream<Char, Traits>::failbit);

    in.flags(prev_flags);
    in.exceptions(prev_exceptions);
}

}} // namespace boost::pfr

#endif // BOOST_PFR_PRECISE_IO_HPP

max_stars_repo_name: learnforpractice/tinygo

max_issues_repo_name: learnforpractice/tinygo

max_forks_repo_name: learnforpractice/tinygo


text:
/*
Copyright 2015 Cloudbase Solutions Srl
All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may 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 "stdafx.h"

#include <tuple>

#include "UserRights.h"
#include "Win32Exception.h"

#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>

namespace po = boost::program_options;

enum Action
{
    NONE,
    LIST,
    GRANT,
    REVOKE
};

const std::string version = "1.0";

void CheckOption(const po::variables_map& vm, const std::string& option_name)
{
    if (!vm.count(option_name))
    {
        throw std::logic_error("Option \"" + option_name + "\" is required.");
    }
}

std::tuple<Action, std::wstring, std::wstring> GetOptions(int argc, _TCHAR* argv[])
{
    po::options_description desc(
        "Copyright Cloudbase Solutions Srl (c) 2015\nVersion: " +
        version + " - http://www.cloudbase.it\n\nAllowed options");
    desc.add_options()
        ("help,h", "display usage info")
        ("list,l", po::wvalue<std::wstring>(), "list existing account rights and privileges")
        ("grant,g", po::wvalue<std::wstring>(), "grant account right or privilege")
        ("revoke,r", po::wvalue<std::wstring>(), "revoke account right or privilege")
        ("value,v", po::wvalue<std::wstring>(), "account right or privilege");

    po::variables_map vm;
    po::basic_parsed_options<wchar_t> opt = po::parse_command_line(argc, argv, desc);
    po::store(opt, vm);
    po::notify(vm);

    if (vm.count("list") + vm.count("grant") + vm.count("revoke") + vm.count("help") > 1)
    {
        throw std::logic_error("Only one action can be specified: help, list, grant, revoke");
    }

    std::vector<std::wstring> v = po::collect_unrecognized(opt.options, po::include_positional);
    if (v.size() > 0)
    {
        throw std::logic_error("Unrecognized options. Use -h and --help for usage information.");
    }

    if (vm.count("list"))
    {
        return std::make_tuple(Action::LIST,
                               vm["list"].as<std::wstring>(),
                               std::wstring());
    }
    else if (vm.count("grant"))
    {
        CheckOption(vm, "value");
        return std::make_tuple(Action::GRANT,
                               vm["grant"].as<std::wstring>(),
                               vm["value"].as<std::wstring>());
    }
    else if (vm.count("revoke"))
    {
        CheckOption(vm, "value");
        return std::make_tuple(Action::REVOKE,
            vm["revoke"].as<std::wstring>(),
            vm["value"].as<std::wstring>());
    }
    else
    {
        // Display usage
        std::cout << desc << std::endl;
        return std::make_tuple(Action::NONE, std::wstring(), std::wstring());
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    std::locale::global(std::locale(""));

    PSID sid = NULL;

    try
    {
        Action action;
        std::wstring name;
        std::wstring privilege;

        std::tie(action, name, privilege) = GetOptions(argc, argv);

        if (action == Action::NONE)
        {
            return 0;
        }

        DWORD sidSize = 1024;
        PSID sid = malloc(sidSize);
        if (!sid)
        {
            throw std::exception("Malloc failed");
        }

        ZeroMemory(sid, sidSize);

        GetSid(sid, &sidSize, name.c_str());

        switch (action)
        {
        case  Action::LIST:
            {
                std::vector<std::wstring>& v = GetPrivileges(sid);
                for (std::vector<std::wstring>::iterator it = v.begin(); it != v.end(); ++it)
                {
                    std::wcout << *it << std::endl;
                }
            }
            break;
        case Action::GRANT:
            GrantPrivilege(sid, privilege.c_str());
            std::wcout << L"User right / privilege granted: " << privilege << std::endl;
            break;
        case Action::REVOKE:
            try
            {
                RevokePrivilege(sid, privilege.c_str());
                std::wcout << L"User right / privilege revoked: " << privilege << std::endl;
            }
            catch (ErrorFileNotFoundException&)
            {
                std::wcout << L"The user does not hold the requested user right / privilege: " << privilege << std::endl;
            }
            break;
        }

        free(sid);
        sid = NULL;
    }
    catch (const Win32Exception& ex)
    {
        if (sid)
        {
            free(sid);
            sid = NULL;
        }

        std::wcerr << ex.GetMessage() << std::endl;
        return 1;
    }
    catch (const std::exception& ex)
    {
        if (sid)
        {
            free(sid);
            sid = NULL;
        }

        std::wcerr << ex.what() << std::endl;
        return 1;
    }

	return 0;
}

ext: cpp

max_stars_repo_name: cloudbase/SetUserAccountRight

max_issues_repo_name: cloudbase/SetUserAccountRights

max_forks_repo_name: cloudbase/SetUserAccountRights


text:
//---------------------------------------------------------------------------//
// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@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
//
// See http://boostorg.github.com/compute for more information.
//---------------------------------------------------------------------------//

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

#include <boost/compute/system.hpp>
#include <boost/compute/function.hpp>
#include <boost/compute/algorithm/copy_n.hpp>
#include <boost/compute/container/vector.hpp>
#include <boost/compute/experimental/tabulate.hpp>

#include "check_macros.hpp"
#include "context_setup.hpp"

namespace compute = boost::compute;

BOOST_AUTO_TEST_CASE(tabulate_negative_int)
{
    BOOST_COMPUTE_FUNCTION(int, negate, (int x),
    {
        return -x;
    });

    compute::vector<int> vector(10, context);
    compute::experimental::tabulate(vector.begin(), vector.end(), negate, queue);
    CHECK_RANGE_EQUAL(int, 10, vector, (0, -1, -2, -3, -4, -5, -6, -7, -8, -9));
}

BOOST_AUTO_TEST_SUITE_END()


text:
// @copyright 2017 - 2018 Shaun Ostoic
// Distributed under the MIT License.
// (See accompanying file LICENSE.md or copy at https://opensource.org/licenses/MIT)

#pragma once

#include <boost/winapi/basic_types.hpp>

namespace boost::winapi
{

#if !defined (BOOST_USE_WINDOWS_H)
	// Universal well-known SIDs
	constexpr auto SECURITY_NULL_SID_AUTHORITY_         = {0,0,0,0,0,0};
	constexpr auto SECURITY_WORLD_SID_AUTHORITY_        = {0,0,0,0,0,1};
	constexpr auto SECURITY_LOCAL_SID_AUTHORITY_        = {0,0,0,0,0,2};
	constexpr auto SECURITY_CREATOR_SID_AUTHORITY_      = {0,0,0,0,0,3};
	constexpr auto SECURITY_NON_UNIQUE_AUTHORITY_       = {0,0,0,0,0,4};
	constexpr auto SECURITY_RESOURCE_MANAGER_AUTHORITY_ = {0,0,0,0,0,9};

	// NT well-known SIDs
	constexpr auto SECURITY_NULL_RID_                                   = (0x00000000L);
	constexpr auto SECURITY_WORLD_RID_                                  = (0x00000000L);
	constexpr auto SECURITY_LOCAL_RID_                                  = (0x00000000L);
	constexpr auto SECURITY_LOCAL_LOGON_RID_                            = (0x00000001L);
	constexpr auto SECURITY_CREATOR_OWNER_RID_                          = (0x00000000L);
	constexpr auto SECURITY_CREATOR_GROUP_RID_                          = (0x00000001L);
	constexpr auto SECURITY_CREATOR_OWNER_SERVER_RID_                   = (0x00000002L);
	constexpr auto SECURITY_CREATOR_GROUP_SERVER_RID_                   = (0x00000003L);
	constexpr auto SECURITY_CREATOR_OWNER_RIGHTS_RID_                   = (0x00000004L);
	constexpr auto SECURITY_NT_AUTHORITY_                               = {0,0,0,0,0,5};
	constexpr auto SECURITY_DIALUP_RID_                                 = (0x00000001L);
	constexpr auto SECURITY_NETWORK_RID_                                = (0x00000002L);
	constexpr auto SECURITY_BATCH_RID_                                  = (0x00000003L);
	constexpr auto SECURITY_INTERACTIVE_RID_                            = (0x00000004L);
	constexpr auto SECURITY_LOGON_IDS_RID_                              = (0x00000005L);
	constexpr auto SECURITY_LOGON_IDS_RID_COUNT_                        = (3L);
	constexpr auto SECURITY_SERVICE_RID_                                = (0x00000006L);
	constexpr auto SECURITY_ANONYMOUS_LOGON_RID_                        = (0x00000007L);
	constexpr auto SECURITY_PROXY_RID_                                  = (0x00000008L);
	constexpr auto SECURITY_ENTERPRISE_CONTROLLERS_RID_                 = (0x00000009L);
	constexpr auto SECURITY_SERVER_LOGON_RID_                           = SECURITY_ENTERPRISE_CONTROLLERS_RID;
	constexpr auto SECURITY_SERVER_LOGON_RID_                           = SECURITY_ENTERPRISE_CONTROLLERS_RID;
	constexpr auto SECURITY_SERVER_LOGON_RID_                           = SECURITY_ENTERPRISE_CONTROLLERS_RID;
	constexpr auto SECURITY_PRINCIPAL_SELF_RID_                         = (0x0000000AL);
	constexpr auto SECURITY_AUTHENTICATED_USER_RID_                     = (0x0000000BL);
	constexpr auto SECURITY_RESTRICTED_CODE_RID_                        = (0x0000000CL);
	constexpr auto SECURITY_TERMINAL_SERVER_RID_                        = (0x0000000DL);
	constexpr auto SECURITY_REMOTE_LOGON_RID_                           = (0x0000000EL);
	constexpr auto SECURITY_THIS_ORGANIZATION_RID_                      = (0x0000000FL);
	constexpr auto SECURITY_IUSER_RID_                                  = (0x00000011L);
	constexpr auto SECURITY_LOCAL_SYSTEM_RID_                           = (0x00000012L);
	constexpr auto SECURITY_LOCAL_SERVICE_RID_                          = (0x00000013L);
	constexpr auto SECURITY_NETWORK_SERVICE_RID_                        = (0x00000014L);
	constexpr auto SECURITY_NT_NON_UNIQUE_                              = (0x00000015L);
	constexpr auto SECURITY_NT_NON_UNIQUE_SUB_AUTH_COUNT_               = (3L);
	constexpr auto SECURITY_ENTERPRISE_READONLY_CONTROLLERS_RID_        = (0x00000016L);
	constexpr auto SECURITY_BUILTIN_DOMAIN_RID_                         = (0x00000020L);
	constexpr auto SECURITY_WRITE_RESTRICTED_CODE_RID_                  = (0x00000021L);
	constexpr auto SECURITY_PACKAGE_BASE_RID_                           = (0x00000040L);
	constexpr auto SECURITY_PACKAGE_RID_COUNT_                          = (2L);
	constexpr auto SECURITY_PACKAGE_NTLM_RID_                           = (0x0000000AL);
	constexpr auto SECURITY_PACKAGE_SCHANNEL_RID_                       = (0x0000000EL);
	constexpr auto SECURITY_PACKAGE_DIGEST_RID_                         = (0x00000015L);
	constexpr auto SECURITY_CRED_TYPE_BASE_RID_                         = (0x00000041L);
	constexpr auto SECURITY_CRED_TYPE_RID_COUNT_                        = (2L);
	constexpr auto SECURITY_CRED_TYPE_THIS_ORG_CERT_RID_                = (0x00000001L);
	constexpr auto SECURITY_MIN_BASE_RID_                               = (0x00000050L);
	constexpr auto SECURITY_SERVICE_ID_BASE_RID_                        = (0x00000050L);
	constexpr auto SECURITY_SERVICE_ID_RID_COUNT_                       = (6L);
	constexpr auto SECURITY_RESERVED_ID_BASE_RID_                       = (0x00000051L);
	constexpr auto SECURITY_APPPOOL_ID_BASE_RID_                        = (0x00000052L);
	constexpr auto SECURITY_APPPOOL_ID_RID_COUNT_                       = (6L);
	constexpr auto SECURITY_VIRTUALSERVER_ID_BASE_RID_                  = (0x00000053L);
	constexpr auto SECURITY_VIRTUALSERVER_ID_RID_COUNT_                 = (6L);
	constexpr auto SECURITY_USERMODEDRIVERHOST_ID_BASE_RID_             = (0x00000054L);
	constexpr auto SECURITY_USERMODEDRIVERHOST_ID_RID_COUNT_            = (6L);
	constexpr auto SECURITY_CLOUD_INFRASTRUCTURE_SERVICES_ID_BASE_RID_  = (0x00000055L);
	constexpr auto SECURITY_CLOUD_INFRASTRUCTURE_SERVICES_ID_RID_COUNT_ = (6L);
	constexpr auto SECURITY_WMIHOST_ID_BASE_RID_                        = (0x00000056L);
	constexpr auto SECURITY_WMIHOST_ID_RID_COUNT_                       = (6L);
	constexpr auto SECURITY_TASK_ID_BASE_RID_                           = (0x00000057L);
	constexpr auto SECURITY_NFS_ID_BASE_RID_                            = (0x00000058L);
	constexpr auto SECURITY_COM_ID_BASE_RID_                            = (0x00000059L);
	constexpr auto SECURITY_WINDOW_MANAGER_BASE_RID_                    = (0x0000005AL);
	constexpr auto SECURITY_RDV_GFX_BASE_RID_                           = (0x0000005BL);
	constexpr auto SECURITY_DASHOST_ID_BASE_RID_                        = (0x0000005CL);
	constexpr auto SECURITY_DASHOST_ID_RID_COUNT_                       = (6L);
	constexpr auto SECURITY_VIRTUALACCOUNT_ID_RID_COUNT_                = (6L);
	constexpr auto SECURITY_MAX_BASE_RID_                               = (0x0000006FL);
	constexpr auto SECURITY_MAX_ALWAYS_FILTERED_                        = (0x000003E7L);
	constexpr auto SECURITY_MIN_NEVER_FILTERED_                         = (0x000003E8L);
	constexpr auto SECURITY_OTHER_ORGANIZATION_RID_                     = (0x000003E8L);

#endif

	/////////////////////////////////////////////////////////////////////////////
	//                                                                         //
	// Universal well-known SIDs                                               //
	//                                                                         //
	//     Null SID                     S-1-0-0                                //
	//     World                        S-1-1-0                                //
	//     Local                        S-1-2-0                                //
	//     Creator Owner ID             S-1-3-0                                //
	//     Creator Group ID             S-1-3-1                                //
	//     Creator Owner Server ID      S-1-3-2                                //
	//     Creator Group Server ID      S-1-3-3                                //
	//                                                                         //
	//     (Non-unique IDs)             S-1-4                                  //
	//                                                                         //
	/////////////////////////////////////////////////////////////////////////////
	// **Comment taken from winnt.h
	constexpr auto SECURITY_NULL_SID_AUTHORITY_         = SECURITY_NULL_SID_AUTHORITY;
	constexpr auto SECURITY_WORLD_SID_AUTHORITY_        = SECURITY_WORLD_SID_AUTHORITY;
	constexpr auto SECURITY_LOCAL_SID_AUTHORITY_        = SECURITY_LOCAL_SID_AUTHORITY;
	constexpr auto SECURITY_CREATOR_SID_AUTHORITY_      = SECURITY_CREATOR_SID_AUTHORITY;
	constexpr auto SECURITY_NON_UNIQUE_AUTHORITY_       = SECURITY_NON_UNIQUE_AUTHORITY;
	constexpr auto SECURITY_RESOURCE_MANAGER_AUTHORITY_ = SECURITY_RESOURCE_MANAGER_AUTHORITY;

	///////////////////////////////////////////////////////////////////////////////
	//                                                                           //
	// NT well-known SIDs                                                        //
	//                                                                           //
	//     NT Authority            S-1-5                                         //
	//     Dialup                  S-1-5-1                                       //
	//                                                                           //
	//     Network                 S-1-5-2                                       //
	//     Batch                   S-1-5-3                                       //
	//     Interactive             S-1-5-4                                       //
	//     (Logon IDs)             S-1-5-5-X-Y                                   //
	//     Service                 S-1-5-6                                       //
	//     AnonymousLogon          S-1-5-7       (aka null logon session)        //
	//     Proxy                   S-1-5-8                                       //
	//     Enterprise DC (EDC)     S-1-5-9       (aka domain controller account) //
	//     Self                    S-1-5-10      (self RID)                      //
	//     Authenticated User      S-1-5-11      (Authenticated user somewhere)  //
	//     Restricted Code         S-1-5-12      (Running restricted code)       //
	//     Terminal Server         S-1-5-13      (Running on Terminal Server)    //
	//     Remote Logon            S-1-5-14      (Remote Interactive Logon)      //
	//     This Organization       S-1-5-15                                      //
	//                                                                           //
	//     IUser                   S-1-5-17
	//     Local System            S-1-5-18                                      //
	//     Local Service           S-1-5-19                                      //
	//     Network Service         S-1-5-20                                      //
	//                                                                           //
	//     (NT non-unique IDs)     S-1-5-0x15-... (NT Domain Sids)               //
	//                                                                           //
	//     (Built-in domain)       S-1-5-0x20                                    //
	//                                                                           //
	//     (Security Package IDs)  S-1-5-0x40                                    //
	//     NTLM Authentication     S-1-5-0x40-10                                 //
	//     SChannel Authentication S-1-5-0x40-14                                 //
	//     Digest Authentication   S-1-5-0x40-21                                 //
	//                                                                           //
	//     Other Organization      S-1-5-1000    (>=1000 can not be filtered)    //
	//                                                                           //
	///////////////////////////////////////////////////////////////////////////////
	// **Comment taken from winnt.h
	constexpr auto SECURITY_NT_AUTHORITY_                               = SECURITY_NT_AUTHORITY;
	constexpr auto SECURITY_DIALUP_RID_                                 = SECURITY_DIALUP_RID;
	constexpr auto SECURITY_NETWORK_RID_                                = SECURITY_NETWORK_RID;
	constexpr auto SECURITY_BATCH_RID_                                  = SECURITY_BATCH_RID;
	constexpr auto SECURITY_INTERACTIVE_RID_                            = SECURITY_INTERACTIVE_RID;
	constexpr auto SECURITY_LOGON_IDS_RID_                              = SECURITY_LOGON_IDS_RID;
	constexpr auto SECURITY_LOGON_IDS_RID_COUNT_                        = SECURITY_LOGON_IDS_RID_COUNT;
	constexpr auto SECURITY_SERVICE_RID_                                = SECURITY_SERVICE_RID;
	constexpr auto SECURITY_ANONYMOUS_LOGON_RID_                        = SECURITY_ANONYMOUS_LOGON_RID;
	constexpr auto SECURITY_PROXY_RID_                                  = SECURITY_PROXY_RID;
	constexpr auto SECURITY_ENTERPRISE_CONTROLLERS_RID_                 = SECURITY_ENTERPRISE_CONTROLLERS_RID;
	constexpr auto SECURITY_SERVER_LOGON_RID_                           = SECURITY_SERVER_LOGON_RID;
	constexpr auto SECURITY_PRINCIPAL_SELF_RID_                         = SECURITY_PRINCIPAL_SELF_RID;
	constexpr auto SECURITY_AUTHENTICATED_USER_RID_                     = SECURITY_AUTHENTICATED_USER_RID;
	constexpr auto SECURITY_RESTRICTED_CODE_RID_                        = SECURITY_RESTRICTED_CODE_RID;
	constexpr auto SECURITY_TERMINAL_SERVER_RID_                        = SECURITY_TERMINAL_SERVER_RID;
	constexpr auto SECURITY_REMOTE_LOGON_RID_                           = SECURITY_REMOTE_LOGON_RID;
	constexpr auto SECURITY_THIS_ORGANIZATION_RID_                      = SECURITY_THIS_ORGANIZATION_RID;
	constexpr auto SECURITY_IUSER_RID_                                  = SECURITY_IUSER_RID;
	constexpr auto SECURITY_LOCAL_SYSTEM_RID_                           = SECURITY_LOCAL_SYSTEM_RID;
	constexpr auto SECURITY_LOCAL_SERVICE_RID_                          = SECURITY_LOCAL_SERVICE_RID;
	constexpr auto SECURITY_NETWORK_SERVICE_RID_                        = SECURITY_NETWORK_SERVICE_RID;
	constexpr auto SECURITY_NT_NON_UNIQUE_                              = SECURITY_NT_NON_UNIQUE;
	constexpr auto SECURITY_NT_NON_UNIQUE_SUB_AUTH_COUNT_               = SECURITY_NT_NON_UNIQUE_SUB_AUTH_COUNT;
	constexpr auto SECURITY_ENTERPRISE_READONLY_CONTROLLERS_RID_        = SECURITY_ENTERPRISE_READONLY_CONTROLLERS_RID;
	constexpr auto SECURITY_BUILTIN_DOMAIN_RID_                         = SECURITY_BUILTIN_DOMAIN_RID;
	constexpr auto SECURITY_WRITE_RESTRICTED_CODE_RID_                  = SECURITY_WRITE_RESTRICTED_CODE_RID;
	constexpr auto SECURITY_PACKAGE_BASE_RID_                           = SECURITY_PACKAGE_BASE_RID;
	constexpr auto SECURITY_PACKAGE_RID_COUNT_                          = SECURITY_PACKAGE_RID_COUNT;
	constexpr auto SECURITY_PACKAGE_NTLM_RID_                           = SECURITY_PACKAGE_NTLM_RID;
	constexpr auto SECURITY_PACKAGE_SCHANNEL_RID_                       = SECURITY_PACKAGE_SCHANNEL_RID;
	constexpr auto SECURITY_PACKAGE_DIGEST_RID_                         = SECURITY_PACKAGE_DIGEST_RID;
	constexpr auto SECURITY_CRED_TYPE_BASE_RID_                         = SECURITY_CRED_TYPE_BASE_RID;
	constexpr auto SECURITY_CRED_TYPE_RID_COUNT_                        = SECURITY_CRED_TYPE_RID_COUNT;
	constexpr auto SECURITY_CRED_TYPE_THIS_ORG_CERT_RID_                = SECURITY_CRED_TYPE_THIS_ORG_CERT_RID;
	constexpr auto SECURITY_MIN_BASE_RID_                               = SECURITY_MIN_BASE_RID;
	constexpr auto SECURITY_SERVICE_ID_BASE_RID_                        = SECURITY_SERVICE_ID_BASE_RID;
	constexpr auto SECURITY_SERVICE_ID_RID_COUNT_                       = SECURITY_SERVICE_ID_RID_COUNT;
	constexpr auto SECURITY_RESERVED_ID_BASE_RID_                       = SECURITY_RESERVED_ID_BASE_RID;
	constexpr auto SECURITY_APPPOOL_ID_BASE_RID_                        = SECURITY_APPPOOL_ID_BASE_RID;
	constexpr auto SECURITY_APPPOOL_ID_RID_COUNT_                       = SECURITY_APPPOOL_ID_RID_COUNT;
	constexpr auto SECURITY_VIRTUALSERVER_ID_BASE_RID_                  = SECURITY_VIRTUALSERVER_ID_BASE_RID;
	constexpr auto SECURITY_VIRTUALSERVER_ID_RID_COUNT_                 = SECURITY_VIRTUALSERVER_ID_RID_COUNT;
	constexpr auto SECURITY_USERMODEDRIVERHOST_ID_BASE_RID_             = SECURITY_USERMODEDRIVERHOST_ID_BASE_RID;
	constexpr auto SECURITY_USERMODEDRIVERHOST_ID_RID_COUNT_            = SECURITY_USERMODEDRIVERHOST_ID_RID_COUNT;
	constexpr auto SECURITY_CLOUD_INFRASTRUCTURE_SERVICES_ID_BASE_RID_  = SECURITY_CLOUD_INFRASTRUCTURE_SERVICES_ID_BASE_RID;
	constexpr auto SECURITY_CLOUD_INFRASTRUCTURE_SERVICES_ID_RID_COUNT_ = SECURITY_CLOUD_INFRASTRUCTURE_SERVICES_ID_RID_COUNT;
	constexpr auto SECURITY_WMIHOST_ID_BASE_RID_                        = SECURITY_WMIHOST_ID_BASE_RID;
	constexpr auto SECURITY_WMIHOST_ID_RID_COUNT_                       = SECURITY_WMIHOST_ID_RID_COUNT;
	constexpr auto SECURITY_TASK_ID_BASE_RID_                           = SECURITY_TASK_ID_BASE_RID;
	constexpr auto SECURITY_NFS_ID_BASE_RID_                            = SECURITY_NFS_ID_BASE_RID;
	constexpr auto SECURITY_COM_ID_BASE_RID_                            = SECURITY_COM_ID_BASE_RID;
	constexpr auto SECURITY_WINDOW_MANAGER_BASE_RID_                    = SECURITY_WINDOW_MANAGER_BASE_RID;
	constexpr auto SECURITY_RDV_GFX_BASE_RID_                           = SECURITY_RDV_GFX_BASE_RID;
	constexpr auto SECURITY_DASHOST_ID_BASE_RID_                        = SECURITY_DASHOST_ID_BASE_RID;
	constexpr auto SECURITY_DASHOST_ID_RID_COUNT_                       = SECURITY_DASHOST_ID_RID_COUNT;
	constexpr auto SECURITY_VIRTUALACCOUNT_ID_RID_COUNT_                = SECURITY_VIRTUALACCOUNT_ID_RID_COUNT;
	constexpr auto SECURITY_MAX_BASE_RID_                               = SECURITY_MAX_BASE_RID;
	constexpr auto SECURITY_MAX_ALWAYS_FILTERED_                        = SECURITY_MAX_ALWAYS_FILTERED;
	constexpr auto SECURITY_MIN_NEVER_FILTERED_                         = SECURITY_MIN_NEVER_FILTERED;
	constexpr auto SECURITY_OTHER_ORGANIZATION_RID_                     = SECURITY_OTHER_ORGANIZATION_RID;
}

max_stars_repo_name: Ostoic/distant

max_issues_repo_name: Ostoic/distant

max_forks_repo_name: Ostoic/distant


text:
//  (C) Copyright Gennadiy Rozental 2001-2015.
//  Distributed under the Boost Software License, Version 1.0.
//  (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//
//  See http://www.boost.org/libs/test for the library home page.
//

//[snippet17
#define __BOOST_TEST_MODULE__ const_string test
#include <boost/test/unit_test.hpp>

__BOOST_AUTO_TEST_CASE__( constructors_test )
{
  //...
}

__BOOST_AUTO_TEST_CASE__( data_access_test )
{
  const_string cs1( "test_string" );                                // 1 //
  __BOOST_TEST__( cs1[(size_t)0] == 't' );
  __BOOST_TEST__( cs1[(size_t)4] == '_' );
  __BOOST_TEST__( cs1[cs1.length()-1] == 'g' );

  __BOOST_TEST__( cs1[(size_t)0] == cs1.at( 0 ) );                      // 2 //
  __BOOST_TEST__( cs1[(size_t)2] == cs1.at( 5 ) );
  __BOOST_TEST__( cs1.at( cs1.length() - 1 ) == 'g' );

  BOOST_CHECK_THROW( cs1.at( cs1.length() ), std::out_of_range );   // 3 //
}
//]


text:
#include <boost/stacktrace/frame.hpp>
#include <boost/stacktrace/stacktrace.hpp>
#include <expected.hpp>

using namespace boost::stacktrace;

namespace expected::impl
{
    std::string get_stacktrace()
    {
        return to_string(stacktrace{});
    }
} // namespace expected::impl

max_stars_repo_name: Berrysoft/expected

max_issues_repo_name: Berrysoft/expected

max_forks_repo_name: Berrysoft/expected


text:
#ifndef MPLLIBS_METAPARSE_V1_NEXT_CHAR_HPP
#define MPLLIBS_METAPARSE_V1_NEXT_CHAR_HPP

//    Copyright Abel Sinkovics (abel@sinkovics.hu) 2011.
// 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 <mpllibs/metaparse/v1/fwd/next_char.hpp>

#include <boost/mpl/apply_wrap.hpp>
#include <boost/mpl/tag.hpp>

namespace mpllibs
{
  namespace metaparse
  {
    namespace v1
    {
      template <class P, class Ch>
      struct next_char :
        boost::mpl::apply_wrap2<
          next_char_impl<typename boost::mpl::tag<typename P::type>::type>,
          typename P::type,
          typename Ch::type
        >
      {};
    }
  }
}

#endif


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

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

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

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_GEOMETRY_MULTI_ALGORITHMS_DETAIL_SECTIONS_RANGE_BY_SECTION_HPP
#define BOOST_GEOMETRY_MULTI_ALGORITHMS_DETAIL_SECTIONS_RANGE_BY_SECTION_HPP

#include <boost/assert.hpp>
#include <boost/range.hpp>

#include <boost/geometry/multi/core/tags.hpp>
#include <boost/geometry/multi/core/ring_type.hpp>
#include <boost/geometry/algorithms/detail/sections/range_by_section.hpp>

namespace boost { namespace geometry
{

#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace section
{

template
<
    typename MultiGeometry,
    typename Section,
    typename Policy
>
struct full_section_multi
{
    static inline typename ring_return_type<MultiGeometry const>::type apply(
                MultiGeometry const& multi, Section const& section)
    {
        BOOST_ASSERT
            (
                section.ring_id.multi_index >= 0
                && section.ring_id.multi_index < int(boost::size(multi))
            );

        return Policy::apply(multi[section.ring_id.multi_index], section);
    }
};

}} // namespace detail::section
#endif

#ifndef DOXYGEN_NO_DISPATCH
namespace dispatch
{

template <typename MultiPolygon, typename Section>
struct range_by_section<multi_polygon_tag, MultiPolygon, Section>
    : detail::section::full_section_multi
        <
            MultiPolygon,
            Section,
            detail::section::full_section_polygon
                <
                    typename boost::range_value<MultiPolygon>::type,
                    Section
                >
       >
{};

} // namespace dispatch
#endif

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_MULTI_ALGORITHMS_DETAIL_SECTIONS_RANGE_BY_SECTION_HPP

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
// Copyright (c) 2018, ETH Zurich and UNC Chapel Hill.
// 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 ETH Zurich and UNC Chapel Hill 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 HOLDERS 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.
//
// Author: Johannes L. Schoenberger (jsch-at-demuc-dot-de)

#include "util/misc.h"

#include <cstdarg>

#include <boost/algorithm/string.hpp>

namespace colmap {

std::string EnsureTrailingSlash(const std::string& str) {
  if (str.length() > 0) {
    if (str.back() != '/') {
      return str + "/";
    }
  } else {
    return str + "/";
  }
  return str;
}

bool HasFileExtension(const std::string& file_name, const std::string& ext) {
  CHECK(!ext.empty());
  CHECK_EQ(ext.at(0), '.');
  std::string ext_lower = ext;
  StringToLower(&ext_lower);
  if (file_name.size() >= ext_lower.size() &&
      file_name.substr(file_name.size() - ext_lower.size(), ext_lower.size()) ==
          ext_lower) {
    return true;
  }
  return false;
}

void SplitFileExtension(const std::string& path, std::string* root,
                        std::string* ext) {
  const auto parts = StringSplit(path, ".");
  CHECK_GT(parts.size(), 0);
  if (parts.size() == 1) {
    *root = parts[0];
    *ext = "";
  } else {
    *root = "";
    for (size_t i = 0; i < parts.size() - 1; ++i) {
      *root += parts[i] + ".";
    }
    *root = root->substr(0, root->length() - 1);
    if (parts.back() == "") {
      *ext = "";
    } else {
      *ext = "." + parts.back();
    }
  }
}

void FileCopy(const std::string& src_path, const std::string& dst_path,
              CopyType type) {
  switch (type) {
    case CopyType::COPY:
      boost::filesystem::copy_file(src_path, dst_path);
      break;
    case CopyType::HARD_LINK:
      boost::filesystem::create_hard_link(src_path, dst_path);
      break;
    case CopyType::SOFT_LINK:
      boost::filesystem::create_symlink(src_path, dst_path);
      break;
  }
}

bool ExistsFile(const std::string& path) {
  return boost::filesystem::is_regular_file(path);
}

bool ExistsDir(const std::string& path) {
  return boost::filesystem::is_directory(path);
}

bool ExistsPath(const std::string& path) {
  return boost::filesystem::exists(path);
}

void CreateDirIfNotExists(const std::string& path) {
  if (!ExistsDir(path)) {
    CHECK(boost::filesystem::create_directory(path));
  }
}

std::string GetPathBaseName(const std::string& path) {
  const std::vector<std::string> names =
      StringSplit(StringReplace(path, "\\", "/"), "/");
  if (names.size() > 1 && names.back() == "") {
    return names[names.size() - 2];
  } else {
    return names.back();
  }
}

std::string GetParentDir(const std::string& path) {
  return boost::filesystem::path(path).parent_path().string();
}

std::string GetRelativePath(const std::string& from, const std::string& to) {
  // This implementation is adapted from:
  // https://stackoverflow.com/questions/10167382
  // A native implementation in boost::filesystem is only available starting
  // from boost version 1.60.
  using namespace boost::filesystem;

  path from_path = canonical(path(from));
  path to_path = canonical(path(to));

  // Start at the root path and while they are the same then do nothing then
  // when they first diverge take the entire from path, swap it with '..'
  // segments, and then append the remainder of the to path.
  path::const_iterator from_iter = from_path.begin();
  path::const_iterator to_iter = to_path.begin();

  // Loop through both while they are the same to find nearest common directory
  while (from_iter != from_path.end() && to_iter != to_path.end() &&
         (*to_iter) == (*from_iter)) {
    ++to_iter;
    ++from_iter;
  }

  // Replace from path segments with '..' (from => nearest common directory)
  path rel_path;
  while (from_iter != from_path.end()) {
    rel_path /= "..";
    ++from_iter;
  }

  // Append the remainder of the to path (nearest common directory => to)
  while (to_iter != to_path.end()) {
    rel_path /= *to_iter;
    ++to_iter;
  }

  return rel_path.string();
}

std::vector<std::string> GetFileList(const std::string& path) {
  std::vector<std::string> file_list;
  for (auto it = boost::filesystem::directory_iterator(path);
       it != boost::filesystem::directory_iterator(); ++it) {
    if (boost::filesystem::is_regular_file(*it)) {
      const boost::filesystem::path file_path = *it;
      file_list.push_back(file_path.string());
    }
  }
  return file_list;
}

std::vector<std::string> GetRecursiveFileList(const std::string& path) {
  std::vector<std::string> file_list;
  for (auto it = boost::filesystem::recursive_directory_iterator(path);
       it != boost::filesystem::recursive_directory_iterator(); ++it) {
    if (boost::filesystem::is_regular_file(*it)) {
      const boost::filesystem::path file_path = *it;
      file_list.push_back(file_path.string());
    }
  }
  return file_list;
}

std::vector<std::string> GetDirList(const std::string& path) {
  std::vector<std::string> dir_list;
  for (auto it = boost::filesystem::directory_iterator(path);
       it != boost::filesystem::directory_iterator(); ++it) {
    if (boost::filesystem::is_directory(*it)) {
      const boost::filesystem::path dir_path = *it;
      dir_list.push_back(dir_path.string());
    }
  }
  return dir_list;
}

std::vector<std::string> GetRecursiveDirList(const std::string& path) {
  std::vector<std::string> dir_list;
  for (auto it = boost::filesystem::recursive_directory_iterator(path);
       it != boost::filesystem::recursive_directory_iterator(); ++it) {
    if (boost::filesystem::is_directory(*it)) {
      const boost::filesystem::path dir_path = *it;
      dir_list.push_back(dir_path.string());
    }
  }
  return dir_list;
}

size_t GetFileSize(const std::string& path) {
  std::ifstream file(path, std::ifstream::ate | std::ifstream::binary);
  CHECK(file.is_open()) << path;
  return file.tellg();
}

void PrintHeading1(const std::string& heading) {
  std::cout << std::endl << std::string(78, '=') << std::endl;
  std::cout << heading << std::endl;
  std::cout << std::string(78, '=') << std::endl << std::endl;
}

void PrintHeading2(const std::string& heading) {
  std::cout << std::endl << heading << std::endl;
  std::cout << std::string(std::min<int>(heading.size(), 78), '-') << std::endl;
}

template <>
std::vector<std::string> CSVToVector(const std::string& csv) {
  auto elems = StringSplit(csv, ",;");
  std::vector<std::string> values;
  values.reserve(elems.size());
  for (auto& elem : elems) {
    StringTrim(&elem);
    if (elem.empty()) {
      continue;
    }
    values.push_back(elem);
  }
  return values;
}

template <>
std::vector<int> CSVToVector(const std::string& csv) {
  auto elems = StringSplit(csv, ",;");
  std::vector<int> values;
  values.reserve(elems.size());
  for (auto& elem : elems) {
    StringTrim(&elem);
    if (elem.empty()) {
      continue;
    }
    try {
      values.push_back(std::stoi(elem));
    } catch (const std::invalid_argument&) {
      return std::vector<int>(0);
    }
  }
  return values;
}

template <>
std::vector<float> CSVToVector(const std::string& csv) {
  auto elems = StringSplit(csv, ",;");
  std::vector<float> values;
  values.reserve(elems.size());
  for (auto& elem : elems) {
    StringTrim(&elem);
    if (elem.empty()) {
      continue;
    }
    try {
      values.push_back(std::stod(elem));
    } catch (const std::invalid_argument&) {
      return std::vector<float>(0);
    }
  }
  return values;
}

template <>
std::vector<double> CSVToVector(const std::string& csv) {
  auto elems = StringSplit(csv, ",;");
  std::vector<double> values;
  values.reserve(elems.size());
  for (auto& elem : elems) {
    StringTrim(&elem);
    if (elem.empty()) {
      continue;
    }
    try {
      values.push_back(std::stold(elem));
    } catch (const std::invalid_argument&) {
      return std::vector<double>(0);
    }
  }
  return values;
}

std::vector<std::string> ReadTextFileLines(const std::string& path) {
  std::ifstream file(path);
  CHECK(file.is_open()) << path;

  std::string line;
  std::vector<std::string> lines;
  while (std::getline(file, line)) {
    StringTrim(&line);

    if (line.empty()) {
      continue;
    }

    lines.push_back(line);
  }

  return lines;
}

void RemoveCommandLineArgument(const std::string& arg, int* argc, char** argv) {
  for (int i = 0; i < *argc; ++i) {
    if (argv[i] == arg) {
      for (int j = i + 1; j < *argc; ++j) {
        argv[i] = argv[j];
      }
      *argc -= 1;
      break;
    }
  }
}

}  // namespace colmap

ext: cc

max_issues_repo_name: Skydes/colmap

max_forks_repo_name: Skydes/colmap


text:
#include "client/MockBusClient.h"
#include "client/MockRemoteService.h"
#include <boost/foreach.hpp>
#include "CommonPrivate.h"
#include <iostream>

using namespace std;

MockBusClient::MockBusClient()
: BusClient(NULL)
{
}

MockBusClient::~MockBusClient()
{
}

void MockBusClient::SendRequest(MojServiceRequest::ReplySignal::SlotRef handler, const MojChar* service,
		const MojChar* method, const MojObject& payload, MojUInt32 numReplies)
{
	MockRequestPtr req(new MockRequest(handler, service, method, payload));
	m_requests.push_back(req);
}

void MockBusClient::AddMockService(MockRemoteService& mockService)
{
	const char* name = mockService.GetServiceName();
	m_services[name] = &mockService;
}

void MockBusClient::PrintRequests(const string& desc)
{
	cerr << "## " << desc << " requests: " << m_requests.size() << " ##" << endl;
	BOOST_FOREACH (const MockRequestPtr& req, m_requests) {
		cerr << "Request: " << req->GetService() << "/" << req->GetMethod() << ": " << AsJsonString(req->GetPayload()) << endl;
	}
}

void MockBusClient::ProcessRequests()
{
	while(!m_requests.empty()) {
		MockRequestPtr req = m_requests.front();
		m_requests.pop_front();

		if(m_services.find(req->GetService()) != m_services.end()) {
			MockRemoteService* service = m_services[req->GetService()];
			service->HandleRequest(req);
		}
	}
}

max_stars_repo_name: webOS-ports/mojomail

max_issues_repo_name: openwebos/app-services

max_forks_repo_name: openwebos/app-services


text:
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>

#include <com/cyosp/helpers/StrUtil.hpp>

void StrUtil::eraseWhiteSpace(string& val)
{
    boost::erase_all(val," ");
    boost::erase_all(val,"\n");
    boost::erase_all(val,"\t");
    boost::erase_all(val,"\r");
}

void StrUtil::eraseAllChars(string& val, const char *chars_to_erase)
{
    if (!chars_to_erase)
        return;

    vector<string> tokens;
    boost::split(tokens, val, boost::is_any_of(chars_to_erase), boost::token_compress_on );
    val = "";
    BOOST_FOREACH(string a, tokens) {
        val += a;
    }
}

void StrUtil::splitString(const string& input, const char* delims,
        vector <string>& tokens)
{
    string temp = input;
    boost::trim_if(temp, boost::is_any_of(delims));
    boost::split( tokens, temp, boost::is_any_of(delims), boost::token_compress_on );
}

string StrUtil::float2string(float f)
{
  ostringstream os;
  os << f;
  return os.str();
}

string StrUtil::int2string(int i)
{
  ostringstream os;
  os << i;
  return os.str();
}

string StrUtil::bool2string(bool b)
{
	return (b ? "true" : "false" );
}

float StrUtil::string2float( string s )
{
	std::stringstream ss;
	float f;
	ss.str( s );
	ss >> f;

	return f;
}

max_stars_repo_name: cyosp/MPA

max_issues_repo_name: cyosp/MPA

max_forks_repo_name: cyosp/MPA


text:
// ----------------------------------------------------------------------------
// -                        Open3D: www.open3d.org                            -
// ----------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2018 www.open3d.org
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// ----------------------------------------------------------------------------

#include "ColorMapOptimization.h"

#include <Eigen/Dense>

#include <Core/Utility/Console.h>
#include <Core/Geometry/Image.h>
#include <Core/Geometry/RGBDImage.h>
#include <Core/Geometry/TriangleMesh.h>
#include <Core/Camera/PinholeCameraTrajectory.h>
#include <IO/ClassIO/TriangleMeshIO.h>
#include <Core/Utility/Eigen.h>

namespace three {

namespace {

class ImageWarpingField {

public:
    ImageWarpingField (int width, int height, int number_of_vertical_anchors) {
        InitializeWarpingFields(width, height, number_of_vertical_anchors);
    }

    void InitializeWarpingFields(int width, int height,
            int number_of_vertical_anchors) {
        anchor_h_ = number_of_vertical_anchors;
        anchor_step_ = double(height) / (anchor_h_ - 1);
        anchor_w_ = int(std::ceil(double(width) / anchor_step_) + 1);
        flow_ = Eigen::VectorXd(anchor_w_ * anchor_h_ * 2);
        for (int i = 0; i <= (anchor_w_ - 1); i++) {
            for (int j = 0; j <= (anchor_h_ - 1); j++) {
                int baseidx = (i + j * anchor_w_) * 2;
                flow_(baseidx) = i * anchor_step_;
                flow_(baseidx + 1) = j * anchor_step_;
            }
        }
    }

    Eigen::Vector2d QueryFlow(int i, int j) const {
        int baseidx = (i + j * anchor_w_) * 2;
        // exceptional case: quried anchor index is out of pre-defined space
        if (baseidx < 0 || baseidx > anchor_w_ * anchor_h_ * 2)
            return Eigen::Vector2d(0.0, 0.0);
        else
            return Eigen::Vector2d(flow_(baseidx), flow_(baseidx + 1));
    }

    Eigen::Vector2d GetImageWarpingField(double u, double v) const {
        int i = (int)(u / anchor_step_);
        int j = (int)(v / anchor_step_);
        double p = (u - i * anchor_step_) / anchor_step_;
        double q = (v - j * anchor_step_) / anchor_step_;
        return (1 - p) * (1 - q) * QueryFlow(i, j)
            + (1 - p) * (q)* QueryFlow(i, j + 1)
            + (p)* (1 - q) * QueryFlow(i + 1, j)
            + (p)* (q)* QueryFlow(i + 1, j + 1);
    }

public:
    Eigen::VectorXd flow_;
    int anchor_w_, anchor_h_;
    double anchor_step_;
};

const double IMAGE_BOUNDARY_MARGIN = 10;

inline std::tuple<float, float, float> Project3DPointAndGetUVDepth(
        const Eigen::Vector3d X,
        const PinholeCameraTrajectory& camera, int camid)
{
    std::pair<double, double> f = camera.intrinsic_.GetFocalLength();
    std::pair<double, double> p = camera.intrinsic_.GetPrincipalPoint();
    Eigen::Vector4d Vt = camera.extrinsic_[camid] *
            Eigen::Vector4d(X(0), X(1), X(2), 1);
    float u = float((Vt(0) * f.first) / Vt(2) + p.first);
    float v = float((Vt(1) * f.second) / Vt(2) + p.second);
    float z = float(Vt(2));
    return std::make_tuple(u, v, z);
}

std::tuple<std::vector<std::vector<int>>, std::vector<std::vector<int>>>
        MakeVertexAndImageVisibility(const TriangleMesh& mesh,
        const std::vector<RGBDImage>& images_rgbd,
        const std::vector<Image>& images_mask,
        const PinholeCameraTrajectory& camera,
        const ColorMapOptmizationOption& option)
{
    auto n_camera = camera.extrinsic_.size();
    auto n_vertex = mesh.vertices_.size();
    std::vector<std::vector<int>> visiblity_vertex_to_image;
    std::vector<std::vector<int>> visiblity_image_to_vertex;
    visiblity_vertex_to_image.resize(n_vertex);
    visiblity_image_to_vertex.resize(n_camera);
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
    for (int c = 0; c < n_camera; c++) {
        int viscnt = 0;
        for (int vertex_id = 0; vertex_id < n_vertex; vertex_id++) {
            Eigen::Vector3d X = mesh.vertices_[vertex_id];
            float u, v, d;
            std::tie(u, v, d) = Project3DPointAndGetUVDepth(X, camera, c);
            int u_d = int(round(u)), v_d = int(round(v));
            if (d < 0.0 || !images_rgbd[c].depth_.TestImageBoundary(u_d, v_d))
                continue;
            float d_sensor = *PointerAt<float>(images_rgbd[c].depth_, u_d, v_d);
            if (d_sensor > option.maximum_allowable_depth_)
                continue;
            if (*PointerAt<unsigned char>(images_mask[c], u_d, v_d) == 255)
                continue;
            if (std::fabs(d - d_sensor) <
                    option.depth_threshold_for_visiblity_check_) {
#ifdef _OPENMP
#pragma omp critical
#endif
                {
                    visiblity_vertex_to_image[vertex_id].push_back(c);
                    visiblity_image_to_vertex[c].push_back(vertex_id);
                    viscnt++;
                }
            }
        }
        PrintDebug("[cam %d] %.5f percents are visible\n",
                c, double(viscnt) / n_vertex * 100); fflush(stdout);
    }
    return std::move(std::make_tuple(
            visiblity_vertex_to_image, visiblity_image_to_vertex));
}

std::vector<ImageWarpingField> MakeWarpingFields(
        const std::vector<std::shared_ptr<Image>>& images,
        const ColorMapOptmizationOption& option)
{
    std::vector<ImageWarpingField> fields;
    for (auto i = 0; i < images.size(); i++) {
        int width = images[i]->width_;
        int height = images[i]->height_;
        fields.push_back(ImageWarpingField(width, height,
                option.number_of_vertical_anchors_));
    }
    return std::move(fields);
}

template<typename T>
std::tuple<bool, T> QueryImageIntensity(
        const Image& img, const Eigen::Vector3d& V,
        const PinholeCameraTrajectory& camera, int camid, int ch = -1)
{
    float u, v, depth;
    std::tie(u, v, depth) = Project3DPointAndGetUVDepth(V, camera, camid);
    if (img.TestImageBoundary(u, v, IMAGE_BOUNDARY_MARGIN)) {
        int u_round = int(round(u));
        int v_round = int(round(v));
        if (ch == -1) {
            return std::make_tuple(true,
                    *PointerAt<T>(img, u_round, v_round));
        } else {
            return std::make_tuple(true,
                    *PointerAt<T>(img, u_round, v_round, ch));
        }
    } else {
        return std::make_tuple(false, 0);
    }
}

template<typename T>
std::tuple<bool, T> QueryImageIntensity(
        const Image& img, const ImageWarpingField& field,
        const Eigen::Vector3d& V,
        const PinholeCameraTrajectory& camera, int camid, int ch = -1)
{
    float u, v, depth;
    std::tie(u, v, depth) = Project3DPointAndGetUVDepth(V, camera, camid);
    if (img.TestImageBoundary(u, v, IMAGE_BOUNDARY_MARGIN)) {
        Eigen::Vector2d uv_shift = field.GetImageWarpingField(u, v);
        if (img.TestImageBoundary(uv_shift(0), uv_shift(1),
                IMAGE_BOUNDARY_MARGIN)) {
            int u_shift = int(round(uv_shift(0)));
            int v_shift = int(round(uv_shift(1)));
            if (ch == -1) {
                return std::make_tuple(true,
                        *PointerAt<T>(img, u_shift, v_shift));
            } else {
                return std::make_tuple(true,
                        *PointerAt<T>(img, u_shift, v_shift, ch));
            }
        }
    }
    return std::make_tuple(false, 0);
}

void SetProxyIntensityForVertex(const TriangleMesh& mesh,
        const std::vector<std::shared_ptr<Image>>& images_gray,
        const std::vector<ImageWarpingField>& warping_field,
        const PinholeCameraTrajectory& camera,
        const std::vector<std::vector<int>>& visiblity_vertex_to_image,
        std::vector<double>& proxy_intensity)
{
    auto n_vertex = mesh.vertices_.size();
    proxy_intensity.resize(n_vertex);

#pragma omp parallel for schedule(static)
    for (auto i = 0; i < n_vertex; i++) {
        proxy_intensity[i] = 0.0;
        float sum = 0.0;
        for (auto iter = 0; iter < visiblity_vertex_to_image[i].size();
                iter++) {
            int j = visiblity_vertex_to_image[i][iter];
            float gray;
            bool valid = false;
            std::tie(valid, gray) = QueryImageIntensity<float>(
                    *images_gray[j], warping_field[j],
                    mesh.vertices_[i], camera, j);
            if (valid) {
                sum += 1.0;
                proxy_intensity[i] += gray;
            }
        }
        if (sum > 0) {
            proxy_intensity[i] /= sum;
        }
    }
}

void SetProxyIntensityForVertex(const TriangleMesh& mesh,
        const std::vector<std::shared_ptr<Image>>& images_gray,
        const PinholeCameraTrajectory& camera,
        const std::vector<std::vector<int>>& visiblity_vertex_to_image,
        std::vector<double>& proxy_intensity)
{
    auto n_vertex = mesh.vertices_.size();
    proxy_intensity.resize(n_vertex);

#pragma omp parallel for num_threads( 8 )
    for (auto i = 0; i < n_vertex; i++) {
        proxy_intensity[i] = 0.0;
        float sum = 0.0;
        for (auto iter = 0; iter < visiblity_vertex_to_image[i].size();
                iter++) {
            int j = visiblity_vertex_to_image[i][iter];
            float gray;
            bool valid = false;
            std::tie(valid, gray) = QueryImageIntensity<float>(
                    *images_gray[j], mesh.vertices_[i], camera, j);
            if (valid) {
                sum += 1.0;
                proxy_intensity[i] += gray;
            }
        }
        if (sum > 0) {
            proxy_intensity[i] /= sum;
        }
    }
}

void OptimizeImageCoorNonrigid(
        const TriangleMesh& mesh,
        const std::vector<std::shared_ptr<Image>>& images_gray,
        const std::vector<std::shared_ptr<Image>>& images_dx,
        const std::vector<std::shared_ptr<Image>>& images_dy,
        std::vector<ImageWarpingField>& warping_fields,
        const std::vector<ImageWarpingField>& warping_fields_init,
        PinholeCameraTrajectory& camera,
        const std::vector<std::vector<int>>& visiblity_vertex_to_image,
        const std::vector<std::vector<int>>& visiblity_image_to_vertex,
        std::vector<double>& proxy_intensity,
        const ColorMapOptmizationOption& option)
{
    auto n_vertex = mesh.vertices_.size();
    auto n_camera = camera.extrinsic_.size();
    Eigen::Matrix4d intr = Eigen::Matrix4d::Zero();
    intr.block<3,3>(0,0) = camera.intrinsic_.intrinsic_matrix_;
    intr(3, 3) = 1.0;
    double fx = intr(0, 0);
    double fy = intr(1, 1);
    SetProxyIntensityForVertex(mesh, images_gray, warping_fields, camera,
            visiblity_vertex_to_image, proxy_intensity);
    for (int itr = 0; itr < option.maximum_iteration_; itr++) {
        PrintDebug("[Iteration %04d] ", itr+1);
        double residual = 0.0;
        double residual_reg = 0.0;
        int total_num_ = 0;
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
        for (int i = 0; i < n_camera; i++) {
            int nonrigidval = warping_fields[i].anchor_w_ *
                    warping_fields[i].anchor_h_ * 2;
            Eigen::MatrixXd JJ = Eigen::MatrixXd::Zero(
                    6 + nonrigidval, 6 + nonrigidval);
            Eigen::VectorXd Jb = Eigen::VectorXd::Zero(6 + nonrigidval);
            double rr = 0.0;
            double rr_reg = 0.0;
            int this_num = 0;
            Eigen::Matrix4d pose;
            pose = camera.extrinsic_[i];
            double anchor_step = warping_fields[i].anchor_step_;
            int anchor_w = warping_fields[i].anchor_w_;
            for (auto iter = 0; iter < visiblity_image_to_vertex[i].size();
                    iter++) {
                int j = visiblity_image_to_vertex[i][iter];
                Eigen::Vector3d V = mesh.vertices_[j];
                Eigen::Vector4d G = pose * Eigen::Vector4d(V(0), V(1), V(2), 1);
                Eigen::Vector4d L = intr * G;
                double u = L(0) / L(2);
                double v = L(1) / L(2);
                int ii = (int)(u / anchor_step);
                int jj = (int)(v / anchor_step);
                double p = (u - ii * anchor_step) / anchor_step;
                double q = (v - jj * anchor_step) / anchor_step;
                Eigen::Vector2d grids[4] = {
                    warping_fields[i].QueryFlow(ii, jj),
                    warping_fields[i].QueryFlow(ii, jj + 1),
                    warping_fields[i].QueryFlow(ii + 1, jj),
                    warping_fields[i].QueryFlow(ii + 1, jj + 1),
                };
                Eigen::Vector2d uuvv = (1 - p) * (1 - q) * grids[0]
                    + (1 - p) * (q)* grids[1]
                    + (p)* (1 - q) * grids[2]
                    + (p)* (q)* grids[3];
                double uu = uuvv(0);
                double vv = uuvv(1);
                if (!images_gray[i]->TestImageBoundary(uu, vv,
                        IMAGE_BOUNDARY_MARGIN))
                    continue;
                bool valid; double gray, dIdfx, dIdfy;
                std::tie(valid, gray) = images_gray[i]->FloatValueAt(uu, vv);
                std::tie(valid, dIdfx) = images_dx[i]->FloatValueAt(uu, vv);
                std::tie(valid, dIdfy) = images_dy[i]->FloatValueAt(uu, vv);
                Eigen::Vector2d dIdf(dIdfx, dIdfy);
                Eigen::Vector2d dfdx = ((grids[2] - grids[0]) * (1 - q) +
                        (grids[3] - grids[1]) * q) / anchor_step;
                Eigen::Vector2d dfdy = ((grids[1] - grids[0]) * (1 - p) +
                        (grids[3] - grids[2]) * p) / anchor_step;
                double dIdx = dIdf.dot(dfdx);
                double dIdy = dIdf.dot(dfdy);
                double invz = 1. / G(2);
                double v0 = dIdx * fx * invz;
                double v1 = dIdy * fy * invz;
                double v2 = -(v0 * G(0) + v1 * G(1)) * invz;
                double C[6 + 8];
                C[0] = -G(2) * v1 + G(1) * v2;
                C[1] = G(2) * v0 - G(0) * v2;
                C[2] = -G(1) * v0 + G(0) * v1;
                C[3] = v0;
                C[4] = v1;
                C[5] = v2;
                C[6] = dIdf(0) * (1 - p) * (1 - q);
                C[7] = dIdf(1) * (1 - p) * (1 - q);
                C[8] = dIdf(0) * (1 - p) * (q);
                C[9] = dIdf(1) * (1 - p) * (q);
                C[10] = dIdf(0) * (p)* (1 - q);
                C[11] = dIdf(1) * (p)* (1 - q);
                C[12] = dIdf(0) * (p)* (q);
                C[13] = dIdf(1) * (p)* (q);
                int idx[6 + 8];
                idx[0] = 0;
                idx[1] = 1;
                idx[2] = 2;
                idx[3] = 3;
                idx[4] = 4;
                idx[5] = 5;
                idx[6] = 6 + (ii + jj * anchor_w) * 2;
                idx[7] = 6 + (ii + jj * anchor_w) * 2 + 1;
                idx[8] = 6 + (ii + (jj + 1) * anchor_w) * 2;
                idx[9] = 6 + (ii + (jj + 1) * anchor_w) * 2 + 1;
                idx[10] = 6 + ((ii + 1) + jj * anchor_w) * 2;
                idx[11] = 6 + ((ii + 1) + jj * anchor_w) * 2 + 1;
                idx[12] = 6 + ((ii + 1) + (jj + 1) * anchor_w) * 2;
                idx[13] = 6 + ((ii + 1) + (jj + 1) * anchor_w) * 2 + 1;
                for (int x = 0; x < 14; x++) {
                    for (int y = 0; y < 14; y++) {
                        JJ(idx[x], idx[y]) += C[x] * C[y];
                    }
                }
                double r = (proxy_intensity[j] - gray);
                for (int x = 0; x < 14; x++) {
                    Jb(idx[x]) -= r * C[x];
                }
                rr += r * r;
                this_num++;
            }
            if (this_num == 0)
                continue;
            double weight = option.non_rigid_anchor_point_weight_
                    * this_num / n_vertex;
            for (int j = 0; j < nonrigidval; j++) {
                double r = weight * (warping_fields[i].flow_(j) -
                        warping_fields_init[i].flow_(j));
                JJ(6 + j, 6 + j) += weight * weight;
                Jb(6 + j) += weight * r;
                rr_reg += r * r;
            }
#ifdef _OPENMP
#pragma omp critical
#endif
            {
                bool success = false;
                Eigen::VectorXd result;
                std::tie(success, result) = SolveLinearSystem(JJ, -Jb, false);
                Eigen::Affine3d aff_mat;
                aff_mat.linear() = (Eigen::Matrix3d)
                        Eigen::AngleAxisd(result(2),Eigen::Vector3d::UnitZ())
                        * Eigen::AngleAxisd(result(1),Eigen::Vector3d::UnitY())
                        * Eigen::AngleAxisd(result(0),Eigen::Vector3d::UnitX());
                aff_mat.translation() =
                        Eigen::Vector3d(result(3), result(4), result(5));
                pose = aff_mat.matrix() * pose;
                for (int j = 0; j < nonrigidval; j++) {
                    warping_fields[i].flow_(j) += result(6 + j);
                }
            }
            camera.extrinsic_[i] = pose;
            residual += rr;
            residual_reg += rr_reg;
            total_num_ += this_num;
        }
        PrintDebug("Residual error : %.6f, reg : %.6f\n",
                residual, residual_reg);
        SetProxyIntensityForVertex(mesh, images_gray, warping_fields, camera,
                visiblity_vertex_to_image, proxy_intensity);
    }
}

void OptimizeImageCoorRigid(
        const TriangleMesh& mesh,
        const std::vector<std::shared_ptr<Image>>& images_gray,
        const std::vector<std::shared_ptr<Image>>& images_dx,
        const std::vector<std::shared_ptr<Image>>& images_dy,
        PinholeCameraTrajectory& camera,
        const std::vector<std::vector<int>>& visiblity_vertex_to_image,
        const std::vector<std::vector<int>>& visiblity_image_to_vertex,
        std::vector<double>& proxy_intensity,
        const ColorMapOptmizationOption& option)
{
    int total_num_ = 0;
    auto n_camera = camera.extrinsic_.size();
    Eigen::Matrix4d intr = Eigen::Matrix4d::Zero();
    intr.block<3,3>(0,0) = camera.intrinsic_.intrinsic_matrix_;
    intr(3, 3) = 1.0;
    double fx = intr(0, 0);
    double fy = intr(1, 1);
    SetProxyIntensityForVertex(mesh, images_gray, camera,
            visiblity_vertex_to_image, proxy_intensity);
    for (int itr = 0; itr < option.maximum_iteration_; itr++) {
        PrintDebug("[Iteration %04d] ", itr+1);
        double residual = 0.0;
        total_num_ = 0;
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
        for (int i = 0; i < n_camera; i++) {
            Eigen::MatrixXd JJ(6, 6);
            Eigen::VectorXd Jb(6);
            JJ.setZero();
            Jb.setZero();
            double rr = 0.0;
            int this_num = 0;
            Eigen::Matrix4d pose;
            pose = camera.extrinsic_[i];
            for (auto iter = 0; iter < visiblity_image_to_vertex[i].size();
                    iter++) {
                int j = visiblity_image_to_vertex[i][iter];
                Eigen::Vector3d V = mesh.vertices_[j];
                Eigen::Vector4d G = pose * Eigen::Vector4d(V(0), V(1), V(2), 1);
                Eigen::Vector4d L = intr * G;
                double u = L(0) / L(2);
                double v = L(1) / L(2);
                if (!images_gray[i]->TestImageBoundary(u, v,
                        IMAGE_BOUNDARY_MARGIN))
                    continue;
                bool valid; double gray, dIdx, dIdy;
                std::tie(valid, gray) = images_gray[i]->FloatValueAt(u, v);
                std::tie(valid, dIdx) = images_dx[i]->FloatValueAt(u, v);
                std::tie(valid, dIdy) = images_dy[i]->FloatValueAt(u, v);
                if (gray == -1.0)
                    continue;
                double invz = 1. / G(2);
                double v0 = dIdx * fx * invz;
                double v1 = dIdy * fy * invz;
                double v2 = -(v0 * G(0) + v1 * G(1)) * invz;
                double C[6];
                C[0] = (-G(2) * v1 + G(1) * v2);
                C[1] = (G(2) * v0 - G(0) * v2);
                C[2] = (-G(1) * v0 + G(0) * v1);
                C[3] = v0;
                C[4] = v1;
                C[5] = v2;
                for (int x = 0; x < 6; x++) {
                    for (int y = 0; y < 6; y++) {
                        JJ(x, y) += C[x] * C[y];
                    }
                }
                double r = (proxy_intensity[j] - gray);
                for (int x = 0; x < 6; x++) {
                    Jb(x) -= r * C[x];
                }
                rr += r * r;
                this_num++;
            }
            Eigen::VectorXd result(6);
            result = -JJ.inverse() * Jb;
            Eigen::Affine3d aff_mat;
            aff_mat.linear() = (Eigen::Matrix3d)
                    Eigen::AngleAxisd(result(2), Eigen::Vector3d::UnitZ())
                    * Eigen::AngleAxisd(result(1), Eigen::Vector3d::UnitY())
                    * Eigen::AngleAxisd(result(0), Eigen::Vector3d::UnitX());
            aff_mat.translation() =
                    Eigen::Vector3d(result(3), result(4), result(5));
            pose = aff_mat.matrix() * pose;
            camera.extrinsic_[i] = pose;
#ifdef _OPENMP
#pragma omp critical
#endif
            {
                residual += rr;
                total_num_ += this_num;
            }
        }
        PrintDebug("Residual error : %.6f (avg : %.6f)\n",
                residual, residual / total_num_);
        SetProxyIntensityForVertex(mesh, images_gray, camera,
                visiblity_vertex_to_image, proxy_intensity);
    }
}

void SetGeometryColorAverage(TriangleMesh& mesh,
        const std::vector<RGBDImage>& images_rgbd,
        const std::vector<ImageWarpingField>& warping_fields,
        const PinholeCameraTrajectory& camera,
        const std::vector<std::vector<int>>& visiblity_vertex_to_image)
{
    auto n_vertex = mesh.vertices_.size();
    mesh.vertex_colors_.clear();
    mesh.vertex_colors_.resize(n_vertex);
#pragma omp parallel for schedule(static)
    for (int i = 0; i < n_vertex; i++) {
        mesh.vertex_colors_[i] = Eigen::Vector3d::Zero();
        double sum = 0.0;
        for (auto iter = 0; iter < visiblity_vertex_to_image[i].size();
                iter++) {
            int j = visiblity_vertex_to_image[i][iter];
            unsigned char r_temp, g_temp, b_temp;
            bool valid = false;
            std::tie(valid, r_temp) = QueryImageIntensity<unsigned char>(
                    images_rgbd[j].color_, warping_fields[j],
                    mesh.vertices_[i], camera, j, 0);
            std::tie(valid, g_temp) = QueryImageIntensity<unsigned char>(
                    images_rgbd[j].color_, warping_fields[j],
                    mesh.vertices_[i], camera, j, 1);
            std::tie(valid, b_temp) = QueryImageIntensity<unsigned char>(
                    images_rgbd[j].color_, warping_fields[j],
                    mesh.vertices_[i], camera, j, 2);
            float r = (float)r_temp / 255.0f;
            float g = (float)g_temp / 255.0f;
            float b = (float)b_temp / 255.0f;
            if (valid) {
                mesh.vertex_colors_[i] += Eigen::Vector3d(r, g, b);
                sum += 1.0;
            }
        }
        if (sum > 0.0) {
            mesh.vertex_colors_[i] /= sum;
        }
    }
}

void SetGeometryColorAverage(TriangleMesh& mesh,
        const std::vector<RGBDImage>& images_rgbd,
        const PinholeCameraTrajectory& camera,
        const std::vector<std::vector<int>>& visiblity_vertex_to_image)
{
    auto n_vertex = mesh.vertices_.size();
    mesh.vertex_colors_.clear();
    mesh.vertex_colors_.resize(n_vertex);
#pragma omp parallel for schedule(static)
    for (int i = 0; i < n_vertex; i++) {
        mesh.vertex_colors_[i] = Eigen::Vector3d::Zero();
        double sum = 0.0;
        for (auto iter = 0; iter < visiblity_vertex_to_image[i].size();
                iter++) {
            int j = visiblity_vertex_to_image[i][iter];
            unsigned char r_temp, g_temp, b_temp;
            bool valid = false;
            std::tie(valid, r_temp) = QueryImageIntensity<unsigned char>(
                    images_rgbd[j].color_, mesh.vertices_[i], camera, j, 0);
            std::tie(valid, g_temp) = QueryImageIntensity<unsigned char>(
                    images_rgbd[j].color_, mesh.vertices_[i], camera, j, 1);
            std::tie(valid, b_temp) = QueryImageIntensity<unsigned char>(
                    images_rgbd[j].color_, mesh.vertices_[i], camera, j, 2);
            float r = (float)r_temp / 255.0f;
            float g = (float)g_temp / 255.0f;
            float b = (float)b_temp / 255.0f;
            if (valid) {
                mesh.vertex_colors_[i] += Eigen::Vector3d(r, g, b);
                sum += 1.0;
            }
        }
        if (sum > 0.0) {
            mesh.vertex_colors_[i] /= sum;
        }
    }
}

std::tuple<std::vector<std::shared_ptr<Image>>,
        std::vector<std::shared_ptr<Image>>,
        std::vector<std::shared_ptr<Image>>> MakeGradientImages(
        const std::vector<RGBDImage>& images_rgbd)
{
    auto n_images = images_rgbd.size();
    std::vector<std::shared_ptr<Image>> images_gray;
    std::vector<std::shared_ptr<Image>> images_dx;
    std::vector<std::shared_ptr<Image>> images_dy;
    for (int i=0; i<n_images; i++) {
        auto gray_image = CreateFloatImageFromImage(images_rgbd[i].color_);
        auto gray_image_filtered = FilterImage(*gray_image,
                Image::FilterType::Gaussian3);
        images_gray.push_back(gray_image_filtered);
        images_dx.push_back(FilterImage(*gray_image_filtered,
                Image::FilterType::Sobel3Dx));
        images_dy.push_back(FilterImage(*gray_image_filtered,
                Image::FilterType::Sobel3Dy));
    }
    return std::move(std::make_tuple(images_gray, images_dx, images_dy));
}

std::vector<Image> MakeDepthMasks(
        const std::vector<RGBDImage>& images_rgbd,
        const ColorMapOptmizationOption& option)
{
    auto n_images = images_rgbd.size();
    std::vector<Image> images_mask;
    for (int i=0; i<n_images; i++) {
        PrintDebug("[MakeDepthMasks] Image %d/%d\n", i, n_images);
        int width = images_rgbd[i].depth_.width_;
        int height = images_rgbd[i].depth_.height_;
        auto depth_image = CreateFloatImageFromImage(images_rgbd[i].depth_);
        auto depth_image_gradient_dx = FilterImage(*depth_image,
                Image::FilterType::Sobel3Dx);
        auto depth_image_gradient_dy = FilterImage(*depth_image,
                Image::FilterType::Sobel3Dy);
        auto mask = std::make_shared<Image>();
        mask->PrepareImage(width, height, 1, 1);
        for (int v=0; v<height; v++) {
            for (int u=0; u<width; u++) {
                double dx = *PointerAt<float>(*depth_image_gradient_dx, u, v);
                double dy = *PointerAt<float>(*depth_image_gradient_dy, u, v);
                double mag = sqrt(dx * dx + dy * dy);
                if (mag > option.depth_threshold_for_discontinuity_check_) {
                    *PointerAt<unsigned char>(*mask, u, v) = 255;
                } else {
                    *PointerAt<unsigned char>(*mask, u, v) = 0;
                }
            }
        }
        auto mask_dilated = DilateImage(*mask,
                option.half_dilation_kernel_size_for_discontinuity_map_);
        images_mask.push_back(*mask_dilated);
    }
    return std::move(images_mask);
}

}    // unnamed namespace

void ColorMapOptimization(TriangleMesh& mesh,
        const std::vector<RGBDImage>& images_rgbd,
        PinholeCameraTrajectory& camera,
        const ColorMapOptmizationOption& option
        /* = ColorMapOptmizationOption()*/)
{
    PrintDebug("[ColorMapOptimization]\n");
    std::vector<std::shared_ptr<Image>> images_gray;
    std::vector<std::shared_ptr<Image>> images_dx;
    std::vector<std::shared_ptr<Image>> images_dy;
    std::tie(images_gray, images_dx, images_dy) =
            MakeGradientImages(images_rgbd);

    PrintDebug("[ColorMapOptimization] :: MakingMasks\n");
    auto images_mask = MakeDepthMasks(images_rgbd, option);

    PrintDebug("[ColorMapOptimization] :: VisibilityCheck\n");
    std::vector<std::vector<int>> visiblity_vertex_to_image;
    std::vector<std::vector<int>> visiblity_image_to_vertex;
    std::tie(visiblity_vertex_to_image, visiblity_image_to_vertex) =
            MakeVertexAndImageVisibility(mesh, images_rgbd,
            images_mask, camera, option);

    std::vector<double> proxy_intensity;
    if (option.non_rigid_camera_coordinate_) {
        PrintDebug("[ColorMapOptimization] :: Non-Rigid Optimization\n");
        auto warping_uv_ = MakeWarpingFields(images_gray, option);
        auto warping_uv_init_ = MakeWarpingFields(images_gray, option);
        OptimizeImageCoorNonrigid(mesh, images_gray,
                images_dx, images_dy, warping_uv_, warping_uv_init_, camera,
                visiblity_vertex_to_image, visiblity_image_to_vertex,
                proxy_intensity, option);
        SetGeometryColorAverage(mesh, images_rgbd, warping_uv_, camera,
                visiblity_vertex_to_image);
    } else {
        PrintDebug("[ColorMapOptimization] :: Rigid Optimization\n");
        OptimizeImageCoorRigid(mesh, images_gray, images_dx, images_dy, camera,
                visiblity_vertex_to_image, visiblity_image_to_vertex,
                proxy_intensity, option);
        SetGeometryColorAverage(mesh, images_rgbd, camera,
                visiblity_vertex_to_image);
    }
}

}    // namespace three


text:
#ifndef BOOST_CORE_DEMANGLE_HPP_INCLUDED
#define BOOST_CORE_DEMANGLE_HPP_INCLUDED

// core::demangle
//
// Copyright 2014 Peter Dimov
// Copyright 2014 Andrey Semashev
//
// 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/config.hpp>
#include <string>

#if defined(BOOST_HAS_PRAGMA_ONCE)
#pragma once
#endif

// __has_include is currently supported by GCC and Clang. However GCC 4.9 may
// have issues and returns 1 for 'defined( __has_include )', while
// '__has_include' is actually not supported:
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63662
#if defined(__has_include) && (!defined(BOOST_GCC) || (__GNUC__ + 0) >= 5)
#if __has_include(<cxxabi.h>)
#define BOOST_CORE_HAS_CXXABI_H
#endif
#elif defined(__GLIBCXX__) || defined(__GLIBCPP__)
#define BOOST_CORE_HAS_CXXABI_H
#endif

#if defined(BOOST_CORE_HAS_CXXABI_H)
#include <cxxabi.h>
// For some archtectures (mips, mips64, x86, x86_64) cxxabi.h in Android NDK is
// implemented by gabi++ library
// (https://android.googlesource.com/platform/ndk/+/master/sources/cxx-stl/gabi++/),
// which does not implement abi::__cxa_demangle(). We detect this implementation
// by checking the include guard here.
#if defined(__GABIXX_CXXABI_H__)
#undef BOOST_CORE_HAS_CXXABI_H
#else
#include <cstddef>
#include <cstdlib>
#endif
#endif

namespace boost
{

namespace core
{

inline char const* demangle_alloc(char const* name) BOOST_NOEXCEPT;
inline void demangle_free(char const* name) BOOST_NOEXCEPT;

class scoped_demangled_name
{
  private:
    char const* m_p;

  public:
    explicit scoped_demangled_name(char const* name) BOOST_NOEXCEPT
        : m_p(demangle_alloc(name))
    {
    }

    ~scoped_demangled_name() BOOST_NOEXCEPT
    {
        demangle_free(m_p);
    }

    char const* get() const BOOST_NOEXCEPT
    {
        return m_p;
    }

    BOOST_DELETED_FUNCTION(scoped_demangled_name(scoped_demangled_name const&))
    BOOST_DELETED_FUNCTION(
        scoped_demangled_name& operator=(scoped_demangled_name const&))
};

#if defined(BOOST_CORE_HAS_CXXABI_H)

inline char const* demangle_alloc(char const* name) BOOST_NOEXCEPT
{
    int status = 0;
    std::size_t size = 0;
    return abi::__cxa_demangle(name, NULL, &size, &status);
}

inline void demangle_free(char const* name) BOOST_NOEXCEPT
{
    std::free(const_cast<char*>(name));
}

inline std::string demangle(char const* name)
{
    scoped_demangled_name demangled_name(name);
    char const* p = demangled_name.get();
    if (!p)
        p = name;
    return p;
}

#else

inline char const* demangle_alloc(char const* name) BOOST_NOEXCEPT
{
    return name;
}

inline void demangle_free(char const*) BOOST_NOEXCEPT
{
}

inline std::string demangle(char const* name)
{
    return name;
}

#endif

} // namespace core

} // namespace boost

#undef BOOST_CORE_HAS_CXXABI_H

#endif // #ifndef BOOST_CORE_DEMANGLE_HPP_INCLUDED

max_stars_repo_name: sotaoverride/backup

max_issues_repo_name: sotaoverride/backup

max_forks_repo_name: sotaoverride/backup


text:
/*
 [auto_generated]
 libs/numeric/odeint/test/runge_kutta_controlled_concepts.cpp

 [begin_description]
 This file tests the Stepper concepts of odeint with all Controlled Runge-Kutta steppers.
 It's one of the main tests of odeint.
 [end_description]

 Copyright 2012 Karsten Ahnert
 Copyright 2012-2013 Mario Mulansky

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

// disable checked iterator warning for msvc
#include <boost/config.hpp>
#ifdef BOOST_MSVC
    #pragma warning(disable:4996)
#endif

#define BOOST_TEST_MODULE odeint_runge_kutta_controlled_concepts

#include <vector>
#include <cmath>
#include <iostream>

#include <boost/numeric/odeint/config.hpp>

#include <boost/array.hpp>

#include <boost/test/unit_test.hpp>

#include <boost/ref.hpp>
#include <boost/bind.hpp>
#include <boost/utility.hpp>
#include <boost/type_traits/add_reference.hpp>

#include <boost/mpl/vector.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/mpl/insert_range.hpp>
#include <boost/mpl/end.hpp>
#include <boost/mpl/copy.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/mpl/inserter.hpp>

#include <boost/numeric/odeint/stepper/runge_kutta_cash_karp54_classic.hpp>
#include <boost/numeric/odeint/stepper/runge_kutta_cash_karp54.hpp>
#include <boost/numeric/odeint/stepper/runge_kutta_dopri5.hpp>
#include <boost/numeric/odeint/stepper/runge_kutta_fehlberg78.hpp>
#include <boost/numeric/odeint/stepper/controlled_runge_kutta.hpp>
#include <boost/numeric/odeint/stepper/bulirsch_stoer.hpp>

#include "prepare_stepper_testing.hpp"
#include "dummy_odes.hpp"

using std::vector;

using namespace boost::unit_test;
using namespace boost::numeric::odeint;
namespace mpl = boost::mpl;

const double result = 2.2; // two steps

const double eps = 1.0e-14;

template< class Stepper , class System >
void check_controlled_stepper_concept( Stepper &stepper , System system , typename Stepper::state_type &x )
{
    typedef Stepper stepper_type;
    typedef typename stepper_type::deriv_type container_type;
    //typedef typename stepper_type::order_type order_type;  controlled_error_stepper don't necessarily have a order (burlish-stoer)
    typedef typename stepper_type::time_type time_type;

    time_type t = 0.0 , dt = 0.1;
    controlled_step_result step_result = stepper.try_step( system , x , t , dt );

    BOOST_CHECK_MESSAGE( step_result == success , "step result: " << step_result ); // error = 0 for constant system -> step size is always too small
}

template< class ControlledStepper , typename T >
struct perform_controlled_stepper_test
{
    typedef T vector_space_type;
    void operator()( void ) const
    {
        using std::abs;
        vector_space_type x;
        x = 2.0;
        ControlledStepper controlled_stepper;
        constant_system_functor_vector_space sys;
#ifndef _MSC_VER
        // dont run this for MSVC due to compiler bug 697006
        check_controlled_stepper_concept( controlled_stepper ,
                                          constant_system_vector_space< vector_space_type , vector_space_type , typename ControlledStepper::time_type >
                                          , x );
#else
        check_controlled_stepper_concept( controlled_stepper , boost::cref( sys ) , x );
#endif
        check_controlled_stepper_concept( controlled_stepper , boost::cref( sys ) , x );
        BOOST_CHECK( (abs( x - result )) < eps );
    }
};

template< class ControlledStepper , typename T >
struct perform_controlled_stepper_test< ControlledStepper , std::vector<T> >
{
    typedef std::vector<T> vector_type;
    void operator()( void )
    {
        using std::abs;
        vector_type x( 1 , 2.0 );
        ControlledStepper controlled_stepper;
        constant_system_functor_standard sys;
#ifndef _MSC_VER
        // dont run this for MSVC due to compiler bug 697006

        check_controlled_stepper_concept( controlled_stepper ,
                                          constant_system_standard< vector_type , vector_type , typename ControlledStepper::time_type > ,
                                          x );
#else
        check_controlled_stepper_concept( controlled_stepper , boost::cref( sys ) , x );
#endif
        check_controlled_stepper_concept( controlled_stepper , boost::cref( sys ) , x );
        BOOST_CHECK( (abs( x[0] - result )) < eps );
    }
};

template< class ControlledStepper >
struct perform_controlled_stepper_test< ControlledStepper , vector_space_type >
{
    void operator()( void ) const
    {
        using std::abs;
        vector_space_type x;
        x = 2.0;
        ControlledStepper controlled_stepper;
        constant_system_functor_vector_space sys;
#ifndef _MSC_VER
        // dont run this for MSVC due to compiler bug 697006
        check_controlled_stepper_concept( controlled_stepper ,
                                          constant_system_vector_space< vector_space_type , vector_space_type , typename ControlledStepper::time_type >
                                          , x );
#else
        check_controlled_stepper_concept( controlled_stepper , boost::cref( sys ) , x );
#endif
        check_controlled_stepper_concept( controlled_stepper , boost::cref( sys ) , x );
        BOOST_CHECK( (abs( x - result )) < eps );
    }
};

template< class ControlledStepper , typename T >
struct perform_controlled_stepper_test< ControlledStepper , boost::array<T,1> >
{
    typedef boost::array<T,1> array_type;
    void operator()( void )
    {
        using std::abs;
        array_type x;
        x[0] = 2.0;
        ControlledStepper controlled_stepper;
        constant_system_functor_standard sys;
#ifndef _MSC_VER
        // dont run this for MSVC due to compiler bug 697006
        check_controlled_stepper_concept( controlled_stepper , constant_system_standard< array_type , array_type , typename ControlledStepper::time_type > , x );
#else
        check_controlled_stepper_concept( controlled_stepper , boost::cref( sys ) , x );
#endif
        check_controlled_stepper_concept( controlled_stepper , boost::cref( sys ) , x );
        BOOST_CHECK( (abs( x[0] - result )) < eps );
    }
};

template< class State > class controlled_stepper_methods : public mpl::vector<
    controlled_runge_kutta< runge_kutta_cash_karp54_classic< State , typename detail::extract_value_type<State>::type > > ,
    controlled_runge_kutta< runge_kutta_dopri5< State , typename detail::extract_value_type<State>::type > > ,
    controlled_runge_kutta< runge_kutta_fehlberg78< State , typename detail::extract_value_type<State>::type > > ,
    bulirsch_stoer< State , typename detail::extract_value_type<State>::type >
    > { };

typedef mpl::copy
<
    container_types ,
    mpl::inserter
    <
        mpl::vector0<> ,
        mpl::insert_range
        <
            mpl::_1 ,
            mpl::end< mpl::_1 > ,
            controlled_stepper_methods< mpl::_2 >
            >
        >
    >::type all_controlled_stepper_methods;

BOOST_AUTO_TEST_SUITE( controlled_runge_kutta_concept_test )

BOOST_AUTO_TEST_CASE_TEMPLATE( controlled_stepper_test , ControlledStepper , all_controlled_stepper_methods )
{
    perform_controlled_stepper_test< ControlledStepper , typename ControlledStepper::state_type > tester;
    tester();
}

BOOST_AUTO_TEST_SUITE_END()


text:
#ifndef DELAUNAY3D_HPP
#define DELAUNAY3D_HPP 1

#include "Vector3D.hpp"
#include "Tetrahedron.hpp"
#include <string>
#include <vector>
#include <set>
#include <array>
#include <boost/container/flat_set.hpp>

using std::vector;
using std::string;
//using std::stack;

class Delaunay3D
{
public:
	vector<Tetrahedron> tetras_;
	vector<Vector3D> points_;
	boost::container::flat_set<size_t> empty_tetras_;
	std::size_t Norg_;
	std::size_t outside_neighbor_;

	Delaunay3D();

	Delaunay3D(Delaunay3D const& other);

	Delaunay3D& operator=(Delaunay3D const& other);

	~Delaunay3D();

	void Build(vector<Vector3D> const& points,Vector3D const& maxv,Vector3D const& minv,std::vector<size_t> &order);

	void BuildExtra(vector<Vector3D> const& points);

	void output(string const& filename)const;

	bool CheckCorrect(void);

	void Clean(void);
private:
	void InsertPoint(std::size_t index);
	std::size_t Walk(std::size_t point, std::size_t first_guess);
	void flip14(std::size_t point,std::size_t tetra);
	void flip23(std::size_t tetra0, std::size_t tetra1,std::size_t location0,bool flat_check);
	void flip32(std::size_t tetra0, std::size_t tetra1, std::size_t location0, std::size_t shared_loction, bool flat_check);
	void flip44(std::size_t tetra0, std::size_t tetra1, std::size_t location0, std::size_t neigh0, std::size_t neigh1);
	void FindFlip(std::size_t tetra0, std::size_t tetra1, std::size_t p, size_t p_loc, size_t other_point_loc);
	void ExactFlip(std::size_t tetra0, std::size_t tetra1, std::size_t p);
	std::size_t FindThirdNeighbor(std::size_t tetra0, std::size_t tetra1);

	std::array<Vector3D, 3> b3_temp_,b3_temp2_;
	std::array<Vector3D, 4> b4_temp_;
	std::array<Vector3D, 5> b5_temp_;
	std::array<std::size_t, 4> b4s_temp_,b4s_temp2_;
	std::array<std::size_t, 8> b8s_temp_;
	vector<std::size_t> to_check_;
	std::size_t last_checked_;
	Tetrahedron tet_temp0_, tet_temp1_, newtet_;
};

#endif //DELAUNAY3D_HPP

max_stars_repo_name: GalaxyHunters/Vivid

max_issues_repo_name: GalaxyHunters/Vivid

max_forks_repo_name: GalaxyHunters/Vivid


text:
/*
 * 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)
 *
 * Copyright (c) 2020 Andrey Semashev
 */
/*!
 * \file   atomic/detail/fence_arch_ops_gcc_ppc.hpp
 *
 * This header contains implementation of the \c fence_arch_operations struct.
 */

#ifndef BOOST_ATOMIC_DETAIL_FENCE_ARCH_OPS_GCC_PPC_HPP_INCLUDED_
#define BOOST_ATOMIC_DETAIL_FENCE_ARCH_OPS_GCC_PPC_HPP_INCLUDED_

#include <boost/memory_order.hpp>
#include <boost/atomic/detail/config.hpp>
#include <boost/atomic/detail/header.hpp>

#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif

namespace boost {
namespace atomics {
namespace detail {

//! Fence operations for PowerPC
struct fence_arch_operations_gcc_ppc
{
    static BOOST_FORCEINLINE void thread_fence(memory_order order) BOOST_NOEXCEPT
    {
        if (order != memory_order_relaxed)
        {
#if defined(__powerpc64__) || defined(__PPC64__)
            if (order != memory_order_seq_cst)
                __asm__ __volatile__ ("lwsync" ::: "memory");
            else
                __asm__ __volatile__ ("sync" ::: "memory");
#else
            __asm__ __volatile__ ("sync" ::: "memory");
#endif
        }
    }

    static BOOST_FORCEINLINE void signal_fence(memory_order order) BOOST_NOEXCEPT
    {
        if (order != memory_order_relaxed)
        {
#if defined(__ibmxl__) || defined(__IBMCPP__)
            __fence();
#else
            __asm__ __volatile__ ("" ::: "memory");
#endif
        }
    }
};

typedef fence_arch_operations_gcc_ppc fence_arch_operations;

} // namespace detail
} // namespace atomics
} // namespace boost

#include <boost/atomic/detail/footer.hpp>

#endif // BOOST_ATOMIC_DETAIL_FENCE_ARCH_OPS_GCC_PPC_HPP_INCLUDED_


text:
// Copyright Louis Dionne 2013-2016
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)

#include <boost/hana/detail/ebo.hpp>

#include <boost/hana/assert.hpp>

#include <string>
#include <type_traits>
#include <utility>
namespace hana = boost::hana;
using hana::detail::ebo;

template <int> struct empty { };
template <int> struct idx;
template <typename ...Bases> struct inherit : Bases... { };

static_assert(sizeof(inherit<>) == sizeof(inherit<ebo<idx<0>, empty<0>>>), "");
static_assert(sizeof(inherit<>) == sizeof(inherit<ebo<idx<0>, empty<0>>, ebo<idx<1>, empty<1>>>), "");
static_assert(sizeof(inherit<>) == sizeof(inherit<ebo<idx<0>, empty<0>>, ebo<idx<1>, empty<1>>, ebo<idx<2>, empty<2>>>), "");

int main() {
    // Test default-construction
    {
        constexpr ebo<idx<0>, int> e;
        static_assert(hana::detail::ebo_get<idx<0>>(e) == 0, "");
    }

    // Test construction of a non-empty object
    {
        ebo<idx<0>, std::string> e{"foobar"};
        BOOST_HANA_RUNTIME_CHECK(hana::detail::ebo_get<idx<0>>(e) == "foobar");
    }

    {
        ebo<idx<0>, std::string> e{};
        BOOST_HANA_RUNTIME_CHECK(hana::detail::ebo_get<idx<0>>(e) == "");
    }

    // Test construction of a non default-constructible type
    {
        struct nodefault {
            nodefault() = delete;
            explicit nodefault(char const*) { }
        };
        ebo<idx<0>, nodefault> e{"foobar"};
    }

    // Get lvalue, const lvalue and rvalue with a non-empty type
    {
        ebo<idx<0>, std::string> e{"foobar"};
        std::string& s = hana::detail::ebo_get<idx<0>>(e);
        BOOST_HANA_RUNTIME_CHECK(s == "foobar");
        s = "foobaz";
        BOOST_HANA_RUNTIME_CHECK(hana::detail::ebo_get<idx<0>>(e) == "foobaz");
    }

    {
        ebo<idx<0>, std::string> const e{"foobar"};
        std::string const& s = hana::detail::ebo_get<idx<0>>(e);
        BOOST_HANA_RUNTIME_CHECK(s == "foobar");
    }

    {
        ebo<idx<0>, std::string> e{"foobar"};
        std::string&& s = hana::detail::ebo_get<idx<0>>(std::move(e));
        BOOST_HANA_RUNTIME_CHECK(s == "foobar");
    }

    // Get lvalue, const lvalue and rvalue with an empty type
    {
        ebo<idx<0>, empty<0>> e{};
        empty<0>& s = hana::detail::ebo_get<idx<0>>(e);
        (void)s;
    }

    {
        ebo<idx<0>, empty<0>> const e{};
        empty<0> const& s = hana::detail::ebo_get<idx<0>>(e);
        (void)s;
    }

    {
        ebo<idx<0>, empty<0>> e{};
        empty<0>&& s = hana::detail::ebo_get<idx<0>>(std::move(e));
        (void)s;
    }
}


text:
/*
 * global.cpp
 *
 *  Created on: Sep 2, 2018
 *      Author: jasonr
 */

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <memory>

#include <boost/utility.hpp>

#include "global.h"

namespace Ui
{

class Master: boost::noncopyable
{
public:
    ~Master();

    static void initialize();
    static void shutdown();

private:
    Master();

    static Master & instance();

};

std::unique_ptr<Master> g_instance;

void
Master::initialize()
{
    instance();
}

void
Master::shutdown()
{
    if (g_instance)
        g_instance.reset();
}

Master::Master()
{
}

Master::~Master()
{
}

Master &
Master::instance()
{
    if (!g_instance)
        g_instance = std::unique_ptr<Master>(new Master());
    return *g_instance;
}

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

void
initialize()
{
    Master::initialize();
}

void
shutdown()
{
    Master::shutdown();
}

} // namespace Ui

max_stars_repo_name: etiam/db

max_issues_repo_name: etiam/db

max_forks_repo_name: etiam/db