text:
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "rpc/client.h"
#include "rpc/protocol.h"
#include "util.h"

#include <set>
#include <stdint.h>

#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
#include <univalue.h>

using namespace std;

class CRPCConvertParam
{
public:
    std::string methodName; //!< method whose params want conversion
    int paramIdx;           //!< 0-based idx of param to convert
};

static const CRPCConvertParam vRPCConvertParams[] =
{
    { "stop", 0 },
    { "setmocktime", 0 },
    { "getaddednodeinfo", 0 },
    { "generate", 0 },
    { "generate", 1 },
    { "generatetoaddress", 0 },
    { "generatetoaddress", 2 },
    { "setgenerate", 0 },
    { "setgenerate", 1 },
    { "getnetworkhashps", 0 },
    { "getnetworkhashps", 1 },
    { "sendtoaddress", 1 },
    { "sendtoaddress", 4 },
    { "settxfee", 0 },
    { "getreceivedbyaddress", 1 },
    { "getreceivedbyaccount", 1 },
    { "listreceivedbyaddress", 0 },
    { "listreceivedbyaddress", 1 },
    { "listreceivedbyaddress", 2 },
    { "listreceivedbyaccount", 0 },
    { "listreceivedbyaccount", 1 },
    { "listreceivedbyaccount", 2 },
    { "getbalance", 1 },
    { "getbalance", 2 },
    { "getblockhash", 0 },
    { "move", 2 },
    { "move", 3 },
    { "sendfrom", 2 },
    { "sendfrom", 3 },
    { "listtransactions", 1 },
    { "listtransactions", 2 },
    { "listtransactions", 3 },
    { "listaccounts", 0 },
    { "listaccounts", 1 },
    { "walletpassphrase", 1 },
    { "getblocktemplate", 0 },
    { "listsinceblock", 1 },
    { "listsinceblock", 2 },
    { "sendmany", 1 },
    { "sendmany", 2 },
    { "sendmany", 4 },
    { "addmultisigaddress", 0 },
    { "addmultisigaddress", 1 },
    { "createmultisig", 0 },
    { "createmultisig", 1 },
    { "listunspent", 0 },
    { "listunspent", 1 },
    { "listunspent", 2 },
    { "getblock", 1 },
    { "getblockheader", 1 },
    { "gettransaction", 1 },
    { "getrawtransaction", 1 },
    { "createrawtransaction", 0 },
    { "createrawtransaction", 1 },
    { "createrawtransaction", 2 },
    { "signrawtransaction", 1 },
    { "signrawtransaction", 2 },
    { "sendrawtransaction", 1 },
    { "fundrawtransaction", 1 },
    { "gettxout", 1 },
    { "gettxout", 2 },
    { "gettxoutproof", 0 },
    { "lockunspent", 0 },
    { "lockunspent", 1 },
    { "importprivkey", 2 },
    { "importaddress", 2 },
    { "importaddress", 3 },
    { "importpubkey", 2 },
    { "verifychain", 0 },
    { "verifychain", 1 },
    { "keypoolrefill", 0 },
    { "getrawmempool", 0 },
    { "estimatefee", 0 },
    { "estimatepriority", 0 },
    { "estimatesmartfee", 0 },
    { "estimatesmartpriority", 0 },
    { "prioritisetransaction", 1 },
    { "prioritisetransaction", 2 },
    { "setban", 2 },
    { "setban", 3 },
    { "getmempoolancestors", 1 },
    { "getmempooldescendants", 1 },

    /* ZURBank - data retrieval calls */
    { "zus_gettradehistoryforaddress", 1 },
    { "zus_gettradehistoryforaddress", 2 },
    { "zus_gettradehistoryforpair", 0 },
    { "zus_gettradehistoryforpair", 1 },
    { "zus_gettradehistoryforpair", 2 },
    { "zus_setautocommit", 0 },
    { "zus_getcrowdsale", 0 },
    { "zus_getcrowdsale", 1 },
    { "zus_getgrants", 0 },
    { "zus_getbalance", 1 },
    { "zus_getproperty", 0 },
    { "zus_listtransactions", 1 },
    { "zus_listtransactions", 2 },
    { "zus_listtransactions", 3 },
    { "zus_listtransactions", 4 },
    { "zus_getallbalancesforid", 0 },
    { "zus_listblocktransactions", 0 },
    { "zus_listblockstransactions", 0 },
    { "zus_listblockstransactions", 1 },
    { "zus_getorderbook", 0 },
    { "zus_getorderbook", 1 },
    { "zus_getseedblocks", 0 },
    { "zus_getseedblocks", 1 },
    { "zus_getmetadexhash", 0 },
    { "zus_getfeecache", 0 },
    { "zus_getfeeshare", 1 },
    { "zus_getfeetrigger", 0 },
    { "zus_getfeedistribution", 0 },
    { "zus_getfeedistributions", 0 },
    { "zus_getbalanceshash", 0 },
    { "zus_getwalletbalances", 0 },
    { "zus_getwalletaddressbalances", 0 },

    /* ZURBank - transaction calls */
    { "zus_send", 2 },
    { "zus_sendsto", 1 },
    { "zus_sendsto", 4 },
    { "zus_sendall", 2 },
    { "zus_sendtrade", 1 },
    { "zus_sendtrade", 3 },
    { "zus_sendcanceltradesbyprice", 1 },
    { "zus_sendcanceltradesbyprice", 3 },
    { "zus_sendcanceltradesbypair", 1 },
    { "zus_sendcanceltradesbypair", 2 },
    { "zus_sendcancelalltrades", 1 },
    { "zus_sendissuancefixed", 1 },
    { "zus_sendissuancefixed", 2 },
    { "zus_sendissuancefixed", 3 },
    { "zus_sendissuancemanaged", 1 },
    { "zus_sendissuancemanaged", 2 },
    { "zus_sendissuancemanaged", 3 },
    { "zus_sendissuancecrowdsale", 1 },
    { "zus_sendissuancecrowdsale", 2 },
    { "zus_sendissuancecrowdsale", 3 },
    { "zus_sendissuancecrowdsale", 9 },
    { "zus_sendissuancecrowdsale", 11 },
    { "zus_sendissuancecrowdsale", 12 },
    { "zus_sendissuancecrowdsale", 13 },
    { "zus_senddexsell", 1 },
    { "zus_senddexsell", 4 },
    { "zus_senddexsell", 6 },
    { "zus_senddexaccept", 2 },
    { "zus_senddexaccept", 4 },
    { "zus_sendclosecrowdsale", 1 },
    { "zus_sendgrant", 2 },
    { "zus_sendrevoke", 1 },
    { "zus_sendchangeissuer", 2 },
    { "zus_sendenablefreezing", 1 },
    { "zus_senddisablefreezing", 1 },
    { "zus_sendfreeze", 2 },
    { "zus_sendunfreeze", 2 },
    { "zus_senddeactivation", 1 },
    { "zus_sendactivation", 1 },
    { "zus_sendactivation", 2 },
    { "zus_sendactivation", 3 },
    { "zus_sendalert", 1 },
    { "zus_sendalert", 2 },
    { "zus_funded_send", 2 },
    { "zus_funded_sendall", 2 },

    /* ZURBank - raw transaction calls */
    { "zus_decodetransaction", 1 },
    { "zus_decodetransaction", 2 },
    { "zus_createrawtx_reference", 2 },
    { "zus_createrawtx_input", 2 },
    { "zus_createrawtx_change", 1 },
    { "zus_createrawtx_change", 3 },
    { "zus_createrawtx_change", 4 },

    /* ZURBank - payload creation */
    { "zus_createpayload_simplesend", 0 },
    { "zus_createpayload_sendall", 0 },
    { "zus_createpayload_dexsell", 0 },
    { "zus_createpayload_dexsell", 3 },
    { "zus_createpayload_dexsell", 5 },
    { "zus_createpayload_dexaccept", 0 },
    { "zus_createpayload_sto", 0 },
    { "zus_createpayload_sto", 2 },
    { "zus_createpayload_issuancefixed", 0 },
    { "zus_createpayload_issuancefixed", 1 },
    { "zus_createpayload_issuancefixed", 2 },
    { "zus_createpayload_issuancemanaged", 0 },
    { "zus_createpayload_issuancemanaged", 1 },
    { "zus_createpayload_issuancemanaged", 2 },
    { "zus_createpayload_issuancecrowdsale", 0 },
    { "zus_createpayload_issuancecrowdsale", 1 },
    { "zus_createpayload_issuancecrowdsale", 2 },
    { "zus_createpayload_issuancecrowdsale", 8 },
    { "zus_createpayload_issuancecrowdsale", 10 },
    { "zus_createpayload_issuancecrowdsale", 11 },
    { "zus_createpayload_issuancecrowdsale", 12 },
    { "zus_createpayload_closecrowdsale", 0 },
    { "zus_createpayload_grant", 0 },
    { "zus_createpayload_revoke", 0 },
    { "zus_createpayload_changeissuer", 0 },
    { "zus_createpayload_trade", 0 },
    { "zus_createpayload_trade", 2 },
    { "zus_createpayload_canceltradesbyprice", 0 },
    { "zus_createpayload_canceltradesbyprice", 2 },
    { "zus_createpayload_canceltradesbypair", 0 },
    { "zus_createpayload_canceltradesbypair", 1 },
    { "zus_createpayload_cancelalltrades", 0 },
    { "zus_createpayload_enablefreezing", 0 },
    { "zus_createpayload_disablefreezing", 0 },
    { "zus_createpayload_freeze", 1 },
    { "zus_createpayload_unfreeze", 1 },

    /* ZURBank - backwards compatibility */
    { "getcrowdsale_MP", 0 },
    { "getcrowdsale_MP", 1 },
    { "getgrants_MP", 0 },
    { "send_MP", 2 },
    { "getbalance_MP", 1 },
    { "sendtoowners_MP", 1 },
    { "getproperty_MP", 0 },
    { "listtransactions_MP", 1 },
    { "listtransactions_MP", 2 },
    { "listtransactions_MP", 3 },
    { "listtransactions_MP", 4 },
    { "getallbalancesforid_MP", 0 },
    { "listblocktransactions_MP", 0 },
    { "getorderbook_MP", 0 },
    { "getorderbook_MP", 1 },
    { "trade_MP", 1 }, // depreciated
    { "trade_MP", 3 }, // depreciated
    { "trade_MP", 5 }, // depreciated
};

class CRPCConvertTable
{
private:
    std::set<std::pair<std::string, int> > members;

public:
    CRPCConvertTable();

    bool convert(const std::string& method, int idx) {
        return (members.count(std::make_pair(method, idx)) > 0);
    }
};

CRPCConvertTable::CRPCConvertTable()
{
    const unsigned int n_elem =
        (sizeof(vRPCConvertParams) / sizeof(vRPCConvertParams[0]));

    for (unsigned int i = 0; i < n_elem; i++) {
        members.insert(std::make_pair(vRPCConvertParams[i].methodName,
                                      vRPCConvertParams[i].paramIdx));
    }
}

static CRPCConvertTable rpcCvtTable;

/** Non-RFC4627 JSON parser, accepts internal values (such as numbers, true, false, null)
 * as well as objects and arrays.
 */
UniValue ParseNonRFCJSONValue(const std::string& strVal)
{
    UniValue jVal;
    if (!jVal.read(std::string("[")+strVal+std::string("]")) ||
        !jVal.isArray() || jVal.size()!=1)
        throw runtime_error(string("Error parsing JSON:")+strVal);
    return jVal[0];
}

