text:
/**
 *    Copyright (C) 2018-present MongoDB, Inc.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the Server Side Public License, version 1,
 *    as published by MongoDB, Inc.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    Server Side Public License for more details.
 *
 *    You should have received a copy of the Server Side Public License
 *    along with this program. If not, see
 *    <http://www.mongodb.com/licensing/server-side-public-license>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the Server Side Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */

#include "mongo/platform/basic.h"

#include "mongo/util/processinfo.h"

#include <boost/none.hpp>
#include <boost/optional.hpp>

#include <mach/mach_init.h>
#include <mach/mach_traps.h>
#include <mach/task.h>
#include <mach/task_info.h>

#include <sys/sysctl.h>
#include <sys/types.h>

#include "mongo/bson/bsonobjbuilder.h"
#include "mongo/logv2/log.h"

#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kControl

namespace mongo {

ProcessInfo::ProcessInfo(ProcessId pid) : _pid(pid) {}

ProcessInfo::~ProcessInfo() {}

bool ProcessInfo::supported() {
    return true;
}

// get the number of CPUs available to the scheduler
boost::optional<unsigned long> ProcessInfo::getNumCoresForProcess() {
    long nprocs = sysconf(_SC_NPROCESSORS_ONLN);
    if (nprocs)
        return nprocs;
    return boost::none;
}

int ProcessInfo::getVirtualMemorySize() {
    task_t result;

    mach_port_t task;

    if ((result = task_for_pid(mach_task_self(), _pid.toNative(), &task)) != KERN_SUCCESS) {
        LOGV2(677702, "error getting task");
        return 0;
    }

#if !defined(__LP64__)
    task_basic_info_32 ti;
#else
    task_basic_info_64 ti;
#endif
    mach_msg_type_number_t count = TASK_BASIC_INFO_COUNT;
    if ((result = task_info(task, TASK_BASIC_INFO, (task_info_t)&ti, &count)) != KERN_SUCCESS) {
        LOGV2(677703, "error getting task_info", "result"_attr = result);
        return 0;
    }
    return (int)((double)ti.virtual_size / (1024.0 * 1024));
}

int ProcessInfo::getResidentSize() {
    task_t result;

    mach_port_t task;

    if ((result = task_for_pid(mach_task_self(), _pid.toNative(), &task)) != KERN_SUCCESS) {
        LOGV2(577704, "error getting task");
        return 0;
    }

#if !defined(__LP64__)
    task_basic_info_32 ti;
#else
    task_basic_info_64 ti;
#endif
    mach_msg_type_number_t count = TASK_BASIC_INFO_COUNT;
    if ((result = task_info(task, TASK_BASIC_INFO, (task_info_t)&ti, &count)) != KERN_SUCCESS) {
        LOGV2(677705, "error getting task_info", "result"_attr = result);
        return 0;
    }
    return (int)(ti.resident_size / (1024 * 1024));
}

void ProcessInfo::getExtraInfo(BSONObjBuilder& info) {
    struct task_events_info taskInfo;
    mach_msg_type_number_t taskInfoCount = TASK_EVENTS_INFO_COUNT;

    if (KERN_SUCCESS !=
        task_info(mach_task_self(), TASK_EVENTS_INFO, (integer_t*)&taskInfo, &taskInfoCount)) {
        LOGV2(677706, "error getting extra task_info");
        return;
    }

    info.append("page_faults", taskInfo.pageins);
}

/**
 * Get a sysctl string value by name.  Use string specialization by default.
 */
typedef long long NumberVal;
template <typename Variant>
Variant getSysctlByName(const char* sysctlName) {
    std::string value;
    size_t len;
    int status;
    // NB: sysctlbyname is called once to determine the buffer length, and once to copy
    //     the sysctl value.  Retry if the buffer length grows between calls.
    do {
        status = sysctlbyname(sysctlName, nullptr, &len, nullptr, 0);
        if (status == -1)
            break;
        value.resize(len);
        status = sysctlbyname(sysctlName, &*value.begin(), &len, nullptr, 0);
    } while (status == -1 && errno == ENOMEM);
    if (status == -1) {
        // unrecoverable error from sysctlbyname
        LOGV2(23351, "{sysctlName} unavailable", "sysctlName"_attr = sysctlName);
        return "";
    }

    // Drop any trailing NULL bytes by constructing Variant from a C string.
    return value.c_str();
}

/**
 * Get a sysctl integer value by name (specialization)
 */
template <>
long long getSysctlByName<NumberVal>(const char* sysctlName) {
    long long value = 0;
    size_t len = sizeof(value);
    if (sysctlbyname(sysctlName, &value, &len, nullptr, 0) < 0) {
        LOGV2(23352,
              "Unable to resolve sysctl {sysctlName} (number) ",
              "sysctlName"_attr = sysctlName);
    }
    if (len > 8) {
        LOGV2(23353,
              "Unable to resolve sysctl {sysctlName} as integer.  System returned {len} bytes.",
              "sysctlName"_attr = sysctlName,
              "len"_attr = len);
    }
    return value;
}

void ProcessInfo::SystemInfo::collectSystemInfo() {
    osType = "Darwin";
    osName = "Mac OS X";
    osVersion = getSysctlByName<std::string>("kern.osrelease");
    addrSize = (getSysctlByName<NumberVal>("hw.cpu64bit_capable") ? 64 : 32);
    memSize = getSysctlByName<NumberVal>("hw.memsize");
    memLimit = memSize;
    numCores = getSysctlByName<NumberVal>("hw.ncpu");  // includes hyperthreading cores
    pageSize = static_cast<unsigned long long>(sysconf(_SC_PAGESIZE));
    cpuArch = getSysctlByName<std::string>("hw.machine");
    hasNuma = checkNumaEnabled();

    BSONObjBuilder bExtra;
    bExtra.append("versionString", getSysctlByName<std::string>("kern.version"));
    bExtra.append("alwaysFullSync",
                  static_cast<int>(getSysctlByName<NumberVal>("vfs.generic.always_do_fullfsync")));
    bExtra.append(
        "nfsAsync",
        static_cast<int>(getSysctlByName<NumberVal>("vfs.generic.nfs.client.allow_async")));
    bExtra.append("model", getSysctlByName<std::string>("hw.model"));
    bExtra.append("physicalCores",
                  static_cast<int>(getSysctlByName<NumberVal>("machdep.cpu.core_count")));
    bExtra.append(
        "cpuFrequencyMHz",
        static_cast<int>((getSysctlByName<NumberVal>("hw.cpufrequency") / (1000 * 1000))));
    bExtra.append("cpuString", getSysctlByName<std::string>("machdep.cpu.brand_string"));
    bExtra.append("cpuFeatures", getSysctlByName<std::string>("machdep.cpu.features"));
    bExtra.append("pageSize", static_cast<int>(getSysctlByName<NumberVal>("hw.pagesize")));
    bExtra.append("scheduler", getSysctlByName<std::string>("kern.sched"));
    _extraStats = bExtra.obj();
}

bool ProcessInfo::checkNumaEnabled() {
    return false;
}

}  // namespace mongo

max_stars_repo_name: benety/mongo

max_issues_repo_name: benety/mongo

max_forks_repo_name: benety/mongo


text:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2004-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)
//
// See http://www.boost.org/libs/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////

#ifndef BOOST_INTERPROCESS_TEST_PRINTCONTAINER_HPP
#define BOOST_INTERPROCESS_TEST_PRINTCONTAINER_HPP

#include <boost/interprocess/detail/config_begin.hpp>
#include <functional>
#include <iostream>
#include <algorithm>

namespace boost{
namespace interprocess{
namespace test{

struct PrintValues : public std::unary_function<int, void>
{
   void operator() (int value) const
   {
      std::cout << value << " ";
   }
};

template<class Container>
void PrintContents(const Container &cont, const char *contName)
{
   std::cout<< "Printing contents of " << contName << std::endl;
   std::for_each(cont.begin(), cont.end(), PrintValues());
   std::cout<< std::endl << std::endl;
}

//Function to dump data
template<class MyShmCont
        ,class MyStdCont>
void PrintContainers(MyShmCont *shmcont, MyStdCont *stdcont)
{
   typename MyShmCont::iterator itshm = shmcont->begin(), itshmend = shmcont->end();
   typename MyStdCont::iterator itstd = stdcont->begin(), itstdend = stdcont->end();

   std::cout << "MyShmCont" << std::endl;
   for(; itshm != itshmend; ++itshm){
      std::cout << *itshm << std::endl;
   }
   std::cout << "MyStdCont" << std::endl;

   for(; itstd != itstdend; ++itstd){
      std::cout << *itstd << std::endl;
   }
}

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

#include <boost/interprocess/detail/config_end.hpp>

#endif //#ifndef BOOST_INTERPROCESS_TEST_PRINTCONTAINER_HPP

ext: hpp

max_issues_repo_name: ksundberg/boost-svn

max_forks_repo_name: ksundberg/boost-svn


text:
#pragma once
#include "NetClient.hpp"
#include "ReturnType.hpp"

#include <stdio.h>
#include <cstring>

#include <cstdlib>
#include <string>
#include <vector>

#include <cstdlib>
#include <deque>
#include <iostream>
#include <thread>
#include <boost/asio.hpp>
#include "NetPacket.hpp"
#include "Logger.hpp"

using NetPacketQueue = std::deque<NetPacket>;

class TcpClient;

class BoostAsioTcpClient{
    friend class TcpClient;
private:
    std::function<void(const NetClient & myClient, const std::shared_ptr<NetPacket> netPacket) > onDataReceived_;
    TcpClient *pTcpClient_ = nullptr;
public:
    BoostAsioTcpClient(
            boost::asio::io_service& io_service,
            boost::asio::ip::tcp::resolver::iterator endpoint_iterator,
            decltype(onDataReceived_) onDataReceived,
            TcpClient *pTcpClient
            );

    void write(const NetPacket& msg) {
        io_service_.post([this, msg]() {
            bool write_in_progress = !write_msgs_.empty();
            write_msgs_.push_back(msg);
            if (!write_in_progress){
                write();
            }
        });
    }

    void close(){
        io_service_.post([this]() { socket_.close(); });
    }

private:

