text:
/**
 * This module is a mock of a web service
 * Basically it is a web service that will write create an answer exactly as a reguler handler would.
 * We had to test the web service this way
 **/

#include <assert.h>
#include <httpd.h>
#include <http_config.h>
#include <http_core.h>
#include <http_protocol.h>
// Work-around boost::chrono 1.53 conflict on CR typedef vs define in apache
#undef CR

#include <iostream>
#include <list>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <boost/algorithm/string/split.hpp>
#include <map>
#include <vector>
#include <boost/lexical_cast.hpp>

#define SYSLOG_NAMES
#include <sys/syslog.h>

extern module AP_MODULE_DECLARE_DATA dup_mock;

namespace dupMock {

#define SETTINGS_FROM_PARMS(parms) reinterpret_cast<Conf *>(ap_get_module_config(parms->server->module_config, &dup_mock))
#define SETTINGS_FROM_SERVER(server) reinterpret_cast<Conf *>(ap_get_module_config(server->module_config, &dup_mock))

/*
 * Callback to iterate over the headers tables
 * Pushes a copy of key => value in a list
 */
int iterateOverHeadersCallBack(void *d, const char *key, const char *value) {
    std::map< std::string, std::string> *lHeader = reinterpret_cast< std::map< std::string, std::string> *>(d);

    (*lHeader)[std::string(key)] = std::string(value);

    return 1;
}

struct Conf {

    std::string path; /** Path to look the mock files in */
    std::list<std::pair<std::string, std::string> > mocks; /** Match , content to respond */

};

static Conf conf;

static int	wsmock_handler(request_rec *r);
static void	register_hooks(apr_pool_t *pool);

void *createServerConfig(apr_pool_t *pPool, server_rec* ) {
    return new Conf();
}

const char* readBodyData(request_rec* r) {
    int rc = ap_setup_client_block( r, REQUEST_CHUNKED_DECHUNK);

    if( rc != OK ){
        return NULL;
    }

    if( ap_should_client_block(r) ){

        char buf[HUGE_STRING_LEN];
        apr_off_t rpos = 0;
        apr_off_t length = r->remaining;
        char* result = reinterpret_cast<char*>(apr_pcalloc( r->pool, length + 1));
        syslog(LOG_ERR, "DUP MOCK %ld bytes remaining", r->remaining);

        if( result == NULL ){
            syslog(LOG_ERR, "Unable to allocate memory");
            return NULL;
        }

        long int bytes_read = 1;
        while( bytes_read > 0 ){
            bytes_read = ap_get_client_block(r, buf, HUGE_STRING_LEN);
            syslog(LOG_ERR, "Remaining %ld after we got a block of %ld",
                                     r->remaining, bytes_read);
            if( bytes_read <= 0 ){
                break;
            }
            if ( length < (bytes_read + rpos + 1) ) {
                ///TODO find a more efficient memory reallocation model
                // Compressed body with more bytes than planned, realloc more
                length = (length + bytes_read) * 2;
                // we end up storing again with twice the size
                char *prevres = result;
                result = reinterpret_cast<char*>(apr_pcalloc( r->pool, length + 1));
                syslog(LOG_ERR, "Realloc result buffer to %ld bytes because result is bigger than expected (gziped body decompression)", length);
                // so copy the previous buffer
                memcpy(result, prevres, rpos);
            }
            memcpy(result + rpos, buf, bytes_read);
            rpos += bytes_read;
        }
        return result;

    }
    return NULL;
}

static int wsmock_handler(request_rec *r) {
    std::string answer;

    if (!r->handler || strcmp(r->handler, "dup_mock"))
        return (DECLINED);

    syslog(LOG_ERR, "DUP MOCK HANDLING REQUEST");

    struct Conf *conf = SETTINGS_FROM_SERVER(r->server);
    assert(conf);

    readBodyData(r); // read body data (needed to proper testing of compare input filters

    std::string uri = r->unparsed_uri;

    // dup_mock will be used for dynamic inquiring purposes (get the headers, the method, etc.)
    // it will then dump the requested info in the body
    if (uri.find("/inquire?") != std::string::npos) { // /inquire?method,headers,contenttype
        std::string queryString = uri.substr(uri.find("?")+1,std::string::npos); // get the query string (past the ?)
        std::vector<std::string> infos;
        boost::split(infos, queryString, [](char c) { return c==',';});
        for (const std::string& info : infos) {
            if (info == "method") {
                ap_rputs("Method: ",r);
                ap_rputs(r->method,r);
                ap_rputs("\n",r);
                ap_rputs("Method number: ",r);
                ap_rputs(std::to_string(r->method_number).c_str(),r);
                ap_rputs("\n\n",r);
            } else
            if (info == "headers") {
                std::map< std::string, std::string> headersMap;
                apr_table_do(&iterateOverHeadersCallBack, &headersMap, r->headers_in, NULL);
                for (const auto& pair : headersMap) {
                    ap_rputs((pair.first+": ").c_str(),r);
                    ap_rputs((pair.second+"\n").c_str(),r);
                }
                ap_rputs("\n",r);
            } else
            if (info == "contenttype") {
                ap_rputs("Content-Type2: ",r);
                ap_rputs(r->content_type,r);
                ap_rputs("\n",r);
            }
        }
        return OK;
    } else if (uri.find("/sleep") != std::string::npos) { // /sleep?for=1 or just /sleep (1 sec)
        std::string lastUriPart = uri.substr(uri.find("/sleep"),std::string::npos);
        int duration;

        if (lastUriPart.find("?for") == std::string::npos) duration = 1;
        else sscanf(lastUriPart.c_str(),"/sleep?for=%d",&duration);

        sleep(duration);
        ap_rputs("Slept for ", r);
        ap_rputs(boost::lexical_cast<std::string>(duration).c_str(),r);
        ap_rputs(" sec\n",r);
        syslog(LOG_ERR, "END SLEEP DUP MOCK");
        return OK;
    }

    ap_set_content_type(r, "text/html");

    std::list<std::pair<std::string, std::string> > &mocks = conf->mocks;
    std::list<std::pair<std::string, std::string> >::iterator it = mocks.begin(),
        ite = mocks.end();

    while (it != ite) {
        if (std::string::npos != uri.find(it->first)) {
            ap_rputs(it->second.c_str(), r);
            return OK;
        }
        ++it;
    }

    ap_rputs("*** Generic mock answer (no match) ***", r);
    return OK;
}

static void register_hooks(apr_pool_t *pool) {
    // declare the web service handler
    ap_hook_handler(wsmock_handler, NULL, NULL, APR_HOOK_MIDDLE);
}

const char* setDir(cmd_parms* pParams, void* pCfg, const char* pPath) {
    if (!pPath || strlen(pPath) == 0) {
        return "Set the directory name";
    }
    struct Conf *conf = SETTINGS_FROM_PARMS(pParams);

    assert(conf);
    conf->path = pPath;
    return NULL;
}

std::string read_file(const std::string &fileName) {
    std::string content;
    int fd = open(fileName.c_str(), O_RDONLY);
    if (fd == -1 )
        return std::string("Cannot open file: ") + fileName;
    char buf[1024];
    int r;
    while ((r = read(fd, buf, 1024)) > 0) {
        content.append(buf, r);
    }
    close(fd);
    return content;
}

const char* setMockFile(cmd_parms* pParams, void* pCfg, const char* toMatch, const char *fileName) {
    if (!toMatch || !strlen(toMatch) || !fileName || !strlen(fileName) ) {
        return "Usage: 'String to match in URI' 'filename'";
    }
    struct Conf *conf = SETTINGS_FROM_PARMS(pParams);
    assert(conf);

    if (conf->path.empty()) {
        return "Set mock location first";
    }

    // read content
    std::string fileContent = read_file(conf->path + fileName);

    // Push it into list
    std::list<std::pair<std::string, std::string> > &mocks = conf->mocks;
    std::list<std::pair<std::string, std::string> >::iterator it = mocks.begin(),
        ite = mocks.end();

    while (it != ite) {
        std::list<std::pair<std::string, std::string> >::iterator itn = it;
        ++itn;
        if (itn == ite) {
            break;
        }
        const std::string &loc = itn->first;
        if (loc.size() < strlen(toMatch))
            break;
        ++it;
    }

    if (it == ite) {
        mocks.push_back(std::make_pair(toMatch, fileContent));
    } else {
        mocks.insert(it, std::make_pair(toMatch, fileContent));
    }

    return NULL;
}

command_rec gCmds[] = {
    AP_INIT_TAKE1("MockDir",
                  reinterpret_cast<const char *(*)()>(&dupMock::setDir),
                  0,
                  OR_ALL,
                  "The path where to look for content"),
    AP_INIT_TAKE2("MockFile",
                  reinterpret_cast<const char *(*)()>(&dupMock::setMockFile),
                  0,
                  OR_ALL,
                  "Set a file content as answer for url matching the first parameter"),
};

}; // namespace dupMock

module AP_MODULE_DECLARE_DATA dup_mock = {
    STANDARD20_MODULE_STUFF,
    NULL,
    NULL,
    dupMock::createServerConfig,
    NULL,
    dupMock::gCmds,
    dupMock::register_hooks,
};

ext: cc


text:
// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#ifndef NIX_SOURCE_HDF5_H
#define NIX_SOURCE_HDF5_H

#include <nix/base/ISource.hpp>
#include <nix/hdf5/EntityWithMetadataHDF5.hpp>

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

namespace nix {
namespace hdf5 {

/**
 * An entity that implements ISource for the HDF5 back-end.
 */
class SourceHDF5 : virtual public base::ISource, public EntityWithMetadataHDF5  {

private:

    optGroup source_group;

public:

    /**
     * Standard constructor for existing Source
     */
    SourceHDF5(const std::shared_ptr<base::IFile> &file, const Group &group);

    /**
     * Default constructor.
     */
    SourceHDF5(const std::shared_ptr<base::IFile> &file, const Group &group, const std::string &id, const std::string &type,
               const std::string &name);