/** Convert strings to command-specific RPC representation */
UniValue RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
    UniValue params(UniValue::VARR);

    for (unsigned int idx = 0; idx < strParams.size(); idx++) {
        const std::string& strVal = strParams[idx];

        if (!rpcCvtTable.convert(strMethod, idx)) {
            // insert string value directly
            params.push_back(strVal);
        } else {
            // parse string as JSON, insert bool/number/object/etc. value
            params.push_back(ParseNonRFCJSONValue(strVal));
        }
    }

    return params;
}


text:
/*
    Copyright 2013 Adobe
    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 ADOBE_CSTDINT_HPP
#define ADOBE_CSTDINT_HPP

#include <adobe/config.hpp>

#include <boost/cstdint.hpp>
#include <boost/static_assert.hpp>

#if BOOST_MSVC
#include <cstddef>
#endif

/**************************************************************************************************/

namespace adobe {

/*!
\defgroup tr1 TR1 Components
\ingroup utility
@{
*/

/**************************************************************************************************/

#if defined(BOOST_HAS_STDINT_H) || defined(BOOST_MSVC)

using ::intptr_t;
using ::uintptr_t;

#else

typedef long intptr_t;
typedef unsigned long uintptr_t;

#endif

BOOST_STATIC_ASSERT(!(sizeof(intptr_t) < sizeof(void*)));
BOOST_STATIC_ASSERT(!(sizeof(uintptr_t) < sizeof(void*)));

//! @}
/**************************************************************************************************/
} // namespace adobe

/**************************************************************************************************/

#endif

ext: hpp


text:
/**************************************************************
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 *************************************************************/

#ifndef SD_SLIDESORTER_VIEW_INSERT_ANIMATOR_HXX
#define SD_SLIDESORTER_VIEW_INSERT_ANIMATOR_HXX

#include "controller/SlsAnimator.hxx"
#include <boost/scoped_ptr.hpp>
#include <boost/noncopyable.hpp>

namespace sd { namespace slidesorter { namespace view {

class InsertPosition;

/** Animate the positions of page objects to make room at the insert
    position while a move or copy operation takes place.
*/
class InsertAnimator
    : private ::boost::noncopyable
{
public:
    InsertAnimator (SlideSorter& rSlideSorter);

    /** Set the position at which we have to make room for the display of an
        icon.
    */
    void SetInsertPosition (const InsertPosition& rInsertPosition);

    enum ResetMode { RM_Normal, RM_AbortAnimations };
    /** Restore the normal position of all page objects.
        @param eMode
            This flag controls whether to start an animation that ends in the
            normal positions of all slides (AM_Animated) or to restore the
            normal positions immediately (AM_Immediate).
    */
    void Reset (const controller::Animator::AnimationMode eMode);

private:
    class Implementation;
    ::boost::shared_ptr<Implementation> mpImplementation;
};

} } } // end of namespace ::sd::slidesorter::view

#endif

ext: hxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text:
// Boost.Geometry

// Copyright (c) 2021, Oracle and/or its affiliates.

// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle

// Licensed under the Boost Software License version 1.0.
// http://www.boost.org/users/license.html

#ifndef BOOST_GEOMETRY_STRATEGIES_CENTROID_SPHERICAL_HPP
#define BOOST_GEOMETRY_STRATEGIES_CENTROID_SPHERICAL_HPP

#include <boost/geometry/strategies/detail.hpp>
#include <boost/geometry/strategies/centroid.hpp>
#include <boost/geometry/strategies/centroid/services.hpp>

namespace boost { namespace geometry
{

namespace strategies { namespace centroid
{

template
<
    typename CalculationType = void
>
class spherical
    : public strategies::detail::spherical_base<void>
{
    using base_t = strategies::detail::spherical_base<void>;

public:
    spherical() = default;

    // TODO: Box and Segment should have proper strategies.
    template <typename Geometry, typename Point>
    static auto centroid(Geometry const&, Point const&,
                         std::enable_if_t
                            <
                                util::is_segment<Geometry>::value
                             || util::is_box<Geometry>::value
                            > * = nullptr)
    {
        return strategy::centroid::not_applicable_strategy();
    }
};

namespace services
{

template <typename Geometry>
struct default_strategy<Geometry, spherical_equatorial_tag>
{
    using type = strategies::centroid::spherical<>;
};

} // namespace services

}} // namespace strategies::centroid

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_STRATEGIES_CENTROID_SPHERICAL_HPP


text:
//  Copyright (c) 2007-2012 Hartmut Kaiser
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <hpx/hpx.hpp>
#include <hpx/exception.hpp>
#include <hpx/include/performance_counters.hpp>
#include <hpx/components/binpacking_factory/server/binpacking_factory.hpp>

#include <hpx/util/portable_binary_iarchive.hpp>
#include <hpx/util/portable_binary_oarchive.hpp>

#include <boost/serialization/vector.hpp>
#include <boost/foreach.hpp>
#include <boost/move/move.hpp>

#include <vector>

///////////////////////////////////////////////////////////////////////////////
namespace hpx { namespace components { namespace server
{
    ///////////////////////////////////////////////////////////////////////////
    struct lazy_result
    {
        lazy_result(naming::gid_type const& locality_id)
          : locality_(locality_id)
        {}

        naming::gid_type locality_;
        lcos::future<std::vector<naming::gid_type> > gids_;
    };

    ///////////////////////////////////////////////////////////////////////////
    binpacking_factory::remote_result_type
    binpacking_factory::create_components(components::component_type type,
        std::size_t count) const
    {
        // make sure we get localities for derived component type, if any
        components::component_type prefix_type = type;
        if (type != components::get_base_type(type))
            prefix_type = components::get_derived_type(type);

        // get list of locality prefixes
        std::vector<naming::id_type> localities =
            hpx::find_all_localities(prefix_type);

        if (localities.empty())
        {
            HPX_THROW_EXCEPTION(bad_component_type,
                "binpacking_factory::create_components_binpacked",
                "attempt to create component instance of unknown type: " +
                components::get_component_type_name(type));
        }

        if (count == std::size_t(-1))
            count = localities.size();

        // retrieve the current number of instances of the given component
        std::vector<lcos::future<long> > lazy_counts;
        BOOST_FOREACH(naming::id_type const& id, localities)
        {
            lazy_counts.push_back(
                stubs::runtime_support::get_instance_count_async(id, type));
        }

        // wait for counts to get back, collect statistics
        long maxcount = 0;
        long existing = 0;

        std::vector<long> counts;
        counts.reserve(lazy_counts.size());
        BOOST_FOREACH(lcos::future<long> const& f, lazy_counts)
        {
            counts.push_back(f.get());
            maxcount = (std::max)(maxcount, counts.back());
            existing += counts.back();
        }

        // distribute the number of components to create in a way, so that the
        // overall number of component instances on all localities is
        // approximately the same
        BOOST_ASSERT(maxcount * counts.size() >= std::size_t(existing));
        std::size_t missing = maxcount * counts.size() - existing;
        if (missing == 0) missing = 1;

        double hole_ratio = (std::min)(count, missing) / double(missing);
        BOOST_ASSERT(hole_ratio <= 1.);

        std::size_t overflow_count =
            (count > missing) ? (count - missing) / counts.size() : 0;
        std::size_t excess = count - overflow_count * counts.size();

        typedef std::vector<lazy_result> future_values_type;
        typedef server::runtime_support::bulk_create_components_action
            action_type;

        std::size_t created_count = 0;
        future_values_type v;

        // start an asynchronous operation for each of the localities
        for (std::size_t i = 0; i < counts.size(); ++i)
        {
            std::size_t numcreate =
                std::size_t((maxcount - counts[i]) * hole_ratio) + overflow_count;

            if (excess != 0) {
                --excess;
                ++numcreate;
            }

            if (i == counts.size()-1) {
                // last bin gets all the rest
                if (created_count + numcreate < count)
                    numcreate = count - created_count;
            }

            if (created_count + numcreate > count)
                numcreate = count - created_count;

            if (numcreate == 0)
                break;

            // create one component at a time
            v.push_back(future_values_type::value_type(localities[i].get_gid()));
            lcos::packaged_action<action_type, std::vector<naming::gid_type> > p;
            p.apply(launch::async, localities[i], type, numcreate);
            v.back().gids_ = p.get_future();

            created_count += numcreate;
            if (created_count >= count)
                break;
        }

        // now wait for the results
        remote_result_type results;

        BOOST_FOREACH(lazy_result& lr, v)
        {
            results.push_back(remote_result_type::value_type(lr.locality_, type));
            results.back().gids_ = boost::move(lr.gids_.move());
        }

        return results;
    }