    void readHeader(){
        boost::asio::async_read(socket_,
                                boost::asio::buffer(read_msg_.header(), NetPacket::FixHeaderLength),
                                [this](boost::system::error_code ec, std::size_t /*length*/){
            if (!ec && read_msg_.checkHeader()){
                readPayload();
            }
            else{
                socket_.close();
            }
        });
    }

    void readPayload();

    void write(){
        boost::asio::async_write(socket_,
                                 boost::asio::buffer(write_msgs_.front().header(),
                                                     write_msgs_.front().wholePackLength()),
                                 [this](boost::system::error_code ec, std::size_t /*length*/){
            if (!ec){
                write_msgs_.pop_front();
                if (!write_msgs_.empty())
                {
                    write();
                }
            }
            else{
                socket_.close();
            }
        });
    }

private:
    boost::asio::io_service& io_service_;
    boost::asio::ip::tcp::socket socket_;
    NetPacket read_msg_;
    NetPacketQueue write_msgs_;
};

class TcpClient : public NetClient {
    friend class BoostAsioTcpClient;
private:
    std::string id_;
    boost::asio::io_service io_service;
    std::shared_ptr<BoostAsioTcpClient> pClient = nullptr;
    std::shared_ptr<std::thread> pThread = nullptr;
    bool isConnected_ = false;
public:
    TcpClient() {}

    virtual ReturnType init(
        const std::string &serverHost,
        const std::string &serverPort,
        std::function<void(const NetClient & myClient, const std::shared_ptr<NetPacket> netPacket) > onDataReceived
    ) override {
        boost::asio::ip::tcp::resolver resolver(io_service);
        pClient = std::make_shared<BoostAsioTcpClient>(io_service, resolver.resolve({ serverHost, serverPort }), onDataReceived, this);
        pThread = std::make_shared<std::thread>([this](){ io_service.run(); });
        return 0;
    }

    ~TcpClient(){
        try {
            pClient->close();
            pThread->join();
        }
        catch (std::exception &e) {
            LOGE_STD_EXCEPTION(e);
        }
    }

    virtual bool isConnected() const override {return isConnected_;}

    std::string id(){return id_;}