    /**
     * Default constructor that preserves the creation time.
     */
    SourceHDF5(const std::shared_ptr<base::IFile> &file, const Group &group, const std::string &id, const std::string &type,
               const std::string &name, time_t time);

    //--------------------------------------------------
    // Methods concerning child sources
    //--------------------------------------------------

    bool hasSource(const std::string &name_or_id) const;

    std::shared_ptr<base::ISource> getSource(const std::string &name_or_id) const;

    std::shared_ptr<base::ISource> getSource(size_t index) const;

    ndsize_t sourceCount() const;

    std::shared_ptr<base::ISource> createSource(const std::string &name, const std::string &type);

    bool deleteSource(const std::string &name_or_id);

    //--------------------------------------------------
    // Other methods and functions
    //--------------------------------------------------

    virtual ~SourceHDF5();
};

} // namestace hdf5
} // namespace nix

#endif // NIX_SOURCE_HDF5_H

ext: hpp


text:
//
//  Copyright (c) 2002-2003
//  Toon Knapen, Kresimir Fresl, Joerg Walter
//
// 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_NUMERIC_BINDINGS_TRAITS_MATRIX_RAW_HPP
#define BOOST_NUMERIC_BINDINGS_TRAITS_MATRIX_RAW_HPP

#include <cstddef>
#include <boost/numeric/ublas/config.hpp>
#ifndef BOOST_UBLAS_HAVE_BINDINGS
#  include <boost/numeric/ublas/matrix.hpp>
#endif

namespace boost { namespace numeric { namespace bindings { namespace traits {

  namespace ublas = boost::numeric::ublas;

  // size:

  template <typename M>
  BOOST_UBLAS_INLINE
  int matrix_size1 (const M &m) {
    return (int) m.size1();
  }
  template <typename M>
  BOOST_UBLAS_INLINE
  int matrix_size2 (const M &m) {
    return (int) m.size2();
  }

#if 0
  // MSVC seems to dislike overloads if there is 'generic' template
  template <typename M>
  BOOST_UBLAS_INLINE
  int matrix_size1 (const ublas::matrix_reference<M> &m) {
    return matrix_size1 (m.expression());
  }
  template <typename M>
  BOOST_UBLAS_INLINE
  int matrix_size2 (const ublas::matrix_reference<M> &m) {
    return matrix_size2 (m.expression());
  }
#endif // 0

  template <typename T, typename F, typename A>
  BOOST_UBLAS_INLINE
  int matrix_storage_size (const ublas::matrix<T,F,A>& m) {
    return (int) (m.size1() * m.size2());
  }
  template <typename T, std::size_t M, std::size_t N>
  BOOST_UBLAS_INLINE
  int matrix_storage_size (const ublas::c_matrix<T, M, N> &m) {
    return (int) (M * N);
  }

  template <typename T, typename F, typename A>
  BOOST_UBLAS_INLINE
  int leading_dimension (const ublas::matrix<T,F,A> &m, ublas::row_major_tag) {
    return (int) m.size2();
  }
  template <typename T, typename F, typename A>
  BOOST_UBLAS_INLINE
  int leading_dimension (const ublas::matrix<T,F,A> &m, ublas::column_major_tag) {
    return (int) m.size1();
  }
  template <typename T, typename F, typename A>
  BOOST_UBLAS_INLINE
  int leading_dimension (const ublas::matrix<T,F,A> &m) {
    typedef ublas::matrix<T,F,A> matrix_t;
    return bindings::traits::leading_dimension
      (m, BOOST_UBLAS_TYPENAME matrix_t::orientation_category());
  }
  template <typename M>
  BOOST_UBLAS_INLINE
  int leading_dimension (const ublas::matrix_reference<M> &m) {
    return bindings::traits::leading_dimension (m.expression());
  }
  template <typename M>
  BOOST_UBLAS_INLINE
  int leading_dimension (const ublas::matrix_range<M> &m) {
    return bindings::traits::leading_dimension (m.data());
  }
  template <typename T, std::size_t M, std::size_t N>
  BOOST_UBLAS_INLINE
  int leading_dimension (const ublas::c_matrix<T, M, N> &m) {
    return (int) N;
  }

  // stride:

#if 0
  // MSVC seems to dislike overloads if there is 'generic' template
  template <typename M>
  BOOST_UBLAS_INLINE
  int matrix_stride1 (const M &m) {
    typedef typename M::functor_type functor_type;
    return (int) functor_type::one1 (m.size1(), m.size2());
  }
  template <typename M>
  BOOST_UBLAS_INLINE
  int matrix_stride2 (const M &m) {
    typedef typename M::functor_type functor_type;
    return (int) functor_type::one2 (m.size1(), m.size2());
  }
#endif // 0

  template <typename M, typename F, typename A>
  BOOST_UBLAS_INLINE
  int matrix_stride1 (const ublas::matrix<M,F,A> &m) {
    return (int) F::one1 (m.size1(), m.size2());
  }
  template <typename M, typename F, typename A>
  BOOST_UBLAS_INLINE
  int matrix_stride2 (const ublas::matrix<M,F,A> &m) {
    return (int) F::one2 (m.size1(), m.size2());
  }
  template <typename M>
  BOOST_UBLAS_INLINE
  int matrix_stride1 (const ublas::matrix_reference<M> &m) {
    return matrix_stride1 (m.expression());
  }
  template <typename M>
  BOOST_UBLAS_INLINE
  int matrix_stride2 (const ublas::matrix_reference<M> &m) {
    return matrix_stride2 (m.expression());
  }
  template <typename T, std::size_t M, std::size_t N>
  BOOST_UBLAS_INLINE
  int matrix_stride1 (const ublas::c_matrix<T, M, N> &m) { return (int) N; }
  template <typename T, std::size_t M, std::size_t N>
  BOOST_UBLAS_INLINE
  int matrix_stride2 (const ublas::c_matrix<T, M, N> &m) { return 1; }
  template <typename M>
  BOOST_UBLAS_INLINE
  int matrix_stride1 (const ublas::matrix_range<M> &m) {
    return matrix_stride1 (m.data());
  }
  template <typename M>
  BOOST_UBLAS_INLINE
  int matrix_stride2 (const ublas::matrix_range<M> &m) {
    return matrix_stride2 (m.data());
  }
  template <typename M>
  BOOST_UBLAS_INLINE
  int matrix_stride1 (const ublas::matrix_slice<M> &m) {
    return (int) (m.stride1() * matrix_stride1 (m.data()));
  }
  template <typename M>
  BOOST_UBLAS_INLINE
  int matrix_stride2 (const ublas::matrix_slice<M> &m) {
    return (int) (m.stride2() * matrix_stride2 (m.data()));
  }
  template <typename M>
  BOOST_UBLAS_INLINE
  int vector_stride (const ublas::matrix_row<M> &v) {
    return matrix_stride2 (v.data());
  }
  template <typename M>
  BOOST_UBLAS_INLINE
  int vector_stride (const ublas::matrix_column<M> &v) {
    return matrix_stride1 (v.data());
  }