    ///////////////////////////////////////////////////////////////////////////
    binpacking_factory::remote_result_type
    binpacking_factory::create_components_counterbased(
        components::component_type type, std::size_t count,
        std::string const& countername) const
    {
        // make sure we get localities for derived component type, if any
        components::component_type prefix_type = type;
        if (type != components::get_base_type(type))
            prefix_type = components::get_derived_type(type);

        // get list of locality prefixes
        std::vector<naming::id_type> localities =
            hpx::find_all_localities(prefix_type);

        if (localities.empty())
        {
            HPX_THROW_EXCEPTION(bad_component_type,
                "binpacking_factory::create_components_binpacked",
                "attempt to create component instance of unknown type: " +
                components::get_component_type_name(type));
        }

        if (count == std::size_t(-1))
            count = localities.size();

        // create performance counters on all localities
        performance_counters::counter_path_elements p;
        performance_counters::get_counter_type_path_elements(countername, p);

        // FIXME: make loop asynchronous
        typedef lcos::future<naming::id_type> future_type;

        std::vector<future_type> lazy_counts;
        BOOST_FOREACH(naming::id_type const& id, localities)
        {
            std::string name;
            p.parentinstanceindex_ = naming::get_locality_id_from_id(id);
            performance_counters::get_counter_name(p, name);
            lazy_counts.push_back(performance_counters::get_counter_async(name));
        }

        // wait for counts to get back, collect statistics
        long maxcount = 0;
        long existing = 0;

        // FIXME: make loop asynchronous
        std::vector<long> counts;
        counts.reserve(lazy_counts.size());
        BOOST_FOREACH(future_type const& f, lazy_counts)
        {
            performance_counters::counter_value value =
                performance_counters::stubs::performance_counter::get_value(f.get());
            counts.push_back(value.get_value<long>());
            maxcount = (std::max)(maxcount, counts.back());
            existing += counts.back();
        }

        // distribute the number of components to create in a way, so that the
        // overall number of component instances on all localities is
        // approximately the same
        BOOST_ASSERT(maxcount * counts.size() >= std::size_t(existing));
        std::size_t missing = maxcount * counts.size() - existing;
        if (missing == 0) missing = 1;

        double hole_ratio = (std::min)(count, missing) / double(missing);
        BOOST_ASSERT(hole_ratio <= 1.);

        std::size_t overflow_count =
            (count > missing) ? (count - missing) / counts.size() : 0;
        std::size_t excess = count - overflow_count * counts.size();

        typedef std::vector<lazy_result> future_values_type;
        typedef server::runtime_support::bulk_create_components_action
            action_type;

        std::size_t created_count = 0;
        future_values_type v;

        // start an asynchronous operation for each of the localities
        for (std::size_t i = 0; i < counts.size(); ++i)
        {
            std::size_t numcreate =
                std::size_t((maxcount - counts[i]) * hole_ratio) + overflow_count;

            if (excess != 0) {
                --excess;
                ++numcreate;
            }

            if (i == counts.size()-1) {
                // last bin gets all the rest
                if (created_count + numcreate < count)
                    numcreate = count - created_count;
            }

            if (created_count + numcreate > count)
                numcreate = count - created_count;

            if (numcreate == 0)
                break;

            // create all components  for each locality at a time
            v.push_back(future_values_type::value_type(localities[i].get_gid()));
            lcos::packaged_action<action_type, std::vector<naming::gid_type> > p;
            p.apply(launch::async, localities[i], type, numcreate);
            v.back().gids_ = p.get_future();

            created_count += numcreate;
            if (created_count >= count)
                break;
        }

        // now wait for the results
        remote_result_type results;

        BOOST_FOREACH(lazy_result& lr, v)
        {
            results.push_back(remote_result_type::value_type(lr.locality_, type));
            results.back().gids_ = boost::move(lr.gids_.move());
        }

        return results;
    }
}}}

ext: cpp

max_stars_repo_name: andreasbuhr/hpx

max_issues_repo_name: andreasbuhr/hpx

max_forks_repo_name: andreasbuhr/hpx


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

#include "pxr/usd/usd/stage.h"

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

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

using namespace boost::python;

PXR_NAMESPACE_USING_DIRECTIVE

void wrapMetrics()
{
    def("GetStageUpAxis", UsdGeomGetStageUpAxis, arg("stage"));
    def("SetStageUpAxis", UsdGeomSetStageUpAxis,
        (arg("stage"), arg("upAxis")));
    def("GetFallbackUpAxis", UsdGeomGetFallbackUpAxis);

    def("GetStageMetersPerUnit", UsdGeomGetStageMetersPerUnit, arg("stage"));
    def("StageHasAuthoredMetersPerUnit", UsdGeomStageHasAuthoredMetersPerUnit, arg("stage"));
    def("SetStageMetersPerUnit", UsdGeomSetStageMetersPerUnit,
        (arg("stage"), arg("metersPerUnit")));
    def("LinearUnitsAre", UsdGeomLinearUnitsAre,
        (arg("authoredUnits"), arg("standardUnits"), arg("epsilon")=1e-5));

    boost::python::class_<UsdGeomLinearUnits>
        cls("LinearUnits", boost::python::no_init);
    cls
        .def_readonly("nanometers", UsdGeomLinearUnits::nanometers)
        .def_readonly("micrometers", UsdGeomLinearUnits::micrometers)
        .def_readonly("millimeters", UsdGeomLinearUnits::millimeters)
        .def_readonly("centimeters", UsdGeomLinearUnits::centimeters)
        .def_readonly("meters", UsdGeomLinearUnits::meters)
        .def_readonly("kilometers", UsdGeomLinearUnits::kilometers)
        .def_readonly("lightYears", UsdGeomLinearUnits::lightYears)
        .def_readonly("inches", UsdGeomLinearUnits::inches)
        .def_readonly("feet", UsdGeomLinearUnits::feet)
        .def_readonly("yards", UsdGeomLinearUnits::yards)
        .def_readonly("miles", UsdGeomLinearUnits::miles);
}

max_stars_repo_name: DougRogers-DigitalFish/USD

max_issues_repo_name: DougRogers-DigitalFish/USD

max_forks_repo_name: DougRogers-DigitalFish/USD


text:
/*
 * _Portfolio.cpp
 *
 *  Created on: 2016年3月29日
 *      Author: fasiondog
 */

#include <boost/python.hpp>
#include <hikyuu/trade_sys/portfolio/build_in.h>
#include <hikyuu/trade_sys/selector/crt/SE_Fixed.h>
#include <hikyuu/trade_sys/allocatefunds/crt/AF_EqualWeight.h>
#include "../_Parameter.h"
#include "../pickle_support.h"

using namespace boost::python;
using namespace hku;
namespace py = boost::python;

void (Portfolio::*pf_set_name)(const string&) = &Portfolio::name;
const string& (Portfolio::*pf_get_name)() const = &Portfolio::name;

void export_Portfolio() {
    class_<Portfolio>("Portfolio", R"(实现多标的、多策略的投资组合)", init<>())
      .def(init<const string&>())
      .def(init<const TradeManagerPtr&, const SelectorPtr&, const AFPtr&>())

      .def(self_ns::str(self))
      .def(self_ns::repr(self))

      .add_property("name", make_function(pf_get_name, return_value_policy<copy_const_reference>()),
                    pf_set_name, "名称")
      .add_property(
        "query", make_function(&Portfolio::getQuery, return_value_policy<copy_const_reference>()),
        &Portfolio::setQuery, "查询条件")

      .add_property("tm", &Portfolio::getTM, &Portfolio::setTM, "设置或获取交易管理对象")
      .add_property("se", &Portfolio::getSE, &Portfolio::setSE, "设置或获取交易对象选择算法")
      .add_property("af", &Portfolio::getAF, &Portfolio::setAF, "设置或获取资产分配算法")
      .add_property(
        "proto_sys_list",
        make_function(&Portfolio::getProtoSystemList, return_value_policy<copy_const_reference>()),
        "获取原型系统列")
      .add_property(
        "real_sys_list",
        make_function(&Portfolio::getRealSystemList, return_value_policy<copy_const_reference>()),
        "由 PF 运行时设定的实际运行系统列表")

      .def("get_param", &Portfolio::getParam<boost::any>, R"(get_param(self, name)

    获取指定的参数

    :param str name: 参数名称
    :return: 参数值
    :raises out_of_range: 无此参数)")

      .def("set_param", &Portfolio::setParam<object>, R"(set_param(self, name, value)

    设置参数

    :param str name: 参数名称
    :param value: 参数值
    :raises logic_error: Unsupported type! 不支持的参数类型)")

      .def("have_param", &Portfolio::haveParam, "是否存在指定参数")

      .def("reset", &Portfolio::reset, "复位操作")
      .def("clone", &Portfolio::clone, "克隆操作")

      .def("run", &Portfolio::run, (arg("query"), arg("force") = false), R"(run(self, query)

    运行投资组合策略。在查询条件及各组件没有变化时，PF在第二次执行时，默认不会实际进行计算。
    但由于各个组件的参数可能改变，此种情况无法自动判断是否需要重计算，可以手工指定进行强制计算。

    :param Query query: 查询条件
    :param bool force: 强制重新计算)")

#if HKU_PYTHON_SUPPORT_PICKLE
      .def_pickle(name_init_pickle_suite<Portfolio>())
#endif
      ;

    register_ptr_to_python<PortfolioPtr>();

    def("PF_Simple", PF_Simple,
        (arg("tm") = TradeManagerPtr(), arg("se") = SE_Fixed(), arg("af") = AF_EqualWeight()),
        R"(PF_Simple([tm, se, af])

    创建一个多标的、单系统策略的投资组合

    :param TradeManager tm: 交易管理
    :param SelectorBase se: 交易对象选择算法
    :param AllocateFundsBase af: 资金分配算法)");
}

max_stars_repo_name: kknet/hikyuu

max_issues_repo_name: kknet/hikyuu

max_forks_repo_name: kknet/hikyuu


text:
#include "XradiaReader.h"

#include<iostream>
#include <cstdint>
#ifdef WIN32
#include "Winsock2.h"
#endif
//#include <boost/endian/conversion.hpp>
#include <boost/make_shared.hpp>
#include <boost/format.hpp>

#include "pole.h"
#include "CCPiConsoleUserInterface.h"

namespace CCPi{

	XradiaReader::XradiaReader(std::string filename, CCPiUserApplicationInterface *uai):localUAI(false)
	{
		this->filename = filename;
		type = UINT_16;
		if(uai==NULL)
		{
			this->uai = new CCPiConsoleUserInterface();
			localUAI = true;
		}else{
			this->uai = uai;
		}
		extractMetaDataAll();
	}

	XradiaReader::~XradiaReader()
	{
		if(localUAI)
			delete uai;
	}

	int XradiaReader::getImageWidth()
	{
		return imageWidth;
	}

	int XradiaReader::getImageHeight()
	{
		return imageHeight;
	}

	XradiaReader::DataType XradiaReader::getDataType()
	{
		return type;
	}

	std::vector<float> XradiaReader::getAngles()
	{
		return angles;
	}

	int XradiaReader::getNumberOfImages()
	{
		return numberOfImages;
	}

	std::vector<float> XradiaReader::getXShifts()
	{
		return xShifts;
	}
	std::vector<float> XradiaReader::getYShifts()
	{
		return yShifts;
	}

	boost::shared_ptr< short_pixel > XradiaReader::getImageDataInShort()
	{
		return shortImageData;
	}
	boost::shared_ptr< float_pixel > XradiaReader::getImageDataInFloat()
	{
		return floatImageData;
	}

	void XradiaReader::extractMetaDataAll()
	{
		imageWidth = extractMetaDataInt("ImageInfo/ImageWidth");
		imageHeight = extractMetaDataInt("ImageInfo/ImageHeight");
		int dtype = extractMetaDataInt("ImageInfo/DataType");
		if(dtype==10)
			type = FLOAT;
		else if(dtype==5)
			type = UINT_16;
		else
			uai->LogMessage("Error data type not read properly");
		numberOfImages = extractMetaDataInt("ImageInfo/ImagesTaken");
		xShifts = extractMetaDataFloatArray("Alignment/X-Shifts", numberOfImages);
		yShifts = extractMetaDataFloatArray("Alignment/Y-Shifts", numberOfImages);
		xSamplePosition = extractMetaDataFloatArray("ImageInfo/XPosition", numberOfImages);
		ySamplePosition = extractMetaDataFloatArray("ImageInfo/YPosition", numberOfImages);
		zSamplePosition = extractMetaDataFloatArray("ImageInfo/ZPosition", numberOfImages);
		srcToObject = extractMetaDataFloatArray("ImageInfo/StoRADistance", numberOfImages)[0]; //Just use the first value
		detToObject = extractMetaDataFloatArray("ImageInfo/DtoRADistance", numberOfImages)[0]; //Just use the first value
		angles = extractMetaDataFloatArray("ImageInfo/Angles", numberOfImages);
		if(type==UINT_16){
			shortImageData = boost::make_shared< short_pixel >(boost::extents[numberOfImages][imageWidth][imageHeight]);
		}else if(type==FLOAT){
			floatImageData = boost::make_shared< float_pixel >(boost::extents[numberOfImages][imageWidth][imageHeight]);
		}
		extractImageData();
	}

	int XradiaReader::extractMetaDataInt(std::string streamName)
	{
		POLE::Storage* storage = new POLE::Storage( filename.c_str() );
		storage->open(); // Open the storage
		if(storage->result() != POLE::Storage::Ok)
		{
			uai->LogMessage("Error: opening the file: "+filename);
			return -1;
		}
		POLE::Stream* stream = new POLE::Stream(storage, streamName);
		POLE::uint64 datasize = stream->size();
		void *data = new char[datasize];
		stream->read( (unsigned char*)data, datasize);
		int* iData = (int*)data;
		int retval = iData[0];//boost::endian::little_to_native(iData[0]);
		delete[] data;
		delete stream;
		delete storage;
		return retval;
	}

	std::vector<float> XradiaReader::extractMetaDataFloatArray(std::string streamName,int numberOfValues)
	{
		std::vector<float> retval;
		POLE::Storage* storage = new POLE::Storage( filename.c_str() );
		storage->open(); // Open the storage
		if(storage->result() != POLE::Storage::Ok)
		{
			uai->LogMessage("Error: opening the file: " + filename);
			return retval;
		}
		POLE::Stream* stream = new POLE::Stream(storage, streamName);
		POLE::uint64 datasize = stream->size();
		void *data = new char[datasize];
		stream->read( (unsigned char*)data, datasize);
		float* iData = (float*)data;
		for(int i=0;i<numberOfValues;i++)
		{
			float val = iData[i];//boost::endian::little_to_native(iData[i]);
			retval.push_back(val);
		}
		delete[] data;
		delete stream;
		delete storage;
		return retval;
	}

	void XradiaReader::extractImageData()
	{
		POLE::Storage* storage = new POLE::Storage( filename.c_str() );
		storage->open(); // Open the storage
		if(storage->result() != POLE::Storage::Ok)
		{
			uai->LogMessage("Error: opening the file: "+filename);
			return;
		}
		uai->SetProgressValue(0.0);
		if(type==FLOAT)
		{
			float val;
			for(int imageId=1;imageId<=numberOfImages;imageId++)
			{
				int pageId = (int)ceil(imageId/100.0);
				std::stringstream streamName;
				streamName<<"ImageData"<<pageId+1<<"/Image"<<imageId;
				uai->SetStatusMessage("Reading Image:"+streamName.str());
				uai->SetProgressValue(imageId/(numberOfImages*1.0f));
				POLE::Stream* stream = new POLE::Stream(storage, streamName.str().c_str());
				POLE::uint64 datasize = stream->size();
				void *data = new char[datasize];
				stream->read( (unsigned char*)data, datasize);
				float* iData = (float*)data;
				for(int i=0;i<imageWidth;i++)
				{
					for(int j=0;j<imageHeight;j++)
					{
						val = iData[i*imageHeight+j];//boost::endian::little_to_native(iData[i*imageHeight+j]);
						(*floatImageData)[imageId][i][j]=val;
					}
				}
				delete[] data;
				delete stream;
			}
		}else if(type=UINT_16){
			short val;
			void *data = new char[imageHeight*imageWidth*4];
			for(int imageId=0;imageId<numberOfImages;imageId++)
			{
				int pageId = (int)ceil((imageId+1)/100.0);
				std::stringstream streamName;
				streamName<<"ImageData"<<pageId<<"/Image"<<boost::format("%i")%(imageId+1);
				uai->SetStatusMessage("Reading Image:"+streamName.str());
				uai->SetProgressValue(imageId/(numberOfImages*1.0f));
				POLE::Stream* stream = new POLE::Stream(storage, streamName.str().c_str());
				POLE::uint64 datasize = stream->size();
				stream->read( (unsigned char*)data, datasize);
				short* iData = (short*)data;
				for(int i=0;i<imageWidth;i++)
				{
					for(int j=0;j<imageHeight;j++)
					{
						val = iData[i*imageHeight+j];//boost::endian::little_to_native(iData[i*imageHeight+j]);
						(*shortImageData)[imageId][i][j]=val;
					}
				}
				delete stream;
			}
			delete[] data;
		}
		delete storage;
		uai->SetProgressValue(1.0);
	}

}

max_stars_repo_name: vais-ral/CCPi-Reconstruction

max_issues_repo_name: vais-ral/CCPi-Reconstruction

max_forks_repo_name: vais-ral/CCPi-Reconstruction


text:
// MIT License
//
// Copyright (c) 2021 Oliver Schick
//
// 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 <mpo19/utility.hpp>

#include <vector>
#include <list>
#include <map>
#include <random>
#include <functional>
#include <string>
#include <numeric>
#include <algorithm>

#define BOOST_TEST_MODULE circuits_test
#include <boost/test/included/unit_test.hpp>
#include <boost/test/data/test_case.hpp>
#include <boost/test/data/monomorphic.hpp>

namespace bdata = boost::unit_test::data;
constexpr int m = 10000;

BOOST_DATA_TEST_CASE(utility_log_test
                     , bdata::random(1, m) ^ bdata::xrange(10000)
                     , s1, idx)
{
    (void) idx;
    static_assert(ceil_log2(0) == 0, "");
    static_assert(ceil_log2(1) == 0, "");
    static_assert(floor_log2(0) == 0, "");
    static_assert(floor_log2(1) == 0, "");
    uint64_t clog = ceil_log2(s1), flog = floor_log2(s1);
    BOOST_TEST( (1u << flog) <= uint64_t(s1) );
    BOOST_TEST( (1u << clog) >= uint64_t(s1) );
    if(clog == flog) BOOST_TEST( (1u << flog) == uint64_t(s1) );
    else BOOST_TEST( (1u << clog) > uint64_t(s1) );

}

BOOST_DATA_TEST_CASE(nothrow_swap_test
                     , bdata::random(0, m) ^ bdata::random(0, m)
                     ^ bdata::xrange(10000)
                     , s1, s2, idx)
{
    (void) idx;
    auto s1_copy = s1;
    auto s2_copy = s2;

    static_assert(noexcept(nothrow_swap), "nothrow_swap throws an exception");
    nothrow_swap(s1_copy, s2_copy);
    BOOST_TEST(s1_copy == s2);
    BOOST_TEST(s2_copy == s1);

}

BOOST_DATA_TEST_CASE(utility_words_to_hold_bitlen_test
                     , bdata::random(1, m) ^ bdata::xrange(10000)
                     , s1, idx)
{
    (void) idx;

    BOOST_TEST(bytes_to_hold_bitlen(s1) == words_to_hold_bitlen(s1, CHAR_BIT));
    BOOST_TEST(bytes_to_hold_bitlen(s1 * CHAR_BIT) == s1);
    BOOST_TEST(words_to_hold_bitlen(s1 * 16, 16) == s1);
    BOOST_TEST(words_to_hold_bitlen(s1 * 32, 16) == 2*s1);
    BOOST_TEST(words_to_hold_bitlen(s1 * 16, 32) == s1/2 + s1%2);

}

BOOST_DATA_TEST_CASE(utility_code_len_test
                     , bdata::random(1, std::numeric_limits<int>::max()) ^ bdata::xrange(10000)
                     , len, idx)
{
    (void) idx;
    char buf[encode_len_buffer_size];
    size_t num_chars = encode_len(buf, len);
    size_t dec_len = decode_len([&, i = 0u](unsigned char* c, size_t len) mutable{
        assert(i + len <= encode_len_buffer_size);
        std::copy(buf + i, buf + i + len, c);
        i += len;
    });

    BOOST_TEST(dec_len == len);
    BOOST_TEST(num_chars == words_to_hold_bitlen(ceil_log2(len), CHAR_BIT - 1));
}

BOOST_DATA_TEST_CASE(utility_test
                     , bdata::random(0, m) ^ bdata::xrange(10)
                     , s1, idx)
{
    (void) idx;

    static_assert(is_range<std::vector<int>>(), "");
    static_assert(is_range<std::list<int>>(), "");
    static_assert(is_range<std::map<int, double>>(), "");
    static_assert(!is_range<int>(), "");
    static_assert(!is_range<std::map<int, double>::iterator>(), "");

    static_assert(is_serializable<int>(), "");
    static_assert(!is_serializable<std::vector<int>>(), "");

    static_assert(is_deserializable<int>(), "");
    static_assert(!is_deserializable<std::vector<int>>(), "");

    auto f = [](int, double) {};
    auto any_arg = [](auto) {};
    auto any = [](auto...) {};

    static_assert(is_invocable<decltype(f)(int, double)>::value, "");
    static_assert(!is_invocable<decltype(f)(int, double, float)>::value, "");
    static_assert(is_invocable<decltype(any_arg)(int)>::value, "");
    static_assert(is_invocable<decltype(any_arg)(double)>::value, "");
    static_assert(!is_invocable<decltype(any_arg)()>::value, "");
    static_assert(is_invocable<decltype(any)(int, double, char, float)>::value, "");
    static_assert(is_invocable<decltype(any)(double, double, std::vector<int>)>::value, "");
    static_assert(is_invocable<decltype(any)()>::value, "");

    std::vector<int> v(100 + idx), v_copy;
    std::vector<std::vector<int>> vv(10 + idx), vv_copy;

    std::mt19937 gen(s1 + idx);
    std::uniform_int_distribution<int> d{0, m};

    std::generate(v.begin(), v.end(), [&] {return d(gen);});

    for(auto& vec : vv) {
        vec.resize(10 + idx);
        std::generate(vec.begin(), vec.end(), [&] {return d(gen);});
    }

    v_copy = v;
    vv_copy = vv;

    multi_for_each(v, [&](auto& el) {
        el += s1;
    });

    std::transform(v_copy.begin(), v_copy.end(), v_copy.begin(), [&](auto const& el) {
        return el + s1;
    });

    BOOST_TEST(std::equal(v.begin(), v.end(), v_copy.begin()));

    multi_for_each(vv, vv_copy, [](auto& a, auto& b) {
        a += 2*b;
    });

    for(size_t i = 0; i != vv.size(); ++i) {
        for(size_t j = 0; j != vv[i].size(); ++j) {
            BOOST_TEST(vv[i][j]/3 == vv_copy[i][j]);
        }
    }

    BOOST_TEST(tree_accumulate(v, std::plus<> {}) == std::accumulate(v.begin(), v.end(), 0, std::plus<> {}));
    auto res1 = tree_accumulate(v, std::plus<> {}, [](auto&& a, size_t idx) {
        return 2*a + idx;
    });

    int sum = 0;
    for(size_t i = 0; i != v.size(); ++i) {
        sum += 2*v[i] + i;
    }

    BOOST_TEST(res1 == sum);
}


text:
#include <eosio/chain/apply_context.hpp>
#include <eosio/chain/controller.hpp>
#include <eosio/chain/transaction_context.hpp>
#include <eosio/chain/producer_schedule.hpp>
#include <eosio/chain/exceptions.hpp>
#include <boost/core/ignore_unused.hpp>
#include <eosio/chain/authorization_manager.hpp>
#include <eosio/chain/resource_limits.hpp>
/*
#include <eosio/chain/wasm_interface_private.hpp>
#include <eosio/chain/wasm_eosio_validation.hpp>
#include <eosio/chain/wasm_eosio_injection.hpp>
*/
#include <eosio/chain/global_property_object.hpp>
#include <eosio/chain/account_object.hpp>
#include <eosio/chain/symbol.hpp>

#include <fc/exception/exception.hpp>
#include <fc/crypto/sha256.hpp>
#include <fc/crypto/sha1.hpp>
#include <fc/io/raw.hpp>

#include <softfloat.hpp>
#include <compiler_builtins.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>

using namespace eosio::chain;
#include <fstream>
#include <dlfcn.h>
#include "xxhash.h"
//vm_api.cpp
extern "C" void vm_api_init();

class init_vm_api {
public:
   init_vm_api() {
      vm_api_init();
   }
};

static init_vm_api _init_vm_api;
static apply_context *s_ctx = nullptr;

//eosio.token.cpp
void token_create( uint64_t issuer, const char* maximum_supply, size_t size);
void token_issue( uint64_t to, const char* quantity, size_t size1, const char* memo, size_t size2 );
void token_transfer( uint64_t from, uint64_t to, const char* quantity, size_t size1, const char* memo, size_t size2);

namespace eosio {
namespace chain {

void set_apply_context(apply_context *ctx) {
   s_ctx = ctx;
}

apply_context *get_apply_context() {
   return s_ctx;
}

static inline apply_context& ctx() {
   return *s_ctx;
}

#include <eosiolib_native/vm_api.h>

#include "action.cpp"
#include "chain.cpp"
#include "system.cpp"
#include "crypto.cpp"
#include "db.cpp"
#include "privileged.cpp"
#include "transaction.cpp"
#include "print.cpp"
#include "permission.cpp"

static struct vm_api _vm_api = {
};

extern "C" void vm_api_init() {
   static bool s_init = false;
   if (!s_init){
      s_init = true;
      // _vm_api.vm_apply = vm_apply;
      _vm_api.read_action_data = read_action_data;
      _vm_api.action_data_size = action_data_size;
      _vm_api.get_action_info = get_action_info;

      _vm_api.require_recipient = require_recipient;
      _vm_api.require_auth = require_auth;
      _vm_api.require_auth2 = require_auth2;
      _vm_api.has_auth = has_auth;
      _vm_api.is_account = is_account;

      _vm_api.send_inline = send_inline;
      _vm_api.send_context_free_inline = send_context_free_inline;
      _vm_api.publication_time = publication_time;
      _vm_api.current_receiver = current_receiver;
      _vm_api.get_active_producers = get_active_producers;

      _vm_api.assert_sha256 = assert_sha256;
      _vm_api.assert_sha1 = assert_sha1;
      _vm_api.assert_sha512 = assert_sha512;
      _vm_api.assert_ripemd160 = assert_ripemd160;
      _vm_api.assert_recover_key = assert_recover_key;
      _vm_api.sha256 = sha256;
      _vm_api.sha1 = sha1;
      _vm_api.sha512 = sha512;
      _vm_api.ripemd160 = ripemd160;
      _vm_api.recover_key = recover_key;
      _vm_api.sha3 = nullptr;

      _vm_api.db_store_i64 = db_store_i64;
      _vm_api.db_update_i64 = db_update_i64;
      _vm_api.db_remove_i64 = db_remove_i64;
      _vm_api.db_get_i64 = db_get_i64;
      _vm_api.db_next_i64 = db_next_i64;

      _vm_api.db_previous_i64 = db_previous_i64;
      _vm_api.db_find_i64 = db_find_i64;
      _vm_api.db_lowerbound_i64 = db_lowerbound_i64;
      _vm_api.db_upperbound_i64 = db_upperbound_i64;
      _vm_api.db_end_i64 = db_end_i64;

      _vm_api.db_store_i256 = db_store_i256;
      _vm_api.db_update_i256 = db_update_i256;
      _vm_api.db_remove_i256 = db_remove_i256;
      _vm_api.db_get_i256 = db_get_i256;
      _vm_api.db_find_i256 = db_find_i256;
//      _vm_api.db_upperbound_i256 = db_upperbound_i256;
//      _vm_api.db_lowerbound_i256 = db_lowerbound_i256;

      _vm_api.db_idx64_store = db_idx64_store;
      _vm_api.db_idx64_update = db_idx64_update;

      _vm_api.db_idx64_remove = db_idx64_remove;
      _vm_api.db_idx64_next = db_idx64_next;
      _vm_api.db_idx64_previous = db_idx64_previous;
      _vm_api.db_idx64_find_primary = db_idx64_find_primary;
      _vm_api.db_idx64_find_secondary = db_idx64_find_secondary;
      _vm_api.db_idx64_lowerbound = db_idx64_lowerbound;
      _vm_api.db_idx64_upperbound = db_idx64_upperbound;
      _vm_api.db_idx64_end = db_idx64_end;
      _vm_api.db_idx128_store = db_idx128_store;

      _vm_api.db_idx128_update = db_idx128_update;
      _vm_api.db_idx128_remove = db_idx128_remove;
      _vm_api.db_idx128_next = db_idx128_next;
      _vm_api.db_idx128_previous = db_idx128_previous;
      _vm_api.db_idx128_find_primary = db_idx128_find_primary;
      _vm_api.db_idx128_find_secondary = db_idx128_find_secondary;
      _vm_api.db_idx128_lowerbound = db_idx128_lowerbound;
      _vm_api.db_idx128_upperbound = db_idx128_upperbound;

      _vm_api.db_idx128_end = db_idx128_end;
      _vm_api.db_idx256_store = db_idx256_store;
      _vm_api.db_idx256_update = db_idx256_update;
      _vm_api.db_idx256_remove = db_idx256_remove;
      _vm_api.db_idx256_next = db_idx256_next;

      _vm_api.db_idx256_previous = db_idx256_previous;
      _vm_api.db_idx256_find_primary = db_idx256_find_primary;
      _vm_api.db_idx256_find_secondary = db_idx256_find_secondary;
      _vm_api.db_idx256_lowerbound = db_idx256_lowerbound;
      _vm_api.db_idx256_upperbound = db_idx256_upperbound;
      _vm_api.db_idx256_end = db_idx256_end;
      _vm_api.db_idx_double_store = db_idx_double_store;
      _vm_api.db_idx_double_update = db_idx_double_update;
      _vm_api.db_idx_double_remove = db_idx_double_remove;
      _vm_api.db_idx_double_next = db_idx_double_next;
      _vm_api.db_idx_double_previous = db_idx_double_previous;
      _vm_api.db_idx_double_find_primary = db_idx_double_find_primary;
      _vm_api.db_idx_double_find_secondary = db_idx_double_find_secondary;
      _vm_api.db_idx_double_lowerbound = db_idx_double_lowerbound;
      _vm_api.db_idx_double_upperbound = db_idx_double_upperbound;
      _vm_api.db_idx_double_end = db_idx_double_end;
      _vm_api.db_idx_long_double_store = db_idx_long_double_store;
      _vm_api.db_idx_long_double_update = db_idx_long_double_update;
      _vm_api.db_idx_long_double_remove = db_idx_long_double_remove;
      _vm_api.db_idx_long_double_next = db_idx_long_double_next;
      _vm_api.db_idx_long_double_previous = db_idx_long_double_previous;
      _vm_api.db_idx_long_double_find_primary = db_idx_long_double_find_primary;
      _vm_api.db_idx_long_double_find_secondary = db_idx_long_double_find_secondary;
      _vm_api.db_idx_long_double_lowerbound = db_idx_long_double_lowerbound;
      _vm_api.db_idx_long_double_upperbound = db_idx_long_double_upperbound;
      _vm_api.db_idx_long_double_end = db_idx_long_double_end;

      _vm_api.check_transaction_authorization = check_transaction_authorization;
      _vm_api.check_permission_authorization = check_permission_authorization;
      _vm_api.get_permission_last_used = get_permission_last_used;
      _vm_api.get_account_creation_time = get_account_creation_time;

      _vm_api.prints = prints;
      _vm_api.prints_l = prints_l;
      _vm_api.printi = printi;
      _vm_api.printui = printui;
      _vm_api.printi128 = printi128;
      _vm_api.printui128 = printui128;
      _vm_api.printsf = printsf;
      _vm_api.printdf = printdf;
      _vm_api.printqf = printqf;
      _vm_api.printn = printn;
      _vm_api.printhex = printhex;

      _vm_api.set_resource_limits = set_resource_limits;
      _vm_api.get_resource_limits = get_resource_limits;
      _vm_api.set_proposed_producers = set_proposed_producers;
      _vm_api.is_privileged = is_privileged;
      _vm_api.set_privileged = set_privileged;
      _vm_api.set_blockchain_parameters_packed = set_blockchain_parameters_packed;
      _vm_api.get_blockchain_parameters_packed = get_blockchain_parameters_packed;
      _vm_api.activate_feature = activate_feature;

      _vm_api.eosio_abort = eosio_abort;
      _vm_api.eosio_assert = eosio_assert;
      _vm_api.eosio_assert_message = eosio_assert_message;
      _vm_api.eosio_assert_code = eosio_assert_code;
      _vm_api.eosio_exit = eosio_exit;
      _vm_api.current_time = current_time;
      _vm_api.now = now;

      _vm_api.checktime = checktime;
      _vm_api.check_context_free = check_context_free;

      _vm_api.send_deferred = _send_deferred;
      _vm_api.cancel_deferred = _cancel_deferred;
      _vm_api.read_transaction = read_transaction;
      _vm_api.transaction_size = transaction_size;

      _vm_api.tapos_block_num = tapos_block_num;
      _vm_api.tapos_block_prefix = tapos_block_prefix;
      _vm_api.expiration = expiration;
      _vm_api.get_action = get_action;

      _vm_api.assert_privileged = assert_privileged;
      _vm_api.assert_context_free = assert_context_free;
      _vm_api.get_context_free_data = get_context_free_data;

      _vm_api.token_create = token_create;
      _vm_api.token_issue = token_issue;
      _vm_api.token_transfer = token_transfer;

      _vm_api.get_last_error = get_last_error;
      _vm_api.set_last_error = set_last_error;
      _vm_api.clear_last_error = clear_last_error;
   }
   vm_register_api(&_vm_api);
}

}}

max_stars_repo_name: uuosio/eos

max_issues_repo_name: uuosio/eos

max_forks_repo_name: uuosio/eos


text:
#include <map>
#include <string>
#include <vector>

#include <boost/shared_ptr.hpp>

#include <muduo/base/Mutex.h>

using std::string;

class CustomerData : boost::noncopyable
{
 public:
  CustomerData()
    : data_(new Map)//构造函数中申请一个map
  { }

  int query(const string& customer, const string& stock) const;//查询

 private:
  typedef std::pair<string, int> Entry;//条目
  typedef std::vector<Entry> EntryList;//条目链表
  typedef std::map<string, EntryList> Map;
  typedef boost::shared_ptr<Map> MapPtr;

  void update(const string& customer, const EntryList& entries);
  void update(const string& message);

  static int findEntry(const EntryList& entries, const string& stock);
  static MapPtr parseData(const string& message);

  MapPtr getData() const
  {
    muduo::MutexLockGuard lock(mutex_);
    return data_;
  }

  mutable muduo::MutexLock mutex_;
  MapPtr data_;//存储map
};

int CustomerData::query(const string& customer, const string& stock) const
{
  //读的时候引用计数+1,防止并发写
  MapPtr data = getData();

  Map::const_iterator entries = data->find(customer);
  if (entries != data->end())//找到
    return findEntry(entries->second, stock);
  else
    return -1;
  //读完引用计数-1
}

void CustomerData::update(const string& customer, const EntryList& entries)
{
  muduo::MutexLockGuard lock(mutex_);
  if (!data_.unique())
  {
    MapPtr newData(new Map(*data_));
    data_.swap(newData);
  }
  assert(data_.unique());
  (*data_)[customer] = entries;
}

void CustomerData::update(const string& message)
{
  MapPtr newData = parseData(message);
  if (newData)
  {
    muduo::MutexLockGuard lock(mutex_);
    data_.swap(newData);
  }
}

int main()
{
  CustomerData data;
}

ext: cc


text:
/**
 * @file
 *
 * @brief cppcms controller implementation managing snippet entry resources
 *
 * @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
 */

#include <algorithm>
#include <iostream>
#include <regex>
#include <stdexcept>
#include <stdlib.h>
#include <vector>

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

#include <authentication_application.hpp>
#include <database_application.hpp>
#include <model_configformat.hpp>
#include <model_entry.hpp>
#include <model_importedconfig.hpp>
#include <model_pluginformat.hpp>
#include <model_user.hpp>
#include <root_application.hpp>
#include <service.hpp>

namespace kdbrest
{

/**
 * @brief the constructor of the database endpoint application
 *
 * @param srv a service container
 */
DatabaseApp::DatabaseApp (cppcms::service & srv) : cppcms::application (srv)
{
	dispatcher ().assign ("/(([a-zA-Z0-9\\-\\.]+)(/([a-zA-Z0-9\\-\\.]+)){3})/{0,1}", &DatabaseApp::getUniqueEntry, this, 1);
	mapper ().assign ("entry", "/{1}");

	dispatcher ().assign ("/(([a-zA-Z0-9\\-\\.]+)(/([a-zA-Z0-9\\-\\.]+)){0,2})/{0,1}", &DatabaseApp::getEntriesByPrefix, this, 1);
	mapper ().assign ("search", "/{1}");

	dispatcher ().assign ("(/?)", &DatabaseApp::getAllEntries, this);
	mapper ().assign ("");

	// force caching of database
	(void) kdbrest::service::StorageEngine::instance ();
}

/**
 * @brief root resource handler
 *
 * the function delegates work to different helper methods
 * based on the HTTP method in the current request.
 *
 * for a GET request, it serves a list of entries.
 * for a POST request, it attempts an insert.
 */
void DatabaseApp::getAllEntries ()
{
	RootApp::setCORSHeaders (response (), "GET,POST,OPTIONS");

	if (request ().request_method () == "GET")
	{
		this->handleGet (request (), response ());
		return;
	}
	else if (request ().request_method () == "POST")
	{
		this->handleInsert (request (), response ());
		return;
	}
	else if (request ().request_method () == "OPTIONS")
	{
		RootApp::setOk (response ());
		return;
	}
	else
	{
		RootApp::setMethodNotAllowed (response ()); // send HTTP 405
		return;
	}
}

/**
 * @brief search resource handler
 *
 * the function delegates work to different helper methods
 * based on the HTTP method in the current request.
 *
 * for a GET request, it serves a list of entries, while
 * taking an additional GET parameter into account to limit
 * the resulting entry list.
 *
 * @param keyPart a part of a possible entry key to reduce search space
 */
void DatabaseApp::getEntriesByPrefix (std::string keyPart)
{
	RootApp::setCORSHeaders (response (), "GET,OPTIONS");

	if (request ().request_method () == "GET")
	{
		this->handleGet (request (), response (), keyPart);
		return;
	}
	else if (request ().request_method () == "OPTIONS")
	{
		RootApp::setOk (response ());
		return;
	}
	else
	{
		RootApp::setMethodNotAllowed (response ()); // send HTTP 405
		return;
	}
}

/**
 * @brief unique entry resource handler
 *
 * the function delegates work to different helper methods
 * based on the HTTP method in the current request.
 * it operates on a well-specified unique resource.
 *
 * for a GET request, it serves detailed information of an entry.
 * for a PUT request, it attempts an update on an entry.
 * for a DELETE request, it attempts the deletion of an entry.
 *
 * @param key the unique snippet key of an entry resource
 */
void DatabaseApp::getUniqueEntry (std::string key)
{
	RootApp::setCORSHeaders (response (), "GET,PUT,DELETE,OPTIONS");

	if (request ().request_method () == "GET")
	{
		this->handleGetUnique (request (), response (), key);
		return;
	}
	else if (request ().request_method () == "PUT")
	{
		this->handleUpdate (request (), response (), key);
		return;
	}
	else if (request ().request_method () == "DELETE")
	{
		this->handleDelete (request (), response (), key);
		return;
	}
	else if (request ().request_method () == "OPTIONS")
	{
		RootApp::setOk (response ());
		return;
	}
	else
	{
		RootApp::setMethodNotAllowed (response ()); // send HTTP 405
		return;
	}
}

/**
 * @brief handles the retrieval of a list of snippet entries
 *
 * @param req a request
 * @param resp a response
 * @param keyPart a part of a possible entry key to reduce search space
 */
void DatabaseApp::handleGet (cppcms::http::request & req, cppcms::http::response & resp, const std::string keyPart) const
{
	// first get the complete entry list
	std::vector<kdbrest::model::Entry> entries = service::StorageEngine::instance ().getAllEntries ();

	// if we are searching a sub-tree, filter first
	if (!keyPart.empty ())
	{
		service::SearchEngine::instance ().filterConfigurationsByName (entries, keyPart);
	}

	// then execute search based on parameters
	this->processFiltering (req, entries);
	// and sort the list
	this->processSorting (req, entries);

	// finally create the output
	this->generateAndSendEntryList (req, resp, entries);
}

/**
 * @brief handles a request to retrieve details for a single snippet entry
 *
 * @param req a request
 * @param resp a response
 * @param key the unique snippet key of the entry which shall be retrieved
 */
void DatabaseApp::handleGetUnique (cppcms::http::request & req, cppcms::http::response & resp, const std::string key) const
{
	try
	{
		model::Entry entry = service::StorageEngine::instance ().getEntry (key);

		const std::string raw = req.get (PARAM_RAW);
		if (!raw.empty ())
		{
			try
			{
				model::ConfigFormat configFormat = service::ConvertEngine::instance ().exportTo (raw, entry);
				RootApp::setOkRaw (resp, configFormat.getConfig (), MIME_TEXT_PLAIN);
				return; // quit here
			}
			catch (kdbrest::exception::UnsupportedConfigurationFormatException const & e)
			{
				RootApp::setBadRequest (resp, "Configuration format not supported.", "ENTRY_UNSUPPORTED_FORMAT");
				return; // quit early
			}
			catch (kdbrest::exception::ParseConfigurationException const & e)
			{
				RootApp::setBadRequest (resp, "The snippet cannot be represented using the submitted format.",
							"ENTRY_UNABLE_TO_EXPORT_SNIPPET");
				return; // quit early
			}
		}

		// create output data & add meta information
		cppcms::json::value data;
		data["key"]["full"] = entry.getPublicName ();
		data["key"]["organization"] = entry.getOrganization ();
		data["key"]["application"] = entry.getApplication ();
		data["key"]["scope"] = entry.getScope ();
		data["key"]["slug"] = entry.getSlug ();
		int i = 0;
		for (auto elem : entry.getTags ())
		{
			data["meta"]["tags"][i++] = elem;
		}
		data["meta"]["title"] = entry.getTitle ();
		data["meta"]["description"] = entry.getDescription ();
		data["meta"]["author"] = entry.getAuthor ();
		data["meta"]["created_at"] = entry.getCreatedAt ();

		// get the configuration in all supported formats
		std::vector<model::ConfigFormat> formats = service::ConvertEngine::instance ().exportToAll (entry);

		// first output the config of the plugin that was used during import
		int j = 0;
		auto it = formats.begin ();
		while (it != formats.end ())
		{
			if (it->getPluginformat ().getPluginnameWithConfig () == entry.getUploadPlugin ())
			{
				data["value"][j]["format"] = it->getPluginformat ().getFileformat ();
				data["value"][j]["plugin"] = it->getPluginformat ().getPluginnameWithConfig ();
				data["value"][j]["value"] = it->getConfig ();
				data["value"][j]["validated"] = it->isValidated ();
				j++;
				formats.erase (it);
				break;
			}
			it++;
		}
		// then output the other formats
		for (auto & elem : formats)
		{
			data["value"][j]["format"] = elem.getPluginformat ().getFileformat ();
			data["value"][j]["plugin"] = elem.getPluginformat ().getPluginnameWithConfig ();
			data["value"][j]["value"] = elem.getConfig ();
			data["value"][j]["validated"] = elem.isValidated ();
			j++;
		}

		RootApp::setOk (resp, data, MIME_APPLICATION_JSON);
	}
	catch (exception::EntryNotFoundException const & e)
	{
		RootApp::setNotFound (resp, "The requested entry does not exist.", "ENTRY_DOES_NOT_EXIST");
		return;
	}
}

/**
 * @brief handles a creation request for a new snippet entry
 *
 * @param req a request
 * @param resp a response
 */
void DatabaseApp::handleInsert (cppcms::http::request & req, cppcms::http::response & resp) const
{
	// first check if the currently authenticated user may create new database entries
	if (!AuthenticationApp::validateAuthentication (req, resp, Config::instance ().getConfig ().get<int> ("permissions.entry.create")))
	{
		return; // quit early, error message set already
	}

	model::User currentUser ("");
	try
	{
		currentUser = AuthenticationApp::getCurrentUser (req);
	}
	catch (exception::ElektraRestException const & e)
	{
		RootApp::setUnauthorized (resp, "You need to be authenticated to perform this action.", "NEED_AUTHENTICATION");
		return; // quit early
	}

	model::Entry entry ("");
	try
	{
		entry = this->buildAndValidateEntry (req, resp);
	}
	catch (exception::EntryValidationException const & e)
	{
		// error already written to output
		return; // so quit early
	}

	if (service::StorageEngine::instance ().entryExists (entry.getPublicName ()))
	{
		RootApp::setBadRequest (resp, "An entry with the given details does already exist.", "ENTRY_DOES_ALREADY_EXIST");
		return; // quit early
	}

	try
	{
		service::StorageEngine::instance ().createEntry (entry);
	}
	catch (exception::EntryAlreadyExistsException const & e)
	{
		RootApp::setBadRequest (resp, "An entry with the given details does already exist.", "ENTRY_DOES_ALREADY_EXIST");
		return; // quit early
	}

	RootApp::setOk (resp, "The entry has been created successfully.", "ENTRY_CREATED_SUCCESSFULLY");
}

/**
 * @brief handles an update request for a snippet entry
 *
 * @param req a request
 * @param resp a response
 * @param key the unique snippet key of the entry which shall be updated
 */
void DatabaseApp::handleUpdate (cppcms::http::request & req, cppcms::http::response & resp, const std::string & key) const
{
	// first lets find the entry
	model::Entry oldEntry ("");
	try
	{
		oldEntry = service::StorageEngine::instance ().getEntry (key);
	}
	catch (exception::EntryNotFoundException const & e)
	{
		RootApp::setNotFound (resp, "The entry to update does not exist.", "ENTRY_DOES_NOT_EXIST");
		return; // quit early
	}

	// now check if the currently authenticated user may even update it
	if (!AuthenticationApp::validateAuthentication (req, resp, Config::instance ().getConfig ().get<int> ("permissions.entry.edit"),
							oldEntry.getAuthor ()))
	{
		return; // quit early, error response already set
	}

	// build a new entry from the input
	model::Entry newEntry ("");
	try
	{
		newEntry = this->buildAndValidateEntry (req, resp, key);
	}
	catch (exception::EntryValidationException const & e)
	{
		// error already written to output
		return; // so quit early
	}

	// update the entry data with the new input
	this->copyEntryData (newEntry, oldEntry);

	// store updated entry
	try
	{
		service::StorageEngine::instance ().updateEntry (oldEntry);
	}
	catch (exception::EntryNotFoundException const & e)
	{
		RootApp::setBadRequest (resp, "An entry with the given details does not exist.", "ENTRY_DOES_NOT_EXIST");
		return; // quit early
	}

	RootApp::setOk (resp, "The entry has been updated successfully.", "ENTRY_UPDATED_SUCCESSFULLY");
}

/**
 * @brief handles a delete request of a snippet entry
 *
 * @param req a request
 * @param resp a response
 * @param key the unique snippet key of the entry which shall be deleted
 */
void DatabaseApp::handleDelete (cppcms::http::request & req, cppcms::http::response & resp, const std::string & key) const
{
	// first find the entry to delete
	model::Entry entry ("");
	try
	{
		entry = service::StorageEngine::instance ().getEntry (key);
	}
	catch (exception::EntryNotFoundException const & e)
	{
		RootApp::setNotFound (resp, "The entry to delete does not exist.", "ENTRY_DOES_NOT_EXIST");
		return; // quit early
	}

	// now check if the currently authenticated user may even update it
	if (!AuthenticationApp::validateAuthentication (req, resp, Config::instance ().getConfig ().get<int> ("permissions.entry.delete"),
							entry.getAuthor ()))
	{
		return; // quit early, error response already set
	}

	try
	{
		service::StorageEngine::instance ().deleteEntry (entry);
	}
	catch (exception::EntryNotFoundException const & e)
	{
		RootApp::setBadRequest (resp, "An entry with the given details does not exist.", "ENTRY_DOES_NOT_EXIST");
		return; // quit early
	}

	RootApp::setOk (resp, "The entry has been deleted successfully.", "ENTRY_DELETED_SUCCESSFULLY");
}

/**
 * @brief attempts to parse input data from a request data pack
 *
 * @param response a response for error output
 * @param requestData a json value containing all request post data
 * @param input_data the target struct to place input data in
 * @param withKeyParts if key part fields should be fetches as well
 */
void DatabaseApp::retrieveEntryInputData (cppcms::http::response & resp, const cppcms::json::value & requestData, entry_input_data & data,
					  const bool withKeyParts) const
{
	// check some special fields before retrieving them
	if (requestData.type ("configuration") != cppcms::json::is_object ||
	    (requestData.type ("tags") != cppcms::json::is_undefined && requestData.type ("tags") != cppcms::json::is_array))
	{
		RootApp::setBadRequest (resp, "The submitted data could not be parsed.", "REQUEST_MALFORMED_DATA");
		throw exception::InvalidPostDataFormatException (); // quit early
	}

	// retrieve submitted data
	if (withKeyParts)
	{
		try
		{
			data.organization = requestData.get<std::string> ("organization");
		}
		catch (cppcms::json::bad_value_cast const & e)
		{
			RootApp::setBadRequest (resp, "You have to supply an organization.", "ENTRY_MISSING_ORGANIZATION");
			throw exception::EntryValidationException (); // quit early
		}

		try
		{
			data.application = requestData.get<std::string> ("application");
		}
		catch (cppcms::json::bad_value_cast const & e)
		{
			RootApp::setBadRequest (resp, "You have to supply an application.", "ENTRY_MISSING_APPLICATION");
			throw exception::EntryValidationException (); // quit early
		}

		try
		{
			data.scope = requestData.get<std::string> ("scope");
		}
		catch (cppcms::json::bad_value_cast const & e)
		{
			RootApp::setBadRequest (resp, "You have to supply a scope.", "ENTRY_MISSING_SCOPE");
			throw exception::EntryValidationException (); // quit early
		}

		try
		{
			data.slug = requestData.get<std::string> ("slug");
		}
		catch (cppcms::json::bad_value_cast const & e)
		{
			RootApp::setBadRequest (resp, "You have to supply a slug.", "ENTRY_MISSING_SLUG");
			throw exception::EntryValidationException (); // quit early
		}
	}

	try
	{
		data.title = requestData.get<std::string> ("title");
	}
	catch (cppcms::json::bad_value_cast const & e)
	{
		RootApp::setBadRequest (resp, "You have to supply a title.", "ENTRY_MISSING_TITLE");
		throw exception::EntryValidationException (); // quit early
	}

	try
	{
		data.description = requestData.get<std::string> ("description");
	}
	catch (cppcms::json::bad_value_cast const & e)
	{
		RootApp::setBadRequest (resp, "You have to supply a description.", "ENTRY_MISSING_DESCRIPTION");
		throw exception::EntryValidationException (); // quit early
	}

	try
	{
		data.conf_format = requestData.get<std::string> ("configuration.format");
	}
	catch (cppcms::json::bad_value_cast const & e)
	{
		RootApp::setBadRequest (resp, "You have to supply a configuration format.", "ENTRY_MISSING_CONFIGURATION_FORMAT");
		throw exception::EntryValidationException (); // quit early
	}

	try
	{
		data.conf_value = requestData.get<std::string> ("configuration.value");
	}
	catch (cppcms::json::bad_value_cast const & e)
	{
		RootApp::setBadRequest (resp, "You have to supply a configuration snippet.", "ENTRY_MISSING_CONFIGURATION_VALUE");
		throw exception::EntryValidationException (); // quit early
	}

	if (requestData.type ("tags") != cppcms::json::is_undefined)
	{
		data.tags = requestData["tags"].array ();
	}
}

/**
 * @brief validates input data for a snippet entry
 *
 * @param response a response to use for error output
 * @param input_data the input data to validate
 * @param withKeyParts whether to validate also key parts
 */
void DatabaseApp::validateEntryInputData (cppcms::http::response & resp, const entry_input_data & data, const bool withKeyParts) const
{
	// regex for formats
	std::regex regex_parts (REGEX_ENTRY_PARTS);
	std::regex regex_title (REGEX_ENTRY_TITLE);
	std::regex regex_description (REGEX_ENTRY_DESCRIPTION);
	std::regex regex_tags (REGEX_ENTRY_TAGS);

	// validate inputs
	if (withKeyParts)
	{
		if (!std::regex_match (data.organization, regex_parts))
		{
			RootApp::setBadRequest (resp, "The submitted organization has an invalid format.", "ENTRY_INVALID_ORGANIZATION");
			throw exception::EntryValidationException (); // quit early
		}
		if (!std::regex_match (data.application, regex_parts))
		{
			RootApp::setBadRequest (resp, "The submitted application has an invalid format.", "ENTRY_INVALID_APPLICATION");
			throw exception::EntryValidationException (); // quit early
		}
		if (!std::regex_match (data.scope, regex_parts))
		{
			RootApp::setBadRequest (resp, "The submitted scope has an invalid format.", "ENTRY_INVALID_SCOPE");
			throw exception::EntryValidationException (); // quit early
		}
		if (!std::regex_match (data.slug, regex_parts))
		{
			RootApp::setBadRequest (resp, "The submitted slug has an invalid format.", "ENTRY_INVALID_SLUG");
			throw exception::EntryValidationException (); // quit early
		}
	}

	if (!std::regex_match (data.title, regex_title))
	{
		RootApp::setBadRequest (resp,
					"The submitted title has an invalid format. It has to be at least 3 signs long and may not contain "
					"line breakings.",
					"ENTRY_INVALID_TITLE");
		throw exception::EntryValidationException (); // quit early
	}
	if (!std::regex_match (data.description, regex_description))
	{
		RootApp::setBadRequest (resp, "The submitted description has an invalid format. It has to be at least 3 signs long.",
					"ENTRY_INVALID_DESCRIPTION");
		throw exception::EntryValidationException (); // quit early
	}
	for (auto & tag : data.tags)
	{
		if (tag.type () != cppcms::json::is_string || !std::regex_match (tag.str (), regex_tags))
		{
			RootApp::setBadRequest (resp,
						"You have supplied a malformed tag. Tags may only consist of lower case "
						"letters, numbers, dots (.) and dashes (-).",
						"ENTRY_INVALID_TAG");
			throw exception::EntryValidationException (); // quit early
		}
	}
}

/**
 * @brief builds and validates a snippet entry from a request
 *
 * @note the method sets response messages itself in case an error occurs.
 *		 if that happens, an exception is thrown so that the calling method
 *		 has a chance to quit early too.
 *
 * @param req a request
 * @param resp a response
 * @param keyName in case an entry is built for an update, the keyname has to be provided
 * @return the built and validated entry
 */
model::Entry DatabaseApp::buildAndValidateEntry (cppcms::http::request & req, cppcms::http::response & resp,
						 const std::string keyName) const
{
	// check if request data is of type application/json
	if (req.content_type_parsed ().media_type () != MIME_APPLICATION_JSON)
	{
		RootApp::setNotAcceptable (resp, "You have supplied an unsupported Content-Type.", "REQUEST_UNSUPPORTED_CONTENT_TYPE");
		throw exception::EntryValidationException (); // quit early
	}

	// try to parse request body data
	cppcms::json::value requestData;
	try
	{
		requestData = RootApp::parsePostDataAsJson (req);
	}
	catch (kdbrest::exception::InvalidPostDataFormatException const & e)
	{
		RootApp::setBadRequest (resp, "The submitted data is not of type application/json.", "REQUEST_MALFORMED_DATA");
		throw exception::EntryValidationException (); // quit early
	}

	// required request fields
	entry_input_data input_data;
	try
	{
		this->retrieveEntryInputData (resp, requestData, input_data, keyName.empty ());
	}
	catch (kdbrest::exception::InvalidPostDataFormatException const & e)
	{
		throw exception::EntryValidationException (); // error is set already
	}
	catch (kdbrest::exception::EntryValidationException const & e)
	{
		throw; // error is set already
	}

	// validate the input data
	try
	{
		this->validateEntryInputData (resp, input_data, keyName.empty ());
	}
	catch (kdbrest::exception::EntryValidationException const & e)
	{
		throw; // error is set already
	}

	// convert tags to vector<string>
	std::vector<std::string> taglist;
	for (auto & tag : input_data.tags)
	{
		taglist.push_back (tag.str ()); // at this point we know that tag is a string
	}

	// retrieve current user for author information
	model::User currentUser ("");
	try
	{
		currentUser = AuthenticationApp::getCurrentUser (req);
	}
	catch (exception::ElektraRestException const & e)
	{
		RootApp::setUnauthorized (resp, "You need to be authenticated to perform this action.", "NEED_AUTHENTICATION");
		throw exception::EntryValidationException (); // quit early
	}

	// build the entry
	std::string entryKey = input_data.organization + "/" + input_data.application + "/" + input_data.scope + "/" + input_data.slug;
	if (!keyName.empty ())
	{
		entryKey = keyName;
	}
	model::Entry entry (entryKey);
	entry.setTitle (input_data.title);
	entry.setDescription (input_data.description);
	entry.setCreatedAt (static_cast<long> (time (0)));
	entry.setAuthor (currentUser.getUsername ());
	entry.setTags (taglist);

	// try to import the submitted snippet into the internal format
	try
	{
		model::ImportedConfig cfg =
			service::ConvertEngine::instance ().import (input_data.conf_value, input_data.conf_format, entry);
		auto subkeys = cfg.getKeySet ();
		entry.addSubkeys (subkeys);
		entry.setUploadPlugin (cfg.getPluginformat ().getPluginnameWithConfig ());
	}
	catch (exception::UnsupportedConfigurationFormatException const & e)
	{
		RootApp::setBadRequest (resp, "The given configuration has an invalid or unsupported format.",
					"ENTRY_INVALID_CONFIGURATION_FORMAT");
		throw exception::EntryValidationException (); // quit early
	}
	catch (exception::ParseConfigurationException const & e)
	{
		RootApp::setBadRequest (resp, "The given configuration could not be parsed within the given format.",
					"ENTRY_INVALID_CONFIGURATION_VALUE");
		throw exception::EntryValidationException ();
	}

	// and finally return the built entry object
	return entry;
}

/**
 * @brief extracts the max number of rows to print from a request
 *
 * @param req a request
 * @return the max number of rows to print or the default value if not set
 */
inline int DatabaseApp::getMaxrows (cppcms::http::request & req) const
{
	int maxrows = ELEKTRA_REST_OUTPUT_MAX_ENTRIES;

	std::string s_maxrows = req.get (PARAM_ROWS);
	if (!s_maxrows.empty ())
	{
		try
		{
			maxrows = std::stoi (s_maxrows);
			if (maxrows > ELEKTRA_REST_OUTPUT_MAX_ENTRIES)
			{
				maxrows = ELEKTRA_REST_OUTPUT_MAX_ENTRIES;
			}
		}
		catch (std::invalid_argument const & e)
		{
		}
	}

	return maxrows;
}

/**
 * @brief extracts the offset parameter from a request
 *
 * @param req a request
 * @return the offset extracted from the request parameter, if not set 0
 */
inline int DatabaseApp::getOffset (cppcms::http::request & req) const
{
	int offset = 0;

	std::string s_offset = req.get (PARAM_OFFSET);
	if (!s_offset.empty ())
	{
		try
		{
			offset = std::stoi (s_offset);
		}
		catch (std::invalid_argument const & e)
		{
		}
	}

	return offset;
}

/**
 * @brief filters a vector of snippet entries based on parameters of a request
 *
 * @param req a request
 * @param entries the entry vector to filter
 */
inline void DatabaseApp::processFiltering (cppcms::http::request & req, std::vector<model::Entry> & entries) const
{
	// retrieve parameter values
	std::string filter = req.get (PARAM_FILTER);
	std::string filterby = req.get (PARAM_FILTERBY);

	// only proceed if a filter is set
	if (!filter.empty ())
	{
		// if the filter is unknown, take default
		if (filterby != "all" && filterby != "key" && filterby != "title" && filterby != "description" && filterby != "author" &&
		    filterby != "tags")
		{
			filterby = Config::instance ().getConfig ().get<std::string> ("output.default.entry.filterby");
		}

		service::SearchEngine::instance ().findConfigurationsByFilter (entries, filter, filterby);
	}
}

/**
 * @brief sorts a vector of snippet entries based on parameters of a request
 *
 * @param req a request
 * @param entries the entry vector to sort
 */
inline void DatabaseApp::processSorting (cppcms::http::request & req, std::vector<model::Entry> & entries) const
{
	// retrieve parameter values
	std::string sort = req.get (PARAM_SORT);
	std::string sortby = req.get (PARAM_SORTBY);

	// validate the sort direction input or set default
	if (!boost::iequals (sort, PARAM_VAL_SORT_ASC) && !boost::iequals (sort, PARAM_VAL_SORT_DESC))
	{
		sort = Config::instance ().getConfig ().get<std::string> ("output.default.entry.sort");
		;
	}

	// validate the sortby input or set default
	if (SORT_ENTRY_MAP.find (sortby) == SORT_ENTRY_MAP.end ())
	{
		sortby = Config::instance ().getConfig ().get<std::string> ("output.default.entry.sortby");
		;
	}

	// do the sorting
	if (boost::iequals (sort, PARAM_VAL_SORT_ASC))
	{
		// sort from left to right
		std::sort (entries.begin (), entries.end (), SORT_ENTRY_MAP.at (sortby));
	}
	else
	{
		// sort from right to left
		std::sort (entries.rbegin (), entries.rend (), SORT_ENTRY_MAP.at (sortby));
	}
}

/**
 * @brief creates the output for a list of snippet entries
 *
 * @note not all snippets in the list may actually be printed to the output.
 *       which snippets are used in the output depends on additional parameters.
 *
 * @param req a request
 * @param resp a response
 * @param entries a list of snippets, of which some may be used for the output
 */
void DatabaseApp::generateAndSendEntryList (cppcms::http::request & req, cppcms::http::response & resp,
					    const std::vector<model::Entry> & entries) const
{
	int offset = this->getOffset (req);
	int maxrows = this->getMaxrows (req);

	cppcms::json::value data;
	int elements = static_cast<int> (entries.size ()) - offset;
	elements = (elements > 0) ? elements : 0;
	elements = (elements < maxrows) ? elements : maxrows;
	int remaining = (static_cast<int> (entries.size ()) - offset) - elements;
	data["offset"] = offset;
	data["elements"] = elements;
	data["remaining"] = (remaining > 0) ? remaining : 0;

	if (offset < static_cast<int> (entries.size ()))
	{
		int index = 0;
		int offset_it = 0;
		for (auto & elem : entries)
		{

			// break for maxrows
			if (index >= maxrows)
			{
				break;
			}

			// skip to offset
			if (offset_it < offset)
			{
				offset_it++;
				continue;
			}

			data["entries"][index]["key"]["full"] = elem.getPublicName ();
			data["entries"][index]["key"]["organization"] = elem.getOrganization ();
			data["entries"][index]["key"]["application"] = elem.getApplication ();
			data["entries"][index]["key"]["scope"] = elem.getScope ();
			data["entries"][index]["key"]["slug"] = elem.getSlug ();
			data["entries"][index]["title"] = elem.getTitle ();
			data["entries"][index]["description"] = elem.getDescription ();
			data["entries"][index]["created_at"] = elem.getCreatedAt ();
			data["entries"][index]["author"] = elem.getAuthor ();

			int i = 0;
			for (auto & tag : elem.getTags ())
			{
				data["entries"][index]["tags"][i] = tag;
				i++;
			}

			index++;
		}
	}

	RootApp::setOk (resp, data, MIME_APPLICATION_JSON);
}

/**
 * @brief copies meta data from one entry to another
 *
 * does not copy the key of the entry itself, only meta data
 * and the configuration snippet. does also not copy data
 * that can only be changed by the system (creation date and
 * author).
 *
 * @param from source entry
 * @param to target entry
 */
void DatabaseApp::copyEntryData (model::Entry & from, model::Entry & to) const
{
	to.setDescription (from.getDescription ()); // set new description
	to.setTitle (from.getTitle ());		    // set new title
	to.setTags (from.getTags ());		    // set new tags
	to.getSubkeys ().clear ();		    // clear old config
	auto ks = from.getSubkeys ();
	to.addSubkeys (ks);			      // replace config
	to.setUploadPlugin (from.getUploadPlugin ()); // replace old upload format
}

} // namespace kdbrest

max_stars_repo_name: mirunix/libelektra

max_issues_repo_name: mirunix/libelektra

max_forks_repo_name: mirunix/libelektra


text:
// graph-tool -- a general graph modification and manipulation thingy
//
// Copyright (C) 2006-2015 Tiago de Paula Peixoto <tiago@skewed.de>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

#include "graph.hh"
#include "graph_filtering.hh"
#include "graph_properties.hh"

#include <boost/mpl/contains.hpp>
#include <boost/python/extract.hpp>

using namespace std;
using namespace boost;
using namespace graph_tool;

//
// Property map copying
// ====================

template <class IteratorSel, class PropertyMaps>
struct copy_property
{
    template <class GraphTgt, class GraphSrc, class PropertyTgt>
    void operator()(const GraphTgt& tgt, const GraphSrc* src,
                    PropertyTgt dst_map, boost::any prop_src) const
    {
        try
        {
            auto src_map = boost::any_cast<typename PropertyTgt::checked_t>(prop_src);
            dispatch(tgt, src, dst_map, src_map);
        }
        catch (bad_any_cast)
        {
            typedef typename property_traits<PropertyTgt>::value_type val_tgt;
            typedef typename IteratorSel::template get_descriptor<GraphSrc>::type src_d;

            DynamicPropertyMapWrap<val_tgt, src_d> src_map(prop_src, PropertyMaps());

            dispatch(tgt, src, dst_map, src_map);
        }
    }

    template <class GraphTgt, class GraphSrc, class PropertyTgt, class PropertySrc>
    void dispatch(const GraphTgt& tgt, const GraphSrc* src,
                  PropertyTgt dst_map, PropertySrc src_map) const
    {
        try
        {
            typename IteratorSel::template apply<GraphSrc>::type vs, vs_end;
            typename IteratorSel::template apply<GraphTgt>::type vt, vt_end;
            tie(vt, vt_end) = IteratorSel::range(tgt);
            for (tie(vs, vs_end) = IteratorSel::range(*src); vs != vs_end; ++vs)
            {
                if (vt == vt_end)
                    throw ValueException("Error copying properties: "
                                         "graphs not compatible");
                dst_map[*vt] = get(src_map, *vs);
                ++vt;
            }
        }
        catch (bad_lexical_cast&)
        {
            throw ValueException("property values are not convertible");
        }
    }

};

struct edge_selector
{
    template <class Graph>
    struct apply
    {
        typedef typename graph_traits<Graph>::edge_iterator type;
    };

    template <class Graph>
    struct get_descriptor
    {
        typedef typename graph_traits<Graph>::edge_descriptor type;
    };

    template <class Graph>
    static pair<typename apply<Graph>::type,
                typename apply<Graph>::type>
    range(Graph& g)
    {
        return edges(g);
    }
};

struct vertex_selector
{
    template <class Graph>
    struct apply
    {
        typedef typename graph_traits<Graph>::vertex_iterator type;
    };

    template <class Graph>
    struct get_descriptor
    {
        typedef typename graph_traits<Graph>::vertex_descriptor type;
    };

    template <class Graph>
    static pair<typename apply<Graph>::type,
                typename apply<Graph>::type>
    range(Graph& g)
    {
        return vertices(g);
    }
};

struct graph_views:
    boost::mpl::transform<graph_tool::detail::always_directed_never_reversed,
                          boost::mpl::quote1<std::add_pointer> >::type {};

void GraphInterface::CopyVertexProperty(const GraphInterface& src,
                                        boost::any prop_src,
                                        boost::any prop_tgt)
{
    run_action<>()
        (*this, std::bind(copy_property<vertex_selector,vertex_properties>(),
                          std::placeholders::_1, std::placeholders::_2,
                          std::placeholders::_3, prop_src),
         graph_views(), writable_vertex_properties())
        (src.GetGraphView(), prop_tgt);
}

void GraphInterface::CopyEdgeProperty(const GraphInterface& src,
                                      boost::any prop_src,
                                      boost::any prop_tgt)
{
    run_action<>()
        (*this, std::bind(copy_property<edge_selector,edge_properties>(),
                          std::placeholders::_1, std::placeholders::_2,
                          std::placeholders::_3, prop_src),
         graph_views(), writable_edge_properties())
        (src.GetGraphView(), prop_tgt);
}

max_stars_repo_name: johankaito/fufuka

max_issues_repo_name: johankaito/fufuka

max_forks_repo_name: johankaito/fufuka


text:
/**
 * Copyright (c) 2019 Melown Technologies SE
 *
 * 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef semantic_roof_hpp_included_
#define semantic_roof_hpp_included_

#include <vector>
#include <array>

#include <boost/variant.hpp>

#include "utility/enum-io.hpp"
#include "math/geometry_core.hpp"

namespace semantic { namespace roof {

struct Rectangular {
    using Curb = std::array<double, 4>;
    using Hip = std::array<double, 2>;
    using EaveHeight = std::array<double, 4>;

    constexpr static Curb defaultCurb = { 1.0, 1.0, 0.0, 0.0 };
    constexpr static Hip defaultHip = { 1.0, 1.0 };
    constexpr static EaveHeight defaultEaveHeight = { 0.0, 0.0, 0.0, 0.0 };

    math::Size2f size;
    math::Point2d skew;
    double azimuth = 0.0;
    Curb curb = defaultCurb;
    Hip hip = defaultHip;
    double ridgeHeight = 0.0;
    double curbHeight = 0.0;
    EaveHeight eaveHeight = defaultEaveHeight;

    enum class Key { top = 0, bottom = 1, left = 2, right = 3 };
};

/** Casts Key to integer.
 */
int operator+(Rectangular::Key key);

struct Circular {
    double radius = 0.0;
    double curb = 0.0;
    double ridgeHeight = 0.0;
    double curbHeight = 0.0;
    double eaveHeight = 0.0;
};

typedef boost::variant<Circular, Rectangular> Instance;
enum class Type { circular = 0, rectangular };

struct Roof {
    typedef std::vector<Roof> list;

    math::Point3 center;
    Instance instance;

    Type type() const { return static_cast<Type>(instance.which()); }

    // needed by python bindings
    bool operator==(const Roof &r) const;
};

// inline stuff

UTILITY_GENERATE_ENUM_IO(Type,
                         ((rectangular))
                         ((circular))
                         )

UTILITY_GENERATE_ENUM_IO(Rectangular::Key,
                         ((top))
                         ((bottom))
                         ((left))
                         ((right))
                         )

inline int operator+(Rectangular::Key key) {
    return static_cast<int>(key);
}

} } // namespace roof::semantic

#endif // semantic_roof_hpp_included_

max_stars_repo_name: melowntech/libsemantic

max_issues_repo_name: melowntech/libsemantic

max_forks_repo_name: melowntech/libsemantic