    ReturnType send(const NetPacket &netPacket) const override {
        pClient->write(netPacket);
#ifdef _DEBUG
        LOGV << netPacket.info();
#endif // _DEBUG

        return 0;
    }

};

BoostAsioTcpClient::BoostAsioTcpClient(
        boost::asio::io_service& io_service,
        boost::asio::ip::tcp::resolver::iterator endpoint_iterator,
        decltype(onDataReceived_) onDataReceived,
        TcpClient *pTcpClient
        )
    : io_service_(io_service)
    , socket_(io_service)
    , onDataReceived_(onDataReceived)
    , pTcpClient_(pTcpClient)
{
    // connect(endpoint_iterator);

    boost::asio::async_connect(socket_,
                               endpoint_iterator,
                               [this](boost::system::error_code ec,
                               boost::asio::ip::tcp::resolver::iterator){
        if (ec) {
            socket_.close();
            return;
        }

        pTcpClient_->isConnected_ = true;
        readHeader();
    });
}

void BoostAsioTcpClient::readPayload(){
    boost::asio::async_read(socket_, boost::asio::buffer(read_msg_.payload(), read_msg_.payloadLength()),
                            [this](boost::system::error_code ec, std::size_t /*length*/) {
        if (ec) {
            socket_.close();
            return;
        }

        ////////////////////////////////
        ////////////////////////////////
        ////////////////////////////////
        ////////////////////////////////
        /* GOT DATA! */
        ////////////////////////////////
        ////////////////////////////////
        ////////////////////////////////
        ////////////////////////////////
        ////////////////////////////////
        ////////////////////////////////
        onDataReceived_(*pTcpClient_, std::make_shared<NetPacket>(read_msg_));
        readHeader();
    });
}

max_stars_repo_name: zhang-ray/easy-voice-call

max_issues_repo_name: zhang-ray/easy-voice-call

max_forks_repo_name: zhang-ray/easy-voice-call


text:
#ifndef BOOST_SMART_PTR_MAKE_SHARED_HPP_INCLUDED
#define BOOST_SMART_PTR_MAKE_SHARED_HPP_INCLUDED

//  make_shared.hpp
//
//  Copyright (c) 2007, 2008, 2012 Peter Dimov
//
//  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/smart_ptr/make_shared.html
//  for documentation.

#include <boost/smart_ptr/make_shared_object.hpp>

#if !defined( BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION ) && !defined( BOOST_NO_SFINAE )
# include <boost/smart_ptr/make_shared_array.hpp>
# include <boost/smart_ptr/allocate_shared_array.hpp>
#endif

#endif // #ifndef BOOST_SMART_PTR_MAKE_SHARED_HPP_INCLUDED

max_stars_repo_name: rudylee/expo

max_issues_repo_name: rudylee/expo

max_forks_repo_name: rudylee/expo


text:
#include "Corners.h"
#include "TilesetGenerator.h"
#include "TileGenerator.h"
#include <functional>
#include <stdexcept>
#include <sstream>
#include <boost/filesystem.hpp>
#include "common.h"

namespace tilegen
{

TilesetGenerator::TilesetGenerator(const Options& options,
                                   std::unique_ptr<partition::TilePartitionerBase> tile_partitioner) :
    options(options),
    mTilePartitioner(std::move(tile_partitioner)),
    mDebugTileBuilder(mDebugTile, {0., 0., 1., 1.})
    // TODO (Serin) this sf::Rect is repeated in TilePartitionerNoise, factor it out
{
    if (options.debugOutput)
    {
        mDebugTile.create(options.tileFormat.resolution.x, options.tileFormat.resolution.y);
        partition::TilePartitionerBase::DebugModuleWriter bound_debug_tile_writer =
            std::bind(&TilesetGenerator::writeDebugTile, this,
                      std::placeholders::_1, std::placeholders::_2);
        mTilePartitioner->setDebugModuleWriter(bound_debug_tile_writer);
    }
    for (auto& terrain : options.terrains)
    {
        images.addTerrain(terrain.first, terrain.second.fileName, options.paths.filename,
                          terrain.second.offsetX, terrain.second.offsetY, options.tileFormat.resolution);
    }
}

void TilesetGenerator::generate(std::function<void(const sf::Texture&, std::string)> callback)
{
    metaOutput.setResolution(options.tileFormat.resolution);
    boost::filesystem::path p(options.relativeOutputDirectory);
    for (const auto& clique : options.cliques)
    {
        CornersGenerator corners_generator(clique, static_cast<size_t>(CORNERS));
        std::pair<size_t, size_t> tileset_resolution = corners_generator.size2D(options.tileFormat.resolution);
        mResX = tileset_resolution.first;
        mResY = tileset_resolution.second;
        std::unique_ptr<sf::RenderTexture> output{getBlankImage(mResX, mResY)};
        mDebugTilesets.clear();

        const auto filename_base = getOutputImageFilename(clique);
        const auto filename = filename_base + options.tileFormat.fileType;

        // MetaOutput.addTileset, addTile should use this version of filename;
        // relative to output dir, not options dir!
        metaOutput.addTileset(clique, filename, mResX, mResY);
        generateClique(clique, *output, filename);
        output->display();

        p.append(filename);
        callback(output->getTexture(), p.string());
        p.remove_filename();
        for (const auto& it : mDebugTilesets)
        {
            it.second->display();
            std::stringstream debug_filename_ss;
            debug_filename_ss << filename_base << it.first.description() << "." << options.tileFormat.fileType;
            const auto debug_file_path = (p / "debug" / debug_filename_ss.str()).string();
            callback(it.second->getTexture(), debug_file_path);
        }
    }
}

void TilesetGenerator::generateClique(const Options::Clique& clique, sf::RenderTexture& image, std::string filename)
{
    CornersGenerator corners_generator(clique, static_cast<size_t>(CORNERS));
    for (auto it = corners_generator.cbegin(); it != corners_generator.cend(); ++it)
    {
        const auto& corner_terrains = *it;
        mCurrentTilePosition = it.coordinates2D();
        TileGenerator::generate(image, mCurrentTilePosition.first, mCurrentTilePosition.second, corner_terrains,
                                images, options, *mTilePartitioner.get());
        metaOutput.addTile(corner_terrains, filename,
                           mCurrentTilePosition.first*options.tileFormat.resolution.x,
                           mCurrentTilePosition.second*options.tileFormat.resolution.y);
    }
}

void TilesetGenerator::writeDebugTile(const DebugTilesetID& debugTilesetID, noise::module::ModulePtr module)
{
    if (mDebugTilesets.find(debugTilesetID) == mDebugTilesets.end())
    {
        mDebugTilesets.emplace(std::make_pair(DebugTilesetID(debugTilesetID), std::move(getBlankImage(mResX, mResY))));
    }
    sf::RenderTexture& tileset = *mDebugTilesets.at(debugTilesetID).get();
    // There are far more map lookups here than necessary.

    mDebugTileBuilder.build(module.get()->getModule());
    sf::Texture tile_texture;
    tile_texture.loadFromImage(mDebugTile);
    sf::Sprite tile_sprite(tile_texture);
    tile_sprite.setPosition(
        (float)mCurrentTilePosition.first*options.tileFormat.resolution.x,
        (float)mCurrentTilePosition.second*options.tileFormat.resolution.y);
    tileset.draw(tile_sprite);
}

std::string TilesetGenerator::getOutputImageFilename(const Options::Clique& clique) const
{
    std::stringstream ss;
    for (auto terrain : clique)
    {
        ss << terrain << ".";
    }
    return ss.str();
}

std::unique_ptr<sf::RenderTexture> TilesetGenerator::getBlankImage(size_t res_x, size_t res_y) const
{
    std::unique_ptr<sf::RenderTexture> output{std::make_unique<sf::RenderTexture>()};
    output->create(res_x, res_y);
    output->clear(sf::Color(0,0,0,255));
    return output;
}

} // namespace tilegen

ext: cpp


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

#include <gtest/gtest.h>
#include <climits>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <boost/regex.hpp>
#include "predicate.h"

int main(int argc, char* argv[])
{
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

namespace baikaldb {

TEST(test_covent_pattern, case_all) {
    LikePredicate pred;
    pred.covent_pattern("%?bd\\_vid%");
    boost::regex regex;
    try {
        pred._regex = pred._regex_pattern;
        std::cout << boost::regex_match("www.bad/aca?bd_vid", pred._regex) << "\n";
        std::cout << boost::regex_match("www.bad/aca?bd_vidxxx", pred._regex) << "\n";
        std::cout << boost::regex_match("www.bad/aca?bdvid", pred._regex) << "\n";
        //regex = pred._regex_pattern;
        std::cout << pred._regex_pattern << "\n";
    } catch (boost::regex_error& e) {
        DB_FATAL("regex error:%d,  _regex_pattern:%s",
                e.code(), pred._regex_pattern.c_str());
    }
}

}  // namespace baikal

max_stars_repo_name: lvxinup/BaikalDB

max_issues_repo_name: lvxinup/BaikalDB

max_forks_repo_name: lvxinup/BaikalDB


text:
// Copyright 2018 The Beam Team
//
// 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 "log_rotation.h"
#include "helpers.h"
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <map>
#include <vector>

namespace beam {

LogRotation::LogRotation(io::Reactor& reactor, unsigned rotatePeriodSec, unsigned cleanPeriodSec) :
    _cleanPeriodSec(cleanPeriodSec),
    _logRotateTimer(io::Timer::create(reactor))
{
    _logRotateTimer->start(
        rotatePeriodSec * 1000, true,
        BIND_THIS_MEMFN(on_timer)
    );
}

void LogRotation::on_timer() {
    Logger::get()->rotate();
    auto currentTime = time_t(local_timestamp_msec() / 1000);
    while (!_expiration.empty()) {
        auto it = _expiration.begin();
        if (it->first > currentTime)
            break;
        boost::filesystem::remove_all(it->second);
        _expiration.erase(it);
    }
    _expiration.insert( { currentTime + _cleanPeriodSec, Logger::get()->get_current_file_name() } );
}

static void clean_old_logfiles_2(const std::string& directory, const std::string& prefix, unsigned cleanPeriodSec) {
    namespace fs = boost::filesystem;

    static const unsigned SECS_IN_DAY = 86400;

    // day -> files
    using DayBuckets = std::map<unsigned, std::vector<fs::path>>;
    DayBuckets days;

    auto now = time_t(local_timestamp_msec() / 1000);

    try {
        fs::directory_iterator it(fs::system_complete(directory));
        fs::directory_iterator end;
        for (; it != end; ++it) {
            auto p = it->path();
            if (!fs::is_regular_file(p) ||
                !boost::starts_with(p.filename().string(), prefix) ||
                !(p.extension().string() == ".log")
            ) continue;
            auto dayAgo = unsigned( (now - fs::last_write_time(p)) / SECS_IN_DAY );
            days[dayAgo].push_back(p);
        }

        unsigned cleanPeriodDays = cleanPeriodSec / SECS_IN_DAY; // will take only working days into account, sex intraday

        unsigned day = 0;
        for (const auto& x : days) {
            if (day++ < cleanPeriodDays) continue; // skip specified working days
            for (auto& p : x.second) {
                LOG_INFO() << "removing old log file " << p;
                boost::filesystem::remove_all(p);
            }
        }

    } catch (const boost::exception& e) {
        LOG_ERROR() << "cleanup old logs failed, " << boost::diagnostic_information(e);
    } catch (...) {
        //~
    }
}

void clean_old_logfiles(const std::string& directory, const std::string& prefix, unsigned cleanPeriodSec) {
    clean_old_logfiles_2(directory, prefix, cleanPeriodSec);

    /*
     * maybe we'll return this
     *
    namespace fs = boost::filesystem;

    try {
        auto expiration = time_t(local_timestamp_msec() / 1000) - cleanPeriodSec;
        fs::directory_iterator it(fs::system_complete(directory));
        fs::directory_iterator end;
        for (; it != end; ++it) {
            auto p = it->path();
            if (fs::last_write_time(p) > expiration || !fs::is_regular_file(p))
                continue;
            if (boost::starts_with(p.filename().string(), prefix) && p.extension().string() == ".log") {
                boost::filesystem::remove_all(p);
            }
        }
    } catch (...) {
        //~
    }
     */
}

} //namespace

max_stars_repo_name: Satori-Nakamoto/litecash

max_issues_repo_name: Satori-Nakamoto/litecash

max_forks_repo_name: Satori-Nakamoto/litecash


text:
/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */
#include "joynr/Util.h"

#include <cctype>
#include <cstring>
#include <fstream>
#include <iterator>
#include <regex>
#include <sstream>
#include <stdexcept>
#include <string>

#include <boost/filesystem.hpp>
#include <boost/uuid/random_generator.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>

#include "joynr/Logger.h"

namespace joynr
{

namespace util
{

bool fileExists(const std::string& fileName)
{
    std::ifstream fileToTest(fileName);
    return fileToTest.good();
}

void writeToFile(const std::string& fileName,
                 const std::string& strToSave,
                 std::ios_base::openmode mode)
{
    std::ofstream file;
    file.open(fileName, mode);
    if (!file.is_open()) {
        throw std::runtime_error("Could not open file " + fileName + " for writing: " +
                                 std::strerror(errno));
    }

    // append input string to file
    file << strToSave;
}

void saveStringToFile(const std::string& fileName, const std::string& strToSave)
{
    writeToFile(fileName, strToSave, std::ios::out);
}

void appendStringToFile(const std::string& fileName, const std::string& strToSave)
{
    writeToFile(fileName, strToSave, std::ios::app);
}

std::string loadStringFromFile(const std::string& fileName)
{
    // read from file
    std::ifstream inStream(fileName.c_str(), std::ios::in | std::ios::binary);
    if (!inStream.is_open()) {
        throw std::runtime_error("Could not open file " + fileName + " for reading: " +
                                 std::strerror(errno));
    }

    // validate the file size
    constexpr std::uint64_t MAX_FILE_SIZE = 2 * 1024 * 1024 * 1024UL;
    std::uint64_t fileSize = boost::filesystem::file_size(fileName);
    if (fileSize > MAX_FILE_SIZE) {
        throw std::runtime_error("File " + fileName + " is too big: " + std::strerror(errno));
    }

    std::string fileContents;
    inStream.seekg(0, std::ios::end);
    fileContents.resize(inStream.tellg());
    inStream.seekg(0, std::ios::beg);
    inStream.read(&fileContents[0], fileContents.size());
    inStream.close();
    return fileContents;
}

std::string attributeGetterFromName(const std::string& attributeName)
{
    assert(!attributeName.empty());
    std::string result = attributeName;
    result[0] = std::toupper(result[0]);
    result.insert(0, "get");
    return result;
}

std::string createUuid()
{
    // instantiation of random generator is expensive,
    // therefore we use a static one:
    static boost::uuids::random_generator uuidGenerator;
    // uuid generator is not threadsafe
    static std::mutex uuidMutex;
    std::lock_guard<std::mutex> uuidLock(uuidMutex);
    return boost::uuids::to_string(uuidGenerator());
}

std::string createMulticastId(const std::string& providerParticipantId,
                              const std::string& multicastName,
                              const std::vector<std::string>& partitions)
{
    std::stringstream multicastId;
    multicastId << providerParticipantId << MULTICAST_PARTITION_SEPARATOR << multicastName;
    for (const auto& partition : partitions) {
        multicastId << MULTICAST_PARTITION_SEPARATOR << partition;
    }
    return multicastId.str();
}

std::string extractParticipantIdFromMulticastId(const std::string& multicastId)
{
    auto separatorIt = multicastId.find(MULTICAST_PARTITION_SEPARATOR);

    if (separatorIt == std::string::npos) {
        throw std::invalid_argument("Cannot extract provider participant Id from multicast Id: " +
                                    multicastId);
    }

    return multicastId.substr(0, separatorIt);
}

void validatePartitions(const std::vector<std::string>& partitions, bool allowWildcards)
{
    static const std::regex patternRegex("^[a-zA-Z0-9]+$");
    const std::vector<std::string>::const_iterator lastPartition = --partitions.cend();
    for (auto partition = partitions.cbegin(); partition != partitions.cend(); ++partition) {
        if (!partition->empty()) {
            if (allowWildcards) {
                if (*partition == SINGLE_LEVEL_WILDCARD) {
                    continue;
                } else if (*partition == MULTI_LEVEL_WILDCARD) {
                    if (partition == lastPartition) {
                        return;
                    }
                }
            }
            if (std::regex_search(*partition, patternRegex)) {
                continue;
            }
        }
        throw std::invalid_argument("Partition " + *partition +
                                    " contains invalid characters.\nMust only contain a-z A-Z 0-9, "
                                    "or be a single level wildcard (" +
                                    SINGLE_LEVEL_WILDCARD +
                                    "),\nor the last partition may be a multi level wildcard (" +
                                    MULTI_LEVEL_WILDCARD + ").");
    }
}

std::string truncateSerializedMessage(const std::string& message)
{
    constexpr std::size_t maxSize = 2048;
    const std::size_t messageSize = message.size();
    if (messageSize > maxSize) {
        return message.substr(0, maxSize) + std::string("<**truncated, length=") +
               std::to_string(messageSize);
    }
    return message;
}

bool isAdditionOnPointerSafe(std::uintptr_t address, int payloadLength)
{
    return address + payloadLength < address;
}

std::string getErrorString(int errorNumber)
{
    // MT-safe retrieval of string describing errorNumber
    char buf[256];
    char* resultBuf = buf;
    int storedErrno = errorNumber;
#if defined(__GLIBC__) && defined(_GNU_SOURCE)
    // POSIX compliant check for conversion errors,
    // see 'man strerror_r'
    errno = 0;
    resultBuf = strerror_r(storedErrno, buf, sizeof(buf));
    if (errno) {
        return "failed to convert errno";
    }
#else
    int rc = strerror_r(storedErrno, buf, sizeof(buf));
    if (rc) {
        return "failed to convert errno";
    }
#endif
    return std::string(resultBuf);
}

} // namespace util

} // namespace joynr


text:
#include "init_pipeline.hpp"
#include <algorithm>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include <iostream>
#include <random>
#include <stdio.h>
#include <utility>

namespace po = boost::program_options;

// Pre-ripples script to get general run information needed to configure parallel jobs.
int main(int argc, char **argv) {

    po::options_description desc("optimize options");
    desc.add_options()("input-mat,i", po::value<std::string>()->required(),
                       "Input mutation-annotated tree file [REQUIRED].")(
        "branch-length,l", po::value<uint32_t>()->default_value(3),
        "Minimum length of the branch to consider to recombination events")(
        "num-descendants,n", po::value<uint32_t>()->default_value(2),
        "Minimum number of leaves that node should have to be considered for "
        "recombination.");

    po::options_description all_options;
    all_options.add(desc);
    po::positional_options_description p;
    po::variables_map vm;
    try {
        po::store(po::command_line_parser(argc, argv)
                      .options(all_options)
                      .positional(p)
                      .run(),
                  vm);
        po::notify(vm);
    } catch (std::exception &e) {
        std::cerr << desc << std::endl;
        // Return with error code 1 unless
        // the user specifies help
        if (vm.count("help"))
            exit(0);
        else
            exit(1);
    }
    std::string input_mat_filename = vm["input-mat"].as<std::string>();
    uint32_t branch_len = vm["branch-length"].as<uint32_t>();
    uint32_t num_descendants = vm["num-descendants"].as<uint32_t>();

    // Load input MAT and uncondense tree
    MAT::Tree T = MAT::load_mutation_annotated_tree(input_mat_filename);
    T.uncondense_leaves();

    // Output text file for mapping UShER node_ids to Chronumental node_ids
    preorder_traversal(T);

    size_t long_branches = find_long_branches(T, branch_len, num_descendants);
		std::cout << long_branches << "\n";
    return 0;
}

max_stars_repo_name: mrkylesmith/usher

max_issues_repo_name: mrkylesmith/usher

max_forks_repo_name: mrkylesmith/usher


text:
#include "tree/map_hdf5.h"

// Standard includes
#include <string>
#include <vector>

// Boost includes
#include <boost/algorithm/string.hpp>

// ROOT includes
#include <TBranch.h>
#include <TLeaf.h>

// root2hdf5 includes
#include "options.h"
#include "tree/walk.h"
#include "tree/structure.h"
#include "tree/leaf_converters.h"

// Standard namespaces
using namespace std;

// Boost namespaces
using namespace boost;

// root2hdf5 namespaces
using namespace root2hdf5::tree::map_hdf5;
using namespace root2hdf5::options;
using namespace root2hdf5::tree::walk;
using namespace root2hdf5::tree::structure;
using namespace root2hdf5::tree::leaf_converters;

boost::tuple<hid_t, hdf5_type_deallocator>
root2hdf5::tree::map_hdf5::hdf5_type_for_tree(TTree *tree)
{
    // Create the deallocator list
    vector<hdf5_type_deallocator> deallocators;

    // Compute the structure type name for the tree
    string hdf5_struct_name = struct_type_name_for_tree(tree);

    // Grab the size for the struct
    size_t hdf5_struct_size = sizeof_type_by_name(hdf5_struct_name);

    // Create the HDF5 data type for the tree and create a deallocator for it
    hid_t result = H5Tcreate(H5T_COMPOUND, hdf5_struct_size);
    if(result < 0)
    {
        if(verbose)
        {
            cerr << "ERROR: Couldn't create compound data type for tree \""
                 << tree->GetName() << "\"" << endl;
        }

        return boost::make_tuple(-1, []()->bool{return true;});
    }
    deallocators.push_back([=]() -> bool {
        // Close out the type
        if(H5Tclose(result) < 0)
        {
            if(verbose)
            {
                cerr << "ERROR: Couldn't close HDF5 data type for tree \""
                     << tree->GetName() << "\"" << endl;
            }

            return false;
        }

        return true;
    });

    // Create data structures to track the current stack of branches, HDF5
    // types, and offsets
    vector<string> path_stack; // Stack of parent paths
    vector<size_t> path_offset_stack = {0}; // Stack of parent offsets in the
                                            // top-level HDF5 struct
    vector<hid_t> hdf5_type_stack = {result}; // Stack of HDF5 compound types

    // Walk the tree and add subtypes
    bool success = walk_tree(
        tree,

        // Branch open
        [&path_stack,
         &path_offset_stack,
         &hdf5_type_stack,
         &deallocators,
         hdf5_struct_name]
        (TBranch *branch) -> bool {
            // Push the branch onto the path stack
            path_stack.push_back(branch->GetName());

            // Calculate the complete path to this branch in the master struct
            string branch_path_in_struct = join(path_stack, ".");

            // Calculate the offset of this branch in the top-level HDF5 struct
            path_offset_stack.push_back(offsetof_member_in_type_by_name(
                hdf5_struct_name,
                branch_path_in_struct
            ));

            // Calculate the size of this branch in the struct
            size_t branch_size_in_struct = sizeof_member_in_type_by_name(
                hdf5_struct_name,
                branch_path_in_struct
            );

            // Create the new compound data type and push it onto the stack
            hid_t branch_type = H5Tcreate(
                H5T_COMPOUND,
                branch_size_in_struct
            );
            if(branch_type < 0)
            {
                if(verbose)
                {
                    cerr << "ERROR: Unable to create compound type for branch "
                         << "at path \"" << branch_path_in_struct << "\""
                         << endl;
                }

                return false;
            }

            // Add the type to the stack
            hdf5_type_stack.push_back(branch_type);

            // Create a deallocator
            deallocators.push_back([=]() -> bool {
                if(H5Tclose(branch_type) < 0)
                {
                    if(verbose)
                    {
                        cerr << "ERROR: Couldn't close HDF5 data type for "
                             << "branch at path \"" << branch_path_in_struct
                             << "\"" << endl;
                    }

                    return false;
                }

                return true;
            });

            return true;
        },

        // Leaf process
        [&path_stack,
         &path_offset_stack,
         &hdf5_type_stack,
         &deallocators,
         hdf5_struct_name]
        (TLeaf *leaf) -> bool {
            // First, find a leaf converter, and if we can't find one, just
            // ignore the leaf (a warning will have already been generated)
            leaf_converter *converter = find_converter(leaf);
            if(converter == NULL)
            {
                return true;
            }

            // Temporarily push the leaf onto the path stack just to calculate
            // its path in the master struct
            path_stack.push_back(leaf->GetName());
            string leaf_path_in_struct = join(path_stack, ".");
            path_stack.pop_back();

            // Calculate the offset of this leaf in the master struct
            size_t leaf_offset_in_struct = offsetof_member_in_type_by_name(
                hdf5_struct_name,
                leaf_path_in_struct
            );

            // Calculate the offset of this branch relative to its parent
            size_t leaf_offset_in_parent
                = leaf_offset_in_struct - path_offset_stack.back();

            // Calculate the HDF5 type for the leaf
            hid_t leaf_type = converter->hdf5_type_for_leaf(leaf, deallocators);

            // Insert the HDF5 type into the parent compound type
            if(H5Tinsert(hdf5_type_stack.back(),
                         leaf->GetName(),
                         leaf_offset_in_parent,
                         leaf_type) < 0)
            {
                if(verbose)
                {
                    cerr << "ERROR: Unable to insert compound type for leaf \""
                     << leaf->GetName() << "\" into parent compound type"
                     << endl;
                }

                return false;
            }

            return true;
        },

        // Branch close
        [&path_stack,
         &path_offset_stack,
         &hdf5_type_stack,
         &deallocators,
         hdf5_struct_name]
        (TBranch *branch) -> bool {
            // Clear this branch off the path stack
            path_stack.pop_back();

            // Grab the offset of this branch in the master struct and pop it
            // off the stack
            size_t branch_offset_in_struct = path_offset_stack.back();
            path_offset_stack.pop_back();

            // Calculate the offset of this branch relative to its parent
            size_t branch_offset_in_parent
                = branch_offset_in_struct - path_offset_stack.back();

            // Pop the type off the stack
            hid_t branch_type = hdf5_type_stack.back();
            hdf5_type_stack.pop_back();

            // Insert the HDF5 type into the parent compound type
            if(H5Tinsert(hdf5_type_stack.back(),
                         branch->GetName(),
                         branch_offset_in_parent,
                         branch_type) < 0)
            {
                if(verbose)
                {
                    cerr << "ERROR: Unable to insert compound type for branch "
                     << "\"" << branch->GetName() << "\" into parent compound "
                     << "type" << endl;
                }

                return false;
            }

            return true;
        }
    );

    // Check that the walking went correctly
    if(!success)
    {
        if(verbose)
        {
            cerr << "ERROR: Unable to generate HDF5 compound type for tree \""
             << tree->GetName() << "\"" << endl;
        }

        result = -1;
    }

    // All done
    return boost::make_tuple(result, [=]() -> bool {
        for(auto it = deallocators.rbegin();
            it != deallocators.rend();
            it++)
        {
            // Iterate over deallocators in reverse so we close types in the
            // opposite order of how we open them
            if(!(*it)())
            {
                return false;
            }
        }

        return true;
    });
}


text:
#include "stlparse.h"

#include <fstream>
#include <vector>
#include <map>
#include <iostream>

#include <Eigen/Dense>

#include "parse_common.h"

#pragma GCC visibility push(hidden)

namespace meshparse {

using namespace Eigen;

using std::cout;
using std::endl;
using std::ifstream;
using std::ios_base;
using std::istream;
using std::pair;

inline uint32_t read_int(istream &file) {
    char buf32[4];
    file.read(buf32, 4);
    return *((uint32_t*) buf32);
}

inline float read_float(istream &file) {
    char buf32[4];
    file.read(buf32, 4);
    return *((float*) buf32);
}

void try_read_face(istream &file, stlmesh &stlm) {
    stlface face;
    face.normal[0] = read_float(file);
    face.normal[1] = read_float(file);
    face.normal[2] = read_float(file);

    for (int i = 0; i < 3; i++) {
        float vx = read_float(file);
        float vy = read_float(file);
        float vz = read_float(file);
        Vector3f vec(vx, vy, vz);

        uint32_t id;
        auto idp = stlm.vert_to_id.find(vec);
        if (idp == stlm.vert_to_id.end()) {
            id = stlm.next_vertid++;
            stlm.vert_to_id.insert(pair<Vector3f, uint32_t>(vec, id));
        } else {
            id = idp->second;
        }
        face.verts[i] = id;
    }

    file.seekg(2, ios_base::cur);
    stlm.faces.push_back(face);
}

bool load_binary_stl(ifstream &file, mesh &mesh) {
    file.seekg(80);
    const uint32_t tris = read_int(file);

    stlmesh stlm;
    for (int i = 0; i < tris; i++) {
        try_read_face(file, stlm);
    }

    stl_to_mesh(stlm, mesh);
    merge_half_edges(mesh);

    cout << "Loaded mesh: " << endl
        << "  " << mesh.verteces.size() << " verteces." << endl
        << "  " << mesh.edges.size() << " edges." << endl;
    return true;
}

} // namespace meshparse

#pragma GCC visibility pop

max_stars_repo_name: haldean/meshparse

max_issues_repo_name: haldean/meshparse

max_forks_repo_name: haldean/meshparse


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

#include <boost/simd/toolbox/constant/include/constants/pi.hpp>
#include <boost/simd/toolbox/constant/include/constants/pio_2.hpp>
#include <boost/simd/toolbox/constant/include/constants/inf.hpp>
#include <boost/simd/toolbox/constant/include/constants/nan.hpp>
#include <boost/simd/toolbox/constant/include/constants/half.hpp>
#include <boost/simd/toolbox/constant/include/constants/minf.hpp>
#include <boost/simd/toolbox/constant/include/constants/gold.hpp>
#include <boost/simd/toolbox/constant/include/constants/sqrt_2.hpp>
#include <boost/simd/toolbox/constant/include/constants/cgold.hpp>
#include <boost/simd/toolbox/constant/include/constants/mhalf.hpp>
#include <boost/simd/toolbox/constant/include/constants/mzero.hpp>
#include <boost/simd/toolbox/constant/include/constants/third.hpp>
#include <boost/simd/toolbox/constant/include/constants/sqrt_2o_2.hpp>
#include <boost/simd/toolbox/constant/include/constants/quarter.hpp>
#include <boost/simd/toolbox/constant/include/constants/twotom10.hpp>
#include <boost/simd/toolbox/constant/include/constants/twotonmb.hpp>
#include <boost/simd/toolbox/constant/include/constants/real_splat.hpp>
#include <boost/simd/toolbox/constant/include/constants/splitfactor.hpp>

#endif


text:
/* Copyright (C) 2010 Ion Torrent Systems, Inc. All Rights Reserved */
#include <Eigen/Dense>
#include <Eigen/LU>
#include "ZeromerMatDiff.h"
#include "IonH5Eigen.h"
#include "SampleStats.h"
#include "SampleQuantiles.h"

void ZeromerMatDiff::ShiftReference(int n_frames, size_t n_flow_wells, float shift,
                                    float *orig_data, float *shifted_data) {
  if (shift == 0.0f) {
    memcpy(shifted_data, orig_data, sizeof(float) * n_flow_wells * n_frames);
    return;
  }
  Eigen::Map<Eigen::MatrixXf, Eigen::Aligned> orig(orig_data, n_flow_wells, n_frames);
  Eigen::Map<Eigen::MatrixXf, Eigen::Aligned> shifted(shifted_data, n_flow_wells, n_frames);
  for (int frame_ix = 0; frame_ix < n_frames; frame_ix++) {
    int start_frame = floor(frame_ix + shift);
    int end_frame = ceil(frame_ix + shift);
    //    if (shift < 0) { std::swap(start_frame, end_frame); }
    if (start_frame >= 0 && end_frame < n_frames) {
      //interpolate...
      float mult = shift - floor(shift);
      shifted.col(frame_ix).array() = (orig.col(end_frame).array() - orig.col(start_frame).array()) * mult;
      shifted.col(frame_ix).array() += orig.col(start_frame).array();
    }
    else {
      // extrapolate backwards
      if (shift < 0) {
        // calculate slope
        shifted.col(frame_ix).array() = (orig.col(1).array() - orig.col(0).array());
        shifted.col(frame_ix).array() = orig.col(0).array() + shifted.col(frame_ix).array() * (frame_ix + shift);
      }
      // extrapolate forwards
      else if (shift > 0) {
        shifted.col(frame_ix).array() = (orig.col(n_frames - 1).array() - orig.col(n_frames - 2).array());
        shifted.col(frame_ix).array() = orig.col(n_frames - 1).array() + shifted.col(frame_ix).array() * (frame_ix + shift - (n_frames - 1));
      }
      else {
        assert(0);
      }
    }
  }
}

void ZeromerMatDiff::PredictZeromersSignal(const float *time, int n_frames,
                                           float *trace, float *ref, float *zeromer,
                                           size_t n_wells, size_t n_flows,
                                           size_t n_flow_wells,
                                           float taue_est, float *__restrict taub,
                                           const std::string &h5_dump) {
  Eigen::Map<Eigen::MatrixXf, Eigen::Aligned> trace_data(trace, n_flow_wells, n_frames);
  Eigen::Map<Eigen::MatrixXf, Eigen::Aligned> ref_data(ref, n_flow_wells, n_frames);
  Eigen::Map<Eigen::MatrixXf, Eigen::Aligned> zeromer_est(zeromer, n_flow_wells, n_frames);
  zeromer_est.setZero();
  Eigen::Map<Eigen::VectorXf, Eigen::Aligned> taub_v(taub, n_flow_wells);
  Eigen::VectorXf cdelta(n_flow_wells);
  cdelta.setZero();
  // column based operations vectorized by eigen for speed
  for (int f_ix = 1; f_ix < trace_data.cols(); f_ix++) {
    float dtime = time[f_ix] - time[f_ix -1];
    zeromer_est.col(f_ix).array() = ref_data.col(f_ix).array() * (taue_est + dtime);
    zeromer_est.col(f_ix) = zeromer_est.col(f_ix) + cdelta;
    zeromer_est.col(f_ix).array() = zeromer_est.col(f_ix).array() / (taub_v.array() + dtime);
    cdelta.array() += ref_data.col(f_ix).array() - zeromer_est.col(f_ix).array();
  }
  if (!h5_dump.empty()) {
    H5File h5(h5_dump);
    h5.Open(true);
    Eigen::MatrixXf trace_data_tmp = trace_data;
    Eigen::MatrixXf ref_data_tmp = ref_data;
    Eigen::MatrixXf zeromer_est_tmp = zeromer_est;
    H5Eigen::WriteMatrix(h5, "/traces", trace_data_tmp);
    H5Eigen::WriteMatrix(h5, "/ref", ref_data_tmp);
    H5Eigen::WriteMatrix(h5, "/shifted_ref", ref_data_tmp);
    H5Eigen::WriteMatrix(h5, "/zeromer", zeromer_est_tmp);
    h5.Close();
  }
  //  zeromer_est = trace_data - zeromer_est;
}

void ZeromerMatDiff::ZeromerMadError(const int *zero_flows, size_t n_zero_flows,
                                     float *signal_data,
                                     size_t n_wells, size_t n_flows,
                                     size_t n_flow_wells, size_t n_frames,
                                     float &mad) {
  // Calculate basics per well for integral, mad, max for each well/flow
  SampleStats<double> mad_mean;
  for (size_t z_ix = 0; z_ix < n_zero_flows; z_ix++) {
    size_t flow_ix = zero_flows[z_ix];
    for (size_t col_ix = 0; col_ix < n_frames; col_ix++) {
      float *__restrict signal_start = signal_data + n_wells * flow_ix + n_flow_wells * col_ix;
      float *__restrict signal_end = signal_start + n_wells;
      while (signal_start != signal_end) {
        mad_mean.AddValue(fabs(*signal_start));
        signal_start++;
      }
    }
  }
  mad = mad_mean.GetMean();
}

void ZeromerMatDiff::ZeromerSumSqErrorTrim(const int *zero_flows, size_t n_zero_flows,
                                           const char *bad_wells,
                                           float *signal_data, float *predict_data,
                                           size_t n_wells, size_t n_flows,
                                           size_t n_flow_wells, size_t n_frames,
                                           double &ssq) {
  double ssq_sum = 0;
  size_t bad_count = 0;
  float max_value = 1000.0f;
  for (size_t z_ix = 0; z_ix < n_zero_flows; z_ix++) {
    size_t flow_ix = zero_flows[z_ix];
    for (size_t col_ix = 0; col_ix < n_frames; col_ix++) {
      float *__restrict signal_start = signal_data + n_wells * flow_ix + n_flow_wells * col_ix;
      float *__restrict signal_end = signal_start + n_wells;
      float *__restrict predict_start = predict_data + n_wells * flow_ix + n_flow_wells * col_ix;
      const char *__restrict bad_start = bad_wells;
      while (signal_start != signal_end) {
        double value = *signal_start - *predict_start; //*signal_start * *signal_start;
        if (*bad_start == 0 && isfinite(value) && fabs(value) <= max_value) {
          ssq_sum += value * value;
        }
        else if (*bad_start == 0) {
          *predict_start = *signal_start + max_value;
          ssq_sum += max_value;
          bad_count++;
        }
        // levmar has it's own version of residual calculation so have to sub in the nan values
        if (!isfinite(value) || std::isnan(value) || value > max_value) {
          *predict_start = *signal_start + max_value;
        }
        bad_start++;
        signal_start++;
        predict_start++;
      }
    }
  }
  ssq = ssq_sum;
}

void ZeromerMatDiff::FitTauB(const int *zero_flows, size_t n_zero_flows,
                             const float *trace_data, const float *ref_data,
                             size_t n_wells, size_t n_flows, size_t n_flow_wells,
                             size_t n_frames, float taue_est, float *__restrict taub) {
  Eigen::Map<Eigen::VectorXf, Eigen::Aligned> taub_v(taub, n_flow_wells);
  Eigen::VectorXf vec_sum_x2(n_wells), vec_sum_xy(n_wells),
    vec_previous(n_wells), taub_sum(n_wells);
  taub_sum.setZero();
  taub_v.setZero();
  for (size_t flow_ix = 0; flow_ix < n_zero_flows; flow_ix++) {
    int z_ix = zero_flows[flow_ix];

    vec_sum_x2.setZero();
    vec_sum_xy.setZero();
    vec_previous.setZero();
    for (size_t frame_ix = 0; frame_ix < n_frames; frame_ix++) {
      size_t offset = frame_ix * n_flow_wells + n_wells * z_ix;
      const float * __restrict trace_ptr_start = trace_data + offset;
      const float * __restrict trace_ptr_end = trace_ptr_start + n_wells;
      const float * __restrict ref_ptr = ref_data + offset;
      float * __restrict previous_ptr = vec_previous.data();
      float * __restrict xx_ptr = vec_sum_x2.data();
      float * __restrict xy_ptr = vec_sum_xy.data();
      while (trace_ptr_start != trace_ptr_end) {
        float diff = *ref_ptr - *trace_ptr_start;
        float taues = *ref_ptr * taue_est;
        float y = *previous_ptr + diff + taues;
        *previous_ptr += diff;
        float x = *trace_ptr_start;
        *xx_ptr += x * x;
        *xy_ptr += x * y;

        trace_ptr_start++;
        ref_ptr++;
        previous_ptr++;
        xx_ptr++;
        xy_ptr++;
      }
    }
    float *__restrict tau_b_start = taub_sum.data();
    float *__restrict tau_b_end = tau_b_start + n_wells;
    float *__restrict xx_ptr = vec_sum_x2.data();
    float *__restrict xy_ptr = vec_sum_xy.data();
    while (tau_b_start != tau_b_end) {
      *tau_b_start++ += *xy_ptr++ / *xx_ptr++;
    }
  }

  /* for now same taub estimate per nuc, just copy for each flow. */
  for (size_t flow_ix = 0; flow_ix < n_flows; flow_ix++) {
    float *__restrict tau_b_start = taub + flow_ix * n_wells;
    float *__restrict tau_b_end = tau_b_start + n_wells;
    float *__restrict tau_b_sum_start = taub_sum.data();
    while (tau_b_start != tau_b_end) {
      *tau_b_start++ = *tau_b_sum_start++ / n_zero_flows;
    }
  }

}

void ZeromerMatDiff::FitTauBNuc(const int *zero_flows, size_t n_zero_flows,
                                const float *trace_data, const float *ref_data,
                                int *nuc_flows,
                                size_t n_wells, size_t n_flows, size_t n_flow_wells,
                                size_t n_frames, float taue_est, float *__restrict taub) {
  float nuc_weight_mult = .3;
  float combo_weight_mult = .7;

  Eigen::Map<Eigen::VectorXf, Eigen::Aligned> taub_v(taub, n_flow_wells);
  Eigen::VectorXf vec_sum_x2(n_wells), vec_sum_xy(n_wells),
    vec_previous(n_wells), taub_sum(n_wells);
  Eigen::MatrixXf taub_nuc(n_wells, 4);
  int nuc_counts[4] = {0,0,0,0};
  taub_nuc.setZero();
  taub_v.setZero();
  taub_sum.setZero();
  for (size_t flow_ix = 0; flow_ix < n_zero_flows; flow_ix++) {
    int z_ix = zero_flows[flow_ix];
    vec_sum_x2.setZero();
    vec_sum_xy.setZero();
    vec_previous.setZero();
    for (size_t frame_ix = 0; frame_ix < n_frames; frame_ix++) {
      size_t offset = frame_ix * n_flow_wells + n_wells * z_ix;
      const float * __restrict trace_ptr_start = trace_data + offset;
      const float * __restrict trace_ptr_end = trace_ptr_start + n_wells;
      const float * __restrict ref_ptr = ref_data + offset;
      float * __restrict previous_ptr = vec_previous.data();
      float * __restrict xx_ptr = vec_sum_x2.data();
      float * __restrict xy_ptr = vec_sum_xy.data();
      while (trace_ptr_start != trace_ptr_end) {
        float diff = *ref_ptr - *trace_ptr_start;
        float taues = *ref_ptr * taue_est;
        float y = *previous_ptr + diff + taues;
        *previous_ptr += diff;
        float x = *trace_ptr_start;
        *xx_ptr += x * x;
        *xy_ptr += x * y;

        trace_ptr_start++;
        ref_ptr++;
        previous_ptr++;
        xx_ptr++;
        xy_ptr++;
      }
    }
    int nuc_ix = nuc_flows[z_ix];
    nuc_counts[nuc_ix]++;
    float *__restrict tau_b_nuc_start = taub_nuc.col(nuc_ix).data();
    float *__restrict tau_b_start = taub_sum.data();
    float *__restrict tau_b_end = tau_b_start + n_wells;
    float *__restrict xx_ptr = vec_sum_x2.data();
    float *__restrict xy_ptr = vec_sum_xy.data();
    while (tau_b_start != tau_b_end) {
      float value = *xy_ptr++ / *xx_ptr++;
      if (!isfinite(value)) {
        value = 0;
      }
      *tau_b_start++ += value;
      *tau_b_nuc_start++ += value;
    }
  }

  /* for now same taub estimate per nuc, just copy for each flow. */
  for (size_t flow_ix = 0; flow_ix < n_flows; flow_ix++) {
    int nuc_ix = nuc_flows[flow_ix];
    float *__restrict tau_b_start = taub + flow_ix * n_wells;
    float *__restrict tau_b_end = tau_b_start + n_wells;
    float *__restrict tau_b_sum_start = taub_sum.data();
    float *__restrict tau_b_nuc_sum_start = taub_nuc.col(nuc_ix).data();
    // little awkward as we mult weight by number of observances but then divide out for average but more readable to keep calc
    float nuc_div = nuc_counts[nuc_ix];
    float nuc_weight = nuc_counts[nuc_ix] * nuc_weight_mult;
    float nuc_mult = nuc_div > 0.0f ? nuc_weight / nuc_div : 0.0f;
    float total_weight = nuc_weight + combo_weight_mult;
    float combo_mult = combo_weight_mult/n_zero_flows;
    while (tau_b_start != tau_b_end) {
      // weighted average of nuc specific and overall for this well taub
      *tau_b_start = ((*tau_b_sum_start * combo_mult) + (*tau_b_nuc_sum_start * nuc_mult)) / total_weight;
      tau_b_start++;
      tau_b_sum_start++;
      tau_b_nuc_sum_start++;
    }
  }
}

max_stars_repo_name: konradotto/TS

max_issues_repo_name: konradotto/TS

max_forks_repo_name: konradotto/TS


text:
#include "config.h"
#include "common.hpp"
#include "fetcher_io.hpp"
#include "tilejson.hpp"
#include "fetch/http.hpp"
#include "logging/logger.hpp"
#include "http_server/server.hpp"
#include "vector_tile.pb.h"

#include <google/protobuf/io/zero_copy_stream_impl.h>

#include <boost/property_tree/ptree.hpp>

#include <mapnik/datasource_cache.hpp>

#include <iostream>

#include <curl/curl.h>

namespace bpt = boost::property_tree;

namespace {

server_options default_options(const std::string &map_file, int compression_level) {
  server_options options;
  options.path_multiplier = 16;
  options.buffer_size = 0;
  options.scale_factor = 1.0;
  options.offset_x = 0;
  options.offset_y = 0;
  options.tolerance = 1;
  options.image_format = "jpeg";
  options.scaling_method = mapnik::SCALING_NEAR;
  options.scale_denominator = 0.0;
  options.thread_hint = 1;
  options.map_file = map_file;
  options.port = "";
  options.max_age = 60;
  options.compression_level = compression_level;
  return options;
}

struct server_guard {
  server_options options;
  http::server3::server server;
  std::string port;

  server_guard(const std::string &map_xml, int compression_level = -1)
    : options(default_options(map_xml, compression_level))
    , server("localhost", options)
    , port(server.port()) {

    server.run(false);
  }

  ~server_guard() {
    server.stop();
  }

  std::string base_url() {
    return (boost::format("http://localhost:%1%") % port).str();
  }
};

void test_fetch_empty() {
  server_guard guard("test/empty_map_file.xml");

  avecado::fetch::http fetch(guard.base_url(), "pbf");
  avecado::fetch_response response(fetch(0, 0, 0).get());

  test::assert_equal<bool>(response.is_left(), true, "should fetch tile OK");
  test::assert_equal<int>(response.left()->mapnik_tile().layers_size(), 0, "should have no layers");
}

void test_fetch_single_line() {
  server_guard guard("test/single_line.xml");

  avecado::fetch::http fetch(guard.base_url(), "pbf");
  avecado::fetch_response response(fetch(0, 0, 0).get());

  test::assert_equal<bool>(response.is_left(), true, "should fetch tile OK");
  test::assert_equal<int>(response.left()->mapnik_tile().layers_size(), 1, "should have one layer");
}

void assert_is_error(avecado::fetch::http &fetch, int z, int x, int y, avecado::fetch_status status) {
  avecado::fetch_response response(fetch(z, x, y).get());
  test::assert_equal<bool>(response.is_right(), true, (boost::format("(%1%, %2%, %3%): response should be failure") % z % x % y).str());
  test::assert_equal<avecado::fetch_status>(response.right().status, status,
                                            (boost::format("(%1%, %2%, %3%): response status is not what was expected") % z % x % y).str());
}

void test_fetch_error_coordinates() {
  using avecado::fetch_status;

  server_guard guard("test/empty_map_file.xml");

  avecado::fetch::http fetch(guard.base_url(), "pbf");

  assert_is_error(fetch, -1, 0, 0, fetch_status::not_found);
  assert_is_error(fetch, 31, 0, 0, fetch_status::not_found);
  assert_is_error(fetch, 0, 0, 1, fetch_status::not_found);
  assert_is_error(fetch, 0, 1, 0, fetch_status::not_found);
  assert_is_error(fetch, 0, 0, -1, fetch_status::not_found);
  assert_is_error(fetch, 0, -1, 0, fetch_status::not_found);
}

void test_fetch_error_extension() {
  using avecado::fetch_status;

  server_guard guard("test/empty_map_file.xml");

  avecado::fetch::http fetch(guard.base_url(), "gif");

  assert_is_error(fetch, 0, 0, 0, fetch_status::not_found);
}

void test_fetch_error_path_segments() {
  using avecado::fetch_status;

  server_guard guard("test/empty_map_file.xml");

  avecado::fetch::http fetch(guard.base_url(), "/0.pbf");

  assert_is_error(fetch, 0, 0, 0, fetch_status::not_found);
}

void test_fetch_error_non_numeric() {
  using avecado::fetch_status;

  server_guard guard("test/empty_map_file.xml");

  std::vector<std::string> patterns;
  patterns.push_back((boost::format("%1%/a/b/c.pbf") % guard.base_url()).str());
  avecado::fetch::http fetch(std::move(patterns));

  assert_is_error(fetch, 0, 0, 0, fetch_status::not_found);
}

void test_no_url_patterns_is_error() {
  std::vector<std::string> patterns;
  bool threw = false;

  avecado::fetch::http fetch(std::move(patterns));

  try {
    avecado::fetch_response response(fetch(0, 0, 0).get());
  } catch (...) {
    threw = true;
  }

  test::assert_equal<bool>(threw, true, "Should have thrown exception when patterns was empty.");
}

void test_fetcher_io() {
  using avecado::fetch_status;

  test::assert_equal<std::string>((boost::format("%1%") % fetch_status::bad_request).str(), "Bad Request");
  test::assert_equal<std::string>((boost::format("%1%") % fetch_status::not_found).str(), "Not Found");
  test::assert_equal<std::string>((boost::format("%1%") % fetch_status::server_error).str(), "Server Error");
  test::assert_equal<std::string>((boost::format("%1%") % fetch_status::not_implemented).str(), "Not Implemented");
}

void test_fetch_tilejson() {
  using avecado::fetch_status;

  server_guard guard("test/single_poly.xml");

  bpt::ptree tilejson = avecado::tilejson(
    (boost::format("%1%/tile.json") % guard.base_url()).str());
}

size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata) {
  std::stringstream *stream = static_cast<std::stringstream*>(userdata);
  size_t total_bytes = size * nmemb;
  stream->write(ptr, total_bytes);
  return stream->good() ? total_bytes : 0;
}

#define CURL_SETOPT(curl, opt, arg) {                                   \
    CURLcode res = curl_easy_setopt((curl), (opt), (arg));              \
    if (res != CURLE_OK) {                                              \
      throw std::runtime_error("Unable to set cURL option " #opt);      \
    }                                                                   \
  }

void test_tile_is_compressed() {
  server_guard guard("test/single_line.xml", 9);
  std::string uri = (boost::format("%1%/0/0/0.pbf") % guard.base_url()).str();
  std::stringstream stream;

  CURL *curl = curl_easy_init();
  CURL_SETOPT(curl, CURLOPT_URL, uri.c_str());
  CURL_SETOPT(curl, CURLOPT_WRITEFUNCTION, write_callback);
  CURL_SETOPT(curl, CURLOPT_WRITEDATA, &stream);

  CURLcode res = curl_easy_perform(curl);
  if (res != CURLE_OK) {
    throw std::runtime_error("cURL operation failed");
  }

  curl_easy_cleanup(curl);

  std::string data = stream.str();
  test::assert_greater_or_equal<size_t>(data.size(), 2, "tile size");
  // see http://tools.ietf.org/html/rfc1950 for header magic values
  test::assert_equal<uint32_t>(uint8_t(data[0]) & 0xf, 8, "compression method = deflate");
  test::assert_less_or_equal<uint32_t>(uint8_t(data[0]) >> 4, 7, "window size <= 7");
  test::assert_equal<uint32_t>(
    (uint32_t(uint8_t(data[0])) * 256 + uint32_t(uint8_t(data[1]))) % 31,
    0, "FCHECK checksum2");
}

void test_tile_is_not_compressed() {
  // check that when the compression level is set to zero, the tile is not
  // compressed and is just the raw PBF.
  server_guard guard("test/single_line.xml", 0);
  std::string uri = (boost::format("%1%/0/0/0.pbf") % guard.base_url()).str();
  std::stringstream stream;

  CURL *curl = curl_easy_init();
  CURL_SETOPT(curl, CURLOPT_URL, uri.c_str());
  CURL_SETOPT(curl, CURLOPT_WRITEFUNCTION, write_callback);
  CURL_SETOPT(curl, CURLOPT_WRITEDATA, &stream);

  CURLcode res = curl_easy_perform(curl);
  if (res != CURLE_OK) {
    throw std::runtime_error("cURL operation failed");
  }

  curl_easy_cleanup(curl);

  // note: this deliberately doesn't use the functions defined on avecado::tile
  // because it needs to avoid any automatic ungzipping.
  stream.seekp(0);
  google::protobuf::io::IstreamInputStream gstream(&stream);
  mapnik::vector::tile tile;
  bool read_ok = tile.ParseFromZeroCopyStream(&gstream);
  test::assert_equal<bool>(read_ok, true, "tile was plain PBF");
}

} // anonymous namespace

int main() {
  int tests_failed = 0;

  std::cout << "== Testing HTTP fetching ==" << std::endl << std::endl;

  // need datasource cache set up so that input plugins are available
  // when we parse map XML.
  mapnik::datasource_cache::instance().register_datasources(MAPNIK_DEFAULT_INPUT_PLUGIN_DIR);

#define RUN_TEST(x) { tests_failed += test::run(#x, &(x)); }
  RUN_TEST(test_fetch_empty);
  RUN_TEST(test_fetch_single_line);
  RUN_TEST(test_fetch_error_coordinates);
  RUN_TEST(test_fetch_error_extension);
  RUN_TEST(test_fetch_error_path_segments);
  RUN_TEST(test_fetch_error_non_numeric);
  RUN_TEST(test_no_url_patterns_is_error);
  RUN_TEST(test_fetcher_io);
  RUN_TEST(test_fetch_tilejson);
  RUN_TEST(test_tile_is_compressed);
  RUN_TEST(test_tile_is_not_compressed);

  std::cout << " >> Tests failed: " << tests_failed << std::endl << std::endl;

  return (tests_failed > 0) ? 1 : 0;
}

max_stars_repo_name: zerebubuth/avecado

max_issues_repo_name: zerebubuth/avecado

max_forks_repo_name: zerebubuth/avecado


text:
//  Copyright (c) 2005-2006 Andre   Merzky (andre@merzky.net)
//  Copyright (c) 2005-2009 Hartmut Kaiser
//  Copyright (c) 2005-2006 Stephan Hirmer (shirmer@cct.lsu.edu)
//
//  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 TASK_CONTAINER_HPP
#define TASK_CONTAINER_HPP

#include <vector>
#include <boost/thread/condition.hpp>

#include <saga/impl/config.hpp>
#include <saga/impl/engine/task_fwd.hpp>
#include <saga/impl/engine/object.hpp>
#include <saga/saga/adaptors/bulk_strategy_base.hpp>

#include <saga/impl/engine/monitorable.hpp>
#include <saga/impl/engine/task_interface.hpp>

#if defined(BOOST_MSVC)
#pragma warning(push)
#pragma warning(disable: 4251 4231 4275 4660)
#endif

///////////////////////////////////////////////////////////////////////////////
namespace saga { namespace impl
{