  // storage:

#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING
  template <typename T, typename F, typename A>
  BOOST_UBLAS_INLINE
  typename ublas::matrix<T,F,A>::const_pointer
  matrix_storage (const ublas::matrix<T,F,A> &m) {
    return &m.data().begin()[0];
  }
#endif
  // We need storage_const() mostly due to MSVC 6.0.
  // But how shall we write portable code otherwise?
  template <typename T, typename F, typename A>
  BOOST_UBLAS_INLINE
  typename ublas::matrix<T,F,A>::const_pointer
  matrix_storage_const (const ublas::matrix<T,F,A> &m) {
    return &m.data().begin()[0];
  }
  template <typename T, typename F, typename A>
  BOOST_UBLAS_INLINE
  typename ublas::matrix<T,F,A>::pointer
  matrix_storage (ublas::matrix<T,F,A> &m) {
    return &m.data().begin()[0];
  }

#if 0
  // MSVC seems to dislike overloads if there is 'generic' template
#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING
  template <typename M>
  BOOST_UBLAS_INLINE
  typename M::const_pointer matrix_storage (const M &m) {
    return &m.data().begin()[0];
  }
#endif
  // We need storage_const() mostly due to MSVC 6.0.
  // But how shall we write portable code otherwise?
  template <typename M>
  BOOST_UBLAS_INLINE
  typename M::const_pointer matrix_storage_const (const M &m) {
    return &m.data().begin()[0];
  }
  template <typename M>
  BOOST_UBLAS_INLINE
  typename M::pointer matrix_storage (M &m) {
    return &m.data().begin()[0];
  }
#endif // 0

#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING
  template <typename M>
  BOOST_UBLAS_INLINE
  typename M::const_pointer
  matrix_storage (const ublas::matrix_reference<M> &m) {
    return matrix_storage (m.expression ());
  }
#endif
  // We need storage_const() mostly due to MSVC 6.0.
  // But how shall we write portable code otherwise?
  template <typename M>
  BOOST_UBLAS_INLINE
  typename M::const_pointer
  matrix_storage_const (const ublas::matrix_reference<M> &m) {
    return matrix_storage_const (m.expression ());
  }
  template <typename M>
  BOOST_UBLAS_INLINE
  typename M::pointer matrix_storage (ublas::matrix_reference<M> &m) {
    return matrix_storage (m.expression ());
  }

#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING
  template <typename T, std::size_t M, std::size_t N>
  BOOST_UBLAS_INLINE
  typename ublas::c_matrix<T, M, N>::const_pointer
  matrix_storage (const ublas::c_matrix<T, M, N> &m) {
    return m.data();
  }
#endif
#ifndef BOOST_MSVC
  // We need storage_const() mostly due to MSVC 6.0.
  // But how shall we write portable code otherwise?
  template <typename T, std::size_t M, std::size_t N>
  BOOST_UBLAS_INLINE
  typename ublas::c_matrix<T, M, N>::const_pointer
  matrix_storage_const (const ublas::c_matrix<T, M, N> &m) {
    return m.data();
  }
  template <typename T, std::size_t M, std::size_t N>
  BOOST_UBLAS_INLINE
  typename ublas::c_matrix<T, M, N>::pointer
  matrix_storage (ublas::c_matrix<T, M, N> &m) {
    return m.data();
  }
#endif

#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING
  template <typename M>
  BOOST_UBLAS_INLINE
  typename M::const_pointer
  matrix_storage (const ublas::matrix_range<M> &m) {
    return matrix_storage (m.data())
      + m.start1() * matrix_stride1 (m.data())
      + m.start2() * matrix_stride2 (m.data());
  }
  template <typename M>
  BOOST_UBLAS_INLINE
  typename M::const_pointer
  matrix_storage (const ublas::matrix_slice<M> &m) {
    return matrix_storage (m.data())
      + m.start1() * matrix_stride1 (m.data ())
      + m.start2() * matrix_stride2 (m.data ());
  }
#endif
  // We need storage_const() mostly due to MSVC 6.0.
  // But how shall we write portable code otherwise?
  template <typename M>
  BOOST_UBLAS_INLINE
  typename M::const_pointer
  matrix_storage_const (const ublas::matrix_range<M> &m) {
    return matrix_storage_const (m.data())
      + m.start1() * matrix_stride1 (m.data ())
      + m.start2() * matrix_stride2 (m.data ());
  }
  template <typename M>
  BOOST_UBLAS_INLINE
  typename M::const_pointer
  matrix_storage_const (const ublas::matrix_slice<M> &m) {
    return matrix_storage_const (m.data())
      + m.start1() * matrix_stride1 (m.data ())
      + m.start2() * matrix_stride2 (m.data ());
  }
  template <typename M>
  BOOST_UBLAS_INLINE
  typename M::pointer matrix_storage (ublas::matrix_range<M> &m) {
    return matrix_storage (m.data())
      + m.start1() * matrix_stride1 (m.data ())
      + m.start2() * matrix_stride2 (m.data ());
  }
  template <typename M>
  BOOST_UBLAS_INLINE
  typename M::pointer matrix_storage (ublas::matrix_slice<M> &m) {
    return matrix_storage (m.data())
      + m.start1() * matrix_stride1 (m.data ())
      + m.start2() * matrix_stride2 (m.data ());
  }

#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING
  template <typename M>
  BOOST_UBLAS_INLINE
  typename M::const_pointer
  vector_storage (const ublas::matrix_row<M> &v) {
    return matrix_storage (v.data())
      + v.index() * matrix_stride1 (v.data());
  }
  template <typename M>
  BOOST_UBLAS_INLINE
  typename M::const_pointer
  vector_storage (const ublas::matrix_column<M> &v) {
    return matrix_storage (v.data())
      + v.index() * matrix_stride2 (v.data());
  }
#endif
  // We need storage_const() mostly due to MSVC 6.0.
  // But how shall we write portable code otherwise?
  template <typename M>
  BOOST_UBLAS_INLINE
  typename M::const_pointer
  vector_storage_const (const ublas::matrix_row<M> &v) {
    return matrix_storage_const (v.data())
      + v.index() * matrix_stride1 (v.data());
  }
  template <typename M>
  BOOST_UBLAS_INLINE
  typename M::const_pointer
  vector_storage_const (const ublas::matrix_column<M> &v) {
    return matrix_storage_const (v.data())
      + v.index() * matrix_stride2 (v.data());
  }
  template <typename M>
  BOOST_UBLAS_INLINE
  typename M::pointer vector_storage (ublas::matrix_row<M> &v) {
    return matrix_storage (v.data())
      + v.index() * matrix_stride1 (v.data());
  }
  template <typename M>
  BOOST_UBLAS_INLINE
  typename M::pointer vector_storage (ublas::matrix_column<M> &v) {
    return matrix_storage (v.data())
      + v.index() * matrix_stride2 (v.data());
  }

}}}}

#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_NO_SYMMETRIC_TRAITS

#include <boost/numeric/bindings/traits/symm_herm_raw.hpp>

#endif // BOOST_NUMERIC_BINDINGS_POOR_MANS_NO_SYMMETRIC_TRAITS

#endif // BOOST_NUMERIC_BINDINGS_TRAITS_MATRIX_RAW_HPP

max_stars_repo_name: inducer/boost-numeric-bindings

max_issues_repo_name: jdsika/holy

max_forks_repo_name: jdsika/holy


text:
#include <ros/ros.h>
#include <actionlib/client/simple_action_client.h>
#include <behaviors/IntakeAction.h>
#include <behaviors/PlaceAction.h>
#include <behaviors/ElevatorAction.h>
#include <behaviors/ClimbAction.h>
#include <behaviors/AlignAction.h>
#include <behaviors/enumerated_elevator_indices.h>
#include <boost/algorithm/string.hpp>
#include <string>

double server_wait_timeout = 20.0; //how long to wait for a server to exist before exiting, in sec.
double server_exec_timeout = 20.0; //how long to wait for an actionlib server call to finish before timing out, in sec. Used for all actionlib calls

bool callElevator(int setpoint_idx)
{
	//create client to call actionlib server
	actionlib::SimpleActionClient<behaviors::ElevatorAction> elevator_ac("/elevator/elevator_server", true);

	ROS_INFO("Waiting for elevator server to start.");
	if(!elevator_ac.waitForServer(ros::Duration(server_wait_timeout)))
	{
		ROS_ERROR("Could not find server within %f seconds.", server_wait_timeout);
	}

	ROS_INFO("Sending goal to elevator server, setpoint = %d", setpoint_idx);
	// send a goal to the action
	behaviors::ElevatorGoal goal;
	goal.setpoint_index = setpoint_idx;
	elevator_ac.sendGoal(goal);

	//wait for the action to return
	bool finished_before_timeout = elevator_ac.waitForResult(ros::Duration(server_exec_timeout));

	if (finished_before_timeout)
	{
		actionlib::SimpleClientGoalState state = elevator_ac.getState();
		ROS_INFO("Action finished with state: %s",state.toString().c_str());
		if(elevator_ac.getResult()->timed_out)
		{
			ROS_INFO("Elevator Server timed out!");
		}
		return true;
	}
	else
	{
		ROS_INFO("Action did not finish before the time out.");
		return false;
	}

}

bool callIntakeCargo()
{
	//create client to call actionlib server
	actionlib::SimpleActionClient<behaviors::IntakeAction> intake_cargo_ac("/cargo_intake/cargo_intake_server", true);

	ROS_INFO("Waiting for cargo intake server to start.");
	if(!intake_cargo_ac.waitForServer(ros::Duration(server_wait_timeout)))
	{
		ROS_ERROR("Could not find server within %f seconds.", server_wait_timeout);
	}

	ROS_INFO("Sending goal to intake cargo server.");
	// send a goal to the action
	behaviors::IntakeGoal intake_cargo_goal;
	intake_cargo_ac.sendGoal(intake_cargo_goal);

	//wait for the action to return
	bool finished_before_timeout = intake_cargo_ac.waitForResult(ros::Duration(server_exec_timeout));

	if (finished_before_timeout)
	{
		actionlib::SimpleClientGoalState state = intake_cargo_ac.getState();
		ROS_INFO("Action finished with state: %s",state.toString().c_str());
		if(intake_cargo_ac.getResult()->timed_out)
		{
			ROS_INFO("Intake cargo server timed out!");
		}
		return true;
	}
	else
	{
		ROS_INFO("Action did not finish before the time out.");
		return false;
	}
}

bool callOuttakeCargo(int setpoint_idx)
{
	//create client to call actionlib server
	actionlib::SimpleActionClient<behaviors::PlaceAction> outtake_cargo_ac("/cargo_outtake/cargo_outtake_server", true);

	ROS_INFO("Waiting for cargo outtake server to start.");
	if(!outtake_cargo_ac.waitForServer(ros::Duration(server_wait_timeout)))
	{
		ROS_ERROR("Could not find server within %f seconds.", server_wait_timeout);
	}

	ROS_INFO("Sending goal to outtake cargo server.");
	// send a goal to the action
	behaviors::PlaceGoal outtake_cargo_goal;
	outtake_cargo_goal.setpoint_index = setpoint_idx;
	outtake_cargo_ac.sendGoal(outtake_cargo_goal);

	//wait for the action to return
	bool finished_before_timeout = outtake_cargo_ac.waitForResult(ros::Duration(server_exec_timeout));

	if (finished_before_timeout)
	{
		actionlib::SimpleClientGoalState state = outtake_cargo_ac.getState();
		ROS_INFO("Action finished with state: %s",state.toString().c_str());
		if(outtake_cargo_ac.getResult()->timed_out)
		{
			ROS_INFO("Outtake cargo server timed out!");
		}
		return true;
	}
	else
	{
		ROS_INFO("Action did not finish before the time out.");
		return false;
	}
}

bool callIntakeHatchPanel()
{
	//create client to call actionlib server
	actionlib::SimpleActionClient<behaviors::IntakeAction> intake_hatch_panel_ac("/hatch_intake/intake_hatch_panel_server", true);

	ROS_INFO("Waiting for panel intake server to start.");
	if(!intake_hatch_panel_ac.waitForServer(ros::Duration(server_wait_timeout)))
	{
		ROS_ERROR("Could not find server within %f seconds.", server_wait_timeout);
	}

	ROS_INFO("Sending goal to intake hatch panel server.");
	// send a goal to the action
	behaviors::IntakeGoal intake_hatch_panel_goal;
	intake_hatch_panel_ac.sendGoal(intake_hatch_panel_goal);

	//wait for the action to return
	bool finished_before_timeout = intake_hatch_panel_ac.waitForResult(ros::Duration(server_exec_timeout));

	if (finished_before_timeout)
	{
		actionlib::SimpleClientGoalState state = intake_hatch_panel_ac.getState();
		ROS_INFO("Action finished with state: %s",state.toString().c_str());
		if(intake_hatch_panel_ac.getResult()->timed_out)
		{
			ROS_INFO("Panel intake server timed out!");
		}
		return true;
	}
	else
	{
		ROS_INFO("Action did not finish before the time out.");
		return false;
	}
}

bool callOuttakeHatchPanel(int setpoint_idx)
{
	//create client to call actionlib server
	actionlib::SimpleActionClient<behaviors::PlaceAction> outtake_hatch_panel_ac("/hatch_outtake/outtake_hatch_panel_server", true);

	ROS_INFO("Waiting for panel outtake server to start.");
	if(!outtake_hatch_panel_ac.waitForServer(ros::Duration(server_wait_timeout)))
	{
		ROS_ERROR("Could not find server within %f seconds.", server_wait_timeout);
	}

	ROS_INFO("Sending goal to outtake hatch panel server.");
	// send a goal to the action
	behaviors::PlaceGoal outtake_hatch_panel_goal;
	outtake_hatch_panel_goal.setpoint_index = setpoint_idx;
	outtake_hatch_panel_ac.sendGoal(outtake_hatch_panel_goal);

	//wait for the action to return
	bool finished_before_timeout = outtake_hatch_panel_ac.waitForResult(ros::Duration(server_exec_timeout));

	if (finished_before_timeout)
	{
		actionlib::SimpleClientGoalState state = outtake_hatch_panel_ac.getState();
		ROS_INFO("Action finished with state: %s",state.toString().c_str());
		if(outtake_hatch_panel_ac.getResult()->timed_out)
		{
			ROS_INFO("Panel outtake server timed out!");
		}
		return true;
	}
	else
	{
		ROS_INFO("Action did not finish before the time out.");
		return false;
	}
}

bool callClimber(int step)
{
	//create client to call actionlib server
	actionlib::SimpleActionClient<behaviors::ClimbAction> climber_ac("/climber/climber_server", true);

	ROS_INFO("Waiting for climber server to start.");
	if(!climber_ac.waitForServer(ros::Duration(server_wait_timeout)))
	{
		ROS_ERROR("Could not find server within %f seconds.", server_wait_timeout);
	}

	ROS_INFO("Sending goal to climber server.");
	// send a goal to the action
	behaviors::ClimbGoal climb_goal;
	climb_goal.step = step;
	climber_ac.sendGoal(climb_goal);

	//wait for the action to return
	bool finished_before_timeout = climber_ac.waitForResult(ros::Duration(server_exec_timeout));

	if (finished_before_timeout)
	{
		actionlib::SimpleClientGoalState state = climber_ac.getState();
		ROS_INFO("Action finished with state: %s",state.toString().c_str());
		if(climber_ac.getResult()->timed_out)
		{
			ROS_INFO("Climber server timed out!");
		}
		return true;
	}
	else
	{
		ROS_INFO("Action did not finish before the time out.");
		return false;
	}
}

bool callAlignHatch()
{
	actionlib::SimpleActionClient<behaviors::AlignAction> align_hatch_ac("/align_hatch/align_hatch_server", true);

	ROS_INFO("Waiting for align hatch server to start.");
	if(!align_hatch_ac.waitForServer(ros::Duration(server_wait_timeout)))
	{
		ROS_ERROR("Could not find server.");
		return false;
	}

	ROS_INFO("Sending goal to the server.");
	behaviors::AlignGoal align_goal;
	align_hatch_ac.sendGoal(align_goal);

	//wait for the action to return
	bool finished_before_timeout = align_hatch_ac.waitForResult(ros::Duration(server_exec_timeout));

	if (finished_before_timeout)
	{
		actionlib::SimpleClientGoalState state = align_hatch_ac.getState();
		ROS_INFO("Action finished with state: %s",state.toString().c_str());
		if(align_hatch_ac.getResult()->timed_out)
		{
			ROS_INFO("Align hatch server timed out!");
		}
		return true;
	}
	else
	{
		ROS_INFO("Action did not finish before the time out.");
		return false;
	}
}

int main (int argc, char **argv)
{
	/*GET DATA FROM USER INPUT
	 * user will type into command line: rosrun behaviors test_actionlib run:=what_to_run setpoint:=setpoint
	 * Possibilities:
	 * What to run:
	 *	intake_cargo
	 *	outtake_cargo
	 *	intake_hatch_panel
	 *	outtake_hatch_panel
	 *	elevator
	 * Setpoint:
	 *	Same thing as in enumerated_elevator_indices.h
	 */
	std::string what_to_run;
	std::string elevator_setpoint;

	what_to_run = ros::getROSArg(argc, argv, "run"); //if can't find the argument, will default to an empty string of length 0
	boost::algorithm::to_lower(what_to_run); //convert to lower case
	//make sure user told us what to run
	if(what_to_run.length() == 0)
	{
		ROS_ERROR("You need to specify the run functionality with: rosrun behaviors test_actionlib run:=____");
		ROS_ERROR("Possible values for run: all, intake_cargo, outtake_cargo, intake_hatch_panel, outtake_hatch_panel, elevator, climber0, climber1, climber2, climber3");
		ROS_ERROR("Note: 'all' will not run the climber");
		return 0;
	}
	elevator_setpoint = ros::getROSArg(argc, argv, "setpoint"); //only used for elevator call or outtake call. Not used for the 'all' run option
	boost::algorithm::to_upper(elevator_setpoint); //convert to upper case

	//make sure we have the setpoint if we need it, and determine what it is
	int setpoint_idx;
	if(what_to_run == "outtake_cargo" || what_to_run == "outtake_hatch_panel" || what_to_run == "elevator")
	{
		//make sure user entered a setpoint
		if(elevator_setpoint.length() == 0)
		{
			ROS_ERROR("You need to specify an elevator setpoint with: rosrun behaviors test_actionlib run:=____ setpoint:=_____");
			ROS_ERROR("Setpoint values are those found in enumerated elevator indices");
			return 0;
		}
		//determine the setpoint index
		if(elevator_setpoint == "CARGO_SHIP") {
			setpoint_idx = CARGO_SHIP;
		}
		else if(elevator_setpoint == "ROCKET_1") {
			setpoint_idx = ROCKET_1;
		}
		else if(elevator_setpoint == "ROCKET_2") {
			setpoint_idx = ROCKET_2;
		}
		else if(elevator_setpoint == "ROCKET_3") {
			setpoint_idx = ROCKET_3;
		}
		else if(elevator_setpoint == "INTAKE") {
			setpoint_idx = INTAKE;
		}
		else if(elevator_setpoint == "ELEVATOR_DEPLOY") {
			setpoint_idx = ELEVATOR_DEPLOY;
		}
		else if(elevator_setpoint == "ELEVATOR_CLIMB") {
			setpoint_idx = ELEVATOR_CLIMB;
		}
		else if(elevator_setpoint == "ELEVATOR_CLIMB_LOW") {
			setpoint_idx = ELEVATOR_CLIMB;
		}
		else if(elevator_setpoint == "ELEVATOR_MAX_INDEX") {
			setpoint_idx = ELEVATOR_MAX_INDEX;
		}
		else {
			ROS_ERROR("Invalid elevator setpoint");
			return 0;
		}
	}
	else {
		elevator_setpoint = "N/A";
	}

	ROS_WARN("what_to_run: %s", what_to_run.c_str());
	ROS_WARN("setpoint: %s", elevator_setpoint.c_str());

	//Actually run stuff ---------------------------------

	ros::init(argc, argv, "test_actionlib");

	//determine what to run and do it
	std::string user_input;
	if(what_to_run == "all") {
		int test_idx = 0; //0 means the first thing to test, 1 the next, etc. This is incremented by user input keyboard presses
		while(ros::ok())
		{
			ROS_INFO("Next action? Type y for yes, and press enter.");
			std::getline(std::cin, user_input); //wait for user input
			if(user_input == "y")
			{
				//then do stuff:
				if(test_idx < 5)
				{
					//if(!callElevator(test_idx)) {return 0;} //this is a bit of a hack, but it will test elevator indices 0 through 4
					callElevator(test_idx);
				}
				else if(test_idx == 5)
				{
					if(!callIntakeCargo()) {return 0;}
				}
				else if(test_idx == 6)
				{
					if(!callOuttakeCargo(CARGO_SHIP)) {return 0;}
				}
				else if(test_idx == 7)
				{
					if(!callIntakeHatchPanel()) {return 0;}
				}
				else if(test_idx == 8)
				{
					if(!callOuttakeHatchPanel(INTAKE)) {return 0;}
				}
				else if(test_idx == 9)
				{
					ROS_INFO("Done testing.");
					return 0;
				}
				test_idx++;
			}
		}
	}
	else if(what_to_run == "intake_cargo") {
		callIntakeCargo();
	}
	else if(what_to_run == "outtake_cargo") {
		callOuttakeCargo(setpoint_idx);
	}
	else if(what_to_run == "intake_hatch_panel") {
		callIntakeHatchPanel();
	}
	else if(what_to_run == "outtake_hatch_panel") {
		callOuttakeHatchPanel(setpoint_idx);
	}
	else if(what_to_run == "elevator") {
		callElevator(setpoint_idx);
	}
	else if(what_to_run == "climber0") {
		callClimber(0);
	}
	else if(what_to_run == "climber1") {
		callClimber(1);
	}
	else if(what_to_run == "climber2") {
		callClimber(2);
	}
	else if(what_to_run == "climber3") {
		callClimber(3);
	}
	else if(what_to_run == "align_hatch")
	{
		callAlignHatch();
	}
	else {
		ROS_ERROR("Invalid run argument");
		return 0;
	}

	//exit
	return 0;
}

ext: cpp


text:
/***********************************************************************************************************************
 *  OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. 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 any contributors may be used to endorse or promote
 *  products derived from this software without specific prior written permission from the respective party.
 *
 *  (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative
 *  works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without
 *  specific prior written permission from Alliance for Sustainable Energy, LLC.
 *
 *  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, THE UNITED STATES GOVERNMENT, OR ANY CONTRIBUTORS BE LIABLE FOR
 *  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 *  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 *  AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **********************************************************************************************************************/

#ifndef OPENSTUDIO_LOOPSCENE_HPP
#define OPENSTUDIO_LOOPSCENE_HPP

#include <QPainter>
#include <QRectF>
#include <boost/smart_ptr.hpp>
#include "../model/Loop.hpp"
#include "OSItem.hpp"
#include "GridScene.hpp"

namespace openstudio {

namespace model {
  class Splitter;

  class Mixer;

  class Node;

  class HVACComponent;

  class ModelObject;
}

class HorizontalBranchItem;

class VerticalBranchItem;

class HorizontalBranchGroupItem;

class DemandSideItem;

class SupplySideItem;

class OASystemItem;

class LoopScene : public GridScene
{

  Q_OBJECT

  public:

  LoopScene( model::Loop loop,
             QObject *parent = nullptr );

  virtual ~LoopScene() {}

  model::Loop loop();

  public slots:

  void addedWorkspaceObject(std::shared_ptr<openstudio::detail::WorkspaceObject_Impl> wPtr, const openstudio::IddObjectType& type, const openstudio::UUID& uuid);

  void removedWorkspaceObject(std::shared_ptr<openstudio::detail::WorkspaceObject_Impl> wPtr, const openstudio::IddObjectType& type, const openstudio::UUID& uuid);

  void layout();

  //signals:
  //
  //void modelObjectSelected( model::OptionalModelObject &, bool readOnly );

  //void removeModelObjectClicked( model::ModelObject & );

  //void hvacComponentDropped(OSItemId itemid, model::HVACComponent & node);

  //void innerNodeClicked( model::ModelObject & );

  private:

  DemandSideItem * createDemandSide();

  SupplySideItem * createSupplySide();

  void initDefault();

  model::Loop m_loop;

  bool m_dirty;
};

} // openstudio

#endif // OPENSTUDIO_LOOPSCENE_HPP

max_stars_repo_name: hongyuanjia/OpenStudio

max_issues_repo_name: hongyuanjia/OpenStudio

max_forks_repo_name: hongyuanjia/OpenStudio


text:
/*
 *                   GridGain Community Edition Licensing
 *                   Copyright 2019 GridGain Systems, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License") modified with Commons Clause
 * Restriction; 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.
 *
 * Commons Clause Restriction
 *
 * The Software is provided to you by the Licensor under the License, as defined below, subject to
 * the following condition.
 *
 * Without limiting other conditions in the License, the grant of rights under the License will not
 * include, and the License does not grant to you, the right to Sell the Software.
 * For purposes of the foregoing, “Sell” means practicing any or all of the rights granted to you
 * under the License to provide to third parties, for a fee or other consideration (including without
 * limitation fees for hosting or consulting/ support services related to the Software), a product or
 * service whose value derives, entirely or substantially, from the functionality of the Software.
 * Any license notice or attribution required by the License must also include this Commons Clause
 * License Condition notice.
 *
 * For purposes of the clause above, the “Licensor” is Copyright 2019 GridGain Systems, Inc.,
 * the “License” is the Apache License, Version 2.0, and the Software is the GridGain Community
 * Edition software provided with this notice.
 */

#ifndef _MSC_VER
#   define BOOST_TEST_DYN_LINK
#endif

#include <boost/test/unit_test.hpp>

#include <ignite/impl/binary/binary_common.h>
#include <ignite/impl/binary/binary_writer_impl.h>

#include "ignite/odbc/system/odbc_constants.h"
#include "ignite/odbc/column.h"

using namespace ignite::impl::binary;
using namespace ignite::odbc::app;
using namespace ignite::odbc;

BOOST_AUTO_TEST_SUITE(ColumnTestSuite)

BOOST_AUTO_TEST_CASE(TestColumnDefaultConstruction)
{
    Column column;

    BOOST_REQUIRE(!column.IsValid());
}

BOOST_AUTO_TEST_CASE(TestColumnShort)
{
    ignite::impl::interop::InteropUnpooledMemory mem(4096);
    ignite::impl::interop::InteropOutputStream outStream(&mem);
    ignite::impl::binary::BinaryWriterImpl writer(&outStream, 0);

    int16_t data = 42;

    writer.WriteInt8(IGNITE_TYPE_SHORT);
    writer.WriteInt16(data);

    outStream.Synchronize();

    ignite::impl::interop::InteropInputStream inStream(&mem);
    ignite::impl::binary::BinaryReaderImpl reader(&inStream);

    Column column(reader);

    BOOST_REQUIRE(column.IsValid());

    BOOST_REQUIRE_EQUAL(column.GetSize(), 2);

    BOOST_REQUIRE_EQUAL(column.GetUnreadDataLength(), 2);

    short shortBuf = 0;
    SqlLen reslen = 0;

    ApplicationDataBuffer appBuf(type_traits::OdbcNativeType::AI_SIGNED_SHORT, &shortBuf, sizeof(shortBuf), &reslen);

    BOOST_REQUIRE_EQUAL(column.ReadToBuffer(reader, appBuf), app::ConversionResult::AI_SUCCESS);

    BOOST_REQUIRE(column.IsValid());

    BOOST_REQUIRE_EQUAL(column.GetSize(), 2);

    BOOST_REQUIRE_EQUAL(column.GetUnreadDataLength(), 0);

    BOOST_REQUIRE_EQUAL(shortBuf, data);

    BOOST_REQUIRE_EQUAL(column.ReadToBuffer(reader, appBuf), app::ConversionResult::AI_NO_DATA);

    BOOST_REQUIRE(column.IsValid());

    BOOST_REQUIRE_EQUAL(column.GetSize(), 2);

    BOOST_REQUIRE_EQUAL(column.GetUnreadDataLength(), 0);
}

BOOST_AUTO_TEST_CASE(TestColumnString)
{
    ignite::impl::interop::InteropUnpooledMemory mem(4096);
    ignite::impl::interop::InteropOutputStream outStream(&mem);
    ignite::impl::binary::BinaryWriterImpl writer(&outStream, 0);

    std::string data("Some test data.");

    writer.WriteString(data.data(), static_cast<int32_t>(data.size()));

    outStream.Synchronize();

    ignite::impl::interop::InteropInputStream inStream(&mem);
    ignite::impl::binary::BinaryReaderImpl reader(&inStream);

    Column column(reader);

    BOOST_REQUIRE(column.IsValid());

    BOOST_REQUIRE_EQUAL(column.GetSize(), data.size());

    BOOST_REQUIRE_EQUAL(column.GetUnreadDataLength(), data.size());

    char strBuf[1024] = {};
    SqlLen reslen = 0;

    ApplicationDataBuffer appBuf(type_traits::OdbcNativeType::AI_CHAR, &strBuf, sizeof(strBuf), &reslen);

    BOOST_REQUIRE_EQUAL(column.ReadToBuffer(reader, appBuf), app::ConversionResult::AI_SUCCESS);

    BOOST_REQUIRE(column.IsValid());

    BOOST_REQUIRE_EQUAL(column.GetSize(), data.size());

    BOOST_REQUIRE_EQUAL(column.GetUnreadDataLength(), 0);

    BOOST_REQUIRE_EQUAL(std::string(strBuf), data);

    BOOST_REQUIRE_EQUAL(column.ReadToBuffer(reader, appBuf), app::ConversionResult::AI_NO_DATA);

    BOOST_REQUIRE(column.IsValid());

    BOOST_REQUIRE_EQUAL(column.GetSize(), data.size());

    BOOST_REQUIRE_EQUAL(column.GetUnreadDataLength(), 0);
}

BOOST_AUTO_TEST_CASE(TestColumnStringSeveral)
{
    ignite::impl::interop::InteropUnpooledMemory mem(4096);
    ignite::impl::interop::InteropOutputStream outStream(&mem);
    ignite::impl::binary::BinaryWriterImpl writer(&outStream, 0);

    std::string data("Lorem ipsum dolor sit amet, consectetur adipiscing elit.");

    writer.WriteString(data.data(), static_cast<int32_t>(data.size()));

    outStream.Synchronize();

    ignite::impl::interop::InteropInputStream inStream(&mem);
    ignite::impl::binary::BinaryReaderImpl reader(&inStream);

    Column column(reader);

    BOOST_REQUIRE(column.IsValid());

    BOOST_REQUIRE_EQUAL(column.GetSize(), data.size());

    BOOST_REQUIRE_EQUAL(column.GetUnreadDataLength(), data.size());

    std::string res;

    std::string strBuf(data.size() / 3 + 2, 0);
    SqlLen reslen = 0;

    ApplicationDataBuffer appBuf(type_traits::OdbcNativeType::AI_CHAR, &strBuf[0], strBuf.size(), &reslen);

    BOOST_REQUIRE_EQUAL(column.ReadToBuffer(reader, appBuf), app::ConversionResult::AI_VARLEN_DATA_TRUNCATED);

    BOOST_REQUIRE(column.IsValid());

    BOOST_REQUIRE_EQUAL(column.GetSize(), data.size());

    BOOST_REQUIRE_EQUAL(column.GetUnreadDataLength(), data.size() - (strBuf.size() - 1));

    res.append(strBuf.c_str());

    BOOST_REQUIRE_EQUAL(column.ReadToBuffer(reader, appBuf), app::ConversionResult::AI_VARLEN_DATA_TRUNCATED);

    BOOST_REQUIRE(column.IsValid());

    BOOST_REQUIRE_EQUAL(column.GetSize(), data.size());

    BOOST_REQUIRE_EQUAL(column.GetUnreadDataLength(), data.size() - 2 * (strBuf.size() - 1));

    res.append(strBuf.c_str());

    BOOST_REQUIRE_EQUAL(column.ReadToBuffer(reader, appBuf), app::ConversionResult::AI_SUCCESS);

    BOOST_REQUIRE(column.IsValid());

    BOOST_REQUIRE_EQUAL(column.GetSize(), data.size());

    BOOST_REQUIRE_EQUAL(column.GetUnreadDataLength(), 0);

    res.append(strBuf.c_str());

    BOOST_REQUIRE_EQUAL(column.ReadToBuffer(reader, appBuf), app::ConversionResult::AI_NO_DATA);

    BOOST_REQUIRE(column.IsValid());

    BOOST_REQUIRE_EQUAL(column.GetSize(), data.size());

    BOOST_REQUIRE_EQUAL(column.GetUnreadDataLength(), 0);

    BOOST_REQUIRE_EQUAL(res, data);
}

BOOST_AUTO_TEST_CASE(TestColumnMultiString)
{
    ignite::impl::interop::InteropUnpooledMemory mem(4096);
    ignite::impl::interop::InteropOutputStream outStream(&mem);
    ignite::impl::binary::BinaryWriterImpl writer(&outStream, 0);

    std::string data1("Some test data.");
    std::string data2("Other TEST DATA.");

    writer.WriteString(data1.data(), static_cast<int32_t>(data1.size()));
    writer.WriteString(data2.data(), static_cast<int32_t>(data2.size()));

    outStream.Synchronize();

    ignite::impl::interop::InteropInputStream inStream(&mem);
    ignite::impl::binary::BinaryReaderImpl reader(&inStream);

    Column column1(reader);

    inStream.Position(column1.GetEndPosition());

    Column column2(reader);

    BOOST_REQUIRE(column1.IsValid());

    BOOST_REQUIRE_EQUAL(column1.GetSize(), data1.size());

    BOOST_REQUIRE_EQUAL(column1.GetUnreadDataLength(), data1.size());

    BOOST_REQUIRE(column2.IsValid());

    BOOST_REQUIRE_EQUAL(column2.GetSize(), data2.size());

    BOOST_REQUIRE_EQUAL(column2.GetUnreadDataLength(), data2.size());

    char strBuf[1024] = {};
    SqlLen reslen = 0;

    ApplicationDataBuffer appBuf(type_traits::OdbcNativeType::AI_CHAR, &strBuf, sizeof(strBuf), &reslen);

    BOOST_REQUIRE_EQUAL(column1.ReadToBuffer(reader, appBuf), app::ConversionResult::AI_SUCCESS);

    BOOST_REQUIRE(column1.IsValid());

    BOOST_REQUIRE_EQUAL(column1.GetSize(), data1.size());

    BOOST_REQUIRE_EQUAL(column1.GetUnreadDataLength(), 0);

    BOOST_REQUIRE_EQUAL(std::string(strBuf), data1);

    BOOST_REQUIRE_EQUAL(column1.ReadToBuffer(reader, appBuf), app::ConversionResult::AI_NO_DATA);

    BOOST_REQUIRE(column1.IsValid());

    BOOST_REQUIRE_EQUAL(column1.GetSize(), data1.size());

    BOOST_REQUIRE_EQUAL(column1.GetUnreadDataLength(), 0);

    BOOST_REQUIRE_EQUAL(column2.ReadToBuffer(reader, appBuf), app::ConversionResult::AI_SUCCESS);

    BOOST_REQUIRE(column2.IsValid());

    BOOST_REQUIRE_EQUAL(column2.GetSize(), data2.size());

    BOOST_REQUIRE_EQUAL(column2.GetUnreadDataLength(), 0);

    BOOST_REQUIRE_EQUAL(std::string(strBuf), data2);

    BOOST_REQUIRE_EQUAL(column2.ReadToBuffer(reader, appBuf), app::ConversionResult::AI_NO_DATA);

    BOOST_REQUIRE(column2.IsValid());

    BOOST_REQUIRE_EQUAL(column2.GetSize(), data2.size());

    BOOST_REQUIRE_EQUAL(column2.GetUnreadDataLength(), 0);
}

BOOST_AUTO_TEST_CASE(TestColumnByteArray)
{
    ignite::impl::interop::InteropUnpooledMemory mem(4096);
    ignite::impl::interop::InteropOutputStream outStream(&mem);
    ignite::impl::binary::BinaryWriterImpl writer(&outStream, 0);

    const int8_t bytes[] = { 'A','B','C','D','E','F','G','H','I','J' };
    std::vector<int8_t> data(bytes, bytes + sizeof(bytes) / sizeof(bytes[0]));
    writer.WriteInt8Array(&data[0], static_cast<int32_t>(data.size()));

    outStream.Synchronize();

    ignite::impl::interop::InteropInputStream inStream(&mem);
    ignite::impl::binary::BinaryReaderImpl reader(&inStream);

    Column column(reader);

    BOOST_REQUIRE(column.IsValid());

    BOOST_REQUIRE_EQUAL(column.GetSize(), data.size());

    BOOST_REQUIRE_EQUAL(column.GetUnreadDataLength(), data.size());

    std::vector<int8_t> buf(data.size());
    SqlLen reslen = 0;

    ApplicationDataBuffer appBuf(type_traits::OdbcNativeType::AI_BINARY, &buf[0], buf.size(), &reslen);

    BOOST_REQUIRE_EQUAL(column.ReadToBuffer(reader, appBuf), app::ConversionResult::AI_SUCCESS);

    BOOST_REQUIRE(column.IsValid());

    BOOST_REQUIRE_EQUAL(column.GetSize(), data.size());

    BOOST_REQUIRE_EQUAL(column.GetUnreadDataLength(), 0);

    BOOST_REQUIRE_EQUAL_COLLECTIONS(buf.begin(), buf.end(), data.begin(), data.end());

    BOOST_REQUIRE_EQUAL(column.ReadToBuffer(reader, appBuf), app::ConversionResult::AI_NO_DATA);

    BOOST_REQUIRE(column.IsValid());

    BOOST_REQUIRE_EQUAL(column.GetSize(), data.size());

    BOOST_REQUIRE_EQUAL(column.GetUnreadDataLength(), 0);
}

BOOST_AUTO_TEST_CASE(TestColumnByteArrayHalfBuffer)
{
    ignite::impl::interop::InteropUnpooledMemory mem(4096);
    ignite::impl::interop::InteropOutputStream outStream(&mem);
    ignite::impl::binary::BinaryWriterImpl writer(&outStream, 0);

    const int8_t bytes[] = { 'A','B','C','D','E','F','G','H','I','J' };
    std::vector<int8_t> data(bytes, bytes + sizeof(bytes)/sizeof(bytes[0]));
    BOOST_REQUIRE_EQUAL(0, data.size() % 2);

    writer.WriteInt8Array(&data[0], static_cast<int32_t>(data.size()));

    outStream.Synchronize();

    ignite::impl::interop::InteropInputStream inStream(&mem);
    ignite::impl::binary::BinaryReaderImpl reader(&inStream);

    Column column(reader);

    BOOST_REQUIRE(column.IsValid());

    BOOST_REQUIRE_EQUAL(column.GetSize(), data.size());

    BOOST_REQUIRE_EQUAL(column.GetUnreadDataLength(), data.size());

    std::vector<int8_t> buf(data.size()/2);
    SqlLen reslen = 0;

    ApplicationDataBuffer appBuf(type_traits::OdbcNativeType::AI_BINARY, &buf[0], buf.size(), &reslen);

    BOOST_REQUIRE_EQUAL(column.ReadToBuffer(reader, appBuf), app::ConversionResult::AI_SUCCESS);

    BOOST_REQUIRE(column.IsValid());

    BOOST_REQUIRE_EQUAL(column.GetSize(), data.size());

    BOOST_REQUIRE_EQUAL(column.GetUnreadDataLength(), data.size() - buf.size());

    std::vector<int8_t> result;
    result.reserve(data.size());
    std::copy(buf.begin(), buf.end(), std::back_inserter(result));

    BOOST_REQUIRE_EQUAL(column.ReadToBuffer(reader, appBuf), app::ConversionResult::AI_SUCCESS);

    BOOST_REQUIRE(column.IsValid());

    BOOST_REQUIRE_EQUAL(column.GetSize(), data.size());

    BOOST_REQUIRE_EQUAL(column.GetUnreadDataLength(), 0);

    std::copy(buf.begin(), buf.end(), std::back_inserter(result));

    BOOST_REQUIRE_EQUAL(column.ReadToBuffer(reader, appBuf), app::ConversionResult::AI_NO_DATA);

    BOOST_REQUIRE(column.IsValid());

    BOOST_REQUIRE_EQUAL(column.GetSize(), data.size());

    BOOST_REQUIRE_EQUAL(column.GetUnreadDataLength(), 0);

    BOOST_REQUIRE_EQUAL_COLLECTIONS(result.begin(), result.end(), data.begin(), data.end());
}

BOOST_AUTO_TEST_CASE(TestColumnByteArrayTwoColumns)
{
    ignite::impl::interop::InteropUnpooledMemory mem(4096);
    ignite::impl::interop::InteropOutputStream outStream(&mem);
    ignite::impl::binary::BinaryWriterImpl writer(&outStream, 0);

    const int8_t bytes1[] = { 'A','B','C','D','E','F','G','H','I','J' };
    const int8_t bytes2[] = { 'a','b','c','d','e','f','g','h','i','j' };
    std::vector<int8_t> data1(bytes1, bytes1 + sizeof(bytes1)/sizeof(bytes1[0]));
    std::vector<int8_t> data2(bytes2, bytes2 + sizeof(bytes2)/sizeof(bytes2[0]));
    writer.WriteInt8Array(&data1[0], static_cast<int32_t>(data1.size()));
    writer.WriteInt8Array(&data2[0], static_cast<int32_t>(data2.size()));

    outStream.Synchronize();

    ignite::impl::interop::InteropInputStream inStream(&mem);
    ignite::impl::binary::BinaryReaderImpl reader(&inStream);

    Column column1(reader);
    inStream.Position(column1.GetEndPosition());
    Column column2(reader);

    BOOST_REQUIRE(column1.IsValid());

    BOOST_REQUIRE_EQUAL(column1.GetSize(), data1.size());

    BOOST_REQUIRE_EQUAL(column1.GetUnreadDataLength(), data1.size());

    BOOST_REQUIRE(column2.IsValid());

    BOOST_REQUIRE_EQUAL(column2.GetSize(), data2.size());

    BOOST_REQUIRE_EQUAL(column2.GetUnreadDataLength(), data2.size());

    int8_t buf[1024] = {};
    SqlLen reslen = 0;

    ApplicationDataBuffer appBuf(type_traits::OdbcNativeType::AI_BINARY, &buf, sizeof(buf), &reslen);

    BOOST_REQUIRE_EQUAL(column1.ReadToBuffer(reader, appBuf), app::ConversionResult::AI_SUCCESS);

    BOOST_REQUIRE(column1.IsValid());

    BOOST_REQUIRE_EQUAL(column1.GetSize(), data1.size());

    BOOST_REQUIRE_EQUAL(column1.GetUnreadDataLength(), 0);

    BOOST_REQUIRE_EQUAL_COLLECTIONS(buf, buf + reslen, data1.begin(), data1.end());

    BOOST_REQUIRE_EQUAL(column1.ReadToBuffer(reader, appBuf), app::ConversionResult::AI_NO_DATA);

    BOOST_REQUIRE(column1.IsValid());

    BOOST_REQUIRE_EQUAL(column1.GetSize(), data1.size());

    BOOST_REQUIRE_EQUAL(column1.GetUnreadDataLength(), 0);

    BOOST_REQUIRE_EQUAL(column2.ReadToBuffer(reader, appBuf), app::ConversionResult::AI_SUCCESS);

    BOOST_REQUIRE(column2.IsValid());

    BOOST_REQUIRE_EQUAL(column2.GetSize(), data1.size());

    BOOST_REQUIRE_EQUAL(column2.GetUnreadDataLength(), 0);

    BOOST_REQUIRE_EQUAL_COLLECTIONS(buf, buf + reslen, data2.begin(), data2.end());

    BOOST_REQUIRE_EQUAL(column2.ReadToBuffer(reader, appBuf), app::ConversionResult::AI_NO_DATA);

    BOOST_REQUIRE(column2.IsValid());

    BOOST_REQUIRE_EQUAL(column2.GetSize(), data1.size());

    BOOST_REQUIRE_EQUAL(column2.GetUnreadDataLength(), 0);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: DirectXceriD/gridgain

max_issues_repo_name: DirectXceriD/gridgain

max_forks_repo_name: DirectXceriD/gridgain


text:
#pragma once

#include <boost/container/flat_map.hpp>
#include <boost/container/flat_set.hpp>
#include <memory>
#include <sdbusplus/asio/object_server.hpp>
#include <string>
#include <tuple>
#include <vector>

/** @brief interface_map_type is the underlying datastructure the mapper uses.
 *
 * The 3 levels of map are
 * object paths
 *   connection names
 *      interface names
 */
using interface_map_type = boost::container::flat_map<
    std::string, boost::container::flat_map<
                     std::string, boost::container::flat_set<std::string>>>;

/**
 *  Associations and some metadata are stored in associationInterfaces.
 *  The fields are:
 *   * ifacePos - holds the D-Bus interface object
 *   * endpointsPos - holds the endpoints array that shadows the property
 */
static constexpr auto ifacePos = 0;
static constexpr auto endpointsPos = 1;
using Endpoints = std::vector<std::string>;

// map[interface path: tuple[dbus_interface,vector[endpoint paths]]]
using AssociationInterfaces = boost::container::flat_map<
    std::string,
    std::tuple<std::shared_ptr<sdbusplus::asio::dbus_interface>, Endpoints>>;

/**
 * The associationOwners map contains information about creators of
 * associations, so that when a org.openbmc.Association interface is
 * removed or its 'associations' property is changed, the mapper owned
 * association objects can be correctly handled.  It is a map of the
 * object path of the org.openbmc.Association owner to a map of the
 * service the path is owned by, to a map of the association objects to
 * their endpoint paths:
 * map[ownerPath : map[service : map[assocPath : [endpoint paths]]]
 * For example:
 * [/logging/entry/1 :
 *   [xyz.openbmc_project.Logging :
 *     [/logging/entry/1/callout : [/system/cpu0],
 *      /system/cpu0/fault : [/logging/entry/1]]]]
 */
using AssociationPaths =
    boost::container::flat_map<std::string,
                               boost::container::flat_set<std::string>>;

using AssociationOwnersType = boost::container::flat_map<
    std::string, boost::container::flat_map<std::string, AssociationPaths>>;

/**
 * Store the contents of the associations property on the interface
 * For example:
 * ["inventory", "activation", "/xyz/openbmc_project/inventory/system/chassis"]
 */
constexpr auto forwardTypePos = 0;
constexpr auto reverseTypePos = 1;
constexpr auto reversePathPos = 2;
using Association = std::tuple<std::string, std::string, std::string>;

/**
 * PendingAssociations tracks associations that cannot be created because
 * the endpoint (the last element of the Association tuple) doesn't exist.
 * When that endpoint shows up on D-Bus, both association paths can then
 * be created.  Also, if a valid association has an endpoint removed from
 * D-Bus, then a new PendingAssociations entry will be created until it
 * reappears.  It has all of the information it needs to recreate the
 * association.
 */
constexpr auto ownerPos = 0;
constexpr auto assocPos = 1;
using ExistingEndpoint = std::tuple<std::string, Association>;
using ExistingEndpoints = std::vector<ExistingEndpoint>;
using PendingAssociations = std::map<std::string, ExistingEndpoints>;

/**
 *  The return type of findAssociations().
 *  The string in the tuple is the association owner.
 */
using FindAssocResults = std::vector<std::tuple<std::string, Association>>;

/**
 * Keeps all association related maps together.
 */
struct AssociationMaps
{
    AssociationInterfaces ifaces;
    AssociationOwnersType owners;
    PendingAssociations pending;
};

max_stars_repo_name: sotaoverride/backup

max_issues_repo_name: sotaoverride/backup

max_forks_repo_name: sotaoverride/backup


text:
/*!
@file
Forward declares `boost::hana::size`.

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

#ifndef BOOST_HANA_FWD_SIZE_HPP
#define BOOST_HANA_FWD_SIZE_HPP

#include <boost/hana/config.hpp>
#include <boost/hana/fwd/length.hpp>

BOOST_HANA_NAMESPACE_BEGIN
    //! Equivalent to `length`; provided for consistency with the
    //! standard library.
    //! @ingroup group-Foldable
    //!
    //! This method is an alias to `length` provided for convenience and
    //! consistency with the standard library. As an alias, `size` is not
    //! tag-dispatched on its own and `length` should be customized instead.
    //!
    //!
    //! Example
    //! -------
    //! @include example/size.cpp
    constexpr auto size = hana::length;
BOOST_HANA_NAMESPACE_END

#endif // !BOOST_HANA_FWD_SIZE_HPP

max_stars_repo_name: rudylee/expo

max_issues_repo_name: rudylee/expo

max_forks_repo_name: rudylee/expo


text:
#ifndef SHIFT_TOOLS_PROTOGEN_GENERATORS_PROTO_GENERATOR_HPP
#define SHIFT_TOOLS_PROTOGEN_GENERATORS_PROTO_GENERATOR_HPP

#include <shift/core/boost_disable_warnings.hpp>
#include <boost/program_options.hpp>
#include <shift/core/boost_restore_warnings.hpp>
#include "shift/tools/protogen/generators/base_generator.hpp"
#include "shift/tools/protogen/file_writer.hpp"

namespace shift::tools::protogen::generators
{
///
class proto_generator : public base_generator
{
  // public:
  //  /// @see base_generator::active.
  //  virtual bool active() const override;

  //  /// @see base_generator::output_paths.
  //  virtual std::vector<std::filesystem::path> output_paths() const
  //  override;

  //  ///
  //  bool generate(namescope& root_scope, namescope& limit_scope) override;

  //  /// A wrapper for base_generator::relative_path to ease use.
  //  static std::string relative_name(const node* node,
  //                                   const namescope* current_scope);

  // private:
  //  ///
  //  void write(std::string_view source_filename, const namescope& scope);

  //  ///
  //  void write(const alias& alias);

  //  ///
  //  void write(const enumeration& enumeration);

  //  ///
  //  void write(const message& message);

  //  ///
  //  void write(std::string_view source_filename, const interface& interface);

  //  ///
  //  void write(const service& service);

  //  ///
  //  void write_attributes(const node& node);

  //  file_writer _source;
};
}

#endif

max_stars_repo_name: cspanier/shift

max_issues_repo_name: cspanier/shift

max_forks_repo_name: cspanier/shift


text:
// Copyright 2018-2019 Carnegie Mellon University.  See LICENSE file for terms.

#include "bua.hpp"
#include "descriptors.hpp"
#include "options.hpp"

#include <Sawyer/ProgressBar.h>
#include <Sawyer/ThreadWorkers.h>
#include <Sawyer/GraphTraversal.h>
#include <Sawyer/GraphAlgorithm.h>
#include <boost/range/adaptor/map.hpp>

#include <atomic>

#define PHAROS_BUA_TESTING 0

namespace pharos {

namespace {

struct ProgressSuffix {
  size_t * total = nullptr;
  ProgressSuffix() {}
  ProgressSuffix(size_t & t): total(&t) {}
  void print(std::ostream &o) const {
    if (total) {
      o << "/" << total;
    }
  }
};

std::ostream& operator<<(std::ostream &o, const ProgressSuffix &suffix) {
  suffix.print(o);
  return o;
}

} // unnamed namespace

Sawyer::Message::Facility BottomUpAnalyzer::mlog;

BottomUpAnalyzer::BottomUpAnalyzer(DescriptorSet & ds_, ProgOptVarMap const & vm_)
  : ds(ds_), vm(vm_)
{}

// The default visitor simply computes the PDG and returns.
void BottomUpAnalyzer::visit(FunctionDescriptor *fd) {
  fd->get_pdg();
}

// The default start is a NOP.
void BottomUpAnalyzer::start() {
  GDEBUG << "Starting bottom up function analysis." << LEND;
}

// The default finish is a NOP.
void BottomUpAnalyzer::finish() {
  GDEBUG << "Finishing bottom up function analysis." << LEND;
}

static std::atomic_flag mlog_initialized = ATOMIC_FLAG_INIT;
Sawyer::Message::Facility & BottomUpAnalyzer::initDiagnostics()
{
  if (!mlog_initialized.test_and_set()) {
    mlog.initialize("BUAD");
    mlog.initStreams(get_logging_destination());
    Sawyer::Message::mfacilities.insert(mlog);
  }
  return mlog;
}

void BottomUpAnalyzer::analyze() {
  // User overridden start() method.
  start();

  auto const level = ds.get_concurrency_level();
  if (level == 1) {
    mode = SINGLE_THREADED;
  }

  AddrSet const selected_funcs = get_selected_funcs (ds, vm);
  size_t const total_funcs = selected_funcs.size();
  processed_funcs = 0;

  FDG fdg{ds};

  // Function to determine whether a function is to be included in the analysis
  auto included = [&selected_funcs](FunctionDescriptor const * fd) {
    if (!FDG::valid_descriptor(fd)) {
      return false;
    }
    if (selected_funcs.find(fd->get_address()) == selected_funcs.end()) {
      GTRACE << "Function " << fd->address_string() << " excluded" << LEND;
      return false;
    }
    return true;
  };

  // Function to create the PDG for a function
  auto get_pdg = [&mlog = this->mlog, &included](size_t, FunctionDescriptor const *fd) {
    if (included(fd)) {
      MDEBUG << "Starting PDG generation for function " << fd->address_string() << LEND;
      auto timer = make_timer();
      fd->get_pdg();
      timer.stop();
      MDEBUG << "Finished PDG generation for function " << fd->address_string()
             << " in " << timer << 's' << LEND;
    }
  };

  // Function that calls visit
  auto visit_func = [this, &included](size_t, FunctionDescriptor *fd) {
    if (included(fd)) {
      assert(fd);
      GDEBUG << "Visiting function " << fd->address_string() << LEND;
      // Visit the function.
      auto timer = make_timer();
      visit(fd);
      timer.stop();
      ++processed_funcs;
      GDEBUG << "Finished visiting function " << fd->address_string() << " in "
             << timer << 's' << std::endl;
    }
  };

  // Fun function across function descriptors in parallel, with progress bar
  auto run_in_parallel = [&fdg, level, total_funcs](
    auto func, std::string const & title)
  {
    Sawyer::ProgressBar<size_t, ProgressSuffix> progress(
      total_funcs, olog[Sawyer::Message::MARCH], title);
    auto process = [&func, &progress](size_t s, FunctionDescriptor * fd) {
      func(s, fd);
      ++progress;
    };
    Sawyer::workInParallel(fdg.graph(), level, process);
  };

  switch (mode) {
   case PDG_THREADED_VISIT_SINGLE:
    run_in_parallel(get_pdg, "Function PDG analysis");
    // fallthrough
   case SINGLE_THREADED:
    {
      auto ordered_funcs = fdg.bottom_up_order();
      Sawyer::ProgressBar<size_t, ProgressSuffix> progress(
        total_funcs, olog[Sawyer::Message::MARCH], "Function analysis");
      for (FunctionDescriptor* fd : ordered_funcs) {
        visit_func(0, fd);
        ++progress;
      }
    }
    break;
   case PDG_THREADED_VISIT_THREADED:
    run_in_parallel(get_pdg, "Function PDG analysis");
    // fallthrough
   case MULTI_THREADED:
    run_in_parallel(visit_func, "Function analysis");
    break;
  }
  if (total_funcs != processed_funcs) {
    GERROR << "Found only " << processed_funcs << " functions of "
           << total_funcs << " specifically requested for analysis." << LEND;
  }

  // User overridden finish() method.
  finish();
}

FunctionDescriptor * FDG::indeterminate_{
  reinterpret_cast<FunctionDescriptor *>(&FDG::indeterminate_)};

FDG::FDG(DescriptorSet & ds)
{
  // For the V_ constants
  using namespace Rose::BinaryAnalysis::Partitioner2;

  // Get a function descriptor from an address
  auto func = [&ds](auto fn) {
    return ds.get_rw_func(fn->address());
  };

  // Add all functions to the graph
  for (auto & fn : boost::adaptors::values(ds.get_func_map())) {
    g_.insertVertex(ds.get_rw_func(fn.get_address()));
  }

  // Add an indeterminate node to the graph
  auto indeterminate_iter = g_.insertVertex(indeterminate());

  auto insert_edge = [this](auto start, auto tgt) {
    auto vs = g_.insertVertexMaybe(start);
    auto vt = g_.insertVertexMaybe(tgt);
    for (auto & oe : vs->outEdges()) {
      if (oe.target()->id() == vt->id()) {
        return;
      }
    }
    g_.insertEdge(vs, vt);
  };

  // Get the partitioner
  auto & p = ds.get_partitioner();
  // Get the partitioner's CFG
  auto & pcfg = p.cfg();

  // For each edge in the cfg
  for (auto & edge : pcfg.edges()) {
    // If the edge is from a basic block
    if (edge.source()->value().type() == V_BASIC_BLOCK) {

      // Based on the type of the target of the edge
      switch (edge.target()->value().type()) {
       case V_BASIC_BLOCK:
        // If it's a basic block, add an edge to our graph for each function/function pair that
        // those basic blocks are in
        for (auto & source : edge.source()->value().owningFunctions().values()) {
          auto s = func(source);
          if (s) {
            for (auto & target : edge.target()->value().owningFunctions().values()) {
              if (source != target || edge.value().type() == E_FUNCTION_CALL
                  || edge.value().type() == E_FUNCTION_XFER)
              {
                auto t = func(target);
                if (t) {
                  insert_edge(s, t);
                }
              }
            }
          }
        }
        break;
       case V_INDETERMINATE:
        // If it's the indeterminate not, add an edge to our indeterminate node
        for (auto & source : edge.source()->value().owningFunctions().values()) {
          auto s = func(source);
          if (s) {
            insert_edge(s, indeterminate());
          }
        }
        break;
       default:
        break;
      }
    }
  }

  // Find the set of vertices that can reach the indeterminate node.  Do this by doing a
  // reverse depth first search from the indeterminate node, accumulating the vertices reached.
  auto traversal = Sawyer::Container::Algorithm::DepthFirstReverseVertexTraversal<Graph>{
    g_, indeterminate_iter};
  std::set<Graph::VertexIterator> not_simple;
  traversal.mapVertices([&not_simple](auto v) { not_simple.insert(v); });

  // Connect the indeterminate node to all simple nodes that have no non-simple predecessors.
  auto is_simple = [&not_simple](auto vertex) {
    return not_simple.find(vertex) == not_simple.end();
  };
  auto vertices = g_.vertices();
  for (auto v = begin(vertices); v != end(vertices); ++v) {
    if (is_simple(v)
        && std::none_of(begin(v->inEdges()), end(v->inEdges()),
                        [&is_simple](auto & e){ return is_simple(e.source()); }))
    {
      g_.insertEdge(indeterminate_iter, v);
    }
  }

  // Break any cycles remaining
  Sawyer::Container::Algorithm::graphBreakCycles(g_);
}

std::vector<FunctionDescriptor *> FDG::bottom_up_order() const
{
  std::vector<FunctionDescriptor *> result;

  // Copy the graph
  Graph g{graph()};

  // While the graph is not empty...
  while (!g.isEmpty()) {
    std::vector<Graph::VertexIterator> to_erase;
    auto vertices = g.vertices();

    // Build a list of vertices that have no outgoing edges, and add them to the result vector
    for (auto v = begin(vertices); v != end(vertices); ++v) {
      if (v->nOutEdges() == 0) {
        to_erase.push_back(v);
        if (valid_descriptor(v->value())) {
          result.push_back(v->value());
        }
      }
    }

    // Then remove those vertices from the graph
    assert(!to_erase.empty());
    for (auto v : to_erase) {
      g.eraseVertex(v);
    }
  }

  return result;
}

} // namespace pharos

/* Local Variables:   */
/* mode: c++          */
/* fill-column:    95 */
/* comment-column: 0  */
/* End:               */

max_stars_repo_name: JanWielemaker/pharos

max_issues_repo_name: sei-ccohen/pharos

max_forks_repo_name: sei-ccohen/pharos


text:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2006. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////

#include<boost/interprocess/exceptions.hpp>
#include <boost/interprocess/detail/posix_time_types_wrk.hpp>

namespace boost {
namespace interprocess {

inline barrier::barrier(unsigned int count)
{
   if (count == 0)
      throw std::invalid_argument("count cannot be zero.");
   detail::barrierattr_wrapper barrier_attr;
   detail::barrier_initializer barrier
      (m_barrier, barrier_attr, static_cast<int>(count));
   barrier.release();
}

inline barrier::~barrier()
{
   int res = pthread_barrier_destroy(&m_barrier);
   assert(res  == 0);(void)res;
}

inline bool barrier::wait()
{
   int res = pthread_barrier_wait(&m_barrier);

   if (res != PTHREAD_BARRIER_SERIAL_THREAD && res != 0){
      throw interprocess_exception(res);
   }
   return res == PTHREAD_BARRIER_SERIAL_THREAD;
}

}  //namespace interprocess {
}  //namespace boost {

max_issues_repo_name: foxostro/CheeseTesseract

max_forks_repo_name: foxostro/CheeseTesseract