text:
#include <glog/logging.h>
#include <boost/uuid/random_generator.hpp>
#include <boost/uuid/uuid_io.hpp>

#include <sys/mtio.h>
#include <sys/ioctl.h>
#include <sys/sysctl.h>
#include <unistd.h>

#include "Drive.hpp"

namespace iolibbsd {

/**
 * Opens a drive with the given pass-through and sequential access devices.
 */
Drive::Drive(const char *sa, const char *pass) {
    CHECK(sa != NULL) << "Sequential access device file must be specified";

    this->devSa = sa;
    this->devPass = pass;

    // Determine unit number and control device
    _determineUnitNumber();
    _createCtrlDevice();

    // Determine maximum IO size (for writes/reads)
    _getMaxIOSize();

	// Generate UUID
	boost::uuids::basic_random_generator<boost::mt19937> gen;
	this->uuid = gen();
}

/**
 * De-allocates the drive, closing any presently open file handles.
 */
Drive::~Drive() {
    // Use the close method, but force it by setting reference count to 1
    LOG_IF(WARNING, this->fdSaRefs > 1) << "More than one open reference on file descriptor at dellocation!";

    this->fdSaRefs = 1;
    _closeSa();
}

/**
 * Returns a copy of the drive file's path.
 */
iolib_string_t Drive::getDeviceFile() {
	iolib_string_t string = static_cast<iolib_string_t>(malloc(256));
	strncpy(string, this->devSa, 256);
	return string;
}

/**
 * Return a stringified version of the UUID.
 */
std::string Drive::getUuid() {
	return boost::uuids::to_string(this->uuid);
}

/**
 * Gets status information from the drive.
 */
iolib_error_t Drive::getDriveStatus(iolib_drive_status_t *status) {
    int err = 0;

    // Ensure device is open
    _openSaCtl();

    // Perform the ioctl
    struct mtget mtStatus;
    err = ioctl(this->fdSaCtl, MTIOCGET, &mtStatus);
    PLOG_IF(ERROR, err != 0) << "Couldn't execute MTIOCGET on " << this->devSaCtl;

    // Extract the status and convert it to our value
    status->deviceStatus = _mtioToNativeStatus(mtStatus.mt_dsreg);
    status->deviceError = mtStatus.mt_erreg;

    // NOTE: The rest of the fields in the struct are not yet implemented

    // Close device once we're done.
    _closeSaCtl();

    return err;
}

/**
 * Queries the drive with a GET UNIT STATUS command to determine its current
 * state, using the MTIOCGET ioctl.
 */
iolib_drive_operation_t Drive::getDriveOp() {
    iolib_drive_operation_t status = kDriveStatusUnknown;
    int err = 0;

    // Ensure device is open
    _openSaCtl();

    // Perform the ioctl
    struct mtget mtStatus;
    err = ioctl(this->fdSaCtl, MTIOCGET, &mtStatus);
    PLOG_IF(ERROR, err != 0) << "Couldn't execute MTIOCGET on " << this->devSaCtl;

    // Extract the status and convert it to our value
    status = _mtioToNativeStatus(mtStatus.mt_dsreg);

    // Close device once we're done.
    _closeSaCtl();

    return status;
}

/**
 * Gets the drive's current logical block position.
 *
 * NOTE: This may be inaccurate (or entirely wrong) if the drive is not idle.
 */
off_t Drive::getLogicalBlkPos() {
    int err = 0;

    // Ensure device is open
    _openSaCtl();

    // Perform the ioctl
    struct mtget mtStatus;
    err = ioctl(this->fdSaCtl, MTIOCGET, &mtStatus);
    PLOG_IF(ERROR, err != 0) << "Couldn't execute MTIOCGET on " << this->fdSaCtl;

    // Extract the "relative file number of current position"
    off_t fileNo = mtStatus.mt_fileno;

    // Close device once we're done.
    _closeSaCtl();

    return fileNo;
}

/**
 * Seeks the drive to the given logical block position.
 */
iolib_error_t Drive::seekToLogicalBlkPos(off_t inPos) {
    int err = 0;
    struct mtop mt_com;

    // Ensure device is open
    _openSa();

    // Calculate the difference between the current position and this position.
    int difference = getLogicalBlkPos() - inPos;

    mt_com.mt_count = std::abs(difference);

    // If it's positive, execute the "forward space file" command.
    if(difference > 0) {
        mt_com.mt_op = MTFSF;

        err = ioctl(this->fdSa, MTIOCTOP, &mt_com);
        PLOG_IF(ERROR, err != 0) << "Couldn't execute MTIOCTOP MTFSF on " << this->devSa;
    }
    // If negative, run "backward space file" command.
    else if(difference < 0) {
        mt_com.mt_op = MTBSF;

        err = ioctl(this->fdSa, MTIOCTOP, &mt_com);
        PLOG_IF(ERROR, err != 0) << "Couldn't execute MTIOCTOP MTBSF on " << this->devSa;
    }
    // …And if the difference is zero, we do nothing.

    // Close device once we're done.
    _closeSa();
    return err;
}

/**
 * Skips one file ahead.
 */
iolib_error_t Drive::skipFileMark() {
    int err = 0;
    struct mtop mt_com;

    // Ensure device is open
    _openSa();

    // Set up seek struct
    mt_com.mt_count = 1;
    mt_com.mt_op = MTFSF;

    err = ioctl(this->fdSa, MTIOCTOP, &mt_com);
    PLOG_IF(ERROR, err != 0) << "Couldn't execute MTIOCTOP MTFSF on " << this->devSa;

    // Close device once we're done.
    _closeSa();
    return err;
}

/**
 * Rewinds the tape to the beginning.
 */
iolib_error_t Drive::rewind() {
    int err = 0;

    // Ensure device is open
    _openSa();

    // Perform the ioctl
    struct mtop mt_com;

    mt_com.mt_count = 1;
    mt_com.mt_op = MTREW;

    err = ioctl(this->fdSa, MTIOCTOP, &mt_com);
    PLOG_IF(ERROR, err != 0) << "Couldn't execute MTIOCTOP MTREW on " << this->devSa;

    // Close device once we're done.
    _closeSa();
    return err;
}

/**
 * Ejects the tape currently in the drive.
 *
 * This is implemented as taking the drive offline. Inserting a new tape should
 * bring the drive online again.
 */
iolib_error_t Drive::eject() {
    int err = 0;

    // Ensure device is open
    _openSa();

    // Perform the ioctl
    struct mtop mt_com;

    mt_com.mt_count = 1;
    mt_com.mt_op = MTOFFL;

    err = ioctl(this->fdSa, MTIOCTOP, &mt_com);
    PLOG_IF(ERROR, err != 0) << "Couldn't execute MTIOCTOP MTOFFL on " << this->devSa;

    // Close device once we're done.
    _closeSa();
    return err;
}

/**
 * Writes a file mark at the current position on tape.
 */
iolib_error_t Drive::writeFileMark() {
    int err = 0;

    // Ensure device is open
    _openSa();

    // Perform the ioctl
    struct mtop mt_com;

    mt_com.mt_count = 1;
    mt_com.mt_op = MTWEOF;

    err = ioctl(this->fdSa, MTIOCTOP, &mt_com);
    PLOG_IF(ERROR, err != 0) << "Couldn't execute MTIOCTOP MTWEOF on " << this->devSa;

    // Close device once we're done.
    _closeSa();
    return err;
}

/**
 * Writes the specified data to the tape. If the write is larger than the
 * maximum IO size permissible for this drive, it will be split into chunks
 * of that size.
 */
size_t Drive::writeTape(void *buf, size_t len, iolib_error_t *outErr) {
    int err = 0;

    size_t totalBytesWritten = 0;
    int lastWriteLen = 0;

    // Ensure device is open
    _openSa();

    // Prepare for writing
    uint8_t *writePtr = reinterpret_cast<uint8_t *>(buf);

    while(totalBytesWritten < len) {
        size_t bytesLeft = len - totalBytesWritten;

        // Check if the number of bytes written is less than the chunk size.
        if(bytesLeft < this->maxBlockSz) {
            // If so, simply do a write of that remaining size.
            lastWriteLen = write(this->fdSa, writePtr, bytesLeft);
            PLOG_IF(ERROR, lastWriteLen == -1) << "Couldn't write to " << this->devSa;
        }
        // Otherwise, perform a write of the max IO size
        else {
            lastWriteLen = write(this->fdSa, writePtr, this->maxBlockSz);
            PLOG_IF(ERROR, lastWriteLen == -1) << "Couldn't write to " << this->devSa;
        }

        // Update the counter and pointer following the write
        if(lastWriteLen >= 0) {
            writePtr += lastWriteLen;
            totalBytesWritten += lastWriteLen;
        } else {
            // If we're out of space, return a specific return code.
            if(errno == ENOSPC) {
                *outErr = IOLIB_ERROR_EOM;
                return -1;
            }
        }
    }

    // Close device once we're done.
    _closeSa();
    return totalBytesWritten;
}

/**
 * Reads the specified number of bytes from the tape. If a file mark is
 * encountered before the buffer can be filled, the read is terminated.
 */
size_t Drive::readTape(void *buf, size_t len, iolib_error_t *outErr) {
    int err = 0;

    size_t totalBytesRead = 0;
    int lastReadLen = 0;

    // Ensure device is open
    _openSa();

    // Prepare for writing
    uint8_t *readPtr = reinterpret_cast<uint8_t *>(buf);

    while(totalBytesRead < len) {
        size_t bytesLeft = len - totalBytesRead;

        // Check if the number of bytes to be read is less than the chunk size.
        if(bytesLeft < this->maxBlockSz) {
            // If so, simply do a read of that remaining size.
            lastReadLen = read(this->fdSa, readPtr, bytesLeft);
            PLOG_IF(ERROR, lastReadLen == -1) << "Couldn't read from " << this->devSa;

            if(lastReadLen != bytesLeft) {
                LOG(INFO) << "Read " << lastReadLen << " bytes, expected "
                          << bytesLeft << "; assuming end of tape";
                break;
            }
        }
        // Otherwise, perform a write of the max IO size
        else {
            lastReadLen = read(this->fdSa, readPtr, this->maxBlockSz);
            PLOG_IF(ERROR, lastReadLen == -1) << "Couldn't read from " << this->devSa;

            if(lastReadLen != this->maxBlockSz) {
                LOG(INFO) << "Read " << lastReadLen << " bytes, expected "
                          << this->maxBlockSz << "; assuming end of tape";
                break;
            }
        }

        // If no more bytes were read, we're done
        if(lastReadLen == 0) {
            break;
        }

        // Update the counter and pointer following the read
        readPtr += lastReadLen;
        totalBytesRead += lastReadLen;
    }

    return totalBytesRead;
}

/**
 * Determines the unit number of this drive.
 */
void Drive::_determineUnitNumber() {
    // Extract the unit number from the device string
    std::string devSaStr(this->devSa);

    size_t last_index = devSaStr.find_last_not_of("0123456789");
    std::string unitNumberStr = devSaStr.substr(last_index + 1);

    this->saUnitNumber = stoi(unitNumberStr);
}

/**
 * Determines the maximum IO size for this drive.
 */
void Drive::_getMaxIOSize() {
    // Get the maximum block size for this device
    char sysCtlName[64];
    snprintf(reinterpret_cast<char *>(&sysCtlName), 64,
             "kern.cam.sa.%d.maxio", this->saUnitNumber);

    int maxIO;
    size_t maxIOLen = sizeof(int);
    sysctlbyname(sysCtlName, &maxIO, &maxIOLen, NULL, 0);

    this->maxBlockSz = maxIO;

    VLOG(2) << "\t\tMaximum IO size: " << this->maxBlockSz << " bytes";
}

/**
 * Creates the path to the drive's control device.
 */
void Drive::_createCtrlDevice() {
    char *buffer = new char[128];
    snprintf(buffer, 128, "/dev/sa%d.ctl", this->saUnitNumber);
    this->devSaCtl = buffer;

    VLOG(2) << "\t\tControl device: " << this->devSaCtl;
}

/**
 * Opens the sequential access device.
 *
 * NOTE: This works on a reference counter principle. This function can be
 * called as many times as desired, and a counter is incremented every time,
 * but the file is only opened if it isn't open yet.
 */
void Drive::_openSa() {
    // Only open the device if it's not already open
    if(this->fdSa == -1) {
        this->fdSa = open(this->devSa, O_RDWR | O_EXLOCK);
        PCHECK(this->fdSa != -1) << "Couldn't open " << this->devSa << ": ";

        this->fdSaRefs++;
    } else {
        this->fdSaRefs++;
    }
}

void Drive::_openSaCtl() {
   // Only open the device if it's not already open
   if(this->fdSaCtl == -1) {
       this->fdSaCtl = open(this->devSaCtl, O_RDWR | O_EXLOCK);
       PCHECK(this->fdSaCtl != -1) << "Couldn't open " << this->devSaCtl << ": ";

       this->fdSaCtlRefs++;
   } else {
       this->fdSaCtlRefs++;
   }
}

/**
 * Closes the sequential access device, if opened.
 *
 * NOTE: This works on a reference counter principle. This function can be
 * called as many times as desired, and a counter is decremented every time,
 * but the file is only closed if the counter reaches zero.
 */
void Drive::_closeSa() {
    int err = 0;

    if(this->fdSa != -1 && --this->fdSaRefs == 0) {
        err = close(this->fdSa);

        if(err != 0) {
            PLOG(ERROR) << "Couldn't close " << this->devSa << ": ";
        }

        this->fdSa = -1;
    }
}

void Drive::_closeSaCtl() {
   int err = 0;

   if(this->fdSaCtl != -1 && --this->fdSaCtlRefs == 0) {
       err = close(this->fdSaCtl);

       if(err != 0) {
           PLOG(ERROR) << "Couldn't close " << this->devSaCtl << ": ";
       }

       this->fdSaCtl = -1;
   }
}

/**
 * Converts an mtio status value to the iolib native type.
 */
iolib_drive_operation_t Drive::_mtioToNativeStatus(short dsreg) {
    switch(dsreg) {
        case MTIO_DSREG_REST:
            return kDriveStatusIdle;

        case MTIO_DSREG_WR:
            return kDriveStatusWritingData;
        case MTIO_DSREG_FMK:
            return kDriveStatusWritingMetadata;
        case MTIO_DSREG_ZER:
            return kDriveStatusErasing;
        case MTIO_DSREG_RD:
            return kDriveStatusReading;

        case MTIO_DSREG_FWD:
            return kDriveStatusSeekingForwards;
        case MTIO_DSREG_REV:
            return kDriveStatusSeekingBackwards;
        case MTIO_DSREG_REW:
            return kDriveStatusRewinding;

        case MTIO_DSREG_TEN:
            return kDriveStatusRetensioning;
        case MTIO_DSREG_UNL:
            return kDriveStatusUnloading;
        case MTIO_DSREG_LD:
            return kDriveStatusLoading;

        // We have an "other" status
        default:
            return kDriveStatusOther;
    }
}

} // namespace iolibbsd

max_stars_repo_name: backuperator/daemon

max_issues_repo_name: backuperator/daemon

max_forks_repo_name: backuperator/daemon


text:
//=======================================================================
// Copyright 2000 University of Notre Dame.
// Authors: Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#ifndef BOOST_EDGE_CONNECTIVITY
#define BOOST_EDGE_CONNECTIVITY

// WARNING: not-yet fully tested!

#include <boost/config.hpp>
#include <vector>
#include <set>
#include <algorithm>
#include <boost/graph/edmonds_karp_max_flow.hpp>

namespace boost {

  namespace detail {

    template <class Graph>
    inline
    std::pair<typename graph_traits<Graph>::vertex_descriptor,
              typename graph_traits<Graph>::degree_size_type>
    min_degree_vertex(Graph& g)
    {
      typedef graph_traits<Graph> Traits;
      typename Traits::vertex_descriptor p;
      typedef typename Traits::degree_size_type size_type;
      size_type delta = (std::numeric_limits<size_type>::max)();

      typename Traits::vertex_iterator i, iend;
      for (tie(i, iend) = vertices(g); i != iend; ++i)
        if (degree(*i, g) < delta) {
          delta = degree(*i, g);
          p = *i;
        }
      return std::make_pair(p, delta);
    }

    template <class Graph, class OutputIterator>
    void neighbors(const Graph& g,
                   typename graph_traits<Graph>::vertex_descriptor u,
                   OutputIterator result)
    {
      typename graph_traits<Graph>::adjacency_iterator ai, aend;
      for (tie(ai, aend) = adjacent_vertices(u, g); ai != aend; ++ai)
        *result++ = *ai;
    }

    template <class Graph, class VertexIterator, class OutputIterator>
    void neighbors(const Graph& g,
                   VertexIterator first, VertexIterator last,
                   OutputIterator result)
    {
      for (; first != last; ++first)
        neighbors(g, *first, result);
    }

  } // namespace detail

  // O(m n)
  template <class VertexListGraph, class OutputIterator>
  typename graph_traits<VertexListGraph>::degree_size_type
  edge_connectivity(VertexListGraph& g, OutputIterator disconnecting_set)
  {
    //-------------------------------------------------------------------------
    // Type Definitions
    typedef graph_traits<VertexListGraph> Traits;
    typedef typename Traits::vertex_iterator vertex_iterator;
    typedef typename Traits::edge_iterator edge_iterator;
    typedef typename Traits::out_edge_iterator out_edge_iterator;
    typedef typename Traits::vertex_descriptor vertex_descriptor;
    typedef typename Traits::degree_size_type degree_size_type;
    typedef color_traits<default_color_type> Color;

    typedef adjacency_list_traits<vecS, vecS, directedS> Tr;
    typedef typename Tr::edge_descriptor Tr_edge_desc;
    typedef adjacency_list<vecS, vecS, directedS, no_property,
      property<edge_capacity_t, degree_size_type,
        property<edge_residual_capacity_t, degree_size_type,
          property<edge_reverse_t, Tr_edge_desc> > > >
      FlowGraph;
    typedef typename graph_traits<FlowGraph>::edge_descriptor edge_descriptor;

    //-------------------------------------------------------------------------
    // Variable Declarations
    vertex_descriptor u, v, p, k;
    edge_descriptor e1, e2;
    bool inserted;
    vertex_iterator vi, vi_end;
    edge_iterator ei, ei_end;
    degree_size_type delta, alpha_star, alpha_S_k;
    std::set<vertex_descriptor> S, neighbor_S;
    std::vector<vertex_descriptor> S_star, non_neighbor_S;
    std::vector<default_color_type> color(num_vertices(g));
    std::vector<edge_descriptor> pred(num_vertices(g));

    //-------------------------------------------------------------------------
    // Create a network flow graph out of the undirected graph
    FlowGraph flow_g(num_vertices(g));

    typename property_map<FlowGraph, edge_capacity_t>::type
      cap = get(edge_capacity, flow_g);
    typename property_map<FlowGraph, edge_residual_capacity_t>::type
      res_cap = get(edge_residual_capacity, flow_g);
    typename property_map<FlowGraph, edge_reverse_t>::type
      rev_edge = get(edge_reverse, flow_g);

    for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) {
      u = source(*ei, g), v = target(*ei, g);
      tie(e1, inserted) = add_edge(u, v, flow_g);
      cap[e1] = 1;
      tie(e2, inserted) = add_edge(v, u, flow_g);
      cap[e2] = 1; // not sure about this
      rev_edge[e1] = e2;
      rev_edge[e2] = e1;
    }

    //-------------------------------------------------------------------------
    // The Algorithm

    tie(p, delta) = detail::min_degree_vertex(g);
    S_star.push_back(p);
    alpha_star = delta;
    S.insert(p);
    neighbor_S.insert(p);
    detail::neighbors(g, S.begin(), S.end(),
                      std::inserter(neighbor_S, neighbor_S.begin()));

    std::set_difference(vertices(g).first, vertices(g).second,
                        neighbor_S.begin(), neighbor_S.end(),
                        std::back_inserter(non_neighbor_S));

    while (!non_neighbor_S.empty()) { // at most n - 1 times
      k = non_neighbor_S.front();

      alpha_S_k = edmonds_karp_max_flow
        (flow_g, p, k, cap, res_cap, rev_edge, &color[0], &pred[0]);

      if (alpha_S_k < alpha_star) {
        alpha_star = alpha_S_k;
        S_star.clear();
        for (tie(vi, vi_end) = vertices(flow_g); vi != vi_end; ++vi)
          if (color[*vi] != Color::white())
            S_star.push_back(*vi);
      }
      S.insert(k);
      neighbor_S.insert(k);
      detail::neighbors(g, k, std::inserter(neighbor_S, neighbor_S.begin()));
      non_neighbor_S.clear();
      std::set_difference(vertices(g).first, vertices(g).second,
                          neighbor_S.begin(), neighbor_S.end(),
                          std::back_inserter(non_neighbor_S));
    }
    //-------------------------------------------------------------------------
    // Compute edges of the cut [S*, ~S*]
    std::vector<bool> in_S_star(num_vertices(g), false);
    typename std::vector<vertex_descriptor>::iterator si;
    for (si = S_star.begin(); si != S_star.end(); ++si)
      in_S_star[*si] = true;

    degree_size_type c = 0;
    for (si = S_star.begin(); si != S_star.end(); ++si) {
      out_edge_iterator ei, ei_end;
      for (tie(ei, ei_end) = out_edges(*si, g); ei != ei_end; ++ei)
        if (!in_S_star[target(*ei, g)]) {
          *disconnecting_set++ = *ei;
          ++c;
        }
    }
    return c;
  }

} // namespace boost

#endif // BOOST_EDGE_CONNECTIVITY

ext: hpp


text:
#ifndef ELLE_PYTHON_GIL_HH
# define ELLE_PYTHON_GIL_HH

#include <boost/python.hpp>

/* boost::python call policy that release/acquires the gil
* (global interpreter lock).
* Pass as third argument to def, or to init's [] operator:
* - def("foo", &foo, release_gil_call_policies())
* - init<...>()[release_gil_call_policies]
*/

namespace elle
{
  namespace python
  {
    namespace
    {
      static std::vector<PyThreadState*> state;
    }
    struct release_gil_call_policies: public boost::python::default_call_policies
    {
      template <class ArgumentPackage>
      static bool precall(ArgumentPackage const& arg)
      {
        state.push_back(PyEval_SaveThread());
        return boost::python::default_call_policies::precall(arg);
      }
      template <class ArgumentPackage>
      static PyObject* postcall(ArgumentPackage const& args, PyObject* result)
      {
        PyEval_RestoreThread(state.back());
        state.pop_back();
        return boost::python::default_call_policies::postcall(args, result);
      }
    };
}}

#endif

ext: hh

max_stars_repo_name: infinitio/elle

max_issues_repo_name: infinitio/elle

max_forks_repo_name: infinitio/elle


text:
#include <iostream>

#include <boost/program_options.hpp>
#include <csignal>

#include "motors/simumotorupdater.h"
#include "engine/robot.h"
#include "networking/controller.h"

int main(int argc, const char **argv)
{
	namespace po = boost::program_options;
	using namespace mote::walking;

	boost::filesystem::path configurationDirectory(CONFIGURATION_FOLDER);
	std::string configurationFile((configurationDirectory / "arash.json").string());

	// Declare the supported options.
	po::options_description desc("Allowed options");
	desc.add_options()
		("help,h", "Display this help")
		("config,c", po::value<std::string>(&configurationFile)->default_value(configurationFile), "set the configuration file");

	po::variables_map vm;
	po::store(po::parse_command_line(argc, argv, desc), vm);
	po::notify(vm);

	if (vm.count("help"))
	{
		std::cout << desc << "\n";
		return 0;
	}

	std::cerr << "Configuration file: " << configurationFile << std::endl;
	Configuration configuration;
	configuration.loadFromFile(configurationFile);
	std::cerr << "-- Robot: " << configuration.robot << std::endl;
	std::cerr << std::endl;

	sensors::IMU imu;
	HumanoidPart robotPart;

	Robot robot(configuration, imu, robotPart);
	std::unique_ptr<networking::UDPClient> udpClient;
	std::unique_ptr<motors::SimuMotorUpdater> updater;
	std::unique_ptr<networking::Controller> controller;
	std::unique_ptr<boost::asio::io_service> ioService;
	if (configuration.simu)
	{
		udpClient.reset(new networking::UDPClient(configuration.simu->address, configuration.simu->port));
		updater.reset(new motors::SimuMotorUpdater(*udpClient, robotPart));
		updater->init();
		updater->start();
	}
	if (configuration.controller)
	{
		robot.start();

		ioService.reset(new boost::asio::io_service());
		controller.reset(new networking::Controller(*ioService, configuration.controller->port, robot));
		VERBOSE("Controller enabled at port " << configuration.controller->port << ".");
		controller->run();
	}
	else
	{
		VERBOSE("Controller is not enabled.");
		robot.run();
	}

	return 0;
}

ext: cpp

max_stars_repo_name: jamillosantos/autuofm-walking-gait

max_issues_repo_name: jamillosantos/autuofm-walking-gait

max_forks_repo_name: jamillosantos/autuofm-walking-gait


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

#ifndef BOOST_COROUTINES_DETAIL_PARAMETERS_H
#define BOOST_COROUTINES_DETAIL_PARAMETERS_H

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

#include <boost/coroutine/detail/flags.hpp>

#ifdef BOOST_HAS_ABI_HEADERS
#include BOOST_ABI_PREFIX
#endif

namespace boost {
namespace coroutines {
namespace detail {

template <typename Data> struct parameters {
  Data *data;
  bool do_unwind;
  void *coro;

  parameters() : data(0), do_unwind(false), coro(0) {}

  explicit parameters(void *coro_) : data(0), do_unwind(false), coro(coro_) {
    BOOST_ASSERT(0 != coro);
  }

  explicit parameters(Data *data_, void *coro_)
      : data(data_), do_unwind(false), coro(coro_) {
    BOOST_ASSERT(0 != data);
    BOOST_ASSERT(0 != coro);
  }

  explicit parameters(unwind_t::flag_t) : data(0), do_unwind(true) {}
};

template <typename Data> struct parameters<Data &> {
  Data *data;
  bool do_unwind;
  void *coro;

  parameters() : data(0), do_unwind(false), coro(0) {}

  explicit parameters(void *coro_) : data(0), do_unwind(false), coro(coro_) {
    BOOST_ASSERT(0 != coro);
  }

  explicit parameters(Data *data_, void *coro_)
      : data(data_), do_unwind(false), coro(coro_) {
    BOOST_ASSERT(0 != data);
    BOOST_ASSERT(0 != coro);
  }

  explicit parameters(unwind_t::flag_t) : data(0), do_unwind(true), coro(0) {}
};

template <> struct parameters<void> {
  bool do_unwind;
  void *coro;

  parameters() : do_unwind(false), coro(0) {}

  parameters(void *coro_) : do_unwind(false), coro(coro_) {
    BOOST_ASSERT(0 != coro);
  }

  explicit parameters(unwind_t::flag_t) : do_unwind(true), coro(0) {}
};

} // namespace detail
} // namespace coroutines
} // namespace boost

#ifdef BOOST_HAS_ABI_HEADERS
#include BOOST_ABI_SUFFIX
#endif

#endif // BOOST_COROUTINES_DETAIL_PARAMETERS_H

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
#include "AwsS3Bucket.h"
#include "MultiPartUploader.h"
#include "Tools.h"

#include <aws/s3/model/CopyObjectRequest.h>
#include <aws/s3/model/DeleteObjectRequest.h>
#include <aws/s3/model/GetObjectRequest.h>
#include <aws/s3/model/HeadBucketRequest.h>
#include <aws/s3/model/HeadObjectRequest.h>
#include <aws/s3/model/ListObjectsRequest.h>
#include <aws/s3/model/Object.h>
#include <aws/s3/model/PutObjectRequest.h>

#include <boost/interprocess/streams/bufferstream.hpp>

namespace comm {
namespace network {

AwsS3Bucket::AwsS3Bucket(
    const std::string name,
    std::shared_ptr<Aws::S3::S3Client> client)
    : name(name), client(client) {
}

std::vector<std::string> AwsS3Bucket::listObjects() {
  Aws::S3::Model::ListObjectsRequest request;
  request.SetBucket(this->name);
  std::vector<std::string> result;

  Aws::S3::Model::ListObjectsOutcome outcome =
      this->client->ListObjects(request);
  if (!outcome.IsSuccess()) {
    throw std::runtime_error(outcome.GetError().GetMessage());
  }
  Aws::Vector<Aws::S3::Model::Object> objects =
      outcome.GetResult().GetContents();
  for (Aws::S3::Model::Object &object : objects) {
    result.push_back(object.GetKey());
  }
  return result;
}

bool AwsS3Bucket::isAvailable() const {
  Aws::S3::Model::HeadBucketRequest headRequest;
  headRequest.SetBucket(this->name);
  Aws::S3::Model::HeadBucketOutcome outcome =
      this->client->HeadBucket(headRequest);
  return outcome.IsSuccess();
}

const size_t AwsS3Bucket::getObjectSize(const std::string &objectName) {
  Aws::S3::Model::HeadObjectRequest headRequest;
  headRequest.SetBucket(this->name);
  headRequest.SetKey(objectName);
  Aws::S3::Model::HeadObjectOutcome headOutcome =
      this->client->HeadObject(headRequest);
  if (!headOutcome.IsSuccess()) {
    throw std::runtime_error(headOutcome.GetError().GetMessage());
  }
  return headOutcome.GetResultWithOwnership().GetContentLength();
}

void AwsS3Bucket::renameObject(
    const std::string &currentName,
    const std::string &newName) {
  Aws::S3::Model::CopyObjectRequest copyRequest;
  copyRequest.SetCopySource(this->name + "/" + currentName);
  copyRequest.SetKey(newName);
  copyRequest.SetBucket(this->name);

  Aws::S3::Model::CopyObjectOutcome copyOutcome =
      this->client->CopyObject(copyRequest);
  if (!copyOutcome.IsSuccess()) {
    throw std::runtime_error(copyOutcome.GetError().GetMessage());
  }

  this->deleteObject(currentName);
}

void AwsS3Bucket::writeObject(
    const std::string &objectName,
    const std::string data) {
  // we don't have to handle multiple write here because the GRPC limit is 4MB
  // and minimum size of data to perform multipart upload is 5MB
  Aws::S3::Model::PutObjectRequest request;
  request.SetBucket(this->name);
  request.SetKey(objectName);

  std::shared_ptr<Aws::IOStream> body = std::shared_ptr<Aws::IOStream>(
      new boost::interprocess::bufferstream((char *)data.data(), data.size()));

  request.SetBody(body);

  Aws::S3::Model::PutObjectOutcome outcome = this->client->PutObject(request);

  if (!outcome.IsSuccess()) {
    throw std::runtime_error(outcome.GetError().GetMessage());
  }
}

std::string AwsS3Bucket::getObjectData(const std::string &objectName) {
  Aws::S3::Model::GetObjectRequest request;
  request.SetBucket(this->name);
  request.SetKey(objectName);

  Aws::S3::Model::GetObjectOutcome outcome = this->client->GetObject(request);

  if (!outcome.IsSuccess()) {
    throw std::runtime_error(outcome.GetError().GetMessage());
  }

  const size_t size = this->getObjectSize(objectName);
  if (size > GRPC_CHUNK_SIZE_LIMIT) {
    throw invalid_argument_error(std::string(
        "The file is too big(" + std::to_string(size) + " bytes, max is " +
        std::to_string(GRPC_CHUNK_SIZE_LIMIT) +
        "bytes), please, use getObjectDataChunks"));
  }
  Aws::IOStream &retrievedFile = outcome.GetResultWithOwnership().GetBody();

  std::string result;
  result.resize(size);
  retrievedFile.get((char *)result.data(), size + 1);

  return result;
}

void AwsS3Bucket::getObjectDataChunks(
    const std::string &objectName,
    const std::function<void(const std::string &)> &callback,
    const size_t chunkSize) {
  const size_t fileSize = this->getObjectSize(objectName);

  if (fileSize == 0) {
    return;
  }

  Aws::S3::Model::GetObjectRequest request;
  request.SetBucket(this->name);
  request.SetKey(objectName);
  for (size_t offset = 0; offset < fileSize; offset += chunkSize) {
    const size_t nextSize = std::min(chunkSize, fileSize - offset);

    std::string range = "bytes=" + std::to_string(offset) + "-" +
        std::to_string(offset + nextSize);
    request.SetRange(range);

    Aws::S3::Model::GetObjectOutcome getOutcome =
        this->client->GetObject(request);
    if (!getOutcome.IsSuccess()) {
      throw std::runtime_error(getOutcome.GetError().GetMessage());
    }

    Aws::IOStream &retrievedFile =
        getOutcome.GetResultWithOwnership().GetBody();
    std::string result;
    result.resize(nextSize);
    retrievedFile.get((char *)result.data(), nextSize + 1);
    callback(result);
  }
}

void AwsS3Bucket::appendToObject(
    const std::string &objectName,
    const std::string data) {
  const size_t objectSize = this->getObjectSize(objectName);
  if (objectSize < AWS_MULTIPART_UPLOAD_MINIMUM_CHUNK_SIZE) {
    std::string currentData = this->getObjectData(objectName);
    currentData += data;
    this->writeObject(objectName, currentData);
    return;
  }
  size_t currentSize = 0;
  MultiPartUploader uploader(
      this->client, this->name, objectName + "-multipart");
  std::function<void(const std::string &)> callback =
      [&uploader, &data, &currentSize, objectSize](const std::string &chunk) {
        currentSize += chunk.size();
        if (currentSize < objectSize) {
          uploader.addPart(chunk);
        } else if (currentSize == objectSize) {
          uploader.addPart(std::string(chunk + data));
        } else {
          throw std::runtime_error(
              "size of chunks exceeds the size of the object");
        }
      };
  this->getObjectDataChunks(
      objectName, callback, AWS_MULTIPART_UPLOAD_MINIMUM_CHUNK_SIZE);
  uploader.finishUpload();
  // this will overwrite the target file
  this->renameObject(objectName + "-multipart", objectName);
  const size_t newSize = this->getObjectSize(objectName);
  if (objectSize + data.size() != newSize) {
    throw std::runtime_error(
        "append to object " + objectName +
        " has been performed but the final sizes don't "
        "match, the size is now [" +
        std::to_string(newSize) + "] but should be [" +
        std::to_string(objectSize + data.size()) + "]");
  }
}

void AwsS3Bucket::clearObject(const std::string &objectName) {
  this->writeObject(objectName, "");
}

void AwsS3Bucket::deleteObject(const std::string &objectName) {
  Aws::S3::Model::DeleteObjectRequest deleteRequest;

  deleteRequest.SetKey(objectName);
  deleteRequest.SetBucket(this->name);

  Aws::S3::Model::DeleteObjectOutcome deleteOutcome =
      this->client->DeleteObject(deleteRequest);
  if (!deleteOutcome.IsSuccess()) {
    throw std::runtime_error(deleteOutcome.GetError().GetMessage());
  }
}

} // namespace network
} // namespace comm

max_stars_repo_name: jonringer-comm/comm

max_issues_repo_name: jonringer-comm/comm

max_forks_repo_name: jonringer-comm/comm


text:
#include <iostream>

//#include <boost/type_index.hpp>
using namespace std;
#pragma warning(disable : 4996)

namespace _nmsp1
{
	class Human
	{
	public:
		/*
		//构造函数
		Human(const string& tmpname) :m_sname(tmpname)
		{
			cout << "Human(const string &tmpname)执行" << endl;
		}

		//Human(string&& tmpname) :m_sname(tmpname)
		Human(string&& tmpname) :m_sname(std::move(tmpname)) //move并不具备移动能力，把一个左值转换成一个右值。
		{
			cout << "Human(string&& tmpname)执行" << endl;
		}
		*/

		//构造函数模板
		template<typename T>
		Human(T&& tmpname) : m_sname(std::forward<T>(tmpname))
		{
			cout << "Human(T&& tmpname)构造函数模板执行" << endl;
		}

		//拷贝构造函数
		Human(const Human& th) : m_sname(th.m_sname)
		{
			cout << "Human(const Human& th)拷贝构造函数执行" << endl;
		}

		//移动构造函数
		Human(Human&& th) : m_sname(std::move(th.m_sname))
		{
			cout << "Human(Human&& th)移动构造函数执行" << endl;
		}

	private:
		string m_sname;
	};
}

int main()
{

	string sname = "ZhangSan";
	_nmsp1::Human myhuman1(sname);
	_nmsp1::Human myhuman2(string("LiSi"));         //"LiSi"是const char[5]类型，而string("LiSi")是string类型。

	//_nmsp1::Human myhuman3(myhuman1);             //实际编译器去调用了构造函数模板，而不是调用了拷贝构造函数。 std::enable_if
	_nmsp1::Human myhuman4(std::move(myhuman1));

	const _nmsp1::Human myhuman5(string("WangWu"));
	_nmsp1::Human myhuman6(myhuman5);

	return 0;
}

max_stars_repo_name: mallius/CppPrimer

max_issues_repo_name: mallius/CppPrimer

max_forks_repo_name: mallius/CppPrimer


text:
// Copyright (C) 2001-2003
// William E. Kempf
//
//  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/thread/thread.hpp>
#include <iostream>

struct helloworld
{
    helloworld(const char* who) : m_who(who) { }
    void operator()()
    {
        std::cout << m_who << "says, \"Hello World.\"" << std::endl;
    }
    const char* m_who;
};

int main()
{
    boost::thread thrd(helloworld("Bob"));
    thrd.join();
}

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
/***************************************************************************
 * Copyright 1998-2020 by authors (see AUTHORS.txt)                        *
 *                                                                         *
 *   This file is part of LuxCoreRender.                                   *
 *                                                                         *
 * 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 <boost/format.hpp>

#include "slg/scene/scene.h"
#include "slg/lights/trianglelight.h"

using namespace std;
using namespace luxrays;
using namespace slg;

//------------------------------------------------------------------------------
// SceneObjectDefinitions
//------------------------------------------------------------------------------

void SceneObjectDefinitions::DefineSceneObject(SceneObject *newObj) {
	const SceneObject *oldObj = static_cast<const SceneObject *>(objs.DefineObj(newObj));

	// Delete the old object definition
	delete oldObj;
}

void SceneObjectDefinitions::DefineIntersectableLights(LightSourceDefinitions &lightDefs,
		const Material *mat) const {
	const u_int size = objs.GetSize();

	for (u_int i = 0; i < size; ++i) {
		const SceneObject *so = static_cast<const SceneObject *>(objs.GetObj(i));

		if (so->GetMaterial() == mat)
			DefineIntersectableLights(lightDefs, so);
	}
}

void SceneObjectDefinitions::DefineIntersectableLights(LightSourceDefinitions &lightDefs,
		const SceneObject *obj) const {
	const ExtMesh *mesh = obj->GetExtMesh();

	// Add all new triangle lights
	for (u_int i = 0; i < mesh->GetTotalTriangleCount(); ++i) {
		TriangleLight *tl = new TriangleLight();
		tl->SetName(obj->GetName() + TRIANGLE_LIGHT_POSTFIX + ToString(i));
		tl->lightMaterial = obj->GetMaterial();
		tl->sceneObject = obj;
		// This is initialized in LightSourceDefinitions::Preprocess()
		tl->meshIndex = NULL_INDEX;
		tl->triangleIndex = i;
		tl->Preprocess();

		lightDefs.DefineLightSource(tl);
	}
}

void SceneObjectDefinitions::UpdateMaterialReferences(const Material *oldMat, const Material *newMat) {
	// Replace old material direct references with new ones
	BOOST_FOREACH(NamedObject *o, objs.GetObjs())
		static_cast<SceneObject *>(o)->UpdateMaterialReferences(oldMat, newMat);
}

void SceneObjectDefinitions::UpdateMeshReferences(const ExtMesh *oldMesh, ExtMesh *newMesh,
		boost::unordered_set<SceneObject *> &modifiedObjsList) {
	BOOST_FOREACH(NamedObject *o, objs.GetObjs()) {
		SceneObject *so = static_cast<SceneObject *>(o);

		if (so->UpdateMeshReference(oldMesh, newMesh))
			modifiedObjsList.insert(so);
	}
}

max_stars_repo_name: mbrukman/LuxCore


text:
/**
 * vanilla: VOCDetectionAnnotation.cpp
 * Copyright (c) Torr Vision Group, University of Oxford, 2016. All rights reserved.
 */

#include "VOCDetectionAnnotation.h"

#include "../core/VOCBox.h"

#include <iostream>

#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>

#include <boost/property_tree/xml_parser.hpp>

#include <tvgutil/containers/LimitedContainer.h>
#include <tvgutil/containers/MapUtil.h>
#include <tvgutil/persistence/PropertyUtil.h>
using namespace tvgutil;

//#################### CONSTRUCTORS ####################

VOCDetectionAnnotation::VOCDetectionAnnotation(const std::string& annotationPath)
: VOCAnnotation()
{
  read_annotation(annotationPath);
}

//#################### PUBLIC MEMBER FUNCTIONS ####################

std::vector<VOCObject> VOCDetectionAnnotation::get_objects(const boost::optional<DataTransformation>& dataTransformation) const
{
  if(!dataTransformation) return m_objects;

  std::vector<VOCObject> transformedObjects;
  for(size_t i = 0; i < m_objects.size(); ++i)
  {
    VOCBox vbox = (*dataTransformation).apply_transformation(m_objects[i].rep.get_voc_box(), size);

    VOCObject vObject(m_objects[i].difficult,
                      Shape(vbox),
                      m_objects[i].categoryName,
                      m_objects[i].categoryId);

    transformedObjects.push_back(vObject);
  }

  return transformedObjects;
}

/*
void VOCDetectionAnnotation::save(const std::string& saveDir) const
{
  // TODO;
  throw std::runtime_error("Not implemented yet");
}
*/

//#################### PRIVATE MEMBER FUNCTIONS ####################

void  VOCDetectionAnnotation::read_annotation(const std::string& path)
{
  boost::property_tree::ptree xmlAnnotation = PropertyUtil::load_properties_from_xml(path);
  VOCAnnotation::imageName = (boost::filesystem::path(path)).stem().string();
  std::string filename = xmlAnnotation.get<std::string>("annotation.filename");
  if(imageName != ((boost::filesystem::path(filename)).stem().string()))
    throw std::runtime_error("Mismatch..");

  int width = xmlAnnotation.get<int>("annotation.size.width");
  int height = xmlAnnotation.get<int>("annotation.size.height");
  int depth = xmlAnnotation.get<int>("annotation.size.depth");
  VOCAnnotation::size = Size(width, height, depth);

  BOOST_FOREACH(boost::property_tree::ptree::value_type const &v, xmlAnnotation.get_child("annotation") )
  {
    if(v.first == "object")
    {
      std::string name = v.second.get<std::string>("name");
      bool isDifficult = v.second.get<bool>("difficult");
      int xmin = v.second.get<int>("bndbox.xmin");
      int ymin = v.second.get<int>("bndbox.ymin");
      int xmax = v.second.get<int>("bndbox.xmax");
      int ymax = v.second.get<int>("bndbox.ymax");

      size_t id = MapUtil::lookup(VOCAnnotation::get_category_name_to_id(), name);
      if(id >= m_categoryCount) throw std::runtime_error("id exceeds the number of categories");

      Shape shape(VOCBox(xmin, ymin, xmax, ymax));
      m_objects.push_back(VOCObject(isDifficult, shape, name, id));
    }
  }
}

//#################### OUTPUT ####################

std::ostream& operator<<(std::ostream& os, const VOCDetectionAnnotation& a)
{
  os << "Objects: " << make_limited_container(a.get_objects(), 20) << '\n';
  return os;
}

max_stars_repo_name: torrvision/straighttoshapes

max_issues_repo_name: torrvision/straighttoshapes

max_forks_repo_name: torrvision/straighttoshapes


text:
/*
 For more information, please see: http://software.sci.utah.edu
 The MIT License
 Copyright (c) 2015 Scientific Computing and Imaging Institute,
 University of Utah.

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

//ComputePCA Algorithm: Computes Principal Component Analysis.

#include <Core/Algorithms/Base/AlgorithmPreconditions.h>
#include <Core/Algorithms/Math/ComputePCA.h>
#include <Core/Datatypes/DenseMatrix.h>
#include <Core/Datatypes/DenseColumnMatrix.h>
#include <Core/Datatypes/MatrixTypeConversions.h>
#include <Eigen/SVD>
#include <Core/Algorithms/Base/AlgorithmVariableNames.h>

using namespace SCIRun;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Algorithms::Math;

//Let's do some math.
//Algorithm:
void ComputePCAAlgo::run(MatrixHandle input, DenseMatrixHandle& LeftPrinMat, DenseMatrixHandle& PrinVals, DenseMatrixHandle& RightPrinMat) const{

    //Throws an error if one or both of the input matrix dimensions is zero.
    if (input->nrows() == 0 || input->ncols() == 0){

        THROW_ALGORITHM_INPUT_ERROR("Input has a zero dimension.");
    }

    //Input matrix: nxm
    if (matrixIs::dense(input))
    {
        //First, we have to center the data.
        auto denseInputCentered = centerData(input);

        //After the data is centered, then we compute SVD on the centered matrix.
        //Centered Matrix = U*S*Vt, Vt = V transpose
        Eigen::JacobiSVD<DenseMatrix::EigenBase> svd_mat(denseInputCentered, Eigen::ComputeFullU | Eigen::ComputeFullV);

        //U: Left principal matrix, nxn, orthogonal
        LeftPrinMat = boost::make_shared<DenseMatrix>(svd_mat.matrixU());

        //S: Principal values nxm, diagonal
        PrinVals = boost::make_shared<DenseMatrix>(svd_mat.singularValues());

        //V: Right singular mxm, orthognol
        RightPrinMat = boost::make_shared<DenseMatrix>(svd_mat.matrixV());
    }
    else
    {
        //Throw an error if the matrix is not dense.
        //Sparse matrices not supported at this time.
        THROW_ALGORITHM_INPUT_ERROR("ComputePCA works for dense matrix input only.");
    }
}

//Centers input matrix.
DenseMatrix ComputePCAAlgo::centerData(MatrixHandle input_matrix)
{
    //Casts the matrix as dense.
    auto denseInput = castMatrix::toDense(input_matrix);

    //Counts the number of rows in the input matrix.
    auto rows = denseInput->rows();

    //Calulates the centering matrix (C).
    // C = Identity(nxn) - 1/n * matrix of ones(nxn)
    auto centerMatrix = Eigen::MatrixXd::Identity(rows,rows) - (1.0/rows)*Eigen::MatrixXd::Constant(rows,rows,1);

    //Multiplying the input matrix by the centering matrix.
    auto denseInputCentered = centerMatrix * *denseInput;

    return denseInputCentered;
}

//Run the algorithm.
AlgorithmOutput ComputePCAAlgo::run(const AlgorithmInput& input) const
{
    auto input_matrix = input.get<Matrix>(Variables::InputMatrix);

    DenseMatrixHandle LeftPrinMat;
    DenseMatrixHandle PrinVals;
    DenseMatrixHandle RightPrinMat;

    run(input_matrix, LeftPrinMat, PrinVals, RightPrinMat);

    AlgorithmOutput output;

    output[LeftPrincipalMatrix] = LeftPrinMat;
    output[PrincipalValues] = PrinVals;
    output[RightPrincipalMatrix] = RightPrinMat;

    return output;
}

//Outputs:
AlgorithmOutputName ComputePCAAlgo::LeftPrincipalMatrix("LeftPrincipalMatrix");
AlgorithmOutputName ComputePCAAlgo::PrincipalValues("PrincipalValues");
AlgorithmOutputName ComputePCAAlgo::RightPrincipalMatrix("RightPrincipalMatrix");

ext: cc

max_stars_repo_name: Nahusa/SCIRun


text:
#pragma once

#include "cho_util/core/geometry/geometry_base.hpp"

#include <Eigen/Core>
#include <initializer_list>

namespace cho {
namespace core {

template <typename _Scalar, int N>
class Cuboid : public GeometryBase<Cuboid<_Scalar, N>> {
  using Scalar = _Scalar;

 public:
  explicit constexpr Cuboid() {}
  Cuboid(std::initializer_list<Scalar> args) {
    std::copy(args.begin(), args.end(), data_.data());
  }

  const Scalar* GetPtr() const { return data_.data(); }
  Scalar* GetPtr() { return data_.data(); }
  static constexpr int GetSize() { return N * 2; }

  auto& GetData() { return data_; }
  const auto& GetData() const { return data_; }

  auto GetMin() { return data_.col(0); }
  auto GetMax() { return data_.col(1); }
  auto GetMin() const { return data_.col(0); }
  auto GetMax() const { return data_.col(1); }

  template <typename Derived>
  auto SetMin(const Eigen::DenseBase<Derived>& d) {
    data_.col(0) = d;
  }
  template <typename Derived>
  auto SetMax(const Eigen::DenseBase<Derived>& d) {
    data_.col(1) = d;
  }

 private:
  // [Center, Radius]
  Eigen::Matrix<Scalar, N, 2> data_;

 public:
  friend class GeometryBase<Cuboid>;
  // EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};

template <typename _Scalar, int N>
struct GeometryTraits<Cuboid<_Scalar, N>> {
  using Scalar = _Scalar;
};

}  // namespace core
}  // namespace cho


text:
/* boost random/generate_canonical.hpp header file
 *
 * Copyright Steven Watanabe 2011
 * Distributed under the Boost Software License, Version 1.0. (See
 * accompanying file LICENSE_1_0.txt or copy at
 * http://www.boost.org/LICENSE_1_0.txt)
 *
 * See http://www.boost.org for most recent version including documentation.
 *
 * $Id$
 *
 */

#ifndef BOOST_RANDOM_GENERATE_CANONICAL_HPP
#define BOOST_RANDOM_GENERATE_CANONICAL_HPP

#include <algorithm>
#include <boost/assert.hpp>
#include <boost/config/no_tr1/cmath.hpp>
#include <boost/limits.hpp>
#include <boost/type_traits/is_integral.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/random/detail/signed_unsigned_tools.hpp>
#include <boost/random/detail/generator_bits.hpp>

namespace boost {
namespace random {

namespace detail {

template<class RealType, std::size_t bits, class URNG>
RealType generate_canonical_impl(URNG& g, boost::mpl::true_ /*is_integral*/)
{
    using std::pow;
    typedef typename URNG::result_type base_result;
    std::size_t digits = std::numeric_limits<RealType>::digits;
    RealType R = RealType((g.max)()) - RealType((g.min)()) + 1;
    RealType mult = R;
    RealType limit =
        pow(RealType(2),
            RealType((std::min)(static_cast<std::size_t>(bits), digits)));
    RealType S = RealType(detail::subtract<base_result>()(g(), (g.min)()));
    while(mult < limit) {
        RealType inc = RealType(detail::subtract<base_result>()(g(), (g.min)()));
        S += inc * mult;
        mult *= R;
    }
    return S / mult;
}

template<class RealType, std::size_t bits, class URNG>
RealType generate_canonical_impl(URNG& g, boost::mpl::false_ /*is_integral*/)
{
    using std::pow;
    using std::floor;
    BOOST_ASSERT((g.min)() == 0);
    BOOST_ASSERT((g.max)() == 1);
    std::size_t digits = std::numeric_limits<RealType>::digits;
    std::size_t engine_bits = detail::generator_bits<URNG>::value();
    std::size_t b = (std::min)(bits, digits);
    RealType R = pow(RealType(2), RealType(engine_bits));
    RealType mult = R;
    RealType limit = pow(RealType(2), RealType(b));
    RealType S = RealType(g() - (g.min)());
    while(mult < limit) {
        RealType inc(floor((RealType(g()) - RealType((g.min)())) * R));
        S += inc * mult;
        mult *= R;
    }
    return S / mult;
}

}

/**
 * Returns a value uniformly distributed in the range [0, 1)
 * with at least @c bits random bits.
 */
template<class RealType, std::size_t bits, class URNG>
RealType generate_canonical(URNG& g)
{
    RealType result = detail::generate_canonical_impl<RealType, bits>(
        g, boost::is_integral<typename URNG::result_type>());
    BOOST_ASSERT(result >= 0);
    BOOST_ASSERT(result <= 1);
    if(result == 1) {
        result -= std::numeric_limits<RealType>::epsilon() / 2;
        BOOST_ASSERT(result != 1);
    }
    return result;
}

} // namespace random
} // namespace boost

#endif // BOOST_RANDOM_GENERATE_CANONICAL_HPP

max_stars_repo_name: Abce/boost


text:
// [===========================================================================]
// [                                M o n e t a                                ]
// [---------------------------------------------------------------------------]
// [                                                                           ]
// [                          Copyright (C) 2005-2015                          ]
// [                      Rodrigo Madera <madera@acm.org>                      ]
// [                                                                           ]
// [---------------------------------------------------------------------------]
// [         Distributed under the Boost Software License, Version 1.0         ]
// [ Read accompanying LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt ]
// [===========================================================================]

// TODO: Rename this file.

#pragma once
#include "members.hxx"
#include <boost/assert.hpp>

#include <boost/preprocessor/stringize.hpp>

MONETA_DECLARE_MEMBER_TRAIT(member_name)

#define MONETA_MEMBER_NAME(member, name) \
	MONETA_DEFINE_TRAIT_WITH_GET(member_name, (member), std::string, BOOST_PP_STRINGIZE(name))

namespace moneta { namespace traits {

	MONETA_DEFINE_MEMBER_TRAIT_COLLECTOR(member_name, std::string, get_member_names)

	// FIXME: O(n): Sloooowwww.
	// XXX: Optimize this using hashes or something...
	template <class Entity>
	size_t get_member_name_index(const std::string& name) {
		const std::vector<std::string>& data = get_member_names<Entity>();

		std::vector<std::string>::const_iterator itr = std::find(data.begin(), data.end(), name);
		if (itr == data.end()) {
			BOOST_ASSERT(false);
			return -1;
		}

		return std::distance(data.begin(), itr);
	}

}}

ext: hxx

max_stars_repo_name: madera/Moneta

max_issues_repo_name: madera/Moneta

max_forks_repo_name: madera/Moneta


text:
#include <muduo/base/CountDownLatch.h>
#include <muduo/base/Logging.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/EventLoopThreadPool.h>
#include <muduo/net/TcpClient.h>

#include <boost/bind.hpp>
#include <boost/program_options.hpp>
#include <iostream>

#include <stdio.h>

namespace po = boost::program_options;
using namespace muduo;
using namespace muduo::net;

class Client : boost::noncopyable
{
 public:
  enum Operation
  {
    kGet,
    kSet,
  };

  Client(const string& name,
         EventLoop* loop,
         const InetAddress& serverAddr,
         Operation op,
         int requests,
         int keys,
         int valuelen,
         CountDownLatch* connected,
         CountDownLatch* finished)
    : name_(name),
      client_(loop, serverAddr, name),
      op_(op),
      sent_(0),
      acked_(0),
      requests_(requests),
      keys_(keys),
      valuelen_(valuelen),
      value_(valuelen_, 'a'),
      connected_(connected),
      finished_(finished)
  {
    value_ += "\r\n";
    client_.setConnectionCallback(boost::bind(&Client::onConnection, this, _1));
    client_.setMessageCallback(boost::bind(&Client::onMessage, this, _1, _2, _3));
    client_.connect();
  }

  void send()
  {
    Buffer buf;
    fill(&buf);
    conn_->send(&buf);
  }

 private:

  void onConnection(const TcpConnectionPtr& conn)
  {
    if (conn->connected())
    {
      conn_ = conn;
      connected_->countDown();
    }
    else
    {
      conn_.reset();
    }
  }

  void onMessage(const TcpConnectionPtr& conn,
                 Buffer* buffer,
                 Timestamp receiveTime)
  {
    if (op_ == kSet)
    {
      while (buffer->readableBytes() > 0)
      {
        const char* crlf = buffer->findCRLF();
        if (crlf)
        {
          buffer->retrieveUntil(crlf+2);
          ++acked_;
          if (sent_ < requests_)
          {
            send();
          }
        }
        else
        {
          break;
        }
      }
    }
    else
    {
      while (buffer->readableBytes() > 0)
      {
        const char* end = static_cast<const char*>(memmem(buffer->peek(),
                                                          buffer->readableBytes(),
                                                          "END\r\n", 5));
        if (end)
        {
          buffer->retrieveUntil(end+5);
          ++acked_;
          if (sent_ < requests_)
          {
            send();
          }
        }
        else
        {
          break;
        }
      }
    }
    if (acked_ == requests_)
    {
      conn_->shutdown();
      finished_->countDown();
    }
  }

  void fill(Buffer* buf)
  {
    char req[256];
    if (op_ == kSet)
    {
      snprintf(req, sizeof req, "set %s%d 42 0 %d\r\n", name_.c_str(), sent_ % keys_, valuelen_);
      ++sent_;
      buf->append(req);
      buf->append(value_);
    }
    else
    {
      snprintf(req, sizeof req, "get %s%d\r\n", name_.c_str(), sent_ % keys_);
      ++sent_;
      buf->append(req);
    }
  }

  string name_;
  TcpClient client_;
  TcpConnectionPtr conn_;
  const Operation op_;
  int sent_;
  int acked_;
  const int requests_;
  const int keys_;
  const int valuelen_;
  string value_;
  CountDownLatch* const connected_;
  CountDownLatch* const finished_;
};

int main(int argc, char* argv[])
{
  Logger::setLogLevel(Logger::WARN);

  uint16_t tcpport = 11211;
  string hostIp = "127.0.0.1";
  int threads = 4;
  int clients = 100;
  int requests = 100000;
  int keys = 10000;
  bool set = false;

  po::options_description desc("Allowed options");
  desc.add_options()
      ("help,h", "Help")
      ("port,p", po::value<uint16_t>(&tcpport), "TCP port")
      ("ip,i", po::value<string>(&hostIp), "Host IP")
      ("threads,t", po::value<int>(&threads), "Number of worker threads")
      ("clients,c", po::value<int>(&clients), "Number of concurrent clients")
      ("requests,r", po::value<int>(&requests), "Number of requests per clients")
      ("keys,k", po::value<int>(&keys), "Number of keys per clients")
      ("set,s", "Get or Set")
      ;

  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);
  po::notify(vm);

  if (vm.count("help"))
  {
    std::cout << desc << "\n";
    return 0;
  }
  set = vm.count("set");

  InetAddress serverAddr(hostIp, tcpport);
  LOG_WARN << "Connecting " << serverAddr.toIpPort();

  EventLoop loop;
  EventLoopThreadPool pool(&loop);

  int valuelen = 100;
  Client::Operation op = set ? Client::kSet : Client::kGet;

  double memoryMiB = 1.0 * clients * keys * (32+80+valuelen+8) / 1024 / 1024;
  LOG_WARN << "estimated memcached-debug memory usage " << int(memoryMiB) << " MiB";

  pool.setThreadNum(threads);
  pool.start();

  char buf[32];
  CountDownLatch connected(clients);
  CountDownLatch finished(clients);
  boost::ptr_vector<Client> holder;
  for (int i = 0; i < clients; ++i)
  {
    snprintf(buf, sizeof buf, "%d-", i+1);
    holder.push_back(new Client(buf,
                                pool.getNextLoop(),
                                serverAddr,
                                op,
                                requests,
                                keys,
                                valuelen,
                                &connected,
                                &finished));
  }
  connected.wait();
  LOG_WARN << clients << " clients all connected";
  Timestamp start = Timestamp::now();
  for (int i = 0; i < clients; ++i)
  {
    holder[i].send();
  }
  finished.wait();
  Timestamp end = Timestamp::now();
  LOG_WARN << "All finished";
  double seconds = timeDifference(end, start);
  LOG_WARN << seconds << " sec";
  LOG_WARN << 1.0 * clients * requests / seconds << " QPS";
}

max_stars_repo_name: ArronLin/muduo-master

max_issues_repo_name: weizhenwei/muduo

max_forks_repo_name: weizhenwei/muduo


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

#include <algorithm>
#include <cmath>
#include <stdexcept>

#include <boost/format.hpp>
#include <boost/throw_exception.hpp>

#include "sdm/kernel_projection.hpp"
#include "sdm/log.hpp"
#include "sdm/utils.hpp"

using boost::format;

namespace sdm {

////////////////////////////////////////////////////////////////////////////////
// General matrix math helpers

// symmetrize a matrix: m = (m + m') / 2
void symmetrize(double* matrix, size_t n) {
    // loop over half of matrix
    for (size_t i = 1; i < n; i++) {
        for (size_t j = 0; j < i; j++) {
            matrix[i + j*n] = matrix[j + i*n] =
                (matrix[i + j*n] + matrix[j + i*n]) / 2.;
        }
    }
}

////////////////////////////////////////////////////////////////////////////////
// Eigenvalues / eigenvectors helpers

// LAPACK: computes the eigenvalues/vectors of a square symmetric dense matrix
extern "C" void dsyev_(char *jobz, char *uplo, int *n, double *a,
        int *lda, double *w, double *work, int *lwork, int *info);
// FIXME: figure out how to support ILP64 lapacks, so that matlab interface
//  works on linux without LD_PRELOAD

/* Takes an n x n symmetric matrix and computes its eigendecomposition.
 *
 * Eigenvalues go in the n-element arre vals (in ascending order).
 *
 * Orthonormal eigenvectors go in the columns of the n^2-element array vecs,
 * in column-major order.
 *
 * jobz determines whether eigenvalues are actually calculated, but use the
 * overload below if you don't want them.
 *
 * Throws std::domain_error if dsyev fails.
 */
void eig(double* matrix, int n, double* vals, double* vecs, char jobz='V') {
    char uplo = 'U'; // indicate that upper-triangular part of matrix is present
    int info; // indicates whether the call was successful
    int lwork = 3*n - 1; // size of the work array  // TODO - tweak?
    double *work = new double[lwork]; // the work array

    // copy matrix into vecs, since dsyev_ is in-place
    std::copy(matrix, matrix + n*n, vecs);

    dsyev_(&jobz, &uplo, &n, vecs, &n, vals, work, &lwork, &info);

    delete[] work;

    if (info < 0) {
        BOOST_THROW_EXCEPTION(std::domain_error(
            (format("problem with dsyev argument %d") % (-info)).str()));
    } else if (info > 0) {
        BOOST_THROW_EXCEPTION(std::domain_error("dsyev: failed to converge"));
    }
}

/* Takes an n x n symmetric matrix and stores its eigenvalues in the n-element
 * array vals, in ascending order.
 */
void eig(double* matrix, size_t n, double* vals) {
    double* vecs = new double[n*n]; // allocate memory for dsyev to destroy
    eig(matrix, n, vals, vecs, 'N');
    delete[] vecs;
}

////////////////////////////////////////////////////////////////////////////////
// Spectral reconstruction

// BLAS: scales a vector by a constant
extern "C" void dscal_(int *n, double *alpha, double *x, int *incx);

// BLAS: computes generalized matrix product  C := alpha * A * B + beta * C
extern "C" void dgemm_(char *transa, char *transb,
       int *m, int *n, int *k,
       double *alpha, double *a, int *lda, void *b, int *ldb,
       double *beta, void *c, int *ldc);

/* Given an array of eigenvalues and corresponding orthonormal eigenvectors
 * (in column-major format), calculates the reconstructed matrix, optionally
 * throwing away any negative eigenvalues (which projects to the nearest
 * positive semidefinite matrix).
 */
void spectral_reconstruction(int n, double *eigvals, double *eigvecs,
        double *matrix, bool nonnegative_only = false)
{
    // We're calculating  V * max(diag(D), 0) * V'

    int step = 1;

    // First do the left-hand side: V * max(diag(D), 0)
    // Need to scale each column of V by the corresponding eigenvector
    double *leftside = new double[n * n];
    std::copy(eigvecs, eigvecs + n*n, leftside);

    for (size_t j = 0; j < n; j++) {
        double v = eigvals[j];
        if (nonnegative_only && v < 0)
            v = 0.;

        dscal_(&n, &v, eigvecs + j*n, &step);
    }

    // Now do (V * max(diag(D), 0)) * V'
    char no = 'N';
    char trans = 'T';
    double one = 1.;
    double zero = 0.;
    int size = (int) n;
    dgemm_(&no, &trans, &size, &size, &size,
            &one, leftside, &size, eigvecs, &size,
            &zero, matrix, &size);

    delete[] leftside;
}

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

/* Takes an n x n matrix stored as a flat array, symmetrizes it, and projects
 * in-place to the nearest positive semidefinite matrix.
 */
void project_to_symmetric_psd(double* matrix, size_t n) {
    double* eigvals = new double[n];
    double* eigvecs = new double[n*n];

    symmetrize(matrix, n);

    try {
        FILE_LOG(logDEBUG4) << "about to get eigenvalues of this matrix:\n" <<
            detail::matrixToString(matrix, n, n);

        eig(matrix, n, eigvals, eigvecs);

        // are any of our eigenvalues actually negative?
        // (note that we get the values back in ascending order)
        if (eigvals[0] < 0) {
            spectral_reconstruction(n, eigvals, eigvecs, matrix, true);
            symmetrize(matrix, n);
        }

    } catch (...) { delete[] eigvals; delete[] eigvecs; throw; }
    delete[] eigvals; delete[] eigvecs;
}

/* Takes an n x n matrix, stored as a flat array, symmetrizes it, and projects
 * it in-place to the nearest positive semidefinite matrix with unit diagonal.
 */
void project_to_covariance(double* matrix, size_t n, size_t steps, double tol) {
    // The alternating projection method (algorithm 3.3) of
    //   Nicholas J. Higham, 2002.
    //   Computing the Nearest Correlation Matrix: a Problem from Finance.
    //   IMA Journal of Numerical Analysis, pages 329-343.

    double* eigvals = new double[n];
    double* eigvecs = new double[n*n];

    // Dykstra's correction
    double *S = new double[n*n];
    std::fill(S, S+n*n, 0);

    // R is the corrected form of matrix
    double *R = new double[n*n];

    // X is projected to be symmetric PSD
    double *X = new double[n*n];
    std::copy(matrix, matrix + n*n, X);

    // used to check for x's convergence
    double *prev_X = new double[n*n];

    try {
        symmetrize(matrix, n);

        for (size_t iter = 0; iter < steps; iter++) {
            // remember the previous x
            std::copy(X, X + n*n, prev_X);

            // R is the matrix minus the correction
            for (size_t i = 0; i < n*n; i++)
                R[i] = matrix[i] - S[i];

            // X is projection of R to symmetric PSD matrix
            eig(R, n, eigvals, eigvecs);
            spectral_reconstruction(n, eigvals, eigvecs, X, true);
            symmetrize(X, n);

            // new correction is the difference between X and R
            for (size_t i = 0; i < n*n; i++)
                S[i] = X[i] - R[i];

            // new matrix is X with unit diagonal
            std::copy(X, X + n*n, matrix);
            for (size_t i = 0; i < n; i++)
                matrix[i + i*n] = 1.;

            // have we converged?
            if (iter > 0) {
                double biggest_x = 0;
                double biggest_change = 0;
                for (size_t i = 0; i < n*n; i++) {
                    double mag = std::abs(X[i]);
                    if (mag > biggest_x)
                        biggest_x = mag;

                    double change = std::abs(X[i] - prev_X[i]);
                    if (change > biggest_change)
                        biggest_change = change;
                }

                if (biggest_change <= 1e-7 * biggest_x) {
                    break;
                }
            }
        }

        // make sure we don't have any too-negative eigenvalues
        eig(matrix, n, eigvals);
        if (eigvals[0] < tol) {
            BOOST_THROW_EXCEPTION(std::domain_error(
                    (format("Failed to project to kernel matrix: min eig %g")
                     % eigvals[0]).str()));
        }

    } catch (...) { // fake a finally block
        delete[] eigvals; delete[] eigvecs;
        delete[] S; delete[] R;
        delete[] X; delete[] prev_X;
        throw;
    }
    delete[] eigvals; delete[] eigvecs;
    delete[] S; delete[] R;
    delete[] X; delete[] prev_X;
}

} // end namespace

max_stars_repo_name: dougalsutherland/sdm

max_issues_repo_name: dougalsutherland/sdm

max_forks_repo_name: dougalsutherland/sdm