    /**
      * Class to store and handle some tasks through one handle.
      */
    class task_container
    :   public saga::impl::object,
        public saga::impl::monitorable
    {
     private:
       /*! list of all tasks added to this container */
       typedef std::vector<saga::task> tasks_type;

       typedef tasks_type::iterator iterator_type;
       typedef tasks_type::const_iterator const_iterator_type;

       typedef saga::impl::object::mutex_type mutex_type;

       boost::mutex state_change_mtx;
       boost::condition state_change_cond;
       tasks_type task_list;

       /**
         * searches for the tasks out of task_list, which have the
         * wanted state.
         *
         * @param state the state of the tasks, you are searching for.
         *
         * @return set of tasks, which have already finished
         */
       tasks_type get_tasks_with_state (saga::task_base::state state);
       tasks_type get_tasks_not_with_state (saga::task_base::state state);

       /**
         * Waits for all tasks, stored in task_list to finish.
         */
       void wait_for_all_tasks_to_finish();
       /**
         * Waits for one task stored in task_list to finish.
         */
       void wait_for_one_task_to_finish();

       /**
        * searches and returns a task, with a given uuid
        */
       saga::task get_task_by_uuid(saga::uuid const& id);

       TR1::shared_ptr<saga::adaptors::bulk_strategy_base> bs;

       // call back to be invoked when a task changes its state
       bool state_changed(saga::metric m, boost::condition& c, boost::mutex& mtx);

       // remove all tasks in the parameter
       std::vector<saga::task> const& remove_returned_tasks(
          std::vector<saga::task> const& ret);

     public:
       task_container (void);
       ~task_container (void);

       /**
        * Adds a task to this container.
        *
        * @param t the task, we want to add to this container
        */
       void add_task (saga::task & t);

       /**
        * Removes a task from this container.
        *
        * @param t the task, we want to remove from this container
        *
        * @throw no_such_task, if the task which you want to remove
        *        is not part of this container.
        */
       void remove_task (saga::task t);

       /**
         * Blocking function, which waits timeout sec for the tasks to
         * finish.  If they finish all before the end of this time, the
         * function returns immediately.
         *
         * @return a set of tasks, which have already finished
         *
         * @param timeout number of seconds this function will wait for
         *                tasks to finish before returning.
         * @note timeout <  0.0 : wait until all tasks have finished.
         *       timeout == 0.0 : returns set of finished tasks immed.
         *       timeout >  0.0 : wait for timeout seconds, but if task
         *                        finish all before this time, return.
         *
         * @throw all_tasks_canceled, if all the tasks in this container
         *        have been canceled already.
         */
       tasks_type wait (saga::task_container::wait_mode mode, float timeout);

       /**
         * @returns a set, specifying the current state of all tasks,
         *          stored in this container.
         */
       std::vector <saga::task_base::state> get_states (void);

       /**
         * Cancels every task in this container.
         */
       void cancel (void);

       /**
         * Provides access to list of all tasks of this container.
         *
         * @return the list of all tasks stored in this container.
         */
       tasks_type list_tasks (void) const;

       /**
         * executes the tasks contained in this task container.
         * tries to use bulk adaptors if available
         * if not, executes the tasks one by one
         */
       void run ();

       /**
         * runs the tasks in the taskcontainer one by one, without
         * considerating possible bulk adaptors. Not in the facade.
         */
       void simple_run();

       /**
         * sets one state to all the tasks contained in the taskcontainer
         * @param s the state to set. Not in the facade.
         */
       void set_state_for_all(saga::task_base::state s);

       /**
         * allows to set the state of a task. The task is specified by
         * its uuid. Not in the facade.
         */
       void
       set_state_by_uuid(std::vector<saga::uuid>& ids, saga::task_base::state s);

       /**
         * not in the facade.
         *
         * sets the bulk state for all the tasks, within this container
         */
       void
       set_tasks_for_bulk_treatement(task_interface::bulk_treatment_state s =
          task_interface::actual_bulk_treated);

        ///////////////////////////////////////////////////////////////////////
        //  return the monitorable interface to the facade
        virtual saga::impl::monitorable*
            get_monitorable() { return this; }
        virtual saga::impl::monitorable const*
            get_monitorable() const { return this; }

    };

///////////////////////////////////////////////////////////////////////////////
}} // namespace saga::impl

#endif // TASK_CONTAINER_HPP

max_stars_repo_name: saga-project/saga-cpp

max_issues_repo_name: saga-project/saga-cpp

max_forks_repo_name: saga-project/saga-cpp


text:
#include <filesystem>

#include <boost/filesystem.hpp>

#include "../test-rdg.h"
#include "katana/Experimental.h"
#include "katana/Logging.h"
#include "katana/RDG.h"
#include "katana/RDGManifest.h"
#include "katana/RDGStorageFormatVersion.h"
#include "katana/Result.h"
#include "katana/URI.h"

namespace fs = boost::filesystem;

/// Generate a version of the provided stable rdg, marked as unstable for testing
/// the unstable RDG can vary wildly from the stable RDG at test time since features may
/// be under development
/// Because of this, it is possible that this test catches bugs in storage which are related
/// to unstable features, in addition to bugs related to the unstable storage format
/// feature flag itself
///
/// Tests the following while the feature flag is enabled:
/// 1) loading a stable RDG
/// 2) loading a stable RDG and storing it as unstable
/// 3) loading an unstable RDG and storing it as unstable
katana::Result<void>
TestRoundtripUnstable(
    const std::string& stable_rdg, const std::string& unstable_rdg) {
  KATANA_LOG_ASSERT(!stable_rdg.empty());
  KATANA_LOG_ASSERT(!unstable_rdg.empty());

  // clean up whatever temporary unstable rdg might already be present
  std::filesystem::remove_all(unstable_rdg);

  // load a stable rdg
  katana::RDG rdg = KATANA_CHECKED(LoadRDG(stable_rdg));
  KATANA_LOG_ASSERT(!rdg.IsUnstableStorageFormat());

  // make our in memory rdg unstable
  rdg.SetUnstableStorageFormat();
  KATANA_LOG_ASSERT(rdg.IsUnstableStorageFormat());

  // store the unstable rdg
  std::string rdg_dir1 = KATANA_CHECKED(WriteRDG(std::move(rdg), unstable_rdg));
  KATANA_LOG_ASSERT(!rdg_dir1.empty());
  // ensure where we stored it matches the unstable_rdg path so that the flag-off test can use it
  KATANA_LOG_ASSERT(rdg_dir1 == unstable_rdg);

  // load the unstable rdg
  katana::RDG rdg1 = KATANA_CHECKED(LoadRDG(rdg_dir1));
  KATANA_LOG_ASSERT(rdg1.IsUnstableStorageFormat());

  // RoundTrip it again to ensure we can load an unstable RDG and store it
  std::string rdg_dir2 = KATANA_CHECKED(WriteRDG(std::move(rdg1)));
  KATANA_LOG_ASSERT(!rdg_dir2.empty());
  katana::RDG rdg2 = KATANA_CHECKED(LoadRDG(rdg_dir2));
  KATANA_LOG_ASSERT(rdg2.IsUnstableStorageFormat());

  return katana::ResultSuccess();
}

int
main(int argc, char* argv[]) {
  if (auto init_good = katana::InitTsuba(); !init_good) {
    KATANA_LOG_FATAL("katana::InitTsuba: {}", init_good.error());
  }

  if (argc <= 2) {
    KATANA_LOG_FATAL("missing rdg file directory");
  }

  // Ensure the feature flag is actually set
  KATANA_LOG_ASSERT(KATANA_EXPERIMENTAL_ENABLED(UnstableRDGStorageFormat));

  const std::string& stable_rdg = argv[1];
  const std::string& unstable_rdg = argv[2];

  auto res = TestRoundtripUnstable(stable_rdg, unstable_rdg);
  if (!res) {
    KATANA_LOG_FATAL("test failed: {}", res.error());
  }

  if (auto fini_good = katana::FiniTsuba(); !fini_good) {
    KATANA_LOG_FATAL("katana::FiniTsuba: {}", fini_good.error());
  }

  return 0;
}

max_stars_repo_name: rob-isaac/katana

max_issues_repo_name: rob-isaac/katana

max_forks_repo_name: rob-isaac/katana


text:
#pragma once

#include <bunsan/utility/maker.hpp>

#include <boost/optional.hpp>
#include <boost/serialization/access.hpp>
#include <boost/serialization/nvp.hpp>

#include <string>
#include <unordered_map>
#include <vector>

namespace bunsan {
namespace utility {
namespace makers {

class make : public maker {
 public:
  struct config {
    template <typename Archive>
    void serialize(Archive &ar, const unsigned int) {
      ar & BOOST_SERIALIZATION_NVP(defines);
      ar & BOOST_SERIALIZATION_NVP(targets);
      ar & BOOST_SERIALIZATION_NVP(jobs);
    }

    /// for example {"DESTDIR": "/some/path"}
    std::unordered_map<std::string, std::string> defines;
    std::vector<std::string> targets;  ///< for example ["install"]
    boost::optional<std::size_t> jobs;
  };

 public:
  explicit make(const boost::filesystem::path &exe);

  void exec(const boost::filesystem::path &cwd,
            const std::vector<std::string> &targets) override;

  void setup(const boost::property_tree::ptree &ptree) override;

 private:
  std::vector<std::string> arguments_(
      const std::vector<std::string> &targets) const;

 private:
  const boost::filesystem::path m_exe;
  config m_config;
};

}  // namespace makers
}  // namespace utility
}  // namespace bunsan

max_stars_repo_name: bunsanorg/utility

max_issues_repo_name: bunsanorg/utility

max_forks_repo_name: bunsanorg/utility


text:
//
// win_event.hpp
// ~~~~~~~~~~~~~
//
// Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// 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_ASIO_DETAIL_WIN_EVENT_HPP
#define BOOST_ASIO_DETAIL_WIN_EVENT_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

#include <boost/asio/detail/push_options.hpp>

#include <boost/asio/detail/push_options.hpp>
#include <boost/config.hpp>
#include <boost/system/system_error.hpp>
#include <boost/asio/detail/pop_options.hpp>

#if defined(BOOST_WINDOWS)

#include <boost/asio/error.hpp>
#include <boost/asio/detail/noncopyable.hpp>
#include <boost/asio/detail/socket_types.hpp>

#include <boost/asio/detail/push_options.hpp>
#include <boost/assert.hpp>
#include <boost/throw_exception.hpp>
#include <boost/asio/detail/pop_options.hpp>

namespace boost {
namespace asio {
namespace detail {

class win_event
  : private noncopyable
{
public:
  // Constructor.
  win_event()
    : event_(::CreateEvent(0, true, false, 0))
  {
    if (!event_)
    {
      DWORD last_error = ::GetLastError();
      boost::system::system_error e(
          boost::system::error_code(last_error,
            boost::asio::error::get_system_category()),
          "event");
      boost::throw_exception(e);
    }
  }

  // Destructor.
  ~win_event()
  {
    ::CloseHandle(event_);
  }

  // Signal the event.
  template <typename Lock>
  void signal(Lock& lock)
  {
    BOOST_ASSERT(lock.locked());
    (void)lock;
    ::SetEvent(event_);
  }

  // Reset the event.
  template <typename Lock>
  void clear(Lock& lock)
  {
    BOOST_ASSERT(lock.locked());
    (void)lock;
    ::ResetEvent(event_);
  }

  // Wait for the event to become signalled.
  template <typename Lock>
  void wait(Lock& lock)
  {
    BOOST_ASSERT(lock.locked());
    lock.unlock();
    ::WaitForSingleObject(event_, INFINITE);
    lock.lock();
  }

private:
  HANDLE event_;
};

} // namespace detail
} // namespace asio
} // namespace boost

#endif // defined(BOOST_WINDOWS)

#include <boost/asio/detail/pop_options.hpp>

#endif // BOOST_ASIO_DETAIL_WIN_EVENT_HPP

max_stars_repo_name: jaredhoberock/gotham

max_issues_repo_name: foxostro/CheeseTesseract

max_forks_repo_name: foxostro/CheeseTesseract


text:
#include <boost/shared_ptr.hpp>
#include <nodelet/nodelet.h>
#include <pluginlib/class_list_macros.h>
#include <ros/ros.h>

#include "vesc_driver/vesc_driver.h"

namespace vesc_driver
{

class VescDriverNodelet: public nodelet::Nodelet
{
public:

  VescDriverNodelet() {}

private:

  virtual void onInit(void);

  boost::shared_ptr<VescDriver> vesc_driver_;

}; // class VescDriverNodelet

void VescDriverNodelet::onInit()
{
  NODELET_DEBUG("Initializing VESC driver nodelet");
  vesc_driver_.reset(new VescDriver(getNodeHandle(), getPrivateNodeHandle()));
}

} // namespace vesc_driver

PLUGINLIB_EXPORT_CLASS(vesc_driver::VescDriverNodelet, nodelet::Nodelet);