text:
#include "PostgreSQLObsDBConnectionPool.h"
#include <macgyver/Exception.h>

#include <boost/foreach.hpp>

using namespace std;

namespace
{
template <class T>
struct Releaser
{
  Releaser(SmartMet::Engine::Observation::PostgreSQLObsDBConnectionPool* pool_handle)
      : poolHandle(pool_handle)
  {
  }
  void operator()(T* t) { poolHandle->releaseConnection(t->connectionId()); }
  SmartMet::Engine::Observation::PostgreSQLObsDBConnectionPool* poolHandle;
};
}  // namespace

namespace SmartMet
{
namespace Engine
{
namespace Observation
{
PostgreSQLObsDBConnectionPool::PostgreSQLObsDBConnectionPool(PostgreSQLDatabaseDriver* /* driver */)
{
}

bool PostgreSQLObsDBConnectionPool::addService(
    const Fmi::Database::PostgreSQLConnectionOptions& connectionOptions, int poolSize)
{
  try
  {
    itsConnectionOptions.push_back(connectionOptions);

    itsServicePool.push_back(static_cast<unsigned>(poolSize));
    itsPoolSize += static_cast<unsigned>(poolSize);
    itsWorkingList.resize(itsPoolSize, -1);
    itsWorkerList.resize(itsPoolSize);
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
  return true;
}

bool PostgreSQLObsDBConnectionPool::initializePool(const StationtypeConfig& stc,
                                                   const ParameterMapPtr& pm)
{
  try
  {
    unsigned int filled = 0;
    unsigned long tofill = itsServicePool[filled];
    for (unsigned int i = 0; i < itsWorkingList.size(); i++)
    {
      try
      {
        // Logon here

        itsWorkerList[i] = std::make_shared<PostgreSQLObsDB>(itsConnectionOptions[filled], stc, pm);
        itsWorkingList[i] = 0;
        itsWorkerList[i]->setConnectionId(static_cast<signed>(i));
        if (i == tofill)
        {
          filled++;
          if (filled < itsServicePool.size())
          {
            tofill += itsServicePool[filled];
          }
        }
      }
      catch (std::exception& err)
      {
        cerr << "PostgreSQLObsDBConnectionPool::initializePool: " << err.what() << endl;
        return false;
      }
      catch (...)
      {
        cerr << "PostgreSQLObsDBConnectionPool::initializePool: Unknown error." << endl;
        return false;
      }
    }

    // Everything is OK
    return true;
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

std::shared_ptr<PostgreSQLObsDB> PostgreSQLObsDBConnectionPool::getConnection(
    bool debug /*= false*/)
{
  try
  {
    /*
     *  1 --> active
     *  0 --> inactive
     *
     * Logic of returning connections:
     *
     * 1. Check if worker is idle, if so return that worker.
     * 2. Sleep and start over
     */
    size_t countTimeOut = 0;
    while (true)
    {
      // Local scope to minimize lock life time
      {
        SmartMet::Spine::WriteLock lock(itsGetMutex);
        for (std::size_t i = 0; i < itsWorkingList.size(); i++)
        {
          // We try the connections after the last taken one to go through all the members more
          // efficiently to keep the connections alive
          auto pos = (i + itsLastConnectionID + 1) % itsWorkingList.size();

          if (itsWorkingList[pos] == 0)
          {
            itsWorkingList[pos] = 1;
            itsWorkerList[pos]->setConnectionId(pos);
            itsWorkerList[pos]->setDebug(debug);
            itsLastConnectionID = pos;
            return std::shared_ptr<PostgreSQLObsDB>(itsWorkerList[pos].get(),
                                                    Releaser<PostgreSQLObsDB>(this));
          }
        }
      }

      // Fail after timeout seconds is reached.
      if (++countTimeOut > itsGetConnectionTimeOutSeconds)
      {
        throw Fmi::Exception(
            BCP, "Could not get a database connection. All the database connections are in use!");
      }
      else
      {
        // The timeout counter above assumes the sleep time here is one second. Should be rewritten.
        boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
      }
    }

    // NEVER EXECUTED:
    // throw Fmi::Exception(BCP,"[Observation] Could not get a connection in
    // PostgreSQLObsDBConnectionPool::getConnection()");
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Getting PostgreSQL connection failed!");
  }
}

// ----------------------------------------------------------------------
/*!
 * \brief Shutdown connections
 */
// ----------------------------------------------------------------------

void PostgreSQLObsDBConnectionPool::shutdown()
{
  try
  {
    std::cout << "  -- Shutdown requested (PostgreSQLObsDBConnectionPool)\n";
    for (auto& worker : itsWorkerList)
    {
      auto* sl = worker.get();
      if (sl != nullptr)
        sl->shutdown();
    }
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

void PostgreSQLObsDBConnectionPool::releaseConnection(int connectionId)
{
  try
  {
    // This mutex is not needed since writing the int is atomic. In fact, if there is a queue to
    // get connections, releasing a PostgreSQL back to the pool would have to compete against the
    // threads which are trying to get a connection. The more requests are coming, the less
    // chances we have of releasing the connection back to the pool, which may escalate the
    // problem - Mika

    // boost::mutex::scoped_lock lock(itsGetMutex);

    // Do "destructor" stuff here, because PostgreSQL instances are never destructed

    // Release the worker to the pool
    itsWorkingList[static_cast<unsigned>(connectionId)] = 0;
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

void PostgreSQLObsDBConnectionPool::setGetConnectionTimeOutSeconds(const size_t seconds)
{
  try
  {
    itsGetConnectionTimeOutSeconds = seconds;
  }
  catch (...)
  {
    throw Fmi::Exception::Trace(BCP, "Operation failed!");
  }
}

}  // namespace Observation
}  // namespace Engine
}  // namespace SmartMet

max_stars_repo_name: fmidev/smartmet-engine-observation

max_issues_repo_name: fmidev/smartmet-engine-observation

max_forks_repo_name: fmidev/smartmet-engine-observation


text:
#pragma once

#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/stringize.hpp>
#include <boost/preprocessor/cat.hpp>

#include "freq_index.hpp"
#include "positive_sequence.hpp"
#include "partitioned_sequence.hpp"
#include "uniform_partitioned_sequence.hpp"
#include "binary_freq_collection.hpp"
#include "block_freq_index.hpp"
#include "block_codecs.hpp"
#include "mixed_block.hpp"

namespace ds2i {

    typedef freq_index<compact_elias_fano,
                       positive_sequence<strict_elias_fano>> ef_index;

    typedef freq_index<indexed_sequence<>,
                       positive_sequence<>> single_index;

    typedef freq_index<
        uniform_partitioned_sequence<>,
        positive_sequence<uniform_partitioned_sequence<0, strict_sequence>>
        > uniform_index;

    typedef freq_index<
        partitioned_sequence<>,
        positive_sequence<partitioned_sequence<0, strict_sequence>>
        > opt_index;

    typedef block_freq_index<ds2i::optpfor_block> block_optpfor_index;
    typedef block_freq_index<ds2i::varint_G8IU_block> block_varint_index;
    typedef block_freq_index<ds2i::interpolative_block> block_interpolative_index;
    typedef block_freq_index<ds2i::qmx_block> block_qmx_index;
    typedef block_freq_index<ds2i::mixed_block> block_mixed_index;
}

#define DS2I_INDEX_TYPES (ef)(single)(uniform)(opt)(block_optpfor)(block_varint)(block_interpolative)(block_mixed)(block_qmx)
#define DS2I_BLOCK_INDEX_TYPES (block_optpfor)(block_varint)(block_interpolative)(block_qmx)(block_mixed)

ext: hpp


text: #include <boost/fusion/include/boost_tuple.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/*
Copyright (c) Members of the EGEE Collaboration. 2004.
See http://www.eu-egee.org/partners/ for details on the
copyright holders.

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.
*/

// File: main.cpp
// Author: Francesco Giacomini <Francesco.Giacomini@cnaf.infn.it>
//         Marco Cecchi <marco.cecchi@cnaf.infn.it>
// Copyright (c) 2002 EU DataGrid.

// $Id: main.cpp,v 1.1.2.10.2.4.2.2.2.1.2.2.2.4 2012/02/27 09:42:56 mcecchi Exp $

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cstdlib>
#include <unistd.h> // getpid()
#include <pwd.h> //getpwnam() passwd()

#include <boost/program_options.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread/mutex.hpp>

#include "glite/wms/common/configuration/Configuration.h"
#include "common/src/configuration/JCConfiguration.h"
#include "common/src/configuration/ICEConfiguration.h"
#include "common/src/configuration/WMConfiguration.h"
#include "common/src/configuration/NSConfiguration.h"
#include "common/src/configuration/CommonConfiguration.h"
#include "glite/wms/common/configuration/exceptions.h"
#include "glite/wms/common/logger/logstream_ts.h"
#include "glite/wms/common/logger/edglog.h"
#include "glite/wms/common/logger/logger_utils.h"
#include "glite/wms/common/utilities/input_reader.h"
#include "glite/wms/common/utilities/jobdir_reader.h"

#include "glite/wms/ism/ism.h"
#include "glite/wms/ism/purchaser/ism-purchaser.h"

#include "ism_utils.h"
#include "dynamic_library.h"
#include "signal_handling.h"
#include "events.h"
#include "wm_real.h"
#include "dispatcher_utils.h"
#include "replanner.h"
#include "recovery.h"
#include "lb_utils.h"

namespace po = boost::program_options;
namespace configuration = glite::wms::common::configuration;
namespace logger = glite::wms::common::logger;
namespace utilities = glite::wms::common::utilities;
namespace purchaser = glite::wms::ism::purchaser;
namespace ism = glite::wms::ism;

using namespace glite::wms::manager::server;

namespace {

std::fstream edglog_stream;

std::ostream* out_stream_p = &std::cout;
std::ostream* err_stream_p = &std::cerr;

class run_in_loop
{
  boost::function<void()> m_function;
  int m_period;
  Events& m_events;
  int priority;

public:
  run_in_loop(boost::function<void()> const& f, int s, Events& e, int p)
    : m_function(f), m_period(s), m_events(e), priority(p)
  { }
  void operator()()
  {
    m_function();
    m_events.schedule_at(
      *this,
      std::time(0) + m_period,
      priority
    );
  }
};

std::ostream& get_out_stream()
{
  return *out_stream_p;
}

void set_out_stream(std::ostream& os)
{
  out_stream_p = &os;
}

std::ostream& get_err_stream()
{
  return *err_stream_p;
}

void set_err_stream(std::ostream& os)
{
  err_stream_p = &os;
}

// change the uid and gid to those of user
// no-op if user corresponds to the current effective uid
// only root can set the uid
bool set_user(std::string const& user)
{
  uid_t euid = ::geteuid();

  if (euid == 0 && user.empty()) {
    return false;
  }

  ::passwd* pwd(::getpwnam(user.c_str()));
  if (pwd == 0) {
    return false;
  }
  ::uid_t uid = pwd->pw_uid;
  ::gid_t gid = pwd->pw_gid;

  return
    euid == uid
    || (euid == 0 && ::setgid(gid) == 0 && ::setuid(uid) == 0);
}

bool
is_recovery_enabled()
{
  configuration::Configuration const& config(
    *configuration::Configuration::instance()
  );

  return config.wm()->enable_recovery();
}

bool have_ism_threads()
{
  configuration::Configuration const& config(
    *configuration::Configuration::instance()
  );
  return config.wm()->ism_threads();
}

int ism_update_rate()
{
  configuration::Configuration const& config(
    *configuration::Configuration::instance()
  );
  return config.wm()->ism_update_rate();
}

std::string config_input()
{
  configuration::Configuration const& config(
    *configuration::Configuration::instance()
  );
  return config.wm()->input();
}

std::string get_ice_input()
{
  configuration::Configuration const& config(
    *configuration::Configuration::instance()
  );
  return config.ice()->input();
}

std::string get_jc_input()
{
  configuration::Configuration const& config(
    *configuration::Configuration::instance()
  );
  return config.jc()->input();
}

boost::shared_ptr<utilities::InputReader>
create_input_reader(
  std::string const& input
)
{
  boost::shared_ptr<utilities::InputReader> result;

  try {
    result.reset(new utilities::JobDirReader(input));
  } catch(utilities::JobDirError const& e) {
    Error(e.what());
  }

  return result;
}

} // {anonymous}

int
main(int argc, char* argv[])
try {

  std::string opt_conf_file;

  po::options_description desc("Usage");
  desc.add_options()
    ("help", "display this help and exit")
    (
      "daemon", "run in daemon mode"
    )
    (
      "conf",
      po::value<std::string>(&opt_conf_file)->default_value("glite_wms.conf"),
      "configuration file"
    )
    ;
  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);
  po::notify(vm);

  if (vm.count("help")) {
    get_out_stream() << desc << '\n';
    return EXIT_SUCCESS;
  }

  configuration::Configuration config(
    opt_conf_file,
    configuration::ModuleType::workload_manager
  );

  std::string dguser(config.common()->dguser());
  if (!set_user(dguser)) {
    get_err_stream() << "cannot set the user id to " << dguser << '\n';
    return EXIT_FAILURE;
  }

  if (vm.count("daemon")) {

    // init logger and adjust the err stream to use the same stream

    std::string log_file = config.wm()->log_file();
    if (!log_file.empty()) {
      if (!std::ifstream(log_file.c_str())) {
        std::ofstream(log_file.c_str());
      }
      edglog_stream.open(
        log_file.c_str(),
        std::ios::in | std::ios::out | std::ios::ate
      );
    }
    if (edglog_stream) {
      set_err_stream(edglog_stream);
      logger::threadsafe::edglog.open(
        edglog_stream,
        static_cast<logger::level_t>(config.wm()->log_level())
      );
    } else {
      get_err_stream() << "cannot open the log file " << log_file << '\n';
      return EXIT_FAILURE;
    }
    if (daemon(0, 0)) {
      get_err_stream() << "cannot become daemon (errno = "<< errno << ")\n";
      return EXIT_FAILURE;
    }
  } else { // not daemon

    logger::threadsafe::edglog.open(
      get_err_stream(),
      static_cast<logger::level_t>(config.wm()->log_level())
    );
  }

  Info("This is the gLite Workload Manager, running with pid " << ::getpid());

  std::string const broker_lib(config.wm()->broker_lib());
  if (broker_lib.empty()) {
    Error("empty BrokerLib attribute in configuration");
    return EXIT_FAILURE;
  }

  Info("loading broker dll " << broker_lib);
  DynamicLibrary broker_dll(
    broker_lib,
    DynamicLibrary::immediate_binding | DynamicLibrary::global_visibility
  );

  std::string const input(config_input());
  boost::shared_ptr<utilities::InputReader> input_reader(
    create_input_reader(input)
  );
  if (!input_reader) {
    Error(
      "cannot create input reader of type " << input_reader->name()
      << " from " << input_reader->source()
    );
    return EXIT_FAILURE;
  }
  Info(
    "created input reader of type " << input_reader->name()
    << " from " << input_reader->source()
  );

  boost::shared_ptr<utilities::JobDir> to_jc(
    new utilities::JobDir(get_jc_input())
  );
  boost::shared_ptr<utilities::JobDir> to_ice(
    new utilities::JobDir(get_ice_input())
  );

  // caching the jw template
  std::string template_file(
    config.wm()->job_wrapper_template_dir() + "/jobwrapper.template.sh"
  );
  std::ifstream ifs(template_file.c_str());
  if (!ifs) {
   get_err_stream() << "cannot open input file " << template_file;
   return EXIT_FAILURE;
  }
  std::ostringstream oss;
  oss << ifs.rdbuf();
  boost::shared_ptr<std::string> jw_template_ptr(
    new std::string(oss.str())
  );
  ifs.close();

  init_lb();
  Events event_processor;
  WMReal wm(to_jc, to_ice);

  if (is_recovery_enabled() && "jobdir" == input_reader->name()) {
    Info("starting recovery");
    recovery(
      input_reader,
      event_processor,
      wm,
      jw_template_ptr
    );
  } else {

    Info("skipping recovery");
  }

  glite::wms::manager::main::ISM_manager ism_manager; // first sync purchasing

  {
    if (!init_signal_handler()) {
      Error("cannot initialize signal handling");
      return EXIT_FAILURE;
    }
    // here comes multithreading
    SignalHandler sh(event_processor);
    // right after first synchronous purchasing, before any worker thread
    boost::thread::thread sht(sh);

    Info("spawning " << config.wm()->worker_threads() << " worker threads...");
    boost::thread_group worker_threads;
    for(int i = 0; i < config.wm()->worker_threads(); ++i) {
      worker_threads.add_thread(
        new boost::thread(boost::bind(&Events::run, &event_processor))
      );
    }

    Info("scheduling dispatcher...");
    Dispatcher dispatcher(
      event_processor,
      input_reader,
      wm,
      jw_template_ptr
    );
    event_processor.schedule(dispatcher);

    Info("scheduling ISM purchaser(s)...");
    std::vector<
      boost::shared_ptr<purchaser::ism_purchaser>
    >::const_iterator it = ism_manager.purchasers().begin();
    std::vector<boost::shared_ptr<
      purchaser::ism_purchaser>
    >::const_iterator const end = ism_manager.purchasers().end();

    boost::thread_group ism_threads;
    for ( ; it != end; ++it) {
      if (!have_ism_threads()) {
        // unfortunately, this cannot always be done safely
        event_processor.schedule(
          run_in_loop(
            boost::bind(
              &purchaser::ism_purchaser::operator(),
              *it
            ),
            (*it)->sleep_interval(),
            event_processor,
            ism_priority
          )
        );
      } else {
        ism_threads.add_thread(
          new boost::thread(
            boost::bind(
              &purchaser::ism_purchaser::operator(),
              *it
            )
          )
        );
      }
    }

    Info("scheduling ISM updater...");
    ism::call_update_ism_entries update_ism;
    if (!have_ism_threads()) {
      event_processor.schedule(
        run_in_loop(
          boost::bind(
            &ism::call_update_ism_entries::operator(),
            update_ism
          ),
          ism_update_rate(),
          event_processor,
          ism_priority
        )
      );
    } else {
      ism_threads.add_thread(
        new boost::thread(
          boost::bind(
            &ism::call_update_ism_entries::operator(),
            update_ism
          )
        )
      );
    }

    if (config.wm()->enable_replanner()) {
      Info("scheduling replanner...");
      boost::shared_ptr<ReplannerState> state;
      try {
        state.reset(
          new ReplannerState(
            wm,
            event_processor,
            jw_template_ptr
          )
        );
      } catch (CannotCreateLBContext const& e) {
        Error("Cannot create LB context for Replanner (" << e.what() << ')');
      }
      event_processor.schedule(
        Replanner(state),
        replanner_priority
      );
    }

    Info("WM startup completed...");
    worker_threads.join_all();
    ism_threads.join_all();
  } // dispatcher goes out of scope while worker threads have already
    // terminated, the ISM is still safely here

  exit(0); // nothing really important will be left at this point
} catch (CannotLoadDynamicLibrary const& e) {
  get_err_stream() << "cannot load dynamic library " << e.filename()
                   << ": " << e.error() << '\n';
  return EXIT_FAILURE;
} catch (utilities::JobDirError const& e) {
  Error(
    std::string(e.what()) + " while creating jobdir for either input or output"
  );
  return EXIT_FAILURE;
} catch (std::exception const& e) {
  get_err_stream() << "std::exception " << e.what() << "\n";
  return EXIT_FAILURE;
} catch (...) {
  get_err_stream() << "unknown exception\n";
  return EXIT_FAILURE;
}

ext: cpp

max_stars_repo_name: italiangrid/wms

max_issues_repo_name: italiangrid/wms

max_forks_repo_name: italiangrid/wms


text:
#include <vector>
#include "Drone.h"
#include <math.h>
#include <boost/asio/io_service.hpp>
#include <Fullnavdata.h>
#include <gnuplot_iostream.h>
#include <deque>

/*
 * PRIVATE HEADER
 */

#define DRONE_IP                    "10.42.0.10"
#define CALIBRATION_FILE            "res/calib_bd2.xml"
#define HULLPROTECTIONON            true

/*
 * UTILITY FUNCTIONS
 */
/**
 * Returns:
 *      value if value is inside [min; max],
 *      min if value < min,
 *      max if value > max
 * @param value
 * @param min
 * @param max
 * @return
 */
int interval(int value, int min, int max){
    if( min < value) {
        if( value < max){
            return value;
        }else{
            return max;
        }
    }else{
        return min;
    }
}

/**
 * Returns value if value is greater than +epsilon or lower than -epsilon. Otherwise, 0 is returned
 * @param value
 * @param epsilon
 * @return
 */
float valueIfAboveEpsilon(float value, float epsilon){
    if(0 < value and value < epsilon){
        return 0;
    }
    if( -epsilon < value and value < 0){
        return 0;
    }
    return value;

}

/*
 * MAIN
 */
int main(){

    /// ***************************************************************************** CONNECT TO AND CONFIGURE THE DRONE
    Drone d("10.42.0.10");
    Drone d2("10.42.0.11");
    assert(d.connect());
    assert(d2.connect());

    // Waiting for the drone to be ready
    while(!d.isRunning()){ sleep(1); }
    while(!d2.isRunning()){ sleep(1); }

    std::cout << "INITIALISATION IS OK" << std::endl;

    // Flat trim at start. The drone MUST be on the ground at that time
    if(d.blockingFlatTrim()) {
        std::cout << "FLAT TRIM IS OK" << std::endl;
    }else{
        std::cerr << "FLAT TRIM NOT OK" << std::endl;
        return 1;
    }
    // Flat trim at start. The drone MUST be on the ground at that time
    if(d2.blockingFlatTrim()) {
        std::cout << "FLAT TRIM IS OK" << std::endl;
    }else{
        std::cerr << "FLAT TRIM NOT OK" << std::endl;
        return 1;
    }
    assert(d.setHullPresence(HULLPROTECTIONON));
    assert(d2.setHullPresence(HULLPROTECTIONON));

    assert(d.setVideoAutorecord(false));
    assert(d2.setVideoAutorecord(false));
    //assert(d.stopStreaming());

    assert(d.useFullNavdata());
    assert(d2.useFullNavdata());
    sleep(1);
    assert(d.isUsingFullNavdata());
    assert(d2.isUsingFullNavdata());

    Gnuplot gp;
    gp << "set title \"10 Gyroscope (filt)\"\n";
    gp << "set ylabel \"rad/s\"\n";
    std::deque<float> x1;
    std::deque<float> y1;
    std::deque<float> z1;
    Eigen::Vector3f vec;

    Gnuplot gp2;
    gp2 << "set title \"11 Gyroscope (filt)\"\n";
    gp2 << "set ylabel \"m/s²\"\n";
    std::deque<float> x2;
    std::deque<float> y2;
    std::deque<float> z2;
    Eigen::Vector3f vec2;

/*
    Gnuplot gp3;
    gp3 << "set title \"Magnetometer (raw)\"\n";
    gp3 << "set ylabel \"mG\"\n";
    std::deque<float> x3;
    std::deque<float> y3;
    std::deque<float> z3;
    Eigen::Vector3f vec3;
*/
    while(true)
    {
        if (x1.size() > 150) {
            x1.pop_front();
            y1.pop_front();
            z1.pop_front();
        }

        if (x2.size() > 150) {
            x2.pop_front();
            y2.pop_front();
            z2.pop_front();
        }
/*
        if (x3.size() > 150) {
            x3.pop_front();
            y3.pop_front();
            z3.pop_front();
        }
*/
        d._navdata->lock();
        vec = d._navdata->get_gyroscope_filt();
        vec2 = d2._navdata->get_gyroscope_filt();
        //vec3 = d._navdata->get_magnetometer_raw();
        d._navdata->release();

        x1.push_back(vec(0));
        y1.push_back(vec(1));
        z1.push_back(vec(2));

        x2.push_back(vec2(0));
        y2.push_back(vec2(1));
        z2.push_back(vec2(2));
/*
        x3.push_back(vec3(0));
        y3.push_back(vec3(1));
        z3.push_back(vec3(2));
*/
        gp << "plot '-' binary" << gp.binFmt1d(x1, "array") << "with lines title \"x\",";
        gp << "'-' binary" << gp.binFmt1d(y1, "array") << "with lines title \"y\",";
        gp << "'-' binary" << gp.binFmt1d(z1, "array") << "with lines title \"z\"\n";

        gp.sendBinary1d(x1);
        gp.sendBinary1d(y1);
        gp.sendBinary1d(z1);

        gp.flush();

        gp2 << "plot '-' binary" << gp2.binFmt1d(x2, "array") << "with lines title \"x\",";
        gp2 << "'-' binary" << gp2.binFmt1d(y2, "array") << "with lines title \"y\",";
        gp2 << "'-' binary" << gp2.binFmt1d(z2, "array") << "with lines title \"z\"\n";

        gp2.sendBinary1d(x2);
        gp2.sendBinary1d(y2);
        gp2.sendBinary1d(z2);

        gp2.flush();

/*
        gp3 << "plot '-' binary" << gp3.binFmt1d(x3, "array") << "with lines title \"x\",";
        gp3 << "'-' binary" << gp3.binFmt1d(y3, "array") << "with lines title \"y\",";
        gp3 << "'-' binary" << gp3.binFmt1d(z3, "array") << "with lines title \"z\"\n";

        gp3.sendBinary1d(x3);
        gp3.sendBinary1d(y3);
        gp3.sendBinary1d(z3);

        gp3.flush();
*/
        // 100Hz
        usleep(25 * 1000);
    }

    return 0;
}


text:
/*
Author: Callum Roberts - N0689529

///////////////////////////////////////////////////////////////////////////////////////////
Unit test for - metres Route::maxElevation() const

Design:
-------
Max elevation has the possiablity of being either POSITIVE or NEGATIVE:
1. test for max elevation from a list of positve elevation values.
2. test for max elevation from a list of negative elevation values.
3. test for max elevation from a list of both positve and negative elevation values.

The value of the max elevation could occure multiple time in the same set of data:
4. test for max elevation where the max value occurs multiple times from a list of elevation values.
5. test where the max elevation is constant ie. all the elevation values in the list are the same.

The values in the list of elevations could be staggerd or ordered in a specific way, hence test different list patterns:
6. test for max elevation from a list of alterneting elevation values (high to low, high to low, etc).
7. test for max elevation from a list of alternating elevation values (low to high, low to high, etc).
8. test for max elevation from a list of assending elevation values.
9. test for max elevation from a list of desending elevation values.

Functions may not work with larger datasets:
10. test to see if max elevation is found within a large dataset

cases I did consider, but deemed unnecessary:
A. The maximum altitude on earth is Mt. Everest, so I could have potentially tested to see if a elevation exceeded this.
    if true then it could be incorrect, however if the data was recorded from a plane then this max alt could be exceeded.
B. test for max elevation from a list of randomly alternating elevation values - this was not implementes as it is already
    covered by other tests.

Structure:
---------
The structure of this test suite has been made this way to group together similar tests.
Test 1-3 are to do with testing positive and negative values within the datasets.
Test 4-5 are there to deal with multiple occurences of the same values within the datasets.
Test 6-9 are in place to test different ordering of the dataset values.
Finally test 10 is to see if large datasets can be handled by the function.

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

#include <boost/test/unit_test.hpp>

#include "logs.h"
#include "route.h"
#include "track.h"

using namespace GPS;

BOOST_AUTO_TEST_SUITE( max_elevation )

const bool isFileName = true;

// Tests for positive or negative max elevations:

// Test to see if correct max elevation is returned from only a positive dataset
BOOST_AUTO_TEST_CASE( positive_max_elevation ) {
    Route route = Route(LogFiles::GPXRoutesDir + "positive_elevation_n0689529.gpx", isFileName);
    BOOST_CHECK_CLOSE( route.maxElevation(), 20.000000, 0.001);
}

// Test to see if correct max elevation is returned from only a negative dataset
BOOST_AUTO_TEST_CASE( negative_max_elevation ) {
    Route route = Route(LogFiles::GPXRoutesDir + "negative_elevation_n0689529.gpx", isFileName);
    BOOST_CHECK_CLOSE( route.maxElevation(), -5.000000, 0.001);
}

// Test to see if correct max elevation is returned from a dataset containing
// both positive and negative elevation values
BOOST_AUTO_TEST_CASE( max_elevation_pos_neg_dataset ) {
    Route route = Route(LogFiles::GPXRoutesDir + "pos_neg_elevation_n0689529.gpx", isFileName);
    BOOST_CHECK_CLOSE( route.maxElevation(), 30.000000, 0.001);
}

// Tests for multiples of the same max elevation occuring:

// Test to see if correct max elevation is returned when there are multiple occurences
// of the max elevation at difference recorded points within the dataset
BOOST_AUTO_TEST_CASE( multiple_max_elevation_instances ) {
    Route route = Route(LogFiles::GPXRoutesDir + "multiple_instances_elevation_n0689529.gpx", isFileName);
    BOOST_CHECK_CLOSE( route.maxElevation(), 20.000000, 0.001);
}

// Test to see if max elevation is returned from a dataset where all elevation
// values are the same ie. the recoreded area is flat
BOOST_AUTO_TEST_CASE( flat_elevation ) {
    Route route = Route(LogFiles::GPXRoutesDir + "flat_elevation_n0689529.gpx", isFileName);
    BOOST_CHECK_CLOSE( route.maxElevation(), 0.000000, 0.001);
}

// Tests for max elevation from a dataset that follows a specific pattern

// Test to see if max elevation is returned from a dataset with
// alternating elevation values of high to low.
BOOST_AUTO_TEST_CASE( max_elevation_alternating_high_low ) {
    Route route = Route(LogFiles::GPXRoutesDir + "high_low_elevation_n0689529.gpx", isFileName);
    BOOST_CHECK_CLOSE( route.maxElevation(), 60.000000, 0.001);
}

// Test to see if mac elevation is returned from a dataset with
// alternating elevation values low to high
BOOST_AUTO_TEST_CASE( max_elevation_alternating_low_high ) {
    Route route = Route(LogFiles::GPXRoutesDir + "low_high_elevation_n0689529.gpx", isFileName);
    BOOST_CHECK_CLOSE( route.maxElevation(), 10.000000, 0.001);
}

// Test to see if max elevation is returned form a assending dataset
BOOST_AUTO_TEST_CASE( max_elevation_assending ) {
    Route route = Route(LogFiles::GPXRoutesDir + "assending_elevation_n0689529.gpx", isFileName);
    BOOST_CHECK_CLOSE( route.maxElevation(), 100.000000, 0.001);
}

// Test to see if max elevation is returned from a desending dataset
BOOST_AUTO_TEST_CASE( max_elevation_desending ) {
    Route route = Route(LogFiles::GPXRoutesDir + "desending_elevation_n0689529.gpx", isFileName);
    BOOST_CHECK_CLOSE( route.maxElevation(), 100.000000, 0.001);
}

// Tests for large file sizes:
BOOST_AUTO_TEST_CASE( max_elevation_in_large_dataset ) {
    Route route = Route(LogFiles::GPXRoutesDir + "NorthYorkMoors.gpx", isFileName);
    BOOST_CHECK_EQUAL( route.maxElevation(), 517);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: EdwinLangley/GPX-Route-and-Track

max_issues_repo_name: EdwinLangley/GPX-Route-and-Track

max_forks_repo_name: EdwinLangley/GPX-Route-and-Track


text:
/**

Copyright (c) 2016, Hanselmann Fabian, Heller Florian, Heizmann Heinrich, Kübler Marcel, Mehlhaus Jonas, Meißner Pascal, Qattan Mohamad, Reckling Reno, Stroh Daniel
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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#pragma once

//Pkg includes
#include <boost/shared_ptr.hpp>

//Local includes
#include "typedef.hpp"
#include "VotedPose.hpp"

namespace ISM
{

/**
* VotingBin class. Bin (VotingSpace element) into which votes are accumulated. Contains map from type,id to VotedPoses. See Meissner et al. 2013 , Sec. IV (B).
*/
class VotingBin {
public:
    TypeToInnerMap votes;
    int x, y, z;
    VotingBin(int x, int y, int z) : x(x), y(y), z(z) {}

    //Save reference pose vote according to type and id of the object from which it is coming.
    void insert(const VotedPosePtr& vote);
};

}


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

#include "che/io/file_pssm.h" // header to test

using namespace biosim;

BOOST_AUTO_TEST_SUITE(suite_file_pssm)

BOOST_AUTO_TEST_CASE(file_pssm_read) {
  che::assembly a(che::io::file_pssm::read("../test/data/P01236-short.pssm_ascii"));
  BOOST_CHECK(a.get_chain_id_list().size() == 1);
  BOOST_CHECK(a.get_first_structure("A").get_length() == 47);
  BOOST_CHECK(a.get_first_structure("A").get_ps().size() == 47);
  BOOST_CHECK(a.get_first_structure("A").get_ps()[0].get_identifier_char() == 'L');
  BOOST_CHECK(a.get_first_structure("A").get_ps()[0].get_specificity() == che::cc::specificity_type::secondary);
  BOOST_CHECK(a.get_first_structure("A").get_ss().defined() == false);

  a = che::io::file_pssm::read("../test/data/P01236-short-old-blast.pssm_ascii");
  BOOST_CHECK(a.get_chain_id_list().size() == 1);
  BOOST_CHECK(a.get_first_structure("A").get_length() == 47);
  BOOST_CHECK(a.get_first_structure("A").get_ps().size() == 47);
  BOOST_CHECK(a.get_first_structure("A").get_ps()[0].get_identifier_char() == 'L');
  BOOST_CHECK(a.get_first_structure("A").get_ps()[0].get_specificity() == che::cc::specificity_type::secondary);
  BOOST_CHECK(a.get_first_structure("A").get_ss().defined() == false);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: shze/biosim

max_issues_repo_name: shze/biosim

max_forks_repo_name: shze/biosim


text:
/*=============================================================================
    Copyright (c) 2001-2006 Joel de Guzman
    Copyright (c) 2007 Dan Marsden

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#include <boost/detail/lightweight_test.hpp>
#include <boost/fusion/container/vector/vector.hpp>
#include <boost/fusion/adapted/mpl.hpp>
#include <boost/fusion/sequence/io/out.hpp>
#include <boost/fusion/sequence/intrinsic/at.hpp>
#include <boost/fusion/container/generation/make_vector.hpp>
#include <boost/fusion/algorithm/iteration/fold.hpp>
#include <boost/fusion/algorithm/iteration/accumulate.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/next.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/vector.hpp>

#include <boost/type_traits/remove_const.hpp>
#include <boost/type_traits/remove_reference.hpp>
#include <boost/type_traits/is_reference.hpp>

#include <string>

using boost::mpl::if_;
using boost::mpl::int_;
using boost::is_same;

struct add_ints_only
{
    template<typename T>
    struct result;

    template <typename State, typename T>
    struct result<add_ints_only(State, T)>
    {
        typedef typename boost::remove_const<
            typename boost::remove_reference<State>::type>::type type;
    };

    template <typename State, typename T>
    State
    operator()(State const& state, T const& /*x*/) const
    {
        return state;
    }

    int
    operator()(int state, int x) const
    {
        return x + state;
    }
};

struct count_ints
{
    template<typename T>
    struct result;

    template <typename CountT, typename T>
    struct result<count_ints(CountT, T)>
    {
        typedef typename boost::remove_const<
            typename boost::remove_reference<CountT>::type>::type state;
        typedef typename boost::remove_const<
            typename boost::remove_reference<T>::type>::type elem;

        typedef typename
            if_<
                is_same<elem, int>
              , typename boost::mpl::next<state>::type
              , state
            >::type
        type;
    };

    template <typename CountT, typename T>
    typename result<count_ints(CountT, T)>::type
    operator()(CountT const&, T const&) const
    {
        typedef typename result<count_ints(CountT, T)>::type result_;
        return result_();
    }
};

struct appender
{
    typedef std::string result_type;

    std::string operator()(std::string const& str, char c) const
    {
        return str + c;
    }
};

struct lvalue_adder
{
    template<typename Sig>
    struct result;

    template<typename T0, typename T1>
    struct result<lvalue_adder(T0, T1&)>
    {
        // Second argument still needs to support rvalues - see definition of fusion::fold
        typedef T1 type;
    };

    template<typename T0, typename T1>
    T1 operator()(T0 const& lhs, T1& rhs) const
    {
        return lhs + rhs;
    }
};

int add(int lhs, int rhs)
{
    return lhs + rhs;
}

int
main()
{
    using namespace boost::fusion;
    namespace fusion = boost::fusion;

    {
        typedef vector<int, char, int, double> vector_type;
        vector_type v(12345, 'x', 678910, 3.36);
        int result = fold(v, 0, add_ints_only());
        std::cout << result << std::endl;
        BOOST_TEST(result == 12345+678910);
    }

    {
        typedef vector<int> vector_type;
        vector_type v(12345);

        int n = fusion::fold(v, int_<0>(), count_ints());
        std::cout << n << std::endl;
        BOOST_TEST(n == 1);
    }

    {
        typedef vector<int, char, int, double, int> vector_type;
        vector_type v(12345, 'x', 678910, 3.36, 8756);

        int n = fusion::fold(v, int_<0>(), count_ints());
        std::cout << n << std::endl;
        BOOST_TEST(n == 3);
    }

    {
        typedef boost::mpl::vector<int, char, int, double, int> mpl_vec;
        int n = fusion::fold(mpl_vec(), int_<0>(), count_ints());
        std::cout << n << std::endl;
        BOOST_TEST(n == 3);
    }

    {
        BOOST_TEST(fusion::fold(fusion::make_vector('a','b','c','d','e'), std::string(""), appender())
                   == "abcde");
    }

    {
        vector<int, int> vec(1,2);
        BOOST_TEST(fusion::fold(vec, 0, lvalue_adder()) == 3);
    }

    {
        vector<int, int> vec(1,2);
        BOOST_TEST(fusion::fold(vec, 0, add) == 3);
    }

    {
        typedef vector<int, char, int, double> vector_type;
        vector_type v(12345, 'x', 678910, 3.36);
        int result = accumulate(v, 0, add_ints_only());
        std::cout << result << std::endl;
        BOOST_TEST(result == 12345+678910);
    }

    {
        typedef vector<int> vector_type;
        vector_type v(12345);

        int n = fusion::accumulate(v, int_<0>(), count_ints());
        std::cout << n << std::endl;
        BOOST_TEST(n == 1);
    }

    {
        typedef vector<int, char, int, double, int> vector_type;
        vector_type v(12345, 'x', 678910, 3.36, 8756);

        int n = fusion::accumulate(v, int_<0>(), count_ints());
        std::cout << n << std::endl;
        BOOST_TEST(n == 3);
    }

    {
        typedef boost::mpl::vector<int, char, int, double, int> mpl_vec;
        int n = fusion::accumulate(mpl_vec(), int_<0>(), count_ints());
        std::cout << n << std::endl;
        BOOST_TEST(n == 3);
    }

    {
        BOOST_TEST(fusion::accumulate(fusion::make_vector('a','b','c','d','e'), std::string(""), appender())
                   == "abcde");
    }

    {
        vector<int, int> vec(1,2);
        BOOST_TEST(fusion::accumulate(vec, 0, add) == 3);
    }

    return boost::report_errors();
}

max_stars_repo_name: zyiacas/boost-doc-zh

max_issues_repo_name: sdfict/boost-doc-zh

max_forks_repo_name: sdfict/boost-doc-zh


text:
//  (C) Copyright John Maddock 2006.
//  Use, modification and distribution are subject to the
//  Boost Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

//
// This is not a complete header file, it is included by gamma.hpp
// after it has defined it's definitions.  This inverts the incomplete
// gamma functions P and Q on the first parameter "a" using a generic
// root finding algorithm (TOMS Algorithm 748).
//

#ifndef BOOST_MATH_SP_DETAIL_GAMMA_INVA
#define BOOST_MATH_SP_DETAIL_GAMMA_INVA

#ifdef _MSC_VER
#pragma once
#endif

#include <boost/math/tools/toms748_solve.hpp>
#include <boost/cstdint.hpp>

namespace boost{ namespace math{ namespace detail{

template <class T, class Policy>
struct gamma_inva_t
{
   gamma_inva_t(T z_, T p_, bool invert_) : z(z_), p(p_), invert(invert_) {}
   T operator()(T a)
   {
      return invert ? p - boost::math::gamma_q(a, z, Policy()) : boost::math::gamma_p(a, z, Policy()) - p;
   }
private:
   T z, p;
   bool invert;
};

template <class T, class Policy>
T inverse_poisson_cornish_fisher(T lambda, T p, T q, const Policy& pol)
{
   BOOST_MATH_STD_USING
   // mean:
   T m = lambda;
   // standard deviation:
   T sigma = sqrt(lambda);
   // skewness
   T sk = 1 / sigma;
   // kurtosis:
   // T k = 1/lambda;
   // Get the inverse of a std normal distribution:
   T x = boost::math::erfc_inv(p > q ? 2 * q : 2 * p, pol) * constants::root_two<T>();
   // Set the sign:
   if(p < 0.5)
      x = -x;
   T x2 = x * x;
   // w is correction term due to skewness
   T w = x + sk * (x2 - 1) / 6;
   /*
   // Add on correction due to kurtosis.
   // Disabled for now, seems to make things worse?
   //
   if(lambda >= 10)
      w += k * x * (x2 - 3) / 24 + sk * sk * x * (2 * x2 - 5) / -36;
   */
   w = m + sigma * w;
   return w > tools::min_value<T>() ? w : tools::min_value<T>();
}

template <class T, class Policy>
T gamma_inva_imp(const T& z, const T& p, const T& q, const Policy& pol)
{
   BOOST_MATH_STD_USING  // for ADL of std lib math functions
   //
   // Special cases first:
   //
   if(p == 0)
   {
      return tools::max_value<T>();
   }
   if(q == 0)
   {
      return tools::min_value<T>();
   }
   //
   // Function object, this is the functor whose root
   // we have to solve:
   //
   gamma_inva_t<T, Policy> f(z, (p < q) ? p : q, (p < q) ? false : true);
   //
   // Tolerance: full precision.
   //
   tools::eps_tolerance<T> tol(policies::digits<T, Policy>());
   //
   // Now figure out a starting guess for what a may be,
   // we'll start out with a value that'll put p or q
   // right bang in the middle of their range, the functions
   // are quite sensitive so we should need too many steps
   // to bracket the root from there:
   //
   T guess;
   T factor = 8;
   if(z >= 1)
   {
      //
      // We can use the relationship between the incomplete
      // gamma function and the poisson distribution to
      // calculate an approximate inverse, for large z
      // this is actually pretty accurate, but it fails badly
      // when z is very small.  Also set our step-factor according
      // to how accurate we think the result is likely to be:
      //
      guess = 1 + inverse_poisson_cornish_fisher(z, q, p, pol);
      if(z > 5)
      {
         if(z > 1000)
            factor = 1.01f;
         else if(z > 50)
            factor = 1.1f;
         else if(guess > 10)
            factor = 1.25f;
         else
            factor = 2;
         if(guess < 1.1)
            factor = 8;
      }
   }
   else if(z > 0.5)
   {
      guess = z * 1.2f;
   }
   else
   {
      guess = -0.4f / log(z);
   }
   //
   // Max iterations permitted:
   //
   boost::uintmax_t max_iter = policies::get_max_root_iterations<Policy>();
   //
   // Use our generic derivative-free root finding procedure.
   // We could use Newton steps here, taking the PDF of the
   // Poisson distribution as our derivative, but that's
   // even worse performance-wise than the generic method :-(
   //
   std::pair<T, T> r = bracket_and_solve_root(f, guess, factor, false, tol, max_iter, pol);
   if(max_iter >= policies::get_max_root_iterations<Policy>())
      policies::raise_evaluation_error<T>("boost::math::gamma_p_inva<%1%>(%1%, %1%)", "Unable to locate the root within a reasonable number of iterations, closest approximation so far was %1%", r.first, pol);
   return (r.first + r.second) / 2;
}

} // namespace detail

template <class T1, class T2, class Policy>
inline typename tools::promote_args<T1, T2>::type
   gamma_p_inva(T1 x, T2 p, const Policy& pol)
{
   typedef typename tools::promote_args<T1, T2>::type result_type;
   typedef typename policies::evaluation<result_type, Policy>::type value_type;
   typedef typename policies::normalise<
      Policy,
      policies::promote_float<false>,
      policies::promote_double<false>,
      policies::discrete_quantile<>,
      policies::assert_undefined<> >::type forwarding_policy;

   if(p == 0)
   {
      return tools::max_value<result_type>();
   }
   if(p == 1)
   {
      return tools::min_value<result_type>();
   }

   return policies::checked_narrowing_cast<result_type, forwarding_policy>(
      detail::gamma_inva_imp(
         static_cast<value_type>(x),
         static_cast<value_type>(p),
         1 - static_cast<value_type>(p),
         pol), "boost::math::gamma_p_inva<%1%>(%1%, %1%)");
}

template <class T1, class T2, class Policy>
inline typename tools::promote_args<T1, T2>::type
   gamma_q_inva(T1 x, T2 q, const Policy& pol)
{
   typedef typename tools::promote_args<T1, T2>::type result_type;
   typedef typename policies::evaluation<result_type, Policy>::type value_type;
   typedef typename policies::normalise<
      Policy,
      policies::promote_float<false>,
      policies::promote_double<false>,
      policies::discrete_quantile<>,
      policies::assert_undefined<> >::type forwarding_policy;

   if(q == 1)
   {
      return tools::max_value<result_type>();
   }
   if(q == 0)
   {
      return tools::min_value<result_type>();
   }

   return policies::checked_narrowing_cast<result_type, forwarding_policy>(
      detail::gamma_inva_imp(
         static_cast<value_type>(x),
         1 - static_cast<value_type>(q),
         static_cast<value_type>(q),
         pol), "boost::math::gamma_q_inva<%1%>(%1%, %1%)");
}

template <class T1, class T2>
inline typename tools::promote_args<T1, T2>::type
   gamma_p_inva(T1 x, T2 p)
{
   return boost::math::gamma_p_inva(x, p, policies::policy<>());
}

template <class T1, class T2>
inline typename tools::promote_args<T1, T2>::type
   gamma_q_inva(T1 x, T2 q)
{
   return boost::math::gamma_q_inva(x, q, policies::policy<>());
}

} // namespace math
} // namespace boost

#endif // BOOST_MATH_SP_DETAIL_GAMMA_INVA

max_stars_repo_name: jaredhoberock/gotham

max_issues_repo_name: jaredhoberock/gotham

max_forks_repo_name: jaredhoberock/gotham


text:
/**
 * Copyright Soramitsu Co., Ltd. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

#ifndef LIBP2P_CRYPTO_RANDOM_BOOST_GENERATOR_HPP
#define LIBP2P_CRYPTO_RANDOM_BOOST_GENERATOR_HPP

#include <boost/nondet_random.hpp>
#include <boost/random/uniform_int_distribution.hpp>
#include <libp2p/crypto/random_generator.hpp>

namespace libp2p::crypto::random {
  /**
   * @class BoostRandomGenerator provides implementation
   * of cryptographic-secure random bytes generator;
   * on systems which don't provide true random numbers source
   * it may not compile, so you will need to implement
   * your own random bytes generator
   */
  class BoostRandomGenerator : public CSPRNG {
   public:
    ~BoostRandomGenerator() override = default;
    /**
     * @brief generators random bytes
     * @param len number of bytes
     * @return buffer containing random bytes
     */
    std::vector<uint8_t> randomBytes(size_t len) override;

   private:
    /// boost cryptographic-secure random generator
    boost::random_device generator_;
    /// uniform distribution tool
    boost::random::uniform_int_distribution<uint8_t> distribution_;
  };
}  // namespace libp2p::crypto::random

#endif  // LIBP2P_CRYPTO_RANDOM_BOOST_GENERATOR_HPP


text:
#include "GpgAgentHandler.h"
#include "Log.h"
#include <boost/asio.hpp>
#include <sodium.h>

int main(int argc, char **argv) {
    if (sodium_init() < 0) {
        _debug_cerr << "libsodium initialize failed\n";
        exit(-1);
    }

    boost::asio::io_context ctx;
    KeePassPinentry::GpgAgentHandler handler{ctx};
    handler.serveAgent();
    return 0;
}

max_stars_repo_name: MrChenWithCapsule/KeePassPinentry

max_issues_repo_name: MrChenWithCapsule/KeePassPinentry

max_forks_repo_name: MrChenWithCapsule/KeePassPinentry


text: #include <boost/intrusive/treap.hpp>


text:
#include <boost/interprocess/offset_ptr.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include "Location.hpp"

namespace scene_interface_sma {
	//Define an STL compatible allocator of ints that allocates from the managed_shared_memory.
	//This allocator will allow placing containers in the segment
	typedef boost::interprocess::allocator<boost::interprocess::offset_ptr<Location>, boost::interprocess::managed_shared_memory::segment_manager> LocationsSMA;

	//Alias a vector that uses the previous STL-like allocator so that allocates
	//its values from the segment
	typedef boost::interprocess::vector<boost::interprocess::offset_ptr<Location>, LocationsSMA> Locations;
}

max_stars_repo_name: fbredius/IMOVE

max_issues_repo_name: fbredius/IMOVE

max_forks_repo_name: fbredius/IMOVE


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

#include "core/Raster.h"

#include <boost/log/trivial.hpp>
#include <boost/log/attributes/scoped_attribute.hpp>

#include <fmt/format.h>

#include <cpl_error.h>
#include <gdal_priv.h>
#include <gdal_alg.h>

namespace Raster {

inline void errorCallback(CPLErr err, CPLErrorNum num, const char *message)
{
    BOOST_LOG_SCOPED_THREAD_TAG("Source", "General");

    switch (err) {
    case CE_None:
        break;
    case CE_Debug:
        BOOST_LOG_TRIVIAL(debug) << "GDAL: " << message;
        break;
    case CE_Warning:
        BOOST_LOG_TRIVIAL(warning) << "GDAL: " << message;
        break;
    case CE_Failure:
        BOOST_LOG_TRIVIAL(error) << "GDAL: " << message;
        break;
    case CE_Fatal:
        BOOST_LOG_TRIVIAL(fatal) << "GDAL: " << message;
        break;
    default:
        break;
    }
}

void setConfigOption(const std::string& option, const std::string& value)
{
    CPLSetConfigOption(option.c_str(), value.c_str());
}

std::string getConfigOption(const std::string& option)
{
    return CPLGetConfigOption(option.c_str(), "");
}

//-----------------------------------------------------------------------------
// DriverManager
//-----------------------------------------------------------------------------

class DriverManager
{
public:
    static GDALDriverManager * instance()
    {
        static std::once_flag flag;
        std::call_once(flag, [](){
            GDALAllRegister();
            CPLSetConfigOption("CPL_CURL_GZIP", "YES");
            CPLSetConfigOption("GTIFF_REPORT_COMPD_CS", "YES");
            CPLSetErrorHandler(errorCallback);
        });

        static std::shared_ptr<GDALDriverManager> manager(
            GetGDALDriverManager(),
            [](GDALDriverManager *p) { GDALDestroyDriverManager(); });

        return manager.get();
    }

    DriverManager(const DriverManager&) = delete;
    DriverManager& operator=(const DriverManager&) = delete;
    DriverManager(DriverManager&&) = delete;
    DriverManager& operator=(DriverManager&&) = delete;

private:
    DriverManager() = default;
    ~DriverManager() = default;
};

//-----------------------------------------------------------------------------
// Dataset
//-----------------------------------------------------------------------------

Dataset::Dataset(const std::string& filename,
                 const std::string& drivername,
                 const std::vector<std::string>& options)
{
    GDALDriver *driver = DriverManager::instance()->GetDriverByName(drivername.c_str());
    if (driver == nullptr)
        throw std::runtime_error(fmt::format("Failed to load {} driver.", drivername));

    DriverManager::instance()->RegisterDriver(driver);

    const unsigned int openFlags = GDAL_OF_READONLY | GDAL_OF_RASTER;
    const char *allowedDrivers[] = { drivername.c_str(), nullptr };

    std::vector<const char *> optionsArray;
    for (const auto& option : options)
        optionsArray.push_back(option.c_str());
    optionsArray.push_back(nullptr);

    dataset_ = GDALDataset::Open(filename.c_str(), openFlags, allowedDrivers, optionsArray.data());

    if (dataset_ == nullptr)
        throw std::runtime_error("Failed to open dataset");

    if (dataset_->GetRasterCount() != 1)
        throw std::runtime_error("Invalid band count");

    band_ = dataset_->GetRasterBand(1);

    if (band_ == nullptr)
        throw std::runtime_error("Failed to open raster band");
}

Dataset::~Dataset()
{
    GDALClose(dataset_);
}

GDALRasterBand * Dataset::band()
{
    return band_;
}

GeoTransform Dataset::geoTransform() const
{
    std::array<double, 6> gtarray = { 0 }; // ulx xres xrot uly yrot yres
    CPLErr rc = dataset_->GetGeoTransform(gtarray.data());
    if (rc != CE_None)
        throw std::runtime_error("Failed to read dataset geotransform");

    return GeoTransform(gtarray);
}

std::shared_ptr<PJ> Dataset::projection() const
{
    const char *wkt = dataset_->GetProjectionRef();
    if (wkt == nullptr)
        return nullptr;

    return Projection::createObjectFromWKT(wkt);
}

std::array<int, 2> Dataset::dimensions() const
{
    const int nx = band_->GetXSize();
    const int ny = band_->GetYSize();
    return { nx, ny };
}

std::array<int, 2> Dataset::blockDimensions() const
{
    int nx = 0;
    int ny = 0;
    band_->GetBlockSize(&nx, &ny);
    return { nx, ny };
}

double Dataset::offset() const
{
    // Returns 0 if unknown.
    return band_->GetOffset();
}

double Dataset::scale() const
{
    // Returns 1 if unknown.
    return band_->GetScale();
}

double Dataset::noDataValue() const
{
    // Scale and offset are not applied.
    return band_->GetNoDataValue();
}

Window Dataset::window() const
{
    return window_;
}

Window Dataset::blockWindow() const
{
    return blockWindow_;
}

void Dataset::setBoundingBox(std::shared_ptr<PJ> crs, const Projection::ProjectedExtent& bbox)
{
    // Transform bounding box coordinates to dataset projection.
    auto op = Projection::Pipeline(crs, projection());
    double llx = 0, lly = 0, llz = 0;
    double lrx = 0, lry = 0, lrz = 0;
    double ulx = 0, uly = 0, ulz = 0;
    double urx = 0, ury = 0, urz = 0;
    op.forward(bbox.xmin, bbox.ymin, 0, llx, lly, llz); // SW corner
    op.forward(bbox.xmax, bbox.ymin, 0, lrx, lry, lrz); // SE corner
    op.forward(bbox.xmin, bbox.ymax, 0, ulx, uly, ulz); // NW corner
    op.forward(bbox.xmax, bbox.ymax, 0, urx, ury, urz); // NE corner

    // Get the maximum source window covering the projected bounding box.
    double x0 = std::min(llx, ulx); // SW, NW: West
    double y0 = std::min(lly, lry); // SW, SE: South
    double x1 = std::max(lrx, urx); // SE, NE: East
    double y1 = std::max(uly, ury); // NW, NE: North

    // Calculate pixel offsets and window dimensions.
    auto gt = geoTransform();
    double xoffset = (x0 - gt.ulx) / gt.xres; // xoff = (ulx - xorigin) / xres
    double yoffset = (y1 - gt.uly) / gt.yres; // yoff = (uly - yorigin) / yres
    double nx = (x1 - x0) / gt.xres;           // nx = (lrx - ulx) / xres
    double ny = (y0 - y1) / gt.yres;           // ny = (lry - uly) / yres

    // Round to integer pixels.
    xoffset = std::floor(xoffset + 0.001);
    yoffset = std::floor(yoffset + 0.001);
    nx = std::floor(nx + 0.5);
    ny = std::floor(ny + 0.5);

    // Update the dataset window.
    window_.xmin = static_cast<int>(xoffset);      // xmin = x offset, left
    window_.ymax = static_cast<int>(yoffset);      // ymax = y offset, top
    window_.xmax = static_cast<int>(xoffset + nx); // xmax = x offset, right
    window_.ymin = static_cast<int>(yoffset - ny); // ymin = y offset, bottom

    // Update the block window using the natural block size.
    auto blockDims = blockDimensions();
    blockWindow_.xmin = window_.xmin - (window_.xmin % blockDims[0]);
    blockWindow_.ymin = window_.ymin - (window_.ymin % blockDims[1]);
    blockWindow_.xmax = window_.xmax - (window_.xmax % blockDims[0]) + blockDims[0];
    blockWindow_.ymax = window_.ymax - (window_.ymax % blockDims[1]) + blockDims[1];
}

std::vector<float> Dataset::readBlocksInternal(TaskControl& control, Dataset *p)
{
    control.started();

    auto band = p->band();
    auto window = p->window();
    auto blockWindow = p->blockWindow();
    auto blockDims = p->blockDimensions();

    const int xbmin = blockWindow.xmin;
    const int ybmax = blockWindow.ymax;
    const int nxbuf = blockWindow.nx();
    const int nybuf = blockWindow.ny();
    const int xbsize = blockDims[0];
    const int ybsize = blockDims[1];
    const int nxblocks = nxbuf / xbsize;
    const int nyblocks = nybuf / ybsize;

    const int xoffset = window.xmin - blockWindow.xmin;
    const int yoffset = blockWindow.ymax - window.ymax;

    if (nxbuf <= 0 || nybuf <= 0) {
        control.finished();
        throw std::runtime_error("Invalid buffer size");
    }

    // Create the buffer to hold block data.
    float fillValue = static_cast<float>((p->noDataValue() * p->scale()) + p->offset());
    std::vector<float> buffer(nxbuf * nybuf, fillValue);

    // Setup internal progress callback.
    struct ProgressData {
        ProgressData(TaskControl& control) : control(control) {}
        TaskControl& control;
        int currentBlock = 0;
        int totalBlocks = 0;
    };

    ProgressData pdata(control);
    pdata.currentBlock = 0;
    pdata.totalBlocks = nxblocks * nyblocks;

    static auto pfn = [](double complete, const char *message, void *data) {
        auto pd = static_cast<ProgressData *>(data);
        if (pd->control.interruptRequested())
            return 0;

        double start = (double)pd->currentBlock / (double)pd->totalBlocks;
        pd->control.progress(start + complete / pd->totalBlocks);
        return 1;
    };

    // Set nearest neighbor resampling and progress function.
    GDALRasterIOExtraArg extraArg;
    INIT_RASTERIO_EXTRA_ARG(extraArg);
    extraArg.eResampleAlg = GRIORA_NearestNeighbour;
    extraArg.pfnProgress = pfn;
    extraArg.pProgressData = &pdata;

    // Notify driver of upcoming read requests.
    const GDALDataType dataType = band->GetRasterDataType();
    band->AdviseRead(xbmin, ybmax, nxbuf, nybuf, nxbuf, nybuf, dataType, nullptr);

    for (int ixb = 0; ixb < nxblocks; ++ixb)
    {
        for (int iyb = 0; iyb < nyblocks; ++iyb)
        {
            if (control.interruptRequested()) {
                control.finished();
                throw std::runtime_error("Canceled");
            }

            pdata.currentBlock = iyb + ixb * nyblocks;
            control.message(fmt::format("Reading Block {} of {}", pdata.currentBlock + 1, pdata.totalBlocks));

            // Calculate block index in source raster.
            const int xb = xbmin / xbsize + ixb;
            const int yb = ybmax / ybsize + iyb;

            // Read the block using DirectRasterIO. For WCS, this is faster than
            // GDALRasterBand::GetLockedBlockRef or GDALRasterBand::ReadBlock.
            std::vector<float> block(xbsize * ybsize);
            const int xstart = xb * xbsize;
            const int ystart = yb * ybsize;

            CPLErr rc = band->RasterIO(GF_Read, xstart, ystart, xbsize, ybsize, block.data(), xbsize, ybsize, GDT_Float32, 0, 0, &extraArg);
            if (rc != CE_None) {
                control.finished();
                if (control.interruptRequested())
                    throw std::runtime_error("Canceled");
                else
                    throw std::runtime_error("I/O error");
            }

            for (int ix = 0; ix < xbsize; ++ix) {
                for (int iy = 0; iy < ybsize; ++iy) {
                    int pos = (ix + ixb * xbsize) + (iy + iyb * ybsize) * nxbuf;
                    float value = static_cast<float>((block.at(ix + iy * xbsize) * p->scale()) + p->offset());
                    buffer.at(pos) = value;
                }
            }
        }
    }

    // Copy results to output buffer within source window.
    //float *start = &buffer.at(nxbuf * yoffset + xoffset);
    //const GSpacing linespace = sizeof(float) * nxbuf;
    //band->RasterIO(GF_Write, 0, 0, nx, ny, start, nx, ny, GDT_Float32, 0, linespace);

    control.message("Generating DEM");

    std::vector<float> result;
    result.reserve(window.nx() * window.ny());
    for (int ix = xoffset; ix < window.nx(); ++ix) {
        for (int iy = yoffset; iy < window.ny(); ++iy) {
            result.push_back(buffer.at(ix + iy * xbsize));
        }
    }

    control.finished();
    return result;
}

std::future<std::vector<float>> Dataset::readBlocks(TaskControl& control)
{
    return std::async(std::launch::async, readBlocksInternal, std::ref(control), this);
}

void Dataset::exportGeoTIFF(const std::string& filename) const
{
    GDALDriver *driver = DriverManager::instance()->GetDriverByName("GTiff");
    if (driver == nullptr)
        throw std::runtime_error("Failed to load GeoTIFF driver");

    const int nx = window_.nx();
    const int ny = window_.ny();

    if (nx <= 0 || ny <= 0 || nx * ny != values_.size())
        throw std::runtime_error("Invalid window size");

    GDALDatasetUniquePtr dataset(driver->Create(filename.c_str(), nx, ny, 1, GDT_Float32, nullptr));
    GeoTransform gt = geoTransform();
    gt.ulx += window_.xmin; // ulx + offset
    gt.uly -= window_.ymax; // uly + offset
    dataset->SetGeoTransform(gt.array().data());
    dataset->SetProjection(dataset_->GetProjectionRef());

    GDALRasterBand *band = dataset->GetRasterBand(1);
    band->SetUnitType("m");

    float *start = const_cast<float *>(values_.data());
    band->RasterIO(GF_Write, 0, 0, nx, ny, start, nx, ny, GDT_Float32, 0, 0);
}

} // namespace Raster

max_stars_repo_name: sofea-model/sofea

max_issues_repo_name: sofea-model/sofea

max_forks_repo_name: sofea-model/sofea