text:
#ifndef PROTOC_SERIALIZATION_MAP_HPP
#define PROTOC_SERIALIZATION_MAP_HPP

///////////////////////////////////////////////////////////////////////////////
//
// http://protoc.sourceforge.net/
//
// Copyright (C) 2013 Bjorn Reese <breese@users.sourceforge.net>
//
// Permission to use, copy, modify, and distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
// MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE AUTHORS AND
// CONTRIBUTORS ACCEPT NO RESPONSIBILITY IN ANY CONCEIVABLE MANNER.
//
///////////////////////////////////////////////////////////////////////////////

#include <map>
#include <boost/serialization/split_free.hpp>
#include <protoc/serialization/serialization.hpp>
#include <protoc/serialization/pair.hpp>

namespace boost
{
namespace serialization
{

template <typename Archive, typename Key, typename T, typename Compare, typename Allocator>
struct save_functor< Archive, typename std::map<Key, T, Compare, Allocator> >
{
    void operator () (Archive& ar,
                      const std::map<Key, T, Compare, Allocator>& data,
                      const unsigned int version)
    {
        ar.save_map_begin();
        for (typename std::map<Key, T, Compare, Allocator>::const_iterator it = data.begin();
             it != data.end();
             ++it)
        {
            ar.save_override(*it, version);
        }
        ar.save_map_end();
    }
};

template <typename Archive, typename Key, typename T, typename Compare, typename Allocator>
struct load_functor< Archive, typename std::map<Key, T, Compare, Allocator> >
{
    void operator () (Archive& ar,
                      std::map<Key, T, Compare, Allocator>& data,
                      const unsigned int version)
    {
        ar.load_map_begin();
        while (!ar.at_map_end())
        {
            // We cannot use std::map<Key, T>::value_type because it has a const key
            std::pair<Key, T> value;
            ar.load_override(value, version);
            data.insert(value);
        }
        ar.load_map_end();
    }
};

template <typename Key, typename T, typename Compare, typename Allocator>
struct serialize_functor< typename std::map<Key, T, Compare, Allocator> >
{
    template <typename Archive>
    typename boost::enable_if<typename Archive::is_loading, void>::type
    operator () (Archive& ar,
                 std::map<Key, T, Compare, Allocator>& data,
                 const unsigned int version)
    {
        split_free(ar, data, version);
    }

    template <typename Archive>
    typename boost::enable_if<typename Archive::is_saving, void>::type
    operator () (Archive& ar,
                 const std::map<Key, T, Compare, Allocator>& data,
                 const unsigned int version)
    {
        split_free(ar, data, version);
    }
};

} // namespace serialization
} // namespace boost

#endif // PROTOC_SERIALIZATION_MAP_HPP

ext: hpp


text:
/**
 * \file dcs/meta/count_fwd.hpp
 *
 * \brief Forward declarations for the meta-function which returns the number of
 *  elements in a sequence that are identical to the given type.
 *
 * \author Marco Guazzone (marco.guazzone@gmail.com)
 *
 * <hr/>
 *
 * Copyright 2009 Marco Guazzone (marco.guazzone@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef DCS_META_COUNT_FWD_HPP
#define DCS_META_COUNT_FWD_HPP

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

#if DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION(103000) // 1.30

#include <boost/mpl/count_fwd.hpp>

namespace dcs { namespace meta {

namespace detail {

using ::boost::mpl::count_impl;

} // Namespace detail

using ::boost::mpl::count;

}} // Namespace dcs::meta

#else // DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION

namespace dcs { namespace meta {

namespace detail {

template <typename AssociativeSequenceTagT> struct count_impl;

} // Namespace detail

template <typename AssociativeSequenceT, typename KeyT> struct count;

}} // Namespace dcs::meta

#endif // DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION

#endif // DCS_META_COUNT_FWD_HPP

max_stars_repo_name: sguazt/dcsxx-commons

max_issues_repo_name: sguazt/dcsxx-commons

max_forks_repo_name: sguazt/dcsxx-commons


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

#ifndef PGIBBS_JUNCTION_TREE_HPP
#define PGIBBS_JUNCTION_TREE_HPP

/**
 *
 * Represents a junction tree
 *
 *  \author Joseph Gonzalez
 */

// INCLUDES ===================================================================>

#include <iostream>
#include <iomanip>

#include <fstream>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <cassert>

#include <boost/unordered_map.hpp>

#include <graphlab/logger/assertions.hpp>
#include <graphlab.hpp>

#include "factorized_model.hpp"
#include "mrf.hpp"

struct jtree_vertex_data;
struct jtree_edge_data;

typedef graphlab::graph< jtree_vertex_data, jtree_edge_data> jtree_graph_type;

struct jtree_vertex_data {
  jtree_graph_type::vertex_id_type parent;
  domain_t variables;
  bool calibrated;
  bool sampled;
  std::vector<factor_id_t> factor_ids;
  factor_t factor;
  assignment_t asg;

  jtree_vertex_data() : parent(-1), calibrated(false), sampled(false) { }
}; // End of vertex data

struct jtree_edge_data {
  domain_t variables;
  factor_t message;
  bool calibrated;
  bool received;
  jtree_edge_data() :
    calibrated(false),
    received(false) { }
}; // End of edge data

//// Junction tree construction code
//// =====================================================================>

//! The fast set used in junction tree construction
typedef graphlab::small_set<2*MAX_DIM, jtree_graph_type::vertex_id_type>
vertex_set;

struct jtree_list {
  struct elim_clique {
    //! The parent of this elim clique in the jtree_list
    jtree_graph_type::vertex_id_type parent;
    //! The vertex eliminated when this clique was created
    mrf_graph_type::vertex_id_type elim_vertex;
    //! The vertices created in this clique EXCLUDING elim_vertex
    vertex_set vertices;
    elim_clique() : parent(-1) { }
  };
  typedef std::vector<elim_clique> clique_list_type;
  typedef boost::unordered_map<mrf_graph_type::vertex_id_type,
                               mrf_graph_type::vertex_id_type>
  elim_time_type;

  //! The collection of cliques
  clique_list_type cliques;
  //! the time variable i was eliminated
  elim_time_type   elim_time;

  inline bool contains(const mrf_graph_type::vertex_id_type vid) const {
    return elim_time.find(vid) != elim_time.end();
  }

  inline mrf_graph_type::vertex_id_type
  elim_time_lookup(const mrf_graph_type::vertex_id_type vid) const {
    elim_time_type::const_iterator iter(elim_time.find(vid));
    ASSERT_TRUE(iter != elim_time.end());
    return iter->second;
  }

  inline void clear() {
    cliques.clear();
    elim_time.clear();
  }

  /**
   * Extend the jtree_list data structure by eliminating the vertex.
   * If the jtree list can be extended then it is extended and this
   * function returns true.
   *
   **/
  bool extend(const mrf_graph_type::vertex_id_type elim_vertex,
              const mrf_graph_type& mrf,
              const size_t max_tree_width,
              const size_t max_factor_size);

  /**
   * Convert a jtree_list into a jtree_graph
   */
  void load_graph(const mrf_graph_type& mrf,
                  const size_t num_factors,
                  jtree_graph_type& jt_graph) const;

  /**
   * Check internal data structures
   */
  void validate() const;

};

// /**
//  * Extend the jtree_list data structure by eliminating the vertex.  If
//  * the jtree list can be extended then it is extended and this
//  * function returns true.
//  *
//  **/
// bool extend_jtree_list(const vertex_id_t elim_vertex,
//                        const mrf_graph_type& mrf,
//                        const size_t max_tree_width,
//                        const size_t max_factor_size,
//                        jtree_list& jt_list);

// /**
//  * Convert a jtree_list into a jtree_graph
//  */
// void jtree_list_to_jtree_graph(const jtree_list& jt_list,
//                                const mrf_graph_type& mrf,
//                                const size_t num_factors,
//                                jtree_graph_type& jt_graph);

// /**
//  * Scan the junction tree list to ensure that all invariants hold.
//  */
// bool validate_jtree_list(const jtree_list& jt_list);

#endif

max_issues_repo_name: HybridGraph/GraphLab-PowerGraph

max_forks_repo_name: HybridGraph/GraphLab-PowerGraph


text:
#include "web_server.hpp"
#include <iostream>
#include <functional>
#include <vector>
#include <map>
#include <string>
#include <iterator>
#include "nlohmann/json.hpp"
#include <fstream>
#include <sstream>
#include <atomic>
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>
#include <chrono>
#include <exception>
#include <cstring>
#include "simdjson.h"
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/algorithm/string.hpp>
#include <memory>
using namespace simdjson;
using namespace boost::system;
using namespace boost::asio;
using namespace boost::asio::ip;
using namespace std;
using namespace boost::asio::placeholders;

WebServer::WebServer(boost::filesystem::path web_root) :
		web_root(web_root) {
	server = NULL;
}

WebServer::~WebServer() {
	if (server)
		delete server;
}

void WebServer::defaultGet(std::shared_ptr<HttpServer::Response> response,
	std::shared_ptr<HttpServer::Request> request) {
	boost::filesystem::path path = web_root;

	path /= request->path;

			if (boost::filesystem::is_directory(path))
				path /= "index.html";

			std::string url = request->path;
			std::cout << "get_response call from URL: " << url << std::endl;
			if(url == "/Chart.json")
			{

     			nlohmann::json output = nlohmann::json::array();
				output.push_back(getJSONdata_1());
				output.nlohmann::json::push_back(getJSONdata_2());
				output.nlohmann::json::push_back(getJSONdata_3());
				output.nlohmann::json::push_back(getJSONdata_4());
				output.nlohmann::json::push_back(getJSONdata_5());
				output.nlohmann::json::push_back(getJSONdata_6());
				output.nlohmann::json::push_back(getJSONdata_7());

				send(response, output);
				return;
			}
			else if (boost::filesystem::exists(path)){
				auto ifs = std::make_shared<std::ifstream>();
				ifs->open(path.string(), std::ifstream::in | std::ios::binary);
				if (*ifs) {

					std::streamsize buffer_size = 131072;
					auto buffer = std::make_shared<std::vector<char> >(
							buffer_size);

					std::cout << "Path: " << path.string() << std::endl;

					ifs->seekg(0, std::ios::end);
					auto length = ifs->tellg();

					ifs->seekg(0, std::ios::beg);

					*response << "HTTP/1.1 200 OK\r\nContent-Length: " << length
							<< "\r\n\r\n";
					defaultResourceSend(*server, response, ifs, buffer);
					return;
				}
			}
			else
			{
				std::string sHTML = "
404 Not Found

There's nothing here.
";
				send(response, sHTML);
				return;
			}

	badRequest(response, request);
}

void WebServer::setup() {

	server = new HttpServer();
	server->config.port = 8080;

	std::string url =
			"^((http[s]?|ftp):\\/)?\\/?([^:\\/\\s]+)((\\/\\w+)*\\/)([\\w\\-\\.]+[^#?\\s]+)(.*)?(#[\\w\\-]+)?$";
	std::string jsonUrl =
			"^/(v\\d+(\\.\\d+)*)/json/([\\w\\-\\.]+[^#?\\s]+)(.*)?(#[\\w\\-]+)?";

	server->resource[jsonUrl]["GET"] =
			[&](std::shared_ptr<HttpServer::Response> response,
					std::shared_ptr<HttpServer::Request> request) {

				std::string version = request->path_match[URLPOSITIONVERSION];
				std::string path=request->path_match[URLPOSITIONPATH];
				std::vector<std::string> path_segments;
				boost::split( path_segments, path, boost::is_any_of("/"), boost::token_compress_on );

				std::string query = request->query_string;
				std::vector<std::string> query_segments;
				boost::split( query_segments, query, boost::is_any_of("&"), boost::token_compress_on );

			};

	//Default GET. If no other matches, this anonymous function will be called.
	//Will respond with content in the web/-directory, and its subdirectories.
	//Default file: index.html
	//Can for instance be used to retrieve an HTML 5 client that uses REST-resources on this server
	server->default_resource["GET"] = std::bind(&WebServer::defaultGet, this, std::placeholders::_1, std::placeholders::_2);
}

void WebServer::defaultResourceSend(const HttpServer &server,
		std::shared_ptr<HttpServer::Response> response,
		std::shared_ptr<std::ifstream> ifs,
		std::shared_ptr<std::vector<char> > buffer) {
	std::streamsize read_length;
	if ((read_length = ifs->read(&(*buffer)[0], buffer->size()).gcount()) > 0) {
		response->write(&(*buffer)[0], read_length);
		if (read_length == static_cast<std::streamsize>(buffer->size())) {
			response->send(
					[this, &server, response, ifs, buffer](const boost::system::error_code &ec) {
						if(!ec)
							defaultResourceSend(server, response, ifs, buffer);
						else
							std::cerr << "Connection interrupted" << std::endl;
					});
		}
	}
	return;
}

void WebServer::send(std::shared_ptr<HttpServer::Response> response,
		nlohmann::json o) {
	std::stringstream contentStream;
	contentStream << o;
	std::string message = contentStream.str();
	*response << "HTTP/1.1 200 OK\r\n";
	*response << "Content-Length: " << message.length() << "\r\n";
	*response << "Content-Type: application/json" << "\r\n\r\n";
	*response << message;
	return;
}

ext: cpp


text:
// Author(s): Wieger Wesselink
// Copyright: see the accompanying file COPYING or copy at
// https://svn.win.tue.nl/trac/MCRL2/browser/trunk/COPYING
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
/// \file file_utility_test.cpp
/// \brief Add your file description here.

#include "mcrl2/utilities/file_utility.h"
#include <boost/test/included/unit_test_framework.hpp>

using namespace mcrl2;

BOOST_AUTO_TEST_CASE(test_has_extension)
{
  using utilities::has_extension;
  BOOST_CHECK(has_extension("1.pbes", "pbes"));
  BOOST_CHECK(has_extension("1.pbes.bes", "bes"));
  BOOST_CHECK(!has_extension("1.pbes.bes", "pbes"));
  BOOST_CHECK(!has_extension("bes", "bes"));
  BOOST_CHECK(!has_extension("1.pbes", "bes"));
  BOOST_CHECK(!has_extension("a.pbes.bes","pbes"));  // Ticket #1374.
  BOOST_CHECK(!has_extension("a.besp","bes"));       // Mistake in previous code (until appr. revision 14827).
}

boost::unit_test::test_suite* init_unit_test_suite(int argc, char* argv[])
{
  return nullptr;
}


text:
/*
  Copyright (c) <2015-2016>, <BenHJ>
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.
  2. 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.
  3. Neither the name of the copyright holder nor the names of its contributors
  may be used to endorse or promote products derived from this software without
  specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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.
*/

#pragma once

#include "knoxcrypt/CoreIO.hpp"
#include "knoxcrypt/EntryInfo.hpp"
#include "knoxcrypt/ContentFolder.hpp"

#include <boost/optional.hpp>
#include <memory>
#include <string>

namespace knoxcrypt
{

    class CompoundFolder
    {
      public:
        CompoundFolder() = delete;
        /**
         * @brief constructs a CompoundFolder to write to. In this case the
         * starting block is unknown
         * @param the core knoxcrypt io (path, blocks, password)
         * @param startBlock the index of the starting file block making up entry data
         * @param writable if data entries can be added to folder
         * @param name the name of the entry
         * @param enforceRootBlock true if we want to enforce the starting root block
         */
        CompoundFolder(SharedCoreIO const &io,
                       std::string const &name = "root",
                       bool const enforceRootBlock = false);

        /**
         * @brief constructs a CompoundFolder to read from
         * @param the core knoxcrypt io (path, blocks, password)
         * @param startBlock the index of the starting file block making up entry data
         * @param writable if data entries can be added to folder
         * @param name the name of the entry
         */
        CompoundFolder(SharedCoreIO const &io,
                      uint64_t const startBlock,
                      std::string const &name = "root");

        /**
         * @brief appends a new file entry and start index to the entry data
         * @param name the name of the entry
         * @return a copy of a File that will be used to reference the file data
         */
        void addFile(std::string const &name);

        /**
         * @brief appends a new folder entry and start index of the entry data
         * @param name the name of the entry
         * @return a copy of a CompoundFolder that will be used to reference the folder data
         */
        void addFolder(std::string const &name);

        /**
         * @brief retrieves a File with specific name
         * @param name the name of the entry to lookup
         * @param openDisposition open mode
         * @return a copy of the File with name
         */
        File getFile(std::string const &name,
                            OpenDisposition const &openDisposition) const;

        /**
         * @brief retrieves a CompoundFolder with specific name
         * @param name the name of the entry to lookup
         * @return a copy of the CompoundFolder with name
         */
        std::shared_ptr<CompoundFolder> getFolder(std::string const &name) const;

        /// retrieves main compound folder (the parent of leaf compound folders)
        std::shared_ptr<ContentFolder> getCompoundFolder() const;

        /**
         * @brief retrieves the name of this folder
         * @return the name
         */
        std::string getName() const;

        /**
         * @brief retrieves an entry info it exists
         * @param name the name of the info
         * @return an entry info if it exsist
         */
        SharedEntryInfo getEntryInfo(std::string const &name) const;

        /**
         * @brief returns a vector of all entry infos
         * @return all entry infos
         */
        EntryInfoCacheMap & listAllEntries() const;

        /**
         * @brief returns a vector of file entry infos
         * @return all file entry infos
         */
        std::vector<SharedEntryInfo> listFileEntries() const;

        /**
         * @brief returns a vector of folder entry infos
         * @return all folder entry infos
         */
        std::vector<SharedEntryInfo> listFolderEntries() const;

        /**
         * @brief does what it says
         * @param name the name of the entry
         */
        void removeFile(std::string const &name);

        /**
         * @brief removes a sub folder and all its content
         * @param name the name of the entry
         */
        void removeFolder(std::string const &name);

        /// loops through leaf folders looking for entry to invalidate
        void putMetaDataOutOfUse(std::string const &name);

        /// updates metadata filename with new filename
        void updateMetaDataWithNewFilename(std::string const &srcName,
                                           std::string const &dstName);

        void writeNewMetaDataForEntry(std::string const &name,
                                      EntryType const &entryType,
                                      uint64_t startBlock);

      private:
        void doAddContentFolder();

        void doPopulateContentFolders();

        /// remove an entry info from the cache with given name
        void doRemoveEntryFromCache(std::string const &name);

        // the underlying folder that stores index folders
        using SharedContentFolder = std::shared_ptr<ContentFolder>;
        mutable SharedContentFolder m_compoundFolder;

        // a compound folder will be composed of multiple sub-folders
        // which are there to build up a more efficient folder structure
        std::vector<SharedContentFolder> m_contentFolders;

        // stores the name of this folder
        std::string m_name;

        int m_ContentFolderCount;

        // optimization
        mutable EntryInfoCacheMap m_cache;

        // indicate when need to update cache map
        mutable bool m_cacheShouldBeUpdated;
    };

}

max_stars_repo_name: petrm/knoxcrypt

max_issues_repo_name: petrm/knoxcrypt

max_forks_repo_name: petrm/knoxcrypt


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/imaging/glf/glew.h"
#include "pxr/imaging/glf/contextCaps.h"

#include "pxr/imaging/hdSt/commandBuffer.h"
#include "pxr/imaging/hdSt/geometricShader.h"
#include "pxr/imaging/hdSt/immediateDrawBatch.h"
#include "pxr/imaging/hdSt/indirectDrawBatch.h"
#include "pxr/imaging/hdSt/resourceRegistry.h"

#include "pxr/imaging/hd/bufferArrayRange.h"
#include "pxr/imaging/hd/debugCodes.h"
#include "pxr/imaging/hd/perfLog.h"
#include "pxr/imaging/hd/tokens.h"

#include "pxr/base/gf/matrix4f.h"
#include "pxr/base/tf/diagnostic.h"
#include "pxr/base/tf/stl.h"

#include "pxr/base/work/loops.h"

#include <boost/functional/hash.hpp>

#include <tbb/enumerable_thread_specific.h>

#include <functional>

PXR_NAMESPACE_OPEN_SCOPE

HdStCommandBuffer::HdStCommandBuffer()
    : _visibleSize(0)
    , _visChangeCount(0)
    , _batchVersion(0)
{
    /*NOTHING*/
}

HdStCommandBuffer::~HdStCommandBuffer()
{
}

static
HdSt_DrawBatchSharedPtr
_NewDrawBatch(HdStDrawItemInstance * drawItemInstance)
{
    GlfContextCaps const &caps = GlfContextCaps::GetInstance();

    if (caps.multiDrawIndirectEnabled) {
        return HdSt_DrawBatchSharedPtr(
            new HdSt_IndirectDrawBatch(drawItemInstance));
    } else {
        return HdSt_DrawBatchSharedPtr(
            new HdSt_ImmediateDrawBatch(drawItemInstance));
    }
}

void
HdStCommandBuffer::PrepareDraw(
    HdStRenderPassStateSharedPtr const &renderPassState,
    HdStResourceRegistrySharedPtr const &resourceRegistry)
{
    HD_TRACE_FUNCTION();

    for (auto const& batch : _drawBatches) {
        batch->PrepareDraw(renderPassState, resourceRegistry);
    }
}

void
HdStCommandBuffer::ExecuteDraw(
    HdStRenderPassStateSharedPtr const &renderPassState,
    HdStResourceRegistrySharedPtr const &resourceRegistry)
{
    HD_TRACE_FUNCTION();

    //
    // TBD: sort draw items
    //

    // Reset per-commandBuffer performance counters, updated by batch execution
    HD_PERF_COUNTER_SET(HdPerfTokens->drawCalls, 0);
    HD_PERF_COUNTER_SET(HdTokens->itemsDrawn, 0);

    //
    // draw batches
    //
    for (auto const& batch : _drawBatches) {
        batch->ExecuteDraw(renderPassState, resourceRegistry);
    }
    HD_PERF_COUNTER_SET(HdPerfTokens->drawBatches, _drawBatches.size());

    if (!glBindBuffer) {
        // useful when testing with GL drawing disabled
        HD_PERF_COUNTER_SET(HdTokens->itemsDrawn, _visibleSize);
    }
}

void
HdStCommandBuffer::SwapDrawItems(std::vector<HdStDrawItem const*>* items,
                               unsigned currentBatchVersion)
{
    _drawItems.swap(*items);
    _RebuildDrawBatches();
    _batchVersion = currentBatchVersion;
}

void
HdStCommandBuffer::RebuildDrawBatchesIfNeeded(unsigned currentBatchVersion)
{
    HD_TRACE_FUNCTION();

    bool deepValidation
        = (currentBatchVersion != _batchVersion);

    for (auto const& batch : _drawBatches) {
        if (!batch->Validate(deepValidation) && !batch->Rebuild()) {
            TRACE_SCOPE("Invalid Batches");
            _RebuildDrawBatches();
            _batchVersion = currentBatchVersion;
            return;
        }
    }
    _batchVersion = currentBatchVersion;
}

void
HdStCommandBuffer::_RebuildDrawBatches()
{
    HD_TRACE_FUNCTION();

    _visibleSize = 0;

    _drawBatches.clear();
    _drawItemInstances.clear();
    _drawItemInstances.reserve(_drawItems.size());

    HD_PERF_COUNTER_INCR(HdPerfTokens->rebuildBatches);

    bool bindlessTexture = GlfContextCaps::GetInstance()
                                               .bindlessTextureEnabled;

    // XXX: Temporary sorting by shader.
    std::map<size_t, HdSt_DrawBatchSharedPtr> batchMap;

    for (size_t i = 0; i < _drawItems.size(); i++) {
        HdStDrawItem const * drawItem = _drawItems[i];

        if (!TF_VERIFY(drawItem->GetGeometricShader(), "%s",
                       drawItem->GetRprimID().GetText()) ||
            !TF_VERIFY(drawItem->GetMaterialShader(), "%s",
                       drawItem->GetRprimID().GetText())) {
            continue;
        }

        _drawItemInstances.push_back(HdStDrawItemInstance(drawItem));
        HdStDrawItemInstance* drawItemInstance = &_drawItemInstances.back();

        size_t key = drawItem->GetGeometricShader()->ComputeHash();
        boost::hash_combine(key, drawItem->GetBufferArraysHash());

        if (!bindlessTexture) {
            // Geometric, RenderPass and Lighting shaders should never break
            // batches, however materials can. We consider the material
            // parameters to be part of the batch key here for that reason.
            boost::hash_combine(key, HdMaterialParam::ComputeHash(
                            drawItem->GetMaterialShader()->GetParams()));
        }

        TF_DEBUG(HD_DRAW_BATCH).Msg("%lu (%lu)\n",
                key,
                drawItem->GetBufferArraysHash());
                //, drawItem->GetRprimID().GetText());

        HdSt_DrawBatchSharedPtr batch;
        TfMapLookup(batchMap, key, &batch);
        if (!batch || !batch->Append(drawItemInstance)) {
            batch = _NewDrawBatch(drawItemInstance);
            _drawBatches.push_back(batch);
            batchMap[key] = batch;
        }
    }
}

void
HdStCommandBuffer::SyncDrawItemVisibility(unsigned visChangeCount)
{
    HD_TRACE_FUNCTION();

    if (_visChangeCount == visChangeCount) {
        // There were no changes to visibility since the last time sync was
        // called, no need to re-sync now. Note that visChangeCount starts at
        // 0 in the class and starts at 1 in the change tracker, which ensures a
        // sync after contruction.
        return;
    }

    _visibleSize = 0;
    int const N = 10000;
    tbb::enumerable_thread_specific<size_t> visCounts;

    WorkParallelForN(_drawItemInstances.size()/N+1,
      [&visCounts, this, N](size_t start, size_t end) {
        TRACE_SCOPE("SetVis");
        start *= N;
        end = std::min(end*N, _drawItemInstances.size());
        size_t& count = visCounts.local();
        for (size_t i = start; i < end; ++i) {
            HdStDrawItem const* item = _drawItemInstances[i].GetDrawItem();

            bool visible = item->GetVisible();
            // DrawItemInstance->SetVisible is not only an inline function but
            // also internally calling virtual HdDrawBatch
            // DrawItemInstanceChanged.  shortcut by looking IsVisible(), which
            // is inline, if it's not actually changing.

            // however, if this is an instancing prim and visible, it always has
            // to be called since instanceCount may changes over time.
            if ((_drawItemInstances[i].IsVisible() != visible) ||
                (visible && item->HasInstancer())) {
                _drawItemInstances[i].SetVisible(visible);
            }
            if (visible) {
                ++count;
            }
        }
    });

    for (size_t i : visCounts) {
        _visibleSize += i;
    }

    // Mark visible state as clean;
    _visChangeCount = visChangeCount;
}

void
HdStCommandBuffer::FrustumCull(GfMatrix4d const &viewProjMatrix)
{
    HD_TRACE_FUNCTION();

    const bool
        mtCullingDisabled = TfDebug::IsEnabled(HD_DISABLE_MULTITHREADED_CULLING)
        || _drawItems.size() < 10000;

    struct _Worker {
        static
        void cull(std::vector<HdStDrawItemInstance> * drawItemInstances,
                GfMatrix4d const &viewProjMatrix,
                size_t begin, size_t end)
        {
            for(size_t i = begin; i < end; i++) {
                HdStDrawItemInstance& itemInstance = (*drawItemInstances)[i];
                HdStDrawItem const* item = itemInstance.GetDrawItem();
                bool visible = item->GetVisible() &&
                    item->IntersectsViewVolume(viewProjMatrix);
                if ((itemInstance.IsVisible() != visible) ||
                    (visible && item->HasInstancer())) {
                    itemInstance.SetVisible(visible);
                }
            }
        }
    };

    if (!mtCullingDisabled) {
        WorkParallelForN(_drawItemInstances.size(),
                         std::bind(&_Worker::cull, &_drawItemInstances,
                                   std::cref(viewProjMatrix),
                                   std::placeholders::_1,
                                   std::placeholders::_2));
    } else {
        _Worker::cull(&_drawItemInstances,
                      viewProjMatrix,
                      0,
                      _drawItemInstances.size());
    }

    _visibleSize = 0;
    for (auto const& instance : _drawItemInstances) {
        if (instance.IsVisible()) {
            ++_visibleSize;
        }
    }
}

void
HdStCommandBuffer::SetEnableTinyPrimCulling(bool tinyPrimCulling)
{
    for(auto const& batch : _drawBatches) {
        batch->SetEnableTinyPrimCulling(tinyPrimCulling);
    }
}

PXR_NAMESPACE_CLOSE_SCOPE

max_stars_repo_name: octarrow/USD

max_issues_repo_name: octarrow/USD

max_forks_repo_name: octarrow/USD


text:
// Copyright (c) 2019 The StakeWork Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <chainparams.h>
#include <consensus/dao.h>
#include <coins.h>
#include <random.h>
#include <uint256.h>
#include <test/test_stakework.h>
#include <main.h>

#include <vector>
#include <map>

#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(cfunddb_tests, BasicTestingSetup)

static const unsigned int NUM_SIMULATION_ITERATIONS = 250;

BOOST_AUTO_TEST_CASE(cfunddb_state)
{
    CStateViewDB *pcoinsdbview = new CStateViewDB(1<<23, true);
    CStateViewCache *base = new CStateViewCache(pcoinsdbview);
    CStateViewCache view(base);

    std::map<uint256, CProposal> result_p;
    std::map<uint256, CPaymentRequest> result_r;

    int nRemovedCount = 0;

    for (unsigned int i = 0; i < NUM_SIMULATION_ITERATIONS; i++) {
        CProposal proposal;
        CProposal proposal2;
        CPaymentRequest prequest;
        CPaymentRequest prequest2;
        CPaymentRequestMap mapPaymentRequests;
        CProposalMap mapProposals;

        // Empty entries are not found
        CProposal emptyProposal;
        emptyProposal.hash = GetRandHash();

        view.AddProposal(emptyProposal);

        BOOST_CHECK(!view.HaveProposal(emptyProposal.hash));
        BOOST_CHECK(!view.GetProposal(emptyProposal.hash, proposal));
        BOOST_CHECK(!base->HaveProposal(emptyProposal.hash));
        BOOST_CHECK(!base->GetProposal(emptyProposal.hash, proposal));
        BOOST_CHECK(view.GetAllProposals(mapProposals));
        BOOST_CHECK(mapProposals.size()==0+2*i-nRemovedCount);
        BOOST_CHECK(view.GetAllPaymentRequests(mapPaymentRequests));
        BOOST_CHECK(mapPaymentRequests.size()==0+i);

        CPaymentRequest emptyPaymentRequest;
        emptyPaymentRequest.hash = GetRandHash();

        view.AddPaymentRequest(emptyPaymentRequest);

        BOOST_CHECK(!view.HavePaymentRequest(emptyPaymentRequest.hash));
        BOOST_CHECK(!view.GetPaymentRequest(emptyPaymentRequest.hash, prequest));
        BOOST_CHECK(!base->HavePaymentRequest(emptyPaymentRequest.hash));
        BOOST_CHECK(!base->GetPaymentRequest(emptyPaymentRequest.hash, prequest));
        BOOST_CHECK(view.GetAllProposals(mapProposals));
        BOOST_CHECK(mapProposals.size()==0+2*i-nRemovedCount);
        BOOST_CHECK(view.GetAllPaymentRequests(mapPaymentRequests));
        BOOST_CHECK(mapPaymentRequests.size()==0+i);

        // Construct valid entries
        CProposal validProposal;
        std::string strDZeel = "{\"n\":5000000000,\"a\":\"NP3h1uzYuZX9k3xmT5sZsrEceRFW5kxo2N\",\"d\":604800,\"s\":\"test\",\"v\":2}";
        uint256 hash = GetRandHash();
        uint256 blockhash = GetRandHash();
        CAmount nFee = GetConsensusParameter(Consensus::CONSENSUS_PARAM_PROPOSAL_MIN_FEE, view);

        BOOST_CHECK(TxToProposal(strDZeel, hash, blockhash, nFee, validProposal));
        BOOST_CHECK(validProposal.hash == hash);
        BOOST_CHECK(validProposal.nAmount == 5000000000);
        BOOST_CHECK(validProposal.ownerAddress == "NP3h1uzYuZX9k3xmT5sZsrEceRFW5kxo2N");
        BOOST_CHECK(validProposal.paymentAddress == "NP3h1uzYuZX9k3xmT5sZsrEceRFW5kxo2N");
        BOOST_CHECK(validProposal.nDeadline == 604800);
        BOOST_CHECK(validProposal.strDZeel == "test");
        BOOST_CHECK(validProposal.nFee == nFee);
        BOOST_CHECK(validProposal.txblockhash == blockhash);

        CProposal validProposal2;
        std::string strDZeel2 = "{\"n\":5100000000,\"a\":\"NP3h1uzYuZX9k3xmT5sZsrEceRFW5kxo2N\",\"d\":604800,\"s\":\"test 2\",\"v\":2}";
        uint256 hash2 = GetRandHash();
        uint256 blockhash2 = GetRandHash();

        BOOST_CHECK(TxToProposal(strDZeel2, hash2, blockhash2, nFee, validProposal2));
        BOOST_CHECK(validProposal2.hash == hash2);
        BOOST_CHECK(validProposal2.nAmount == 5100000000);
        BOOST_CHECK(validProposal2.ownerAddress == "NP3h1uzYuZX9k3xmT5sZsrEceRFW5kxo2N");
        BOOST_CHECK(validProposal2.paymentAddress == "NP3h1uzYuZX9k3xmT5sZsrEceRFW5kxo2N");
        BOOST_CHECK(validProposal2.nDeadline == 604800);
        BOOST_CHECK(validProposal2.strDZeel == "test 2");
        BOOST_CHECK(validProposal2.nFee == nFee);
        BOOST_CHECK(validProposal2.txblockhash == blockhash2);

        CPaymentRequest validPaymentRequest;
        std::string strDZeel3 = "{\"h\":\"e8b46f55fd222cf269ab2eb935ba38cc7c9d19b775d9dd781fb6c7b88059bdde\",\"n\":500000000000,\"s\":\"HxYeRn96t7B4H6G2FB11N/8ZpxJ9JhzSLIdn/kqQDV8ZGtfW0EdGS0kUJaoji+RGyBIH1MeA1yctQq4+QC+54lA=\",\"r\":\"eI852p895a9EfFAy\",\"i\":\"test\",\"v\":2}";
        uint256 hash3 = GetRandHash();
        uint256 blockhash3 = GetRandHash();

        BOOST_CHECK(TxToPaymentRequest(strDZeel3, hash3, blockhash3, validPaymentRequest));
        BOOST_CHECK(validPaymentRequest.hash == hash3);
        BOOST_CHECK(validPaymentRequest.nAmount == 500000000000);
        BOOST_CHECK(validPaymentRequest.proposalhash == uint256S("e8b46f55fd222cf269ab2eb935ba38cc7c9d19b775d9dd781fb6c7b88059bdde"));
        BOOST_CHECK(validPaymentRequest.strDZeel == "test");
        BOOST_CHECK(validPaymentRequest.nVersion == 2);
        BOOST_CHECK(validPaymentRequest.txblockhash == blockhash3);

        // View can not have the entry before adding it
        BOOST_CHECK(!view.HaveProposal(hash));
        BOOST_CHECK(!view.HaveProposal(hash2));
        BOOST_CHECK(!view.HavePaymentRequest(hash3));
        BOOST_CHECK(!view.GetProposal(hash, proposal));
        BOOST_CHECK(!view.GetProposal(hash2, proposal));
        BOOST_CHECK(!view.GetPaymentRequest(hash3, prequest));
        BOOST_CHECK(!base->HaveProposal(hash));
        BOOST_CHECK(!base->HaveProposal(hash2));
        BOOST_CHECK(!base->HavePaymentRequest(hash3));
        BOOST_CHECK(!base->GetProposal(hash, proposal));
        BOOST_CHECK(!base->GetProposal(hash2, proposal));
        BOOST_CHECK(!base->GetPaymentRequest(hash3, prequest));
        BOOST_CHECK(view.GetAllProposals(mapProposals));
        BOOST_CHECK(mapProposals.size()==0+2*i-nRemovedCount);
        BOOST_CHECK(view.GetAllPaymentRequests(mapPaymentRequests));
        BOOST_CHECK(mapPaymentRequests.size()==0+i);

        view.AddProposal(validProposal);
        view.AddPaymentRequest(validPaymentRequest);

        // top view should see the added entries
        BOOST_CHECK(view.HaveProposal(hash));
        BOOST_CHECK(!view.HaveProposal(hash2));
        BOOST_CHECK(view.HavePaymentRequest(hash3));
        BOOST_CHECK(view.GetProposal(hash, proposal));
        BOOST_CHECK(!view.GetProposal(hash2, proposal2));
        BOOST_CHECK(view.GetPaymentRequest(hash3, prequest));
        BOOST_CHECK(proposal == validProposal);
        BOOST_CHECK(prequest == validPaymentRequest);
        BOOST_CHECK(view.GetAllProposals(mapProposals));
        BOOST_CHECK(mapProposals.size()==1+2*i-nRemovedCount);
        BOOST_CHECK(view.GetAllPaymentRequests(mapPaymentRequests));
        BOOST_CHECK(mapPaymentRequests.size()==1*(i+1));
        // but they should not be on base view
        BOOST_CHECK(!base->HaveProposal(hash));
        BOOST_CHECK(!base->GetProposal(hash, proposal));
        BOOST_CHECK(!base->HavePaymentRequest(hash3));
        BOOST_CHECK(!base->HaveProposal(hash2));
        BOOST_CHECK(!base->GetProposal(hash2, proposal2));
        BOOST_CHECK(!base->GetPaymentRequest(hash3, prequest));

        view.AddProposal(validProposal2);

        BOOST_CHECK(view.HaveProposal(hash));
        BOOST_CHECK(view.HaveProposal(hash2));
        BOOST_CHECK(view.GetProposal(hash, proposal));
        BOOST_CHECK(view.GetProposal(hash2, proposal2));
        BOOST_CHECK(proposal == validProposal);
        BOOST_CHECK(proposal2 == validProposal2);
        // entries are not on the base view yet
        BOOST_CHECK(!base->HaveProposal(hash));
        BOOST_CHECK(!base->GetProposal(hash, proposal));
        BOOST_CHECK(!base->HaveProposal(hash2));
        BOOST_CHECK(!base->GetProposal(hash2, proposal2));
        BOOST_CHECK(view.GetAllProposals(mapProposals));
        BOOST_CHECK(mapProposals.size()==2*(i+1)-nRemovedCount);
        BOOST_CHECK(view.GetAllPaymentRequests(mapPaymentRequests));
        BOOST_CHECK(mapPaymentRequests.size()==1*(i+1));

        BOOST_CHECK(view.Flush());

        // entries should be removed from the cache top view after flush
        BOOST_CHECK(!view.HaveProposalInCache(hash));
        BOOST_CHECK(!view.HaveProposalInCache(hash2));
        BOOST_CHECK(!view.HavePaymentRequestInCache(hash3));
        // but still visible with Have/Get
        BOOST_CHECK(view.HaveProposal(hash));
        BOOST_CHECK(view.HaveProposal(hash2));
        BOOST_CHECK(view.HavePaymentRequest(hash3));
        BOOST_CHECK(view.GetProposal(hash, proposal));
        BOOST_CHECK(view.GetProposal(hash2, proposal2));
        BOOST_CHECK(view.GetPaymentRequest(hash3, prequest));
        BOOST_CHECK(proposal == validProposal);
        BOOST_CHECK(proposal2 == validProposal2);
        BOOST_CHECK(prequest == validPaymentRequest);
        // after Get they should be back in cache
        BOOST_CHECK(view.HaveProposalInCache(hash));
        BOOST_CHECK(view.HaveProposalInCache(hash2));
        BOOST_CHECK(view.HavePaymentRequestInCache(hash3));
        // entries should be now present on the base view
        BOOST_CHECK(base->HaveProposal(hash));
        BOOST_CHECK(base->GetProposal(hash, proposal));
        BOOST_CHECK(base->HaveProposal(hash2));
        BOOST_CHECK(base->GetProposal(hash2, proposal2));
        BOOST_CHECK(base->HavePaymentRequest(hash3));
        BOOST_CHECK(base->GetPaymentRequest(hash3, prequest));
        BOOST_CHECK(proposal == validProposal);
        BOOST_CHECK(proposal2 == validProposal2);
        BOOST_CHECK(prequest == validPaymentRequest);

        view.RemoveProposal(hash2);
        view.RemovePaymentRequest(hash3);

        // entry should not exist on the top view already before flush
        BOOST_CHECK(!view.HaveProposal(hash2));
        BOOST_CHECK(!view.GetProposal(hash2, proposal2));
        BOOST_CHECK(!view.HavePaymentRequest(hash3));
        BOOST_CHECK(!view.GetPaymentRequest(hash3, prequest));
        // and they should be removed from the top view full list
        BOOST_CHECK(view.GetAllProposals(mapProposals));
        BOOST_CHECK(mapProposals.size()==1+2*i-nRemovedCount);
        BOOST_CHECK(view.GetAllPaymentRequests(mapPaymentRequests));
        BOOST_CHECK(mapPaymentRequests.size()==i);

        BOOST_CHECK(view.Flush());

        // removed entries should not be in the cache after flush
        BOOST_CHECK(!view.HaveProposalInCache(hash));
        BOOST_CHECK(!view.HaveProposalInCache(hash2));
        BOOST_CHECK(!view.HavePaymentRequestInCache(hash3));
        BOOST_CHECK(view.HaveProposal(hash));
        BOOST_CHECK(!view.HaveProposal(hash2));
        BOOST_CHECK(!view.HavePaymentRequest(hash3));
        BOOST_CHECK(view.GetProposal(hash, proposal));
        BOOST_CHECK(!view.GetProposal(hash2, proposal2));
        BOOST_CHECK(!view.GetPaymentRequest(hash3, prequest));
        BOOST_CHECK(proposal == validProposal);
        // gone from base view too
        BOOST_CHECK(base->HaveProposal(hash));
        BOOST_CHECK(base->GetProposal(hash, proposal));
        BOOST_CHECK(proposal == validProposal);
        BOOST_CHECK(!base->HaveProposal(hash2));
        BOOST_CHECK(!base->GetProposal(hash2, proposal2));
        BOOST_CHECK(!base->HavePaymentRequest(hash3));
        BOOST_CHECK(!base->GetPaymentRequest(hash3, prequest));

        view.AddProposal(validProposal2);
        view.AddPaymentRequest(validPaymentRequest);

        // we should be able to re add the entry
        BOOST_CHECK(view.HaveProposal(hash));
        BOOST_CHECK(view.HaveProposal(hash2));
        BOOST_CHECK(view.HavePaymentRequest(hash3));
        BOOST_CHECK(view.GetProposal(hash, proposal));
        BOOST_CHECK(view.GetProposal(hash2, proposal2));
        BOOST_CHECK(view.GetPaymentRequest(hash3, prequest));
        BOOST_CHECK(proposal == validProposal);
        BOOST_CHECK(proposal2 == validProposal2);
        BOOST_CHECK(prequest == validPaymentRequest);
        // it should not be in base view before flush
        BOOST_CHECK(base->HaveProposal(hash));
        BOOST_CHECK(base->GetProposal(hash, proposal));
        BOOST_CHECK(!base->HaveProposal(hash2));
        BOOST_CHECK(!base->GetProposal(hash2, proposal2));
        BOOST_CHECK(!base->HavePaymentRequest(hash3));
        BOOST_CHECK(!base->GetPaymentRequest(hash3, prequest));
        // but it should be in the top view full list
        BOOST_CHECK(view.GetAllProposals(mapProposals));
        BOOST_CHECK(mapProposals.size()==2*(i+1)-nRemovedCount);
        BOOST_CHECK(view.GetAllPaymentRequests(mapPaymentRequests));
        BOOST_CHECK(mapPaymentRequests.size()==1*(i+1));

        BOOST_CHECK(view.Flush());

        // it should not be in cache now
        BOOST_CHECK(!view.HaveProposalInCache(hash));
        BOOST_CHECK(!view.HaveProposalInCache(hash2));
        BOOST_CHECK(!view.HavePaymentRequestInCache(hash3));
        // top view should be able to see it
        BOOST_CHECK(view.HaveProposal(hash));
        BOOST_CHECK(view.HaveProposal(hash2));
        BOOST_CHECK(view.HavePaymentRequest(hash3));
        BOOST_CHECK(view.GetProposal(hash, proposal));
        BOOST_CHECK(view.GetProposal(hash2, proposal2));
        BOOST_CHECK(view.GetPaymentRequest(hash3, prequest));
        // then back in the top view cache
        BOOST_CHECK(view.HaveProposalInCache(hash));
        BOOST_CHECK(view.HaveProposalInCache(hash2));
        BOOST_CHECK(view.HavePaymentRequestInCache(hash3));
        // and still be in the top view full list
        BOOST_CHECK(view.GetAllProposals(mapProposals));
        BOOST_CHECK(mapProposals.size()==2*(i+1)-nRemovedCount);
        BOOST_CHECK(view.GetAllPaymentRequests(mapPaymentRequests));
        BOOST_CHECK(mapPaymentRequests.size()==1*(i+1));
        BOOST_CHECK(proposal == validProposal);
        BOOST_CHECK(proposal2 == validProposal2);
        BOOST_CHECK(prequest == validPaymentRequest);
        // should be present on base view now
        BOOST_CHECK(base->HaveProposal(hash));
        BOOST_CHECK(base->GetProposal(hash, proposal));
        BOOST_CHECK(base->HaveProposal(hash2));
        BOOST_CHECK(base->GetProposal(hash2, proposal2));
        BOOST_CHECK(base->HavePaymentRequest(hash3));
        BOOST_CHECK(base->GetPaymentRequest(hash3, prequest));
        BOOST_CHECK(proposal == validProposal);
        BOOST_CHECK(proposal2 == validProposal2);
        BOOST_CHECK(prequest == validPaymentRequest);

        BOOST_CHECK(view.Flush());

        BOOST_CHECK(!view.HaveProposalInCache(hash));
        BOOST_CHECK(!view.HavePaymentRequestInCache(hash3));

        // test modifying an entry
        {
            CProposalModifier mProposal = view.ModifyProposal(hash);
            mProposal->nVotesYes = 1;
        }

        {
            CPaymentRequestModifier mPaymentRequest = view.ModifyPaymentRequest(hash3);
            mPaymentRequest->nVotesYes = 2;
        }

        BOOST_CHECK(view.HaveProposalInCache(hash));
        BOOST_CHECK(view.HaveProposal(hash));
        BOOST_CHECK(view.GetProposal(hash, proposal));
        BOOST_CHECK(proposal.nVotesYes == 1);

        BOOST_CHECK(view.HavePaymentRequestInCache(hash3));
        BOOST_CHECK(view.HavePaymentRequest(hash3));
        BOOST_CHECK(view.GetPaymentRequest(hash3, prequest));
        BOOST_CHECK(prequest.nVotesYes == 2);

        // we try to modify it again before flush
        {
            CProposalModifier mProposal = view.ModifyProposal(hash);
            mProposal->nVotesNo = 1;
        }

        {
            CPaymentRequestModifier mPaymentRequest = view.ModifyPaymentRequest(hash3);
            mPaymentRequest->nVotesNo = 5;
        }

        BOOST_CHECK(view.HaveProposalInCache(hash));
        BOOST_CHECK(view.HaveProposal(hash));
        BOOST_CHECK(view.GetProposal(hash, proposal));
        BOOST_CHECK(proposal.nVotesYes == 1);
        BOOST_CHECK(proposal.nVotesNo == 1);

        BOOST_CHECK(view.HavePaymentRequestInCache(hash3));
        BOOST_CHECK(view.HavePaymentRequest(hash3));
        BOOST_CHECK(view.GetPaymentRequest(hash3, prequest));
        BOOST_CHECK(prequest.nVotesYes == 2);
        BOOST_CHECK(prequest.nVotesNo == 5);

        BOOST_CHECK(view.Flush());

        // we verify after flush

        BOOST_CHECK(!view.HaveProposalInCache(hash));
        BOOST_CHECK(view.HaveProposal(hash));
        BOOST_CHECK(view.GetProposal(hash, proposal));
        BOOST_CHECK(proposal.nVotesYes == 1);
        BOOST_CHECK(proposal.nVotesNo == 1);

        BOOST_CHECK(!view.HavePaymentRequestInCache(hash3));
        BOOST_CHECK(view.HavePaymentRequest(hash3));
        BOOST_CHECK(view.GetPaymentRequest(hash3, prequest));
        BOOST_CHECK(prequest.nVotesYes == 2);
        BOOST_CHECK(prequest.nVotesNo == 5);

        // and modify afain after flush
        {
            CProposalModifier mProposal = view.ModifyProposal(hash);
            mProposal->nVotesYes = 2;
        }

        {
            CPaymentRequestModifier mPaymentRequest = view.ModifyPaymentRequest(hash3);
            mPaymentRequest->nVotesNo = 7;
        }

        BOOST_CHECK(view.HaveProposalInCache(hash));
        BOOST_CHECK(view.HaveProposal(hash));
        BOOST_CHECK(view.GetProposal(hash, proposal));
        BOOST_CHECK(proposal.nVotesYes == 2);
        BOOST_CHECK(proposal.nVotesNo == 1);

        BOOST_CHECK(view.HavePaymentRequestInCache(hash3));
        BOOST_CHECK(view.HavePaymentRequest(hash3));
        BOOST_CHECK(view.GetPaymentRequest(hash3, prequest));
        BOOST_CHECK(prequest.nVotesYes == 2);
        BOOST_CHECK(prequest.nVotesNo == 7);

        result_p.insert(std::make_pair(hash, proposal));
        result_r.insert(std::make_pair(hash3, prequest));

        BOOST_CHECK(view.GetAllProposals(mapProposals));
        BOOST_CHECK(mapProposals.size()==2*(i+1)-nRemovedCount);

        BOOST_CHECK(view.GetAllPaymentRequests(mapPaymentRequests));
        BOOST_CHECK(mapPaymentRequests.size()==1*(i+1));

        // flip a coin to decide if a proposal should be removed before flushing the base view
        if (insecure_rand() % 5 == 0)
        {
            view.RemoveProposal(hash2);
            view.Flush();
            nRemovedCount++;
            BOOST_CHECK(view.GetAllProposals(mapProposals));
            BOOST_CHECK(mapProposals.size()==2*(i+1)-nRemovedCount);
        }
        else
        {
            result_p.insert(std::make_pair(hash2, validProposal2));
        }

        BOOST_CHECK(base->Flush());
    }

    CProposal proposal;
    CPaymentRequest prequest;

    for (auto& it: result_p)
    {
        BOOST_CHECK(view.HaveProposal(it.first));
        BOOST_CHECK(view.GetProposal(it.first, proposal));
        BOOST_CHECK(proposal == it.second);
    }

    for (auto& it: result_r)
    {
        BOOST_CHECK(view.HavePaymentRequest(it.first));
        BOOST_CHECK(view.GetPaymentRequest(it.first, prequest));
        BOOST_CHECK(prequest == it.second);
    }
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: stakecom/stakework

max_issues_repo_name: stakecom/stakework

max_forks_repo_name: stakecom/stakework


text:
#include <database/MySQLGunzDB.h>

#include <cstddef>
#include <cassert>

#include <boost/bind/bind.hpp>
#include <boost/function.hpp>

using namespace boost;
using namespace mysqlpp;

static void make_get_character_list_query(Query& q, uint32_t aid)
{
	q << "SELECT name,level,marker FROM `character` where accountid=" << aid << " ORDER BY marker ASC";
}

static SmallVector<CharacterEntry, 4> handle_get_character_list(const StoreQueryResult& result)
{
	typedef mysqlpp::StoreQueryResult::const_iterator ResultIt;

	SmallVector<CharacterEntry, 4> charList;

	assert(result.num_rows() <= 4);

	for(ResultIt i = result.begin(), end = result.end(); i != end; ++i)
	{
		const Row& row = *i;

		CharacterEntry character;
		character.index = row["marker"];
		character.level = row["level"];
		character.name = std::string(row["name"]);

		charList.push_back(character);
	}

	return charList;
}

SmallVector<CharacterEntry, 4> MySQLGunzDB::GetCharacterList(const AccountInfo& account)
{
	if(!account.isValid)
		throw InvalidAccountInfo();

	return run_query<SmallVector<CharacterEntry, 4> >(
		boost::bind(make_get_character_list_query, _1, (account.aid)),
		handle_get_character_list
	);
}

max_stars_repo_name: gogo-dev/GoGo

max_issues_repo_name: gogo-dev/GoGo

max_forks_repo_name: gogo-dev/GoGo


text: #include <boost/preprocessor/seq/for_each_i.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/*=============================================================================
    Copyright (c) 2001-2011 Joel de Guzman

    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)
==============================================================================*/
#if !defined(FUSION_SEQUENCE_10022005_0559)
#define FUSION_ITERATOR_10022005_0559

#include <boost/fusion/sequence/sequence_facade.hpp>
#include <boost/fusion/sequence/comparison.hpp>
#include <boost/fusion/sequence/intrinsic.hpp>
#include <boost/fusion/sequence/io.hpp>
#include <boost/fusion/sequence/convert.hpp>

#endif

max_stars_repo_name: PXLVision/opengv

max_issues_repo_name: isuhao/klib

max_forks_repo_name: isuhao/klib


text:
//==============================================================================
//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_TRIGONOMETRIC_CONSTANTS_INVPI_HPP_INCLUDED
#define NT2_TRIGONOMETRIC_CONSTANTS_INVPI_HPP_INCLUDED

#include <nt2/include/functor.hpp>
#include <boost/simd/constant/hierarchy.hpp>
#include <boost/simd/constant/register.hpp>

namespace nt2
{
  namespace tag
  {
   /*!
     @brief Invpi generic tag

     Represents the Invpi constant in generic contexts.

     @par Models:
        Hierarchy
   **/
    BOOST_SIMD_CONSTANT_REGISTER( Invpi, double
                                , 0, 0x3ea2f983
                                , 0x3fd45f306dc9c883ll
                                )
  }
  namespace ext
  {
   template<class Site, class... Ts>
   BOOST_FORCEINLINE generic_dispatcher<tag::Invpi, Site> dispatching_Invpi(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)
   {
     return generic_dispatcher<tag::Invpi, Site>();
   }
   template<class... Args>
   struct impl_Invpi;
  }
  /*!
    Constant\f$\frac1\pi\f$.

    @par Semantic:

    For type T0:

    @code
    T0 r = Invpi<T0>();
    @endcode

    is similar to:

    @code
    T0 r = rec(Pi<T0>());
    @endcode

    @return a value of type T0
  **/
  BOOST_SIMD_CONSTANT_IMPLEMENTATION(tag::Invpi, Invpi);
}

#endif


text:
/*
 * Rotor.cpp
 *
 *  Created on: 14-Jul-2008
 *      Author: malem303
 */

#include <boost/numeric/ublas/io.hpp>

#include "Rotor.h"
#include "Utils.h"
#include "CenterOfGravity.h"

Rotor::Rotor(int numberOfBlades, double radius, double chord, double linearMass, double delta3Angle, HubType hubType, double preconeAngle, double liftCurveSlope, vector<double> dragCoefficientParameters, double horizontalHubOffset, double verticalHubOffset, double hubSpringConstant, ControlRigging collectivePitchRigging, ControlRigging lateralSwashplateRigging, ControlRigging longitudinalSwashplateRigging, double twistAngle, matrix<double> selfInducedWashVelocityModel):
	IndividualElement(selfInducedWashVelocityModel), numberOfBlades(numberOfBlades), radius(radius), chord(chord), linearMass(linearMass),
	delta3Angle(delta3Angle), hubType(hubType), preconeAngle(preconeAngle), liftCurveSlope(liftCurveSlope),
	dragCoefficientParameters(dragCoefficientParameters), horizontalHubOffset(horizontalHubOffset), verticalHubOffset(verticalHubOffset),
	hubSpringConstant(hubSpringConstant), collectivePitch(collectivePitchRigging), twistAngle(twistAngle),
	lateralSwashplateAngle(lateralSwashplateRigging), longitudinalSwashplateAngle(longitudinalSwashplateRigging),
	coningAngle(0.0), longitudinalFlappingAngle(0.0), lateralFlappingAngle(0.0)
{
	// TODO Auto-generated constructor stub

}

Rotor::~Rotor() {
	// TODO Auto-generated destructor stub
}

void Rotor::computeAerodynamicVelocities(double density)
{
	// the rotor is a special case, since it closes the thrust-induced velocity loop
	// so we only want to consider the self induced wash velocity
	vector<double> externalWashVelocity = washVelocityIELA - computeSelfInducedWashVelocity(density);

	// then we substract externalWashVelocity from inertialVelocityIELA
	inertialVelocityIELA -= externalWashVelocity;

	// then we proceed as usual :
	IndividualElement::computeAerodynamicVelocities(density);
}

double Rotor::computeInfluenceFactor(IndividualElement * influencedElement)
{
	vector<double> distanceRotorFromElement = getDistanceIELAFromReferenceAxes() - influencedElement->getDistanceIELAFromReferenceAxes();

	double distanceRadiusRatio = Utils::vectorNorm(distanceRotorFromElement) / radius;
	return (1 + (distanceRadiusRatio / sqrt(1 + pow(distanceRadiusRatio, 2.0))));
}

vector<double> Rotor::computeExternalWashInfluence(IndividualElement * influencedElement, double density)
{
	vector<double> selfInducedWashVelocity = computeSelfInducedWashVelocity(density);

	return Utils::toVec3(0.0, 0.0, computeInfluenceFactor(influencedElement) * selfInducedWashVelocity(2));

}
double Rotor::computeTipLossFactor(double thrustForceFactor) const
{
	double tipLossFactor = 1 - sqrt(2 * fabs(thrustForceFactor))/(float)numberOfBlades; // TODO confirm it is normal thrustForceFactor can be negative

	return (tipLossFactor < 0.9) ? 0.9 : tipLossFactor;
}
double Rotor::computeNormalizedLiftCoefficient(double thrustForceFactor) const
{
	// Dreier p.445
	return 6.0 * thrustForceFactor / computeSolidity();
}

double Rotor::computeNormalizedDragCoefficient(double thrustForceFactor) const
{
	double normalizedLiftCoefficient = computeNormalizedLiftCoefficient(thrustForceFactor);
	return dragCoefficientParameters(0) + normalizedLiftCoefficient * (dragCoefficientParameters(1) + normalizedLiftCoefficient*dragCoefficientParameters(2));
}

double Rotor::computeXForceFactor(double advanceRatio, double aerodynamicInflowRatio, double tipLossFactor, double epsilon0, vector<double> swashplateAngles, vector<double> flappingAngles, double normalizedAerodynamicRollVelocity, double normalizedAerodynamicPitchVelocity) const
{
	return (computeSolidity() * liftCurveSlope / 2.0) *
				(
						-(pow(tipLossFactor, 2.0) * advanceRatio / 2.0) * epsilon0
						+((tipLossFactor * advanceRatio / 2.0) * aerodynamicInflowRatio  - (pow(tipLossFactor, 3.0) / 3) * flappingAngles(1)) * swashplateAngles(0)
						+((pow(tipLossFactor, 2.0) * advanceRatio / 4.0) * aerodynamicInflowRatio - (pow(tipLossFactor, 4.0) / 4.0) * flappingAngles(1)) * swashplateAngles(1)
						+((pow(tipLossFactor, 3.0)/ 6.0) * flappingAngles(0)) * (swashplateAngles(2) + flappingAngles(2))
						+((pow(tipLossFactor, 2.0) / 4.0) * aerodynamicInflowRatio - (pow(tipLossFactor, 2.0) * advanceRatio / 4.0) * flappingAngles(1)) * swashplateAngles(3)
						-(3.0 * pow(tipLossFactor, 2.0) / 4.0) * aerodynamicInflowRatio * flappingAngles(1)
						-(pow(tipLossFactor, 2.0) * advanceRatio / 4.0) * (pow(flappingAngles(0), 2.0) + pow(flappingAngles(1), 2.0))
						+((pow(tipLossFactor, 3.0) / 6.0) * swashplateAngles(0) + (pow(tipLossFactor, 4.0) / 8.0) * swashplateAngles(1) + (pow(tipLossFactor, 2.0) / 2.0) * aerodynamicInflowRatio + (3 * pow(tipLossFactor, 2.0) * advanceRatio / 16.0) * swashplateAngles(3) + (pow(tipLossFactor, 2.0) * advanceRatio / 16.0) * flappingAngles(1) ) * normalizedAerodynamicRollVelocity
						+((pow(tipLossFactor, 3.0) / 6.0) * flappingAngles(0) + (pow(tipLossFactor, 2.0) * advanceRatio / 16.0) * swashplateAngles(2) + (pow(tipLossFactor, 2.0) * advanceRatio / 16.0) * flappingAngles(2) ) * normalizedAerodynamicPitchVelocity
				);
}

double Rotor::computeYForceFactor(double advanceRatio, double aerodynamicInflowRatio, double tipLossFactor, double epsilon0, vector<double> swashplateAngles, vector<double> flappingAngles, double normalizedAerodynamicRollVelocity, double normalizedAerodynamicPitchVelocity) const
{
	return (computeSolidity() * liftCurveSlope / 2.0) *
				(
						((pow(tipLossFactor, 3.0)/ 3.0 + tipLossFactor * pow(advanceRatio, 2.0) / 2.0) * flappingAngles(2) - (3.0 * pow(tipLossFactor, 2.0) * advanceRatio / 4.0) * flappingAngles(0)) * swashplateAngles(0)
						+((pow(tipLossFactor, 4.0)/ 4.0 + pow(tipLossFactor, 2.0) * pow(advanceRatio, 2.0) / 4.0) * flappingAngles(2) - (pow(tipLossFactor, 3.0) * advanceRatio / 2.0) * flappingAngles(0)) * swashplateAngles(1)
						+((pow(tipLossFactor, 2.0)/ 4.0) * aerodynamicInflowRatio + (pow(tipLossFactor, 2.0) * advanceRatio / 4.0) * flappingAngles(1)) * swashplateAngles(2)
						+(-(pow(tipLossFactor, 3.0)/ 6.0 + tipLossFactor * pow(advanceRatio, 2.0) / 2.0) * flappingAngles(0) + (pow(tipLossFactor, 2.0) * advanceRatio / 2.0) * flappingAngles(2)) * swashplateAngles(3)
						+((3.0 * pow(tipLossFactor, 2.0) / 4.0) * flappingAngles(2) - (3.0 * tipLossFactor * advanceRatio / 2.0) * flappingAngles(0)) * aerodynamicInflowRatio
						+((pow(tipLossFactor, 3.0) / 6.0) * flappingAngles(0) + (pow(tipLossFactor, 2.0) * advanceRatio / 4.0) * flappingAngles(2) - tipLossFactor * pow(advanceRatio, 2.0) * flappingAngles(0)) * flappingAngles(1)
						+((pow(tipLossFactor, 2.0) * advanceRatio / 16.0) * swashplateAngles(2) - (pow(tipLossFactor, 3.0) / 6.0) * flappingAngles(0) + (5.0 * pow(tipLossFactor, 2.0) * advanceRatio / 16.0) * flappingAngles(2)) * normalizedAerodynamicRollVelocity
						+((pow(tipLossFactor, 3.0) / 6.0) * swashplateAngles(0) + (pow(tipLossFactor, 4.0) / 8.0) * swashplateAngles(1) + (pow(tipLossFactor, 2.0) / 2.0) * aerodynamicInflowRatio + (pow(tipLossFactor, 2.0) * advanceRatio / 16.0) * swashplateAngles(3) + (7.0 * pow(tipLossFactor, 2.0) * advanceRatio / 16.0) * flappingAngles(1)) * normalizedAerodynamicPitchVelocity
				);
}

double Rotor::computeZForceFactor(double advanceRatio, double aerodynamicInflowRatio, double tipLossFactor, double epsilon0, vector<double> swashplateAngles, double normalizedAerodynamicRollVelocity) const
{
	return -(computeSolidity()*liftCurveSlope / 2.0)* // TODO : verify this sign

				(
						(pow(tipLossFactor, 3)/3.0 + pow(advanceRatio, 2.0) * tipLossFactor/2.0) * swashplateAngles(0)
						+(pow(tipLossFactor, 4)/4.0 + pow(advanceRatio, 2.0) * pow(tipLossFactor, 2)/4.0) * swashplateAngles(1)
						+(pow(tipLossFactor, 2)/2.0 + pow(advanceRatio, 2.0)/4.0)*(1 + epsilon0) * aerodynamicInflowRatio
						+(advanceRatio * pow(tipLossFactor, 2)/2.0 + pow(advanceRatio, 3.0)/8.0) * swashplateAngles(3)
						+(advanceRatio * pow(tipLossFactor, 2)/4.0) * (1 + epsilon0) * normalizedAerodynamicRollVelocity
				);
}

double Rotor::computeXMomentFactor(double advanceRatio, double aerodynamicInflowRatio, double tipLossFactor, double epsilon0, vector<double> swashplateAngles, vector<double> flappingAngles, double normalizedAerodynamicRollVelocity) const
{
	return -(computeSolidity()*liftCurveSlope / 2.0)*
				(
						(pow(tipLossFactor, 3.0) * advanceRatio /3.0) * swashplateAngles(0)
						+(pow(tipLossFactor, 4.0) * advanceRatio / 4.0) * swashplateAngles(1)
						+(pow(tipLossFactor, 2.0) * advanceRatio / 4.0) * aerodynamicInflowRatio
						+(pow(tipLossFactor, 4.0) * advanceRatio / 8.0) * normalizedAerodynamicRollVelocity
						+(pow(tipLossFactor, 4.0)/8.0 + 3 * pow(tipLossFactor, 2.0) * pow(advanceRatio, 2.0) / 16.0) * swashplateAngles(3)
						-(pow(tipLossFactor, 4.0)/8.0 + pow(tipLossFactor, 2.0) * pow(advanceRatio, 2.0) / 16.0) * flappingAngles(1)
				);
}

double Rotor::computeYMomentFactor(double advanceRatio, double aerodynamicInflowRatio, double tipLossFactor, double epsilon0, vector<double> swashplateAngles, vector<double> flappingAngles, double normalizedAerodynamicPitchVelocity) const
{
	return -(computeSolidity()*liftCurveSlope / 2.0)*
				(
						-(pow(tipLossFactor, 3.0) * advanceRatio /3.0) * flappingAngles(0)
						+(pow(tipLossFactor, 4.0) * advanceRatio / 8.0) * normalizedAerodynamicPitchVelocity
						+(pow(tipLossFactor, 4.0)/8.0 + pow(tipLossFactor, 2.0) * pow(advanceRatio, 2.0) / 16.0) * swashplateAngles(2)
						+(pow(tipLossFactor, 4.0)/8.0 + pow(tipLossFactor, 2.0) * pow(advanceRatio, 2.0) / 16.0) * flappingAngles(2)
				);
}

double Rotor::computeZFlappingMomentFactor(double advanceRatio, double aerodynamicInflowRatio, double tipLossFactor, double epsilon0, vector<double> swashplateAngles, vector<double> flappingAngles) const
{
	return (computeSolidity()*liftCurveSlope / 2.0)*
				(
						(pow(tipLossFactor, 4.0) / 4.0 + pow(tipLossFactor, 2.0) * pow(advanceRatio, 2.0) / 4.0) * epsilon0
						-((pow(tipLossFactor, 3.0)/3.0) * swashplateAngles(0) + (pow(tipLossFactor, 4.0)/4.0) * swashplateAngles(1) + (pow(tipLossFactor, 2.0)/2.0) * aerodynamicInflowRatio) * aerodynamicInflowRatio
						-(pow(tipLossFactor, 2.0) * pow(advanceRatio, 2.0) / 4.0) * pow(flappingAngles(0), 2.0)
						-(pow(tipLossFactor, 4.0)/8.0 + 3 * pow(tipLossFactor, 2.0) * pow(advanceRatio, 2.0) / 16.0) * pow(flappingAngles(1), 2.0)
						-(pow(tipLossFactor, 4.0)/8.0 + pow(tipLossFactor, 2.0) * pow(advanceRatio, 2.0) / 16.0) * pow(flappingAngles(2), 2.0)
						+(pow(tipLossFactor, 3.0) * advanceRatio/3.0) * flappingAngles(0) * flappingAngles(2)
						-(pow(tipLossFactor, 2.0) * advanceRatio/2.0) * flappingAngles(1) * aerodynamicInflowRatio
				);
}

double Rotor::computeZSwashplateMomentFactor(double advanceRatio, double aerodynamicInflowRatio, double tipLossFactor, vector<double> swashplateAngles, vector<double> flappingAngles) const
{
	return (computeSolidity()*liftCurveSlope / 2.0)*
				(
						(pow(tipLossFactor, 4.0)/8.0 - pow(tipLossFactor, 2.0) * pow(advanceRatio, 2.0) / 16.0) * swashplateAngles(3) * flappingAngles(1)
						-(pow(tipLossFactor, 2.0) * advanceRatio / 4.0) * swashplateAngles(3) * aerodynamicInflowRatio
						+(pow(tipLossFactor, 3.0) * advanceRatio / 6.0) * swashplateAngles(2) * flappingAngles(0)
						-(pow(tipLossFactor, 4.0) / 8.0 + pow(tipLossFactor, 2.0) * pow(advanceRatio, 2.0) / 16.0) * swashplateAngles(2) * flappingAngles(2)
				);
}

double Rotor::computeZRollPitchMomentFactor(double advanceRatio, double aerodynamicInflowRatio, double tipLossFactor, vector<double> swashplateAngles, vector<double> flappingAngles, double normalizedAerodynamicRollVelocity, double normalizedAerodynamicPitchVelocity) const
{
	return (computeSolidity()*liftCurveSlope / 2.0)*
				(
						(-(pow(tipLossFactor, 4.0) / 8.0) * swashplateAngles(3) - (pow(tipLossFactor, 3.0) * advanceRatio / 6.0) * swashplateAngles(0) -(pow(tipLossFactor, 4.0) * advanceRatio / 8.0) * swashplateAngles(1) -(pow(tipLossFactor, 4.0) / 8.0) * normalizedAerodynamicRollVelocity + (pow(tipLossFactor, 4.0) / 4.0) * flappingAngles(1)) * normalizedAerodynamicRollVelocity
						+(-(pow(tipLossFactor, 4.0) / 8.0) * swashplateAngles(2) + (pow(tipLossFactor, 3.0) * advanceRatio / 3.0) * flappingAngles(0) -(pow(tipLossFactor, 4.0) / 8.0) * normalizedAerodynamicPitchVelocity - (pow(tipLossFactor, 4.0) / 4.0) * flappingAngles(2)) * normalizedAerodynamicPitchVelocity
				);
}

double Rotor::computeZMomentFactor(double advanceRatio, double aerodynamicInflowRatio, double tipLossFactor, double epsilon0, vector<double> swashplateAngles, vector<double> flappingAngles, double normalizedAerodynamicRollVelocity, double normalizedAerodynamicPitchVelocity) const
{
	return 	computeZFlappingMomentFactor(advanceRatio, aerodynamicInflowRatio, tipLossFactor, epsilon0, swashplateAngles, flappingAngles)
			+ computeZSwashplateMomentFactor(advanceRatio, aerodynamicInflowRatio, tipLossFactor, swashplateAngles, flappingAngles)
			+ computeZRollPitchMomentFactor(advanceRatio, aerodynamicInflowRatio, tipLossFactor, swashplateAngles, flappingAngles, normalizedAerodynamicRollVelocity, normalizedAerodynamicPitchVelocity);
}

double Rotor::solveImplicitThrustWashRelation(double & refTipLossFactor, double & refEpsilon0, double normalizedAerodynamicRollVelocity, vector<double> swashplateAngles, double advanceRatio, double inertialInflowRatio, double oldAerodynamicInflowRatio) const
{

	double oldWashInflowRatio = inertialInflowRatio - oldAerodynamicInflowRatio;

	refTipLossFactor = Constants::STANDARD_TIP_LOSS_FACTOR;
	refEpsilon0 = dragCoefficientParameters(0) / liftCurveSlope;

	for(int i = 0; i < 10; i++)
	{
		double inertialZForceFactor = computeZForceFactor(advanceRatio, inertialInflowRatio, refTipLossFactor, refEpsilon0, swashplateAngles, normalizedAerodynamicRollVelocity);

		double newWashInflowRatio = - inertialZForceFactor /
				(
				2 * sqrt(pow(advanceRatio, 2.0) + pow(oldAerodynamicInflowRatio, 2.0))
				+(computeSolidity()*liftCurveSlope / 2.0)*(pow(refTipLossFactor, 2)/2.0 + pow(advanceRatio, 2.0)/4.0)*(1 + refEpsilon0)
				);

		newWashInflowRatio = 0.8 * newWashInflowRatio + 0.2 * oldWashInflowRatio;

		double thrustForceFactor = - computeZForceFactor(advanceRatio, oldAerodynamicInflowRatio, refTipLossFactor, refEpsilon0, swashplateAngles, normalizedAerodynamicRollVelocity);

		refTipLossFactor = computeTipLossFactor(thrustForceFactor);
		refEpsilon0 = computeEpsilon0(thrustForceFactor);

		oldWashInflowRatio = newWashInflowRatio;
		oldAerodynamicInflowRatio = inertialInflowRatio - newWashInflowRatio;

	}

	return oldAerodynamicInflowRatio;
}

double Rotor::computeConingAngle(HubType hubtype, double coningAngle, double precone)
{
	if (hubtype == TEETERING)
		return coningAngle;
	else
		return precone;
}

double Rotor::computeEpsilon0(double thrustForceFactor) const
{
	return computeNormalizedDragCoefficient(thrustForceFactor) / liftCurveSlope;
}

double Rotor::computeInflowRatio(vector<double> velocity, double tangentialVelocity) const
{
	return velocity(2)/ tangentialVelocity;
}

double Rotor::computeLockNumber(double density) const
{
    return (density * chord * liftCurveSlope * pow(radius, 4.0)) / computeBladeInertialMoment();
}

double Rotor::computeSolidity() const
{
    return (this->numberOfBlades * this->chord * M_1_PI) / this->radius ;
}

double Rotor::computeBladeFisrtMassMoment() const
{
    return linearMass * pow(radius, 2.0) / 2.0;;
}

double Rotor::computeBladeInertialMoment() const
{
    return linearMass * pow(radius, 3.0) / 3.0;
}

double Rotor::computeAdvanceRatio(vector<double> velocity, double tangentialVelocity) const
{
	return velocity(0) / tangentialVelocity;
}

double Rotor::computeAerodynamicTangentialVelocity(vector<double> aerodynamicAngularVelocity, double distanceFromRoot) const
{
	return computeAerodynamicRotorVelocity(aerodynamicAngularVelocity) * distanceFromRoot;
}

double Rotor::computeAerodynamicRotorVelocity(vector<double> aerodynamicAngularVelocity) const
{
	return rotorVelocity - aerodynamicAngularVelocity(2);
}

double Rotor::computeInertialRotorVelocity(vector<double> inertialAngularVelocity) const
{
	return rotorVelocity - inertialAngularVelocity(2);
}
void Rotor::computeForcesAndMomentsAtIELA(IndividualElement & centerOfGravity, double density)
{

	matrix<double> transformationIERAFromIELA = Utils::transformationMatrix(rotationAnglesIERAFromIELA);

	vector<double> aerodynamicVelocityIERA = prod(transformationIERAFromIELA, aerodynamicVelocityIELA);
	vector<double> aerodynamicAngularVelocityIERA = prod(transformationIERAFromIELA, aerodynamicAngularVelocityIELA);
	vector<double> washVelocityIERA = prod(transformationIERAFromIELA, washVelocityIELA);
	vector<double> washAngularVelocityIERA = prod(transformationIERAFromIELA, washAngularVelocityIELA);
	vector<double> inertialVelocityIERA = prod(transformationIERAFromIELA, inertialVelocityIELA);
	vector<double> inertialAngularVelocityIERA = prod(transformationIERAFromIELA, inertialAngularVelocityIELA);

	// First we want to rotate to WindMast axes
	double windMastAngle = atan(aerodynamicVelocityIERA(1) / aerodynamicVelocityIERA(0));
	matrix<double> windMastRotationMatrix = Utils::rotationAroundAxisZ(windMastAngle);

	// Then we rotate all velocities, cyclic (swashplate) angles, flapping angles

    vector<double> aerodynamicVelocityWindMast = prod(windMastRotationMatrix, aerodynamicVelocityIERA);
    vector<double> aerodynamicAngularVelocityWindMast = prod(windMastRotationMatrix, aerodynamicAngularVelocityIERA);
    vector<double> washVelocityWindMast = prod(windMastRotationMatrix, washVelocityIERA);
    vector<double> washAngularVelocityWindMast = prod(windMastRotationMatrix, washAngularVelocityIERA);
    vector<double> inertialVelocityWindMast = prod(windMastRotationMatrix, inertialVelocityIERA);
    vector<double> inertialAngularVelocityWindMast = prod(windMastRotationMatrix, inertialAngularVelocityIERA);

    vector<double> tempVec = prod(windMastRotationMatrix, Utils::toVec3(lateralFlappingAngle, longitudinalFlappingAngle, computeConingAngle(hubType, coningAngle, preconeAngle)));
    vector<double> flappingAnglesWindMast = Utils::toVec3(tempVec(2), tempVec(1), tempVec(0));

    tempVec = prod(windMastRotationMatrix, Utils::toVec3(longitudinalSwashplateAngle.getDegreeOfFreedomAngle(), lateralSwashplateAngle.getDegreeOfFreedomAngle(), collectivePitch.getDegreeOfFreedomAngle()));
    double swashplateAnglesWindMastArray[4] = { tempVec(2), twistAngle, tempVec(1), tempVec(0) };
    vector<double> swashplateAnglesWindMast =  Utils::toVector(swashplateAnglesWindMastArray, 4);

    double inertialRotorVelocity = computeInertialRotorVelocity(inertialAngularVelocityWindMast);
    double normalizedAerodynamicRollVelocity = aerodynamicAngularVelocityWindMast(0) / inertialRotorVelocity;
    double normalizedAerodynamicPitchVelocity = aerodynamicAngularVelocityWindMast(1) / inertialRotorVelocity;
    double epsilon0;
    double tipLossFactor;

    double aerodynamicTangentialVelocityWindMast = computeAerodynamicTangentialVelocity(aerodynamicAngularVelocityWindMast, radius);
	double advanceRatio = computeAdvanceRatio(aerodynamicVelocityWindMast, aerodynamicTangentialVelocityWindMast);
	double inertialInflowRatio = computeInflowRatio(inertialVelocityWindMast, aerodynamicTangentialVelocityWindMast);
	double aerodynamicInflowRatio = computeInflowRatio(aerodynamicVelocityWindMast, aerodynamicTangentialVelocityWindMast);

    aerodynamicInflowRatio = solveImplicitThrustWashRelation(tipLossFactor, epsilon0, normalizedAerodynamicRollVelocity, swashplateAnglesWindMast, advanceRatio, inertialInflowRatio, aerodynamicInflowRatio);
    aerodynamicVelocityWindMast(2) = aerodynamicInflowRatio * computeAerodynamicTangentialVelocity(aerodynamicAngularVelocityWindMast, radius);

    CenterOfGravity & refCenterOfGravity = dynamic_cast<CenterOfGravity & >(centerOfGravity);
	vector<double>  inertialAngularVelocityDerivativeWindMast = prod(windMastRotationMatrix, refCenterOfGravity.getInertialAngularVelocityDerivativeCenterOfGravity());

	vector<double>  inertialVelocityDerivativeWindMast = prod(windMastRotationMatrix, refCenterOfGravity.getInertialVelocityDerivativeCenterOfGravity());

	// Solve the flapping equation
	double lockNumber = computeLockNumber(density);
	double aerodynamicRotorVelocity = computeAerodynamicRotorVelocity(aerodynamicAngularVelocityWindMast);
	double normalizedNaturalFlappingFrequency = computeNaturalFlappingFrequency(lockNumber, computeBladeInertialMoment(), inertialRotorVelocity) / inertialRotorVelocity;
	double normalizedRotorVelocity = aerodynamicRotorVelocity / inertialRotorVelocity;
	double normalizedInertialRollVelocity = inertialAngularVelocityWindMast(0) / aerodynamicRotorVelocity;
	double normalizedInertialPitchVelocity = inertialAngularVelocityWindMast(1) / aerodynamicRotorVelocity;

	vector<double> accelerationVector = buildAccelerationVector(normalizedInertialRollVelocity, normalizedInertialPitchVelocity, inertialRotorVelocity, inertialVelocityDerivativeWindMast, inertialAngularVelocityDerivativeWindMast);

	flappingAnglesWindMast = solveFlappingEquation(lockNumber, tipLossFactor, epsilon0, advanceRatio, aerodynamicInflowRatio, normalizedNaturalFlappingFrequency, normalizedRotorVelocity, normalizedAerodynamicRollVelocity, normalizedAerodynamicPitchVelocity, flappingAnglesWindMast, swashplateAnglesWindMast, accelerationVector);

	flappingAnglesWindMast(0) = computeConingAngle(hubType, flappingAnglesWindMast(0), preconeAngle);

	// compute Forces and moments
	double tangentialVelocity = computeAerodynamicTangentialVelocity(aerodynamicAngularVelocityWindMast, radius);
	double forceFactorCoefficient = density * M_PI * pow(radius, 2.0) * pow(tangentialVelocity, 2.0);
	double momentFactorCoefficient = density * M_PI * pow(radius, 3.0) * pow(tangentialVelocity, 2.0);

	vector<double> forcesWindMast = forceFactorCoefficient * Utils::toVec3
			(
			computeXForceFactor(advanceRatio, aerodynamicInflowRatio, tipLossFactor, epsilon0, swashplateAnglesWindMast, flappingAnglesWindMast, normalizedAerodynamicRollVelocity, normalizedAerodynamicPitchVelocity),
			computeYForceFactor(advanceRatio, aerodynamicInflowRatio, tipLossFactor, epsilon0, swashplateAnglesWindMast, flappingAnglesWindMast, normalizedAerodynamicRollVelocity, normalizedAerodynamicPitchVelocity),
			computeZForceFactor(advanceRatio, aerodynamicInflowRatio, tipLossFactor, epsilon0, swashplateAnglesWindMast, normalizedAerodynamicRollVelocity)
			);

	vector<double> momentsWindMast(3);
	switch(hubType)
	{
		case DELTA_3 : 			break; //TODO
		case OFFSET_HINGE : 	break; //TODO

		default :				momentsWindMast(0) = hubSpringConstant * flappingAnglesWindMast(2);
								momentsWindMast(1) = hubSpringConstant * flappingAnglesWindMast(1);
	}

	momentsWindMast(2) = momentFactorCoefficient * computeZMomentFactor(advanceRatio, aerodynamicInflowRatio, tipLossFactor, epsilon0, swashplateAnglesWindMast, flappingAnglesWindMast, normalizedAerodynamicRollVelocity, normalizedAerodynamicPitchVelocity);

	// rotate back to IERA

	vector<double> forcesIERA = prod(trans(windMastRotationMatrix), forcesWindMast);

	vector<double> momentsIERA = prod(trans(windMastRotationMatrix), momentsWindMast);

	aerodynamicVelocityIERA = prod(trans(windMastRotationMatrix), aerodynamicVelocityWindMast);
	//angular velocities are unchanged

	// rotate back to IELA

	aerodynamicVelocityIELA = prod(trans(Utils::transformationMatrix(rotationAnglesIERAFromIELA)), aerodynamicVelocityIERA);

	forcesIELA = prod(trans(Utils::transformationMatrix(rotationAnglesIERAFromIELA)), forcesIERA);
	momentsIELA = prod(trans(Utils::transformationMatrix(rotationAnglesIERAFromIELA)), momentsIERA);

	washVelocityIELA = inertialVelocityIELA - aerodynamicVelocityIELA;
	//angular velocities are unchanged

	// undo the WindMast rotation of the flapping angles
    tempVec = prod(trans(windMastRotationMatrix), Utils::toVec3(flappingAnglesWindMast(2), flappingAnglesWindMast(1), flappingAnglesWindMast(0)));

    coningAngle = tempVec(2);
    longitudinalFlappingAngle = tempVec(1);
    lateralFlappingAngle = tempVec(0);

}

vector<double> Rotor::solveFlappingEquation(double lockNumber, double tipLossFactor, double epsilon0, double advanceRatio, double aerodynamicInflowRatio, double normalizedNaturalFlappingFrequency, double normalizedRotorVelocity, double normalizedAerodynamicRollVelocity, double normalizedAerodynamicPitchVelocity, vector<double> flappingAngles, vector<double> swashplateAngles, vector<double> accelerationVector) const
{
    matrix<double> flappingMatrix = buildFlappingMatrix(advanceRatio, lockNumber, tipLossFactor, epsilon0, normalizedNaturalFlappingFrequency, normalizedRotorVelocity);
    matrix<double> swashplateMatrix = buildSwashplateMatrix(advanceRatio, lockNumber, tipLossFactor, normalizedRotorVelocity);
    matrix<double> ratioMatrix = buildRatioMatrix(advanceRatio, lockNumber, tipLossFactor, epsilon0, normalizedRotorVelocity);
    matrix<double> accelerationMatrix = buildAccelerationMatrix(computeBladeFisrtMassMoment(), computeBladeInertialMoment(), flappingAngles);
    vector<double> ratioVector = Utils::toVec3(aerodynamicInflowRatio, normalizedAerodynamicRollVelocity, normalizedAerodynamicPitchVelocity);

    return prod	(
				Utils::invertMatrix(flappingMatrix),
				prod(swashplateMatrix, swashplateAngles) + prod(ratioMatrix, ratioVector) + prod(accelerationMatrix, accelerationVector)
				);
}

matrix<double> Rotor::buildFlappingMatrix(double advanceRatio, double lockNumber, double tipLossFactor, double epsilon0, double normalizedNaturalFlappingFrequency, double normalizedRotorVelocity) const
{
	matrix<double> flappingMatrix(3,3);
    using namespace std;

//    cout << "adv : " << advanceRatio << " lock :" << lockNumber << " epsilon0 : " << epsilon0 << "norm nat flap : " << normalizedNaturalFlappingFrequency << " normalizedRotorVelocity : " << normalizedRotorVelocity << endl;

	flappingMatrix(0,0) = pow(normalizedNaturalFlappingFrequency, 2.0) / (lockNumber * pow(normalizedRotorVelocity, 2.0) / 2.0);
	flappingMatrix(0,1) = ((advanceRatio * pow(tipLossFactor, 3.0)) / (6 * normalizedRotorVelocity)) * (1 + epsilon0) * (1- normalizedRotorVelocity);
	flappingMatrix(0,2) = 0;

	flappingMatrix(1,0) = 0;
	flappingMatrix(1,1) = ((pow(tipLossFactor, 4.0)/(4.0 * normalizedRotorVelocity)) - (pow(tipLossFactor, 2.0) * pow(advanceRatio,2.0) / 8.0)) * (1 + epsilon0);
	flappingMatrix(1,2) = (1 - pow(normalizedNaturalFlappingFrequency, 2.0)) / (lockNumber * pow(normalizedRotorVelocity, 2.0) / 2.0);

	flappingMatrix(2,0) = (advanceRatio * pow(tipLossFactor, 3.0) / 3.0) * (1 + epsilon0);
	flappingMatrix(2,1) = (1 - pow(normalizedNaturalFlappingFrequency, 2.0)) / (lockNumber * pow(normalizedRotorVelocity, 2.0) / 2.0);
	flappingMatrix(2,2) = -((pow(tipLossFactor, 4.0)/(4.0 * normalizedRotorVelocity)) + (pow(tipLossFactor, 2.0) * pow(advanceRatio,2.0) / 8.0)) * (1 + epsilon0);

	return (lockNumber * pow(normalizedRotorVelocity, 2.0) / 2.0) * flappingMatrix;
}

matrix<double> Rotor::buildSwashplateMatrix(double advanceRatio, double lockNumber, double tipLossFactor, double normalizedRotorVelocity) const
{
	matrix<double> swashplateMatrix(3,4);

	swashplateMatrix(0,0) = (pow(tipLossFactor, 4.0)/4.0) + (pow(tipLossFactor, 2.0) * pow(advanceRatio,2.0) / 4.0);
	swashplateMatrix(0,1) = (pow(tipLossFactor, 5.0)/5.0) + (pow(tipLossFactor, 3.0) * pow(advanceRatio,2.0) / 6.0);
	swashplateMatrix(0,2) = 0;
	swashplateMatrix(0,3) = advanceRatio * pow(tipLossFactor, 3.0) / 3.0;

	swashplateMatrix(1,0) = 2 * pow(tipLossFactor, 3.0) * advanceRatio / 3.0;
	swashplateMatrix(1,1) = pow(tipLossFactor, 4.0) * advanceRatio /2.0;
	swashplateMatrix(1,2) = 0;
	swashplateMatrix(1,3) = (pow(tipLossFactor, 4.0)/4.0) + (3 * pow(tipLossFactor, 2.0) * pow(advanceRatio,2.0) / 8.0);

	swashplateMatrix(2,0) = 0;
	swashplateMatrix(2,1) = 0;
	swashplateMatrix(2,2) = (pow(tipLossFactor, 4.0)/4.0) + (pow(tipLossFactor, 2.0) * pow(advanceRatio,2.0) / 8.0);
	swashplateMatrix(2,3) = 0;

	return (lockNumber * pow(normalizedRotorVelocity, 2.0) / 2.0) * swashplateMatrix;
}

matrix<double> Rotor::buildRatioMatrix(double advanceRatio, double lockNumber, double tipLossFactor, double epsilon0, double normalizedRotorVelocity) const
{
	matrix<double> ratioMatrix(3,3);

	ratioMatrix(0,0) = pow(tipLossFactor, 3.0) / 3;
	ratioMatrix(0,1) = advanceRatio * pow(tipLossFactor, 3.0) / 6;
	ratioMatrix(0,2) = 0;

	ratioMatrix(1,0) = (advanceRatio * pow(tipLossFactor, 2.0) / 2) -( pow(advanceRatio, 3.0) / 8.0 ) ;
	ratioMatrix(1,1) = pow(tipLossFactor, 4.0)/4.0;
	ratioMatrix(1,2) = 0;

	ratioMatrix(2,0) = 0;
	ratioMatrix(2,1) = 0;
	ratioMatrix(2,2) = pow(tipLossFactor, 4.0)/4.0;

	return (lockNumber * pow(normalizedRotorVelocity, 2.0) * (1 + epsilon0) / 2.0) * ratioMatrix;
}

matrix<double> Rotor::buildAccelerationMatrix(double bladeFirstMassMoment, double bladeInertialMassMoment, vector<double> flappingAngles) const
{//TODO change for flappingAngles vector
	matrix<double> accelerationMatrix(3,7);
	accelerationMatrix(0,0) = 0;
	accelerationMatrix(0,1) = 0;
	accelerationMatrix(0,2) = 0;
	accelerationMatrix(0,3) = 0;
	accelerationMatrix(0,4) = -(bladeFirstMassMoment * radius * flappingAngles(1) / (2 * bladeInertialMassMoment));
	accelerationMatrix(0,5) = (bladeFirstMassMoment * radius * flappingAngles(2) / (2 * bladeInertialMassMoment));
	accelerationMatrix(0,6) = (bladeFirstMassMoment * radius) / (bladeInertialMassMoment);

	accelerationMatrix(1,0) = 0;
	accelerationMatrix(1,1) = -2;
	accelerationMatrix(1,2) = 1;
	accelerationMatrix(1,3) = 0;
	accelerationMatrix(1,4) = 0;
	accelerationMatrix(1,5) = -(bladeFirstMassMoment * radius * flappingAngles(0) / (bladeInertialMassMoment));
	accelerationMatrix(1,6) = 0;

	accelerationMatrix(2,0) = 2;
	accelerationMatrix(2,1) = 0;
	accelerationMatrix(2,2) = 0;
	accelerationMatrix(2,3) = 1;
	accelerationMatrix(2,4) = (bladeFirstMassMoment * radius * flappingAngles(0) / (bladeInertialMassMoment));
	accelerationMatrix(2,5) = 0;
	accelerationMatrix(2,6) = 0;

	return accelerationMatrix;
}

double Rotor::computeNaturalFlappingFrequency(double lockNumber, double bladeInertialMoment, double rotorVelocity) const
{
    return sqrt(pow(rotorVelocity, 2.0) * (1.0 + (3.0/2.0) * (horizontalHubOffset / (radius - horizontalHubOffset)) + (hubSpringConstant / (bladeInertialMoment * pow(rotorVelocity, 2.0)) + lockNumber * tan(delta3Angle)) / 8.0));
}

void Rotor::setCyclicAngles(double collectivePitch, double lateralSwashplateAngle, double longitudinalSwashplateAngle)
{
	setCollectivePitch(collectivePitch);
	setLateralSwashplateAngle(lateralSwashplateAngle);
	setLongitudinalSwashplateAngle(longitudinalSwashplateAngle);

}

void Rotor::setCyclicStickPosition(double collectivePitchStickPosition, double lateralSwashplateAngleStickPosition, double longitudinalSwashplateAngleStickPosition)
{
	setCollectivePitchStickPosition(collectivePitchStickPosition);
	setLateralSwashplateStickPosition(lateralSwashplateAngleStickPosition);
	setLongitudinalSwashplateStickPosition(longitudinalSwashplateAngleStickPosition);
}

double Rotor::computeflappingFunction(double azimuth, double distanceFromRoot) const
{
	double normalizedDistanceFromRoot = distanceFromRoot / radius;

	return coningAngle + twistAngle * normalizedDistanceFromRoot - longitudinalFlappingAngle * cos(azimuth) - lateralFlappingAngle * sin(azimuth);
}
vector<double> Rotor::buildAccelerationVector(double normalizedInertialRollVelocity, double normalizedInertialPitchVelocity, double inertialRotorVelocity, vector<double> inertialVelocityDerivative, vector<double> inertialAngularVelocityDerivative) const
{
	vector<double> accelerationVector(7);

	accelerationVector(0) = normalizedInertialRollVelocity;
	accelerationVector(1) = normalizedInertialPitchVelocity;
	accelerationVector(2) = inertialAngularVelocityDerivative(0) / pow(inertialRotorVelocity, 2.0);
	accelerationVector(3) = inertialAngularVelocityDerivative(1) / pow(inertialRotorVelocity, 2.0);
	accelerationVector(4) = inertialVelocityDerivative(0) / (radius * pow(inertialRotorVelocity, 2.0));
	accelerationVector(5) = inertialVelocityDerivative(1) / (radius * pow(inertialRotorVelocity, 2.0));
	accelerationVector(6) = inertialVelocityDerivative(2) / (radius * pow(inertialRotorVelocity, 2.0));

	return accelerationVector;
}

max_stars_repo_name: maxlem/SimurotorDreier

max_issues_repo_name: maxlem/SimurotorDreier

max_forks_repo_name: maxlem/SimurotorDreier


text:
#include <boost/exception/all.hpp>
#include <iostream>

using namespace std;

typedef boost::error_info<struct tag_errmsg, std::string> errmsg_info;
struct allocation_failed: public boost::exception, public std::exception {
	const char *what() const noexcept {
		return "allocation failed";
	}
};

char *allocate_memory(std::size_t size) {
	char *c = new (std::nothrow) char[size];
	if (!c)
		BOOST_THROW_EXCEPTION( allocation_failed { } );
	return c;
}
char *write_lots_of_zeros() {
	char * c = nullptr;
	try {
		c = allocate_memory(std::numeric_limits<std::size_t>::max());
		std::fill_n(c, std::numeric_limits<std::size_t>::max(), 0);
	} catch (boost::exception &e) {
		e << errmsg_info { "writing lots of zeros failed" };
	}

	return c;
}

int main() {
	cout << "----------  start  -----------------" << endl;
	try {
		char *c = write_lots_of_zeros();
		delete[] c;
	} catch (boost::exception &e) {
		std::cerr << boost::diagnostic_information(e);
	}

	cout << "----------  end  -----------------" << endl;
}


text:
#include "crit_heuristic.hpp"
#include <boost/assert.hpp>
#include <boost/heap/pairing_heap.hpp>
#include <cfloat>
#include <unordered_set>

sssp::heuristic::heuristic(const sssp::graph* graph, size_t start_node, const relaxation_heuristic& heuristic)
    : criteria(graph, start_node), m_heuristic(heuristic),
      m_node_info(graph->make_node_map([&](size_t node) { return node_info(*graph, heuristic, node); })) {

    node_info& start = m_node_info[start_node];
    if (start.unsettled_predecessors.empty() ||
        start.tentative_distance <= start.unsettled_predecessors.back().estimated_distance) {
        m_safe_to_relax.insert(start_node);
    }
}

void sssp::heuristic::relaxable_nodes(todo_output& output) const {
    output.insert(m_safe_to_relax.begin(), m_safe_to_relax.end());
}

void sssp::heuristic::changed_predecessor(size_t node, size_t predecessor, double distance) {
    BOOST_ASSERT(!m_node_info[node].settled);
    m_node_info[node].tentative_distance = distance;
}

void sssp::heuristic::relaxed_node(size_t node) {
    m_node_info[node].settled = true;

    auto iter = m_safe_to_relax.find(node);
    if (iter != m_safe_to_relax.end()) {
        m_safe_to_relax.erase(iter);
    }

    for (const auto& outgoing_edge : graph().outgoing_edges(node)) {
        node_info& successor = m_node_info[outgoing_edge.destination];
        while (!successor.unsettled_predecessors.empty() &&
               m_node_info[successor.unsettled_predecessors.back().index].settled) {
            successor.unsettled_predecessors.pop_back();
        }
        if (!successor.settled &&
            (successor.unsettled_predecessors.empty() ||
             successor.tentative_distance <= successor.unsettled_predecessors.back().estimated_distance)) {
            m_safe_to_relax.insert(successor.index);
        }
    }
}

sssp::heuristic::node_info::node_info(const sssp::graph& graph, const relaxation_heuristic& h, size_t index)
    : index(index) {
    for (const auto& incoming_edge : graph.incoming_edges(index)) {
        unsettled_predecessors.emplace_back(incoming_edge.source, h(incoming_edge.source) + incoming_edge.cost);
    }
    std::sort(unsettled_predecessors.begin(), unsettled_predecessors.end(), [](const auto& a, const auto& b) {
        return a.estimated_distance > b.estimated_distance;
    });
}

max_stars_repo_name: kaini/sssp-simulation

max_issues_repo_name: kaini/sssp-simulation

max_forks_repo_name: kaini/sssp-simulation


text:
#ifdef STAN_OPENCL
#include <stan/math/prim/mat.hpp>
#include <stan/math/opencl/multiply.hpp>
#include <stan/math/opencl/copy.hpp>
#include <stan/math/opencl/lower_tri_inverse.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <gtest/gtest.h>
#include <algorithm>

#define EXPECT_MATRIX_NEAR(A, B, DELTA) \
  for (int i = 0; i < A.size(); i++)    \
    EXPECT_NEAR(A(i), B(i), DELTA);

TEST(MathMatrixGPU, inverse_gpu_exception) {
  stan::math::matrix_d m1(2, 3);
  m1 << 1, 2, 3, 4, 5, 6;
  stan::math::matrix_cl m2(m1);
  stan::math::matrix_cl m3(2, 3);
  using stan::math::lower_triangular_inverse;
  EXPECT_THROW(m3 = lower_triangular_inverse(m2), std::invalid_argument);
}

void inverse_test(int size) {
  boost::random::mt19937 rng;
  auto m1 = stan::math::matrix_d(size, size);
  for (int i = 0; i < size; i++) {
    for (int j = 0; j < i; j++) {
      m1(i, j) = stan::math::uniform_rng(-5, 5, rng);
    }
    m1(i, i) = 10000.0;
    for (int j = i + 1; j < size; j++) {
      m1(i, j) = 0.0;
    }
  }
  stan::math::matrix_d m1_cpu(size, size);
  stan::math::matrix_d m1_cl(size, size);

  m1_cpu = stan::math::mdivide_left_tri<Eigen::Lower>(m1);

  stan::math::matrix_cl m2(m1);
  auto m3 = stan::math::lower_triangular_inverse(m2);
  stan::math::copy(m1_cl, m3);
  double max_error = 0;
  for (int i = 0; i < size; i++) {
    for (int j = 0; j <= i; j++) {
      double abs_err = std::fabs(m1_cpu(i, j) - m1_cl(i, j));
      double a = std::max(abs_err / m1_cpu(i, j), abs_err / m1_cl(i, j));
      max_error = std::max(max_error, a);
    }
  }
  EXPECT_LT(max_error, 1e-8);
}
TEST(MathMatrixGPU, inverse_gpu_small) { inverse_test(3); }

TEST(MathMatrixGPU, inverse_gpu_1under_block_size) { inverse_test(31); }

TEST(MathMatrixGPU, inverse_gpu_1over_block_size) { inverse_test(33); }

TEST(MathMatrixGPU, inverse_gpu_big) { inverse_test(512); }

TEST(MathMatrixGPU, inverse_gpu_big_2) { inverse_test(700); }

TEST(MathMatrixGPU, inverse_gpu_big_3) { inverse_test(1500); }
#endif

max_stars_repo_name: vchiapaikeo/prophet

max_issues_repo_name: vchiapaikeo/prophet

max_forks_repo_name: vchiapaikeo/prophet