text:
/*
 * simple_split.hpp
 *
 *  Created on: Sep 22, 2012
 *      Author: mdantone
 */

#ifndef SIMPLESPLIT_HPP_
#define SIMPLESPLIT_HPP_

#include <vector>
#include <iostream>
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"

#include <boost/serialization/utility.hpp>
#include <boost/numeric/conversion/bounds.hpp>
#include <boost/limits.hpp>
#include <boost/random.hpp>
#include <glog/logging.h>
#include "cpp/utils/serialization/opencv_serialization.hpp"

namespace learning
{
namespace forest
{

typedef std::pair<int, unsigned int> IntIndex;
struct less_than {
  bool operator()(const IntIndex& a, const IntIndex& b) const {
    return a.first < b.first;
  }
  bool operator()(const IntIndex& a, const int& b) const {
    return a.first < b;
  }
};

template<typename Sample>
inline void splitVec(const std::vector<Sample*>& data,
    const std::vector<IntIndex>& valSet,
    std::vector<Sample*>& setA,
    std::vector<Sample*>& setB,
    int threshold, int margin = 0) {

  // search largest value such that val<t
  std::vector<IntIndex>::const_iterator it_first, it_second;

  it_first = lower_bound(valSet.begin(), valSet.end(), threshold - margin, less_than());
  if (margin == 0)
    it_second = it_first;
  else
    it_second = lower_bound(valSet.begin(), valSet.end(), threshold + margin, less_than());

  // Split training data into two sets A,B accroding to threshold t
  setA.resize(it_second - valSet.begin());
  setB.resize(valSet.end() - it_first);

  std::vector<IntIndex>::const_iterator it = valSet.begin();
  typename std::vector<Sample*>::iterator itSample;
  for (itSample = setA.begin(); itSample < setA.end(); ++itSample, ++it)
    (*itSample) = data[it->second];

  it = it_first;
  for (itSample = setB.begin(); itSample < setB.end(); ++itSample, ++it)
    (*itSample) = data[it->second];

};

template<typename Sample>
inline void splitVec(const std::vector<Sample*>& data,
    const std::vector<IntIndex>& valSet,
    std::vector<std::vector<Sample*> >& sets,
    int threshold, int margin) {

  // search largest value such that val<t
  std::vector<IntIndex>::const_iterator it_first, it_second;

  it_first = lower_bound(valSet.begin(), valSet.end(), threshold - margin, less_than());
  if (margin == 0)
    it_second = it_first;
  else
    it_second = lower_bound(valSet.begin(), valSet.end(), threshold + margin, less_than());

  if (it_first == it_second) { // no intersection between the two thresholds
    std::vector<IntIndex>::const_iterator it = it_first;
    sets.resize(2);
    // Split training data into two sets A,B according to threshold t
    sets[0].resize(it - valSet.begin());
    sets[1].resize(valSet.size() - sets[0].size());

    it = valSet.begin();
    typename std::vector<Sample*>::iterator itSample;
    for (itSample = sets[0].begin(); itSample < sets[0].end(); ++itSample, ++it)
      (*itSample) = data[it->second];

    it = valSet.begin() + sets[0].size();
    for (itSample = sets[1].begin(); itSample < sets[1].end(); ++itSample, ++it)
      (*itSample) = data[it->second];

    CHECK( (sets[0].size() + sets[1].size()) == valSet.size());

  } else {

    sets.resize(3);
    // Split training data into two sets A,B accroding to threshold t
    sets[0].resize(it_first - valSet.begin());
    sets[1].resize(it_second - it_first);
    sets[2].resize(valSet.end() - it_second);

    std::vector<IntIndex>::const_iterator it = valSet.begin();
    typename std::vector<Sample*>::iterator itSample;
    for (itSample = sets[0].begin(); itSample < sets[0].end(); ++itSample, ++it)
      (*itSample) = data[it->second];

    it = valSet.begin() + sets[0].size();
    for (itSample = sets[1].begin(); itSample < sets[1].end(); ++itSample, ++it)
      (*itSample) = data[it->second];

    it = valSet.begin() + sets[0].size() + sets[1].size();

    for (itSample = sets[2].begin(); itSample < sets[2].end(); ++itSample, ++it)
      (*itSample) = data[it->second];

    CHECK( (sets[0].size() + sets[1].size() + sets[2].size()) == valSet.size());
  }
};

template<typename Feature>
class ThresholdSplit {
public:
  ThresholdSplit(){
    margin = 0;
    oob = 0;
    num_thresholds = 25;
    gain = boost::numeric::bounds<double>::lowest();
    info = boost::numeric::bounds<double>::lowest();
    used_subsampling = false;
  }

  template<typename Sample>
  int get_feature_value(const Sample* sample, const Feature* feature) const {
    return feature->extract(sample->get_images(),
                               sample->get_roi(),
                               sample->is_integral_image());
  }

  template<typename Sample>
  bool eval( const Sample* sample ) const {
    return get_feature_value(sample, &feature) <= threshold;
  }

  void initialize( boost::mt19937* rng, int patch_width_, int patch_height_,
      int num_feat_channels_, int num_thresholds_, int margin_, int depth_) {
    patch_width = patch_width_;
    patch_height = patch_height_;
    num_thresholds = num_thresholds_;
    margin = margin_;
    depth = depth_;

    feature.generate(patch_width, patch_height, rng, num_feat_channels_);
  }

  template<typename Sample>
  void split(const std::vector<Sample*>& data,
    std::vector<Sample*>& set_a, std::vector<Sample*>& set_b) const {
    std::vector<IntIndex> valSet(data.size());
    for (unsigned int l = 0; l < data.size(); ++l) {
      valSet[l].first = get_feature_value(data[l], &feature);
      valSet[l].second = l;
    }
    std::sort(valSet.begin(), valSet.end());
    splitVec(data, valSet, set_a, set_b, threshold, margin);
  }

  template<typename Sample>
  void get_subsampling_ids(size_t n_samples,
      const std::vector<Sample*>& data,
      std::vector<int>& indicies) {
    std::vector<int> pos_indicies, neg_indicies;
    for (unsigned int i = 0; i < data.size(); ++i) {
      if(data[i]->is_pos()) {
        pos_indicies.push_back(i);
      }else{
        neg_indicies.push_back(i);
      }
    }

    srand(0);
    std::random_shuffle( pos_indicies.begin(), pos_indicies.end());
    std::random_shuffle( neg_indicies.begin(), neg_indicies.end());

    int n_pos = std::min(pos_indicies.size(), n_samples);
    int n_neg = std::min(neg_indicies.size(), n_samples);

    pos_indicies.resize( n_pos );
    neg_indicies.resize( n_neg );

    indicies.insert(indicies.end(), pos_indicies.begin(), pos_indicies.end());
    indicies.insert(indicies.end(), neg_indicies.begin(), neg_indicies.end());

  }

  template<typename Sample>
  void get_subsampling_pos_ids(size_t n_samples,
      const std::vector<Sample*>& data,
      std::vector<int>& indicies) {
    for (unsigned int i = 0; i < data.size(); ++i) {
      if(data[i]->is_pos()) {
        indicies.push_back(i);
      }
    }
    srand(0);
    std::random_shuffle( indicies.begin(), indicies.end());
    int n_pos = std::min(indicies.size(), n_samples);
    indicies.resize( n_pos );
  }

  template<typename Sample>
  void train(const std::vector<Sample*>& data, int split_mode_,
      int depth, const std::vector<float>& class_weights,
      int min_child_size, boost::mt19937* rng, int subsampling=0 ) {

    if(subsampling > data.size() ) {
      subsampling = 0;
    }

    split_mode = split_mode_;
    std::vector<IntIndex> valSet;

    // do subsampling
    if( subsampling > 0 ) {
      used_subsampling = true;
      int n_pos = subsampling;
      int n_neg = subsampling;
      int i_pos = 0;
      int i_neg = 0;
      if(split_mode != 0) {
        n_neg = 0;
      }

      valSet.reserve(n_pos + n_neg);
      int i=0;
      while( i < data.size() && ( i_pos < n_pos || i_neg < n_neg ) ) {

        if(data[i]->is_pos() && i_pos < n_pos) {
          valSet.push_back( std::make_pair(get_feature_value(data[i], &feature), i) );
          ++i_pos;
        }else if( !data[i]->is_pos() && i_neg < n_neg ){
          valSet.push_back( std::make_pair(get_feature_value(data[i], &feature), i) );
          ++i_neg;
        }
        ++i;
      }
    } else {

      //extract the features
      int size = MIN(200000, static_cast<int>(data.size()));
      valSet.resize(size);
      for (int l = 0; l < valSet.size(); ++l) {
        valSet[l].first = get_feature_value(data[l], &feature);
        valSet[l].second = l;
      }
    }

    std::sort(valSet.begin(), valSet.end());
    findThreshold(data, valSet, rng, min_child_size, class_weights, split_mode);
  }

  template<typename Sample>
  void findThreshold(const std::vector<Sample*>& data,
        const std::vector<IntIndex>& valSet,
        boost::mt19937* rng_,
        int min_size,
        const std::vector<float>& class_weights,
        int split_mode) {
    info = boost::numeric::bounds<double>::lowest();

    int min_val = valSet.front().first;
    int max_val = valSet.back().first;
    int valueRange = max_val - min_val;
    if (valueRange < 1)
      return;

    // Find best threshold
    boost::uniform_int<> dist_tr(0, valueRange);
    boost::variate_generator<boost::mt19937&, boost::uniform_int<> >
          rand_tr(*rng_, dist_tr);

    std::vector<int> thresholds;
    if(num_thresholds > valueRange){
      for(int i=0; i < valueRange; i++) {
        thresholds.push_back( min_val +i );
      }
    }else{
      while( thresholds.size() < num_thresholds ) {
        int tr = rand_tr() + min_val;
        bool duplicate = false;
        for(int j=0; j < thresholds.size(); j++) {
          if( tr == thresholds[j] ) {
            duplicate = true;
            break;
          }
        }
        if(!duplicate)
          thresholds.push_back( tr );
      }
    }

    sort(thresholds.begin(), thresholds.end());
    for (unsigned int j = 0; j < thresholds.size(); ++j) {
      int tr = thresholds[j];
      std::vector<std::vector<Sample*> > sets;
      splitVec(data, valSet, sets, tr, margin);
      if (sets[0].size() < min_size or sets[1].size() < min_size) {
        continue;
      }

      double infoNew = Sample::evalSplit(sets[0], sets[1],
          class_weights, split_mode,depth);

      if (infoNew > info) {
        threshold = tr;
        info = infoNew;
      }
    }
  }

  void print() {
    feature.print();
    std::cout << " " << threshold << std::endl;
  }

  friend class boost::serialization::access;
  template<class Archive>
  void serialize(Archive & ar, const unsigned int version) {
    ar & feature;
    ar & info;
    ar & gain;
    ar & threshold;

  }

  Feature* get_feature() {
    return &feature;
  }

  Feature feature;

  double info;
  double gain;
  double oob;
  int patch_width;
  int patch_height;
  int threshold;
  int margin;
  int depth;
  int num_thresholds;
  float split_mode;

  bool used_subsampling;

};

} //namespace forest

} //namespace learning
#endif /* SIMPLESPLIT_HPP_ */


text:
///
/// Copyright(c) 2018 Aimin Huang
/// Distributed under the MIT License (http://opensource.org/licenses/MIT)
///
#include <fstream>
#include <sys/stat.h>
#include <boost/lexical_cast.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/mpl/vector.hpp>

#include <vector>
#include <algorithm>
#include <functional>

#include <algorithm>

#include <shannon/message/helper/console_client_initializer.hpp>

#include "demo-console-datastruct.h"

#define Galois_W Shannon::Message::ConsoleDataStructWrap

typedef boost::mpl::vector<
	Galois_W<QuoterOptionConfig, 1>,
	Galois_W<QuoterSystemConfig, 2>,
	Galois_W<GeneratorSystemConfig, 6>,
	Galois_W<GeneratorOptionConfig, 8>,
	Galois_W<GeneratorExpiryMonthConfig, 9>
			> MyConsoleClientInitDataStructs;
typedef Shannon::Message::ConsoleClientInitializer< MyConsoleClientInitDataStructs >	MyConsoleClientInitializer;

#undef Galois_W

//实现一个打印程序运行消息的DemoLogger
void DemoLogger(int data_received, const std::string & msg)
{
	std::cout << "Demo msg content: " << msg <<"\n Connected? "<< (data_received>0?"Yes":"No") <<" DataReceived: "<<( data_received>0 ? data_received-1 : -data_received-1 ) << std::endl;
}

//实现一个基本的DemoParams的更新函数，只在标准输出流中打印收到的参数
struct MyConsoleDemoUpdater{
	MyConsoleDemoUpdater( MyConsoleClientInitializer * my_console, const std::string & subscribe_key)
		:my_console_(my_console), subscribe_key_(subscribe_key){}

	void OnReceiveQuoterOptionConfig(QuoterOptionConfig * demo_params){
		std::cout<< "Received ID: " << demo_params->option_id << ", tolGreater:" << demo_params->tolerance_greater << std::endl;

		if( demo_params->tolerance_greater > 1 ){  ////security check
			Shannon::Message::ConsoleFeedbackField feedback;
			memset(&feedback,0,sizeof(feedback));
			feedback.is_error = true;

			strncpy(feedback.id, subscribe_key_.c_str(), sizeof(feedback.id)-1);
			strncpy(feedback.message, "QuoterOptionConfig.tolerance_greater did not pass security check!", sizeof(feedback.message)-1);
			//////Send Feedback message
			my_console_->SendFeedbackMsg(feedback);

		}
	}
	void OnReceiveQuoterSystemConfig( QuoterSystemConfig * demo_param ){
	}

	void OnReceiveGeneratorOptionConfig(GeneratorOptionConfig * demo_params){
		std::cout<< "ID: " << demo_params->option_id << ", risk rate:" << demo_params->init_calibrated_sigma << std::endl;

		if( demo_params->init_calibrated_sigma < 0 ){  ////security check
			Shannon::Message::ConsoleFeedbackField feedback;
			memset(&feedback,0,sizeof(feedback));
			feedback.is_error = true;

			strncpy(feedback.id, subscribe_key_.c_str(), sizeof(feedback.id)-1);
			strncpy(feedback.message, "GeneratorOptionConfig.riskfree_rate did not pass security check!", sizeof(feedback.message)-1);
			my_console_->SendFeedbackMsg(feedback);
		}
	}

	void OnReceiveGeneratorSystemConfig(GeneratorSystemConfig * demo_params){

	}

private:
	MyConsoleClientInitializer * my_console_;
	const std::string subscribe_key_;
};

int main()
{

	const std::string console_address = "127.0.0.1:8011";
	std::vector<std::string> subscribe_keys;

	MyConsoleClientInitializer * my_console_initializer = new MyConsoleClientInitializer(console_address, DemoLogger);
	my_console_initializer->SetClientName('Q', "Quoter.m");

	subscribe_keys.push_back("m_Quoter1709");
	subscribe_keys.push_back("m_Quoter1801");
	my_console_initializer->Register<QuoterOptionConfig>(subscribe_keys,  SHANNON_MESSAGE_RESUME_RESTART);

	subscribe_keys.resize(0);
	subscribe_keys.push_back("m1709");
	my_console_initializer->Register<QuoterSystemConfig>(subscribe_keys,  SHANNON_MESSAGE_RESUME_RESTART);

	my_console_initializer->start();

///	my_console_initializer->stop();

	std::cout<<"===> Waiting for reading console configuration..."<<std::endl;
	while( !my_console_initializer->IsInit() ){
		boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
	}
	std::cout<<"===> Finished reading console configuration!"<<std::endl;

//	std::map<std::string, GeneratorOptionConfig> generator_option_config_map = my_console_initializer->RtnInitData<GeneratorOptionConfig>( );
//	std::map<std::string, GeneratorSystemConfig> generator_system_config_map = my_console_initializer->RtnInitData<GeneratorSystemConfig>( );

	std::map<std::string, QuoterOptionConfig> quoter_option_config_map = my_console_initializer->RtnInitData<QuoterOptionConfig>( );
	std::map<std::string, QuoterSystemConfig> quoter_system_config_map = my_console_initializer->RtnInitData<QuoterSystemConfig>();

	/**********

		Your specific initialization, possible including (check all parameters from console)

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

	///注册更新回调函数
	MyConsoleDemoUpdater updater(my_console_initializer, "510050");

//	my_console_initializer->RegisterUpdater<GeneratorOptionConfig>(  std::bind(&MyConsoleDemoUpdater::OnReceiveGeneratorOptionConfig, &updater, std::placeholders::_1) );
//	my_console_initializer->RegisterUpdater<GeneratorSystemConfig>(  std::bind(&MyConsoleDemoUpdater::OnReceiveGeneratorSystemConfig, &updater, std::placeholders::_1) );
	my_console_initializer->RegisterUpdater<QuoterOptionConfig>( std::bind(&MyConsoleDemoUpdater::OnReceiveQuoterOptionConfig, &updater, std::placeholders::_1) );
	my_console_initializer->RegisterUpdater<QuoterSystemConfig>(  std::bind(&MyConsoleDemoUpdater::OnReceiveQuoterSystemConfig, &updater, std::placeholders::_1) );

	while(true){
		boost::this_thread::sleep(boost::posix_time::milliseconds(2000 * 100));
	}

	/// For safely exit the program, please add the following line at some point;
	Shannon::Message::ClientBase::safe_exit();
	return 0;
}

ext: cpp


text:
/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */

/**@file Tests for partial failure in a cluster.
 * Partial failure means some nodes experience a failure while others do not.
 * In this case the failed nodes must shut down.
 */

#include "test_tools.h"
#include "unit_test.h"
#include "ClusterFixture.h"
#include <boost/assign.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/bind.hpp>

namespace qpid {
namespace tests {

QPID_AUTO_TEST_SUITE(PartialFailureTestSuite)

using namespace std;
using namespace qpid;
using namespace qpid::cluster;
using namespace qpid::framing;
using namespace qpid::client;
using namespace qpid::client::arg;
using namespace boost::assign;
using broker::Broker;
using boost::shared_ptr;

// Timeout for tests that wait for messages
const sys::Duration TIMEOUT=sys::TIME_SEC/4;

static bool isLogOption(const std::string& s) { return boost::starts_with(s, "--log-enable"); }

void updateArgs(ClusterFixture::Args& args, size_t index) {
    ostringstream clusterLib, testStoreLib, storeName;
    clusterLib << getLibPath("CLUSTER_LIB");
    testStoreLib << getLibPath("TEST_STORE_LIB");
    storeName << "s" << index;
    args.push_back("--auth");
    args.push_back("no");
    args.push_back("--no-module-dir");
    args.push_back("--load-module");
    args.push_back(clusterLib.str());
    args.push_back("--load-module");
    args.push_back(testStoreLib.str());
    args.push_back("--test-store-name");
    args.push_back(storeName.str());
    args.push_back("TMP_DATA_DIR");

    // These tests generate errors deliberately, disable error logging unless a log env var is set.
    if (!::getenv("QPID_TRACE") && !::getenv("QPID_LOG_ENABLE")) {
        remove_if(args.begin(), args.end(), isLogOption);
        args.push_back("--log-enable=critical+:DISABLED"); // hacky way to disable logs.
    }
}

Message pMessage(string data, string q) {
    Message msg(data, q);
    msg.getDeliveryProperties().setDeliveryMode(PERSISTENT);
    return msg;
}

void queueAndSub(Client& c) {
    c.session.queueDeclare(c.name, durable=true);
    c.subs.subscribe(c.lq, c.name);
}

// Handle near-simultaneous errors
QPID_AUTO_TEST_CASE(testCoincidentErrors) {
    ClusterFixture cluster(2, updateArgs, -1);
    Client c0(cluster[0], "c0");
    Client c1(cluster[1], "c1");

    c0.session.queueDeclare("q", durable=true);
    {
        ScopedSuppressLogging allQuiet;
        async(c0.session).messageTransfer(content=pMessage("TEST_STORE_DO: s0[exception]", "q"));
        async(c1.session).messageTransfer(content=pMessage("TEST_STORE_DO: s1[exception]", "q"));

        int alive=0;
        try { Client c00(cluster[0], "c00"); ++alive; c00.close(); } catch (...) {}
        try { Client c11(cluster[1], "c11"); ++alive; c11.close(); } catch (...) {}

        BOOST_CHECK_EQUAL(alive, 1);

        // Close inside ScopedSuppressLogging to avoid warnings
        c0.close();
        c1.close();
    }
}

// Verify normal cluster-wide errors.
QPID_AUTO_TEST_CASE(testNormalErrors) {
    // FIXME aconway 2009-04-10: Would like to put a scope just around
    // the statements expected to fail (in BOOST_CHECK_yTHROW) but that
    // sproadically lets out messages, possibly because they're in
    // Connection thread.

    ClusterFixture cluster(3, updateArgs, -1);
    Client c0(cluster[0], "c0");
    Client c1(cluster[1], "c1");
    Client c2(cluster[2], "c2");

    {
        ScopedSuppressLogging allQuiet;
        queueAndSub(c0);
        c0.session.messageTransfer(content=Message("x", "c0"));
        BOOST_CHECK_EQUAL(c0.lq.get(TIMEOUT).getData(), "x");

        // Session error.
        BOOST_CHECK_THROW(c0.session.exchangeBind(), SessionException);
        c1.session.messageTransfer(content=Message("stay", "c0")); // Will stay on queue, session c0 is dead.

        // Connection error, kill c1 on all members.
        queueAndSub(c1);
        BOOST_CHECK_THROW(
            c1.session.messageTransfer(
                content=pMessage("TEST_STORE_DO: s0[exception] s1[exception] s2[exception] testNormalErrors", "c1")),
                ConnectionException);
        c2.session.messageTransfer(content=Message("stay", "c1")); // Will stay on queue, session/connection c1 is dead.

        BOOST_CHECK_EQUAL(3u, knownBrokerPorts(c2.connection, 3).size());
        BOOST_CHECK_EQUAL(c2.subs.get("c0", TIMEOUT).getData(), "stay");
        BOOST_CHECK_EQUAL(c2.subs.get("c1", TIMEOUT).getData(), "stay");

        // Close inside ScopedSuppressLogging to avoid warnings
        c0.close();
        c1.close();
        c2.close();
    }
}

// Test errors after a new member joins to verify frame-sequence-numbers are ok in update.
QPID_AUTO_TEST_CASE(testErrorAfterJoin) {
    ClusterFixture cluster(1, updateArgs, -1);
    Client c0(cluster[0]);
    {
        ScopedSuppressLogging allQuiet;

        c0.session.queueDeclare("q", durable=true);
        c0.session.messageTransfer(content=pMessage("a", "q"));

        // Kill the new guy
        cluster.add();
        Client c1(cluster[1]);
        c0.session.messageTransfer(content=pMessage("TEST_STORE_DO: s1[exception] testErrorAfterJoin", "q"));
        BOOST_CHECK_THROW(c1.session.messageTransfer(content=pMessage("xxx", "q")), TransportFailure);
        BOOST_CHECK_EQUAL(1u, knownBrokerPorts(c0.connection, 1).size());

        // Kill the old guy
        cluster.add();
        Client c2(cluster[2]);
        c2.session.messageTransfer(content=pMessage("TEST_STORE_DO: s0[exception] testErrorAfterJoin2", "q"));
        BOOST_CHECK_THROW(c0.session.messageTransfer(content=pMessage("xxx", "q")), TransportFailure);

        BOOST_CHECK_EQUAL(1u, knownBrokerPorts(c2.connection, 1).size());

        // Close inside ScopedSuppressLogging to avoid warnings
        c0.close();
        c1.close();
        c2.close();
    }
}

// Test that if one member fails and  others do not, the failure leaves the cluster.
QPID_AUTO_TEST_CASE(testSinglePartialFailure) {
    ClusterFixture cluster(3, updateArgs, -1);
    Client c0(cluster[0], "c0");
    Client c1(cluster[1], "c1");
    Client c2(cluster[2], "c2");

    {
        ScopedSuppressLogging allQuiet;

        c0.session.queueDeclare("q", durable=true);
        c0.session.messageTransfer(content=pMessage("a", "q"));
        // Cause partial failure on c1
        c0.session.messageTransfer(content=pMessage("TEST_STORE_DO: s1[exception] testSinglePartialFailure", "q"));
        BOOST_CHECK_THROW(c1.session.queueQuery("q"), TransportFailure);

        c0.session.messageTransfer(content=pMessage("b", "q"));
        BOOST_CHECK_EQUAL(c0.session.queueQuery("q").getMessageCount(), 3u);
        BOOST_CHECK_EQUAL(2u, knownBrokerPorts(c0.connection, 2).size());

        // Cause partial failure on c2
        c0.session.messageTransfer(content=pMessage("TEST_STORE_DO: s2[exception] testSinglePartialFailure2", "q"));
        BOOST_CHECK_THROW(c2.session.queueQuery("q"), TransportFailure);

        c0.session.messageTransfer(content=pMessage("c", "q"));
        BOOST_CHECK_EQUAL(c0.session.queueQuery("q").getMessageCount(), 5u);
        BOOST_CHECK_EQUAL(1u, knownBrokerPorts(c0.connection, 1).size());

        // Close inside ScopedSuppressLogging to avoid warnings
        c0.close();
        c1.close();
        c2.close();
    }
}

// Test multiple partial falures: 2 fail 2 pass
QPID_AUTO_TEST_CASE(testMultiPartialFailure) {
    ClusterFixture cluster(4, updateArgs, -1);
    Client c0(cluster[0], "c0");
    Client c1(cluster[1], "c1");
    Client c2(cluster[2], "c2");
    Client c3(cluster[3], "c3");

    {
        ScopedSuppressLogging allQuiet;

        c0.session.queueDeclare("q", durable=true);
        c0.session.messageTransfer(content=pMessage("a", "q"));

        // Cause partial failure on c1, c2
        c0.session.messageTransfer(content=pMessage("TEST_STORE_DO: s1[exception] s2[exception] testMultiPartialFailure", "q"));
        BOOST_CHECK_THROW(c1.session.queueQuery("q"), TransportFailure);
        BOOST_CHECK_THROW(c2.session.queueQuery("q"), TransportFailure);

        c0.session.messageTransfer(content=pMessage("b", "q"));
        c3.session.messageTransfer(content=pMessage("c", "q"));
        BOOST_CHECK_EQUAL(c3.session.queueQuery("q").getMessageCount(), 4u);
        // FIXME aconway 2009-06-30: This check fails sporadically with 2 != 3.
        // It should pass reliably.
        // BOOST_CHECK_EQUAL(2u, knownBrokerPorts(c0.connection, 2).size());

        // Close inside ScopedSuppressLogging to avoid warnings
        c0.close();
        c1.close();
        c2.close();
        c3.close();
    }
}

/** FIXME aconway 2009-04-10:
 * The current approach to shutting down a process in test_store
 * sometimes leads to assertion failures and errors in the shut-down
 * process. Need a cleaner solution
 */
#if 0
QPID_AUTO_TEST_CASE(testPartialFailureMemberLeaves) {
    ClusterFixture cluster(2, updateArgs, -1);
    Client c0(cluster[0], "c0");
    Client c1(cluster[1], "c1");

    {
        ScopedSuppressLogging allQuiet;

        c0.session.queueDeclare("q", durable=true);
        c0.session.messageTransfer(content=pMessage("a", "q"));

        // Cause failure on member 0 and simultaneous crash on member 1.
        BOOST_CHECK_THROW(
            c0.session.messageTransfer(
                content=pMessage("TEST_STORE_DO: s0[exception] s1[exit_process] testPartialFailureMemberLeaves", "q")),
                ConnectionException);
        cluster.wait(1);

        Client c00(cluster[0], "c00"); // Old connection is dead.
        BOOST_CHECK_EQUAL(c00.session.queueQuery("q").getMessageCount(), 1u);
        BOOST_CHECK_EQUAL(1u, knownBrokerPorts(c00.connection, 1).size());

        // Close inside ScopedSuppressLogging to avoid warnings
        c0.close();
    }
}
#endif

QPID_AUTO_TEST_SUITE_END()

}} // namespace qpid::tests

max_stars_repo_name: gcsideal/debian-qpid-cpp

max_issues_repo_name: gcsideal/debian-qpid-cpp

max_forks_repo_name: gcsideal/debian-qpid-cpp


text:
//
// Author: Vladimir Migashko <migashko@gmail.com>, (C) 2013-2018
//
// Copyright: See COPYING file that comes with this distribution
//

#pragma once

#include <wfc/domain_object.hpp>
#include <wfc/iinterface.hpp>
#include <wfc/memory.hpp>
#include <wjrpc/outgoing/outgoing_holder.hpp>
#include <wfc/jsonrpc/statistics_options.hpp>

#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>

namespace wfc{ namespace jsonrpc{

template<typename Interface, typename EngineType, typename OptionsType >
class engine_base
  : public domain_object< Interface, OptionsType, statistics_options>
{
public:
  typedef engine_base<Interface, EngineType, OptionsType> self;
  typedef domain_object< Interface, OptionsType, statistics_options> super;

  typedef Interface interface_type;
  typedef EngineType engine_type;
  typedef OptionsType options_type;

  typedef std::shared_ptr<engine_type> engine_ptr;

  typedef typename options_type::engine_options engine_options;

  typedef typename super::io_id_t io_id_t;
  typedef typename super::data_ptr data_ptr;
  typedef typename super::data_type data_type;
  typedef typename super::output_handler_t output_handler_t;
  typedef wflow::workflow workflow_type;
  typedef workflow_type::timer_id_t timer_id_t;

public:

  virtual ~engine_base()
  {
    _engine=nullptr;
  }

  virtual void stop() final override
  {
    if ( _engine != nullptr )
    {
      if ( auto wf = this->get_workflow() )
      {
        wf->release_timer(_timer_id);
        wf->release_timer(_stat_timer_id);
      }
      _engine->stop();

    }
    _engine = nullptr;
  }

  virtual void reg_io(io_id_t io_id, std::weak_ptr<iinterface> witf) override
  {
    if ( this->suspended() )
      return;
    if ( _engine != nullptr )
    {
      _engine->reg_io( io_id, this->wrap([witf]( data_ptr d, io_id_t io_id1, output_handler_t handler)
      {
        if (auto pitf = witf.lock() )
        {
          pitf->perform_io( std::move(d), io_id1, handler);
        }
      }, nullptr));
    }
  }

  virtual void unreg_io(io_id_t io_id) override
  {
    if ( this->suspended() )
      return;
    if ( _engine != nullptr )
    {
      _engine->unreg_io(io_id);
    }
  }

  virtual void perform_io(data_ptr d, io_id_t io_id, output_handler_t handler) override
  {
    if ( this->suspended() )
    {
      if (handler!=nullptr)
        handler(std::move(d) );
      return;
    }

    if ( _engine == nullptr )
      return;

    _engine->perform_io( std::move(d), io_id, std::move(handler) );
  }

  engine_ptr engine() const { return _engine; }

  typedef std::map<std::string, std::vector<std::string> > schema_map_t;

  static std::list<std::string> get_method_list(schema_map_t& schema_map)
  {
    std::list<std::string> result;
    typedef typename engine_type::handler_type::aspect::template select_group< wjrpc::_method_ >::type tag_list;
    self::get_method_list_(result, schema_map, tag_list() );
    return result;
  }

  static std::string schema_help(const std::string& component_name, const std::string& args, const std::string& base_help )
  {
    typedef typename engine_type::handler_type handler_type;
    std::stringstream ss;
    schema_map_t schema_map;
    std::list<std::string> method_list = get_method_list(schema_map);
    if ( args.empty() )
    {
      ss << base_help << std::endl;
      std::string method_ws_schema;
      ss << "Allowed methods for '" << component_name << "' [allowed schemas]:" << std::endl;
      for (auto n : method_list)
      {
        ss << "  " << n;
        auto method_schemas = schema_map[n];
        if ( !method_schemas.empty() )
        {
          std::stringstream ss1;
          bool has_schema_help = !method_ws_schema.empty();
          if ( !has_schema_help )
          {
            ss1 << "\t--help " << component_name << ":schema:"   << n << "=";
          }

          ss << " [";
          for (size_t i = 0; i < method_schemas.size() ; ++i)
          {
            ss << method_schemas[i];
            ss1 << method_schemas[i];
            if ( i == method_schemas.size() - 1)
            {
              ss << "]";
            }
            else
            {
              ss << ",";
              ss1 << ",";
            }
          }
          method_ws_schema = ss1.str();
        }
        ss << std::endl;
      }

      if ( !method_list.empty() )
      {
        ss << "Get the JSON-RPC default schema:"<< std::endl;
        ss << "\t--help " << component_name << ":schema"    << std::endl;
        ss << "\tExamples for method "<< method_list.front() << ":" << std::endl;
        ss << "\t--help " << component_name << ":schema:"   << method_list.front() << std::endl;
        ss << "\t--help " << component_name << ":params:"   << method_list.front() << std::endl;
        ss << "\t--help " << component_name << ":result:"   << method_list.front() << std::endl;
        ss << "\t--help " << component_name << ":request:"  << method_list.front() << std::endl;
        ss << "\t--help " << component_name << ":response:" << method_list.front();

        if ( !method_ws_schema.empty() )
        {
          ss << std::endl;
          ss << "All allowed schemas: " << method_ws_schema << std::endl;
          ss << "Get the JSON-RPC named schema example:"<< std::endl;
          ss << "\t--help " << component_name << ":schema:"   << method_list.front() << "=" << method_ws_schema;
        }
      }
    }
    else
    {
      typedef typename handler_type::schema_list_t schema_list_t;
      typedef typename schema_list_t::value_type schema_type;
      typedef typename schema_type::json schema_json;
      typedef typename schema_json::list schema_list_json;

      size_t eqpos=args.find('=');
      std::string argname = args.substr(0, eqpos);
      std::string argval = ((eqpos!=std::string::npos) ? args.substr(eqpos+1) : std::string());
      std::vector<std::string> schema_list;
      boost::split( schema_list, argval, boost::is_any_of(",") );
      size_t schpos = argname.find(':');
      std::string schema_tname = argname.substr(0, schpos);
      std::string method_name = schpos!=std::string::npos ? argname.substr(schpos+1) : std::string();

      schema_list_t schema = handler_type::create_schema(schema_list);
      if ( schema_tname=="schema" && method_name.empty() )
      {
        typename schema_list_json::serializer()(schema, std::ostreambuf_iterator<char>(ss) );
      }
      else
      {
        auto itr = std::find_if(schema.begin(), schema.end(),
          [method_name](const schema_type& sch)->bool{
            return sch.name == method_name;
          }
        );

        if ( itr!=schema.end() )
        {
          using namespace wjson::literals;
          if ( schema_tname=="schema" )
            typename schema_json::serializer()(*itr, std::ostreambuf_iterator<char>(ss) );
          else if ( schema_tname=="params" )
            ss << itr->params;
          else if ( schema_tname=="result" )
            ss << itr->result;
          else if ( schema_tname=="request" )
            ss << "{'jsonrpc':'2.0','method':'"_json << method_name << "','params':"_json << itr->params << ",'id':1}"_json;
          else if ( schema_tname=="response" )
            ss << "{'jsonrpc':'2.0','result':"_json << itr->result << ",'id':1}"_json;
          else
            ss << "Error: Invalid argument '" << schema_tname << "'";
        }
        else
          ss << "ERROR: procedure '"<<  method_name<<"' not found";
      }
    }
    return ss.str();
  }
protected:

  static void get_method_list_(std::list<std::string>& , schema_map_t&, fas::empty_list)
  {
  }

  template<typename L>
  static void get_method_list_(std::list<std::string>& res, schema_map_t& schema_map, L)
  {
    typedef typename fas::head<L>::type tag;
    res.push_back( tag()() );
    typedef typename engine_type::handler_type::aspect::template advice_cast< tag >::type method_t;
    method_t::get_schema_list(schema_map[tag()()]);
    self::get_method_list_( res, schema_map, typename fas::tail<L>::type() );
  }

  void initialize_engine(options_type eopt)
  {
    if ( _engine == nullptr )
    {
      _engine = std::make_shared<engine_type>();
      _engine->start(eopt, ::iow::io::create_id<size_t>() );
    }
    else
    {
      _engine->reconfigure( eopt );
    }

    if ( auto wf = this->get_workflow() )
    {
      wf->release_timer( _timer_id );
      if ( eopt.remove_outdated_ms != 0 )
      {
        auto pengine = this->_engine;
        _timer_id = wf->create_timer(
          std::chrono::milliseconds(eopt.remove_outdated_ms),
          [pengine]() -> bool
          {
            JSONRPC_LOG_DEBUG( " JSON-RPC remove outdated...");
            if ( size_t count = pengine->remove_outdated() )
            {
              JSONRPC_LOG_WARNING( "JSON-RPC: " << count << " calls is outdated.");
            }
            return true;
          }
        );
      }
    }
    this->initialize_statistics_();
  }

private:
  void initialize_statistics_()
  {
    if ( auto stat = this->get_statistics() )
    {
      auto sopt = this->statistics_options();
      if ( auto wf = this->get_workflow() )
      {
        wf->release_timer(_stat_timer_id);
        if ( sopt.interval_ms != 0 )
        {
          auto sname = this->name();
          auto handler_map  = stat->create_value_meter(sname + sopt.handler_map);
          auto result_map   = stat->create_value_meter(sname + sopt.result_map);
          auto result_queue = stat->create_value_meter(sname + sopt.result_queue);
          _stat_timer_id = wf->create_timer(
            std::chrono::milliseconds(sopt.interval_ms),
            [handler_map, result_map, result_queue, this]()->bool
            {
              if ( nullptr != this->get_statistics() )
              {
                auto si = this->_engine->sizes();
                handler_map.create( static_cast<wrtstat::value_type>(si.handler_map), static_cast<wrtstat::size_type>(0));
                result_map.create(  static_cast<wrtstat::value_type>(si.result_map), static_cast<wrtstat::size_type>(0));
                result_queue.create(static_cast<wrtstat::value_type>(si.result_queue), static_cast<wrtstat::size_type>(0));
                return true;
              }
              return false;
            }
          );
        }
      }
    }
  }

private:
  timer_id_t _timer_id = 0;
  timer_id_t _stat_timer_id = 0;
protected:
  engine_ptr _engine;
};

}}

ext: hpp

max_stars_repo_name: mambaru/wfc

max_issues_repo_name: mambaru/wfc

max_forks_repo_name: mambaru/wfc


text:
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/pointer_cast.hpp>
#include <QWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QApplication>
#include <QTabWidget>
#include <QStatusBar>
#include <QAction>
#include <QKeySequence>
#include <QMessageBox>
#include <QTimer>
#include <QIcon>
#include "../BibleDatabase/Translation.h"
#include "../BibleDatabase/TranslationManager.h"
#include "../BibleDatabase/TranslationLoader.h"
#include "../BibleDatabase/ICommand.h"
#include "../BibleDatabase/CommandLoadTranslation.h"
#include "SearchResultsModel.h"
#include "StarredVersesModel.h"
#include "BrowseVersesModel.h"
#include "UIBibleStudyWidget.h"
#include "UISearchWidget.h"
#include "UISearchResultsWidget.h"
#include "UIStarredVersesWidget.h"
#include "UITextViewWidget.h"
#include "UIBrowseVersesWidget.h"
#include "QtConnectHelper.h"
#include "BackgroundWorker.h"
#include "Version.h"

using namespace BibleStudyGui;
using namespace BibleDatabase;

UIBibleStudyWidget::UIBibleStudyWidget(boost::shared_ptr<TranslationManager> translation_manager, boost::shared_ptr<const BibleDatabase::TranslationLoader> translation_loader) :
    m_translation_manager(translation_manager),
    m_translation_loader(translation_loader),
    m_translation_load_timer(new QTimer),
    m_translation_load_timeout_ms(500),
    m_results_model(new SearchResultsModel(translation_manager)),
    m_starred_verses_model(new StarredVersesModel(translation_manager)),
    m_browse_verses_model(new BrowseVersesModel(translation_manager)),
    m_dummy_central_widget(new QWidget(this)),
    m_tabs(new QTabWidget()),
    m_search(new UISearchWidget(translation_manager)),
    m_results(new UISearchResultsWidget(m_results_model)),
    m_starred_verses(new UIStarredVersesWidget(m_starred_verses_model)),
    m_text(new UITextViewWidget(translation_manager, m_starred_verses_model)),
    m_browse(new UIBrowseVersesWidget(m_browse_verses_model)),
    m_exit_action(new QAction(tr("E&xit"), this)),
    m_about_action(new QAction(tr("&About"), this))
{
    this->setWindowIcon(QIcon(QString(":/icons/BibleStudy.ico")));

    this->connect_signals();
    this->set_font();
    this->initialize_widgets();
    this->initialize_status_bar();
    this->initialize_actions();

    m_translation_load_timer->start(m_translation_load_timeout_ms);
}

void UIBibleStudyWidget::connect_signals()
{
    // Translation loading connections
    QT_CONNECT(m_translation_load_timer, SIGNAL(timeout()), this, SLOT(load_translations()));
    QT_CONNECT(this, SIGNAL(translations_loaded()), m_search, SLOT(display_translation_check_boxes()));
    QT_CONNECT(this, SIGNAL(translations_loaded()), m_browse, SLOT(set_browse_verses_model()));

    // UISearchWidget connections
    QT_CONNECT(m_search, SIGNAL(search_started(QString)), this, SLOT(display_search_status_bar_message(QString)));
    QT_CONNECT(m_search, SIGNAL(search_complete(boost::shared_ptr<BibleDatabase::ISearchResults>)), m_results, SLOT(display_search_results(boost::shared_ptr<BibleDatabase::ISearchResults>)));
    QT_CONNECT(m_search, SIGNAL(search_complete(boost::shared_ptr<BibleDatabase::ISearchResults>)), this, SLOT(raise_results()));
    QT_CONNECT(m_search, SIGNAL(search_complete(boost::shared_ptr<BibleDatabase::ISearchResults>)), this, SLOT(pop_status_bar_message()));

    // UITextViewWidget connections
    QT_CONNECT(m_text, SIGNAL(verse_starred(boost::shared_ptr<BibleDatabase::VerseDisplay>)), m_starred_verses, SLOT(add_starred_verse(boost::shared_ptr<BibleDatabase::VerseDisplay>)));
    QT_CONNECT(m_text, SIGNAL(verse_starred(boost::shared_ptr<BibleDatabase::VerseDisplay>)), this, SLOT(raise_starred_verses()));
    QT_CONNECT(m_text, SIGNAL(verse_unstarred(boost::shared_ptr<BibleDatabase::VerseDisplay>)), m_starred_verses, SLOT(remove_starred_verse(boost::shared_ptr<BibleDatabase::VerseDisplay>)));

    // UISearchResultsWidget connections
    QT_CONNECT(m_results, SIGNAL(verse_display_changed(boost::shared_ptr<BibleDatabase::VerseDisplay>)), m_text, SLOT(display_text(boost::shared_ptr<BibleDatabase::VerseDisplay>)));
    QT_CONNECT(m_results, SIGNAL(results_filter_started(QString)), this, SLOT(display_search_results_filter_status_bar_message(QString)));
    QT_CONNECT(m_results, SIGNAL(results_filter_completed()), this, SLOT(pop_status_bar_message()));

    // UIBrowseVersesWidget connections
    QT_CONNECT(m_browse, SIGNAL(verse_display_changed(boost::shared_ptr<BibleDatabase::VerseDisplay>)), m_text, SLOT(display_text(boost::shared_ptr<BibleDatabase::VerseDisplay>)));

    // UIStarredVersesWidget connections
    QT_CONNECT(m_starred_verses, SIGNAL(verse_display_changed(boost::shared_ptr<BibleDatabase::VerseDisplay>)), m_text, SLOT(display_text(boost::shared_ptr<BibleDatabase::VerseDisplay>)));
}

void UIBibleStudyWidget::set_font()
{
    QFont app_font = QApplication::font();
    app_font.setPointSize(12);
    app_font.setFamily("Bitstream Vera Sans");
    QApplication::setFont(app_font);
}

void UIBibleStudyWidget::initialize_widgets()
{
    m_tabs->addTab(m_browse, tr("&Verse Browser"));
    m_tabs->addTab(m_results, tr("Search &Results"));
    m_tabs->addTab(m_starred_verses, tr("&Starred Verses"));

    QHBoxLayout* bottom_row = new QHBoxLayout();
    bottom_row->addWidget(m_tabs);
    bottom_row->addWidget(m_text);

    QVBoxLayout* mainLayout = new QVBoxLayout();
    mainLayout->addWidget(m_search);
    mainLayout->addLayout(bottom_row);

    m_dummy_central_widget->setLayout(mainLayout);

    this->setCentralWidget(m_dummy_central_widget);
}

void UIBibleStudyWidget::initialize_status_bar()
{
    this->push_status_bar_message(tr("Ready (Version ") + QString(VERSION ")"));
}

void UIBibleStudyWidget::initialize_actions()
{
    m_exit_action->setShortcuts(QKeySequence::Close);
    m_exit_action->setStatusTip(tr("Exit the BibleStudy"));
    connect(m_exit_action, SIGNAL(triggered()), this, SLOT(close()));

    m_about_action->setStatusTip(tr("Show the BibleStudy's About box"));
    connect(m_about_action, SIGNAL(triggered()), this, SLOT(about()));
}

void UIBibleStudyWidget::raise_results()
{
    m_tabs->setCurrentWidget(m_results);
}

void UIBibleStudyWidget::raise_starred_verses()
{
    m_tabs->setCurrentWidget(m_starred_verses);
}

void UIBibleStudyWidget::about()
{
    QMessageBox::about(this, tr("About BibleStudy"), tr("This is the About box."));
}

void UIBibleStudyWidget::display_search_status_bar_message(QString search_text)
{
    this->push_status_bar_message(tr("Searching for ") + search_text);
}

void UIBibleStudyWidget::display_search_results_filter_status_bar_message(QString filter_text)
{
    if (!filter_text.isEmpty())
    {
        this->push_status_bar_message(tr("Filtering search results based on ") + filter_text);
    }
    else
    {
        this->push_status_bar_message(tr("Removing search results filter"));
    }
}

void UIBibleStudyWidget::push_status_bar_message(QString message)
{
    m_status_bar_messages.push(message);
    this->statusBar()->showMessage(message);
}

void UIBibleStudyWidget::pop_status_bar_message()
{
    if (!m_status_bar_messages.empty())
    {
        m_status_bar_messages.pop();
        this->statusBar()->showMessage(m_status_bar_messages.top());
    }
    else
    {
        this->statusBar()->clearMessage();
    }
}

void UIBibleStudyWidget::load_translations()
{
    m_translation_load_timer->stop();

#ifdef LINUX
    TranslationLoadInformation dr_load_information = {"Douay-Rheims", "../share/BibleStudy/Translations/DR.buf" };
    TranslationLoadInformation kjv_load_information = {"King James Version", "../share/BibleStudy/Translations/KJV.buf" };
#else
    TranslationLoadInformation dr_load_information = {"Douay-Rheims", "Translations/DR.buf" };
    TranslationLoadInformation kjv_load_information = {"King James Version", "Translations/KJV.buf" };
#endif

    m_translations_to_load.push_back(dr_load_information);
    m_translations_to_load.push_back(kjv_load_information);

    if (!m_translations_to_load.empty())
    {
        this->setEnabled(false);
        start_next_translation_load();
    }
}

void UIBibleStudyWidget::translation_loaded()
{
    QT_DISCONNECT(m_load_translation_worker.get(), SIGNAL(finished()), this, SLOT(translation_loaded()));

    boost::shared_ptr<CommandLoadTranslation> command_load_translation = boost::dynamic_pointer_cast<CommandLoadTranslation>(m_command_load_translation);
    boost::shared_ptr<const Translation> translation = command_load_translation->get_translation();
    m_translation_manager->add_translation(translation);
    this->pop_status_bar_message();

    if (!m_translations_to_load.empty())
    {
        start_next_translation_load();
    }
    else
    {
        this->setEnabled(true);
        emit translations_loaded();
    }
}

void UIBibleStudyWidget::start_next_translation_load()
{
    TranslationLoadInformation load_information = m_translations_to_load.front();
    m_translations_to_load.pop_front();

    this->push_status_bar_message(tr("Loading translation ") + tr(load_information.translation_long_name.c_str()));
    m_command_load_translation = boost::shared_ptr<ICommand>(new CommandLoadTranslation(m_translation_loader, load_information.translation_file));
    m_load_translation_worker = boost::make_shared<BackgroundWorker>(m_command_load_translation);

    QT_CONNECT(m_load_translation_worker.get(), SIGNAL(finished()), this, SLOT(translation_loaded()));

    m_load_translation_worker->start();
}

max_stars_repo_name: joshpeterson/BibleStudy

max_issues_repo_name: joshpeterson/BibleStudy

max_forks_repo_name: joshpeterson/BibleStudy


text:
//
//  condition.cpp
//  fibio
//
//  Created by Chen Xu on 14-3-4.
//  Copyright (c) 2014 0d0a.com. All rights reserved.
//

#include <boost/system/error_code.hpp>
#include <fibio/fibers/condition_variable.hpp>
#include "fiber_object.hpp"

namespace fibio {
namespace fibers {

static const auto NOPERM = condition_error(boost::system::errc::operation_not_permitted);

void condition_variable::wait(std::unique_lock<mutex>& lock)
{
    auto tf = current_fiber_ptr();
    mutex* m = lock.mutex();
    if (tf != m->owner_) {
        // This fiber doesn't own the mutex
        BOOST_THROW_EXCEPTION(NOPERM);
    }
    {
        std::lock_guard<detail::spinlock> lock(mtx_);
        // The "suspension of this fiber" is actually happened here, not the pause()
        // as other will see there is a fiber in the waiting queue.
        suspended_.push_back(suspended_item({m, tf, 0}));
    }
    {
        detail::relock_guard<mutex> relock(*m);
        tf->pause();
    }
}

void condition_variable::timeout_handler(detail::fiber_ptr_t this_fiber,
                                         detail::timer_t* t,
                                         cv_status& ret,
                                         boost::system::error_code ec)
{
    if (!ec) {
        // Timeout
        // Timeout handler, find and remove this fiber from waiting queue
        std::lock_guard<detail::spinlock> lock(mtx_);
        ret = cv_status::timeout;
        // Find and remove this fiber from waiting queue
        auto i = std::find(suspended_.begin(), suspended_.end(), this_fiber);
        if (i != suspended_.end()) {
            suspended_.erase(i);
        }
    }
    this_fiber->resume();
}

cv_status condition_variable::wait_rel(std::unique_lock<mutex>& lock, detail::duration_t d)
{
    auto tf = current_fiber_ptr();
    mutex* m = lock.mutex();
    cv_status ret = cv_status::no_timeout;
    if (tf != m->owner_) {
        // This fiber doesn't own the mutex
        BOOST_THROW_EXCEPTION(NOPERM);
    }
    detail::timer_t t(tf->get_io_service());
    {
        std::lock_guard<detail::spinlock> lock(mtx_);
        suspended_.push_back(suspended_item({m, tf, &t}));
        t.expires_from_now(d);
        t.async_wait(tf->get_fiber_strand().wrap(std::bind(&condition_variable::timeout_handler,
                                                           this,
                                                           tf,
                                                           &t,
                                                           std::ref(ret),
                                                           std::placeholders::_1)));
    }
    {
        detail::relock_guard<mutex> relock(*m);
        tf->pause();
    }
    return ret;
}

void condition_variable::notify_one()
{
    {
        std::lock_guard<detail::spinlock> lock(mtx_);
        if (suspended_.empty()) {
            return;
        }
        suspended_item p(suspended_.front());
        suspended_.pop_front();
        if (p.t_) {
            // Cancel attached timer if it's set
            // Timer handler will reschedule the waiting fiber
            p.t_->cancel();
            p.t_ = 0;
        } else {
            // No timer attached to the waiting fiber, directly schedule it
            p.f_->resume();
        }
    }
    // Only yield if currently in a fiber
    // CV can be used to notify a fiber from not-a-fiber, i.e. foreign thread
    if (auto cf = current_fiber()) {
        cf->yield();
    }
}

void condition_variable::notify_all()
{
    {
        std::lock_guard<detail::spinlock> lock(mtx_);
        while (!suspended_.empty()) {
            suspended_item p(suspended_.front());
            suspended_.pop_front();
            if (p.t_) {
                // Cancel attached timer if it's set
                // Timer handler will reschedule the waiting fiber
                p.t_->cancel();
            } else {
                // No timer attached to the waiting fiber, directly schedule it
                p.f_->resume();
            }
        }
    }
    // Only yield if currently in a fiber
    // CV can be used to notify a fiber from not-a-fiber, i.e. foreign thread
    if (auto cf = current_fiber()) {
        cf->yield();
    }
}

struct cleanup_handler
{
    condition_variable& c_;
    std::unique_lock<mutex> l_;

    cleanup_handler(condition_variable& cond, std::unique_lock<mutex> lk)
    : c_(cond), l_(std::move(lk))
    {
    }

    void operator()()
    {
        l_.unlock();
        c_.notify_all();
    }
};

inline void run_cleanup_handler(cleanup_handler* h)
{
    std::unique_ptr<cleanup_handler> ch(h);
    (*ch)();
}

void notify_all_at_fiber_exit(condition_variable& cond, std::unique_lock<mutex> lk)
{
    CHECK_CURRENT_FIBER;
    if (auto cf = current_fiber()) {
        cleanup_handler* h = new cleanup_handler(cond, std::move(lk));
        cf->add_cleanup_function(std::bind(run_cleanup_handler, h));
    }
}

} // End of namespace fibers
} // End of namespace fibio

max_stars_repo_name: mind-owner/fibio

max_issues_repo_name: learnerzhang/fibio

max_forks_repo_name: learnerzhang/fibio


text:
/*
 Copyright (C) 2016 Quaternion Risk Management Ltd
 All rights reserved.

 This file is part of ORE, a free-software/open-source library
 for transparent pricing and risk analysis - http://opensourcerisk.org

 ORE is free software: you can redistribute it and/or modify it
 under the terms of the Modified BSD License.  You should have received a
 copy of the license along with this program.
 The license is also available online at <http://opensourcerisk.org>

 This program is distributed on the basis that it will form a useful
 contribution to risk analytics and model standardisation, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/

#include "toplevelfixture.hpp"
#include "utilities.hpp"
#include <boost/test/unit_test.hpp>

#include <qle/termstructures/dynamicblackvoltermstructure.hpp>

#include <ql/math/matrix.hpp>
#include <ql/quotes/simplequote.hpp>
#include <ql/termstructures/volatility/equityfx/blackvariancesurface.hpp>
#include <ql/termstructures/yield/flatforward.hpp>
#include <ql/time/calendars/target.hpp>

using namespace QuantExt;
using namespace QuantLib;
using namespace boost::unit_test_framework;

namespace {

struct TestData {

    TestData() : origRefDate(20, Jan, 2016) {

        Settings::instance().evaluationDate() = origRefDate;

        // set up the reference vol term structure
        refDates.push_back(TARGET().advance(origRefDate, 1 * Years));
        refDates.push_back(TARGET().advance(origRefDate, 2 * Years));
        strikes.push_back(0.90);
        strikes.push_back(1.00);
        strikes.push_back(1.10);

        vol = Matrix(3, 2);
        vol[0][0] = 0.12;
        vol[0][1] = 0.10;
        vol[1][0] = 0.10;
        vol[1][1] = 0.08;
        vol[2][0] = 0.11;
        vol[2][1] = 0.09;

        refVol = Handle<BlackVolTermStructure>(
            boost::make_shared<BlackVarianceSurface>(origRefDate, TARGET(), refDates, strikes, vol, Actual365Fixed()));
        refVol->enableExtrapolation();

        // set up floating spot and term structures
        spot = boost::make_shared<SimpleQuote>(1.00);
        spot_q = Handle<Quote>(spot);
        rate = boost::make_shared<SimpleQuote>(0.02);
        rate_q = Handle<Quote>(rate);
        div = boost::make_shared<SimpleQuote>(0.02);
        div_q = Handle<Quote>(div);

        riskfreeTs = Handle<YieldTermStructure>(boost::make_shared<FlatForward>(0, TARGET(), rate_q, Actual365Fixed()));
        dividendTs = Handle<YieldTermStructure>(boost::make_shared<FlatForward>(0, TARGET(), div_q, Actual365Fixed()));
    }

    SavedSettings backup;
    const Date origRefDate;
    std::vector<Date> refDates;
    std::vector<Real> strikes;
    Matrix vol;
    Handle<BlackVolTermStructure> refVol;
    boost::shared_ptr<SimpleQuote> spot, rate, div;
    Handle<Quote> spot_q, rate_q, div_q;
    Handle<YieldTermStructure> riskfreeTs, dividendTs;
};

} // anonymous namespace

BOOST_FIXTURE_TEST_SUITE(QuantExtTestSuite, qle::test::TopLevelFixture)

BOOST_AUTO_TEST_SUITE(DynamicBlackVolTermStructureTest)

BOOST_AUTO_TEST_CASE(testConstantVarianceStickyStrike) {

    BOOST_TEST_MESSAGE("Testing constant variance, sticky strike dynamics of "
                       "DynamicBlackVolTermStructure...");

    TestData d;

    Handle<DynamicBlackVolTermStructure<tag::surface> > dyn(
        boost::make_shared<DynamicBlackVolTermStructure<tag::surface> >(
            d.refVol, 0, TARGET(), ConstantVariance, StickyStrike, d.riskfreeTs, d.dividendTs, d.spot_q));

    dyn->enableExtrapolation();

    Real tol = 1.0E-8;

    // initially we should get the same volatilities

    BOOST_CHECK_CLOSE(dyn->blackVol(0.5, 0.80), d.refVol->blackVol(0.5, 0.80), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(0.5, 0.90), d.refVol->blackVol(0.5, 0.90), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(0.5, 0.95), d.refVol->blackVol(0.5, 0.95), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(0.5, 1.15), d.refVol->blackVol(0.5, 1.15), tol);

    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 0.80), d.refVol->blackVol(1.5, 0.80), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 0.90), d.refVol->blackVol(1.5, 0.90), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 0.95), d.refVol->blackVol(1.5, 0.95), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 1.15), d.refVol->blackVol(1.5, 1.15), tol);

    BOOST_CHECK_CLOSE(dyn->blackVol(5.0, 0.80), d.refVol->blackVol(5.0, 0.80), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(5.0, 0.90), d.refVol->blackVol(5.0, 0.90), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(5.0, 0.95), d.refVol->blackVol(5.0, 0.95), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(5.0, 1.15), d.refVol->blackVol(5.0, 1.15), tol);

    // check atm vol retrieval via null strike (atm is spot here)

    BOOST_CHECK_CLOSE(dyn->blackVol(0.5, Null<Real>()), d.refVol->blackVol(0.5, d.spot->value()), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, Null<Real>()), d.refVol->blackVol(1.5, d.spot->value()), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(5.0, Null<Real>()), d.refVol->blackVol(5.0, d.spot->value()), tol);

    // move forward in time, we expect a constant surface in every respect
    // even when atm is changing via spot or rates

    Settings::instance().evaluationDate() = TARGET().advance(d.origRefDate, 6 * Months);
    d.spot->setValue(0.9);
    BOOST_CHECK_CLOSE(dyn->blackVol(0.7, 0.80), d.refVol->blackVol(0.7, 0.80), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(0.7, 0.90), d.refVol->blackVol(0.7, 0.90), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(0.7, 0.95), d.refVol->blackVol(0.7, 0.95), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(0.7, 1.15), d.refVol->blackVol(0.7, 1.15), tol);

    Settings::instance().evaluationDate() = TARGET().advance(d.origRefDate, 18 * Months);
    d.rate->setValue(0.01);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.7, 0.80), d.refVol->blackVol(1.7, 0.80), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.7, 0.90), d.refVol->blackVol(1.7, 0.90), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.7, 0.95), d.refVol->blackVol(1.7, 0.95), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.7, 1.15), d.refVol->blackVol(1.7, 1.15), tol);

    Settings::instance().evaluationDate() = TARGET().advance(d.origRefDate, 3 * Years);
    d.div->setValue(0.03);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.71, 0.80), d.refVol->blackVol(1.71, 0.80), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.71, 0.90), d.refVol->blackVol(1.71, 0.90), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.71, 0.95), d.refVol->blackVol(1.71, 0.95), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.71, 1.15), d.refVol->blackVol(1.71, 1.15), tol);

} // testConstantVarianceStickyStrike

BOOST_AUTO_TEST_CASE(testConstantVarianceStickyLogMoneyness) {

    BOOST_TEST_MESSAGE("Testing constant variance, sticky log-moneyness "
                       "dynamics of DynamicBlackVolTermStructure...");

    TestData d;

    Handle<DynamicBlackVolTermStructure<tag::surface> > dyn(
        boost::make_shared<DynamicBlackVolTermStructure<tag::surface> >(
            d.refVol, 0, TARGET(), ConstantVariance, StickyLogMoneyness, d.riskfreeTs, d.dividendTs, d.spot_q));

    dyn->enableExtrapolation();

    Real tol = 1.0E-8;

    // initially we should get the same volatilities

    BOOST_CHECK_CLOSE(dyn->blackVol(0.5, 0.80), d.refVol->blackVol(0.5, 0.80), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(0.5, 0.90), d.refVol->blackVol(0.5, 0.90), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(0.5, 0.95), d.refVol->blackVol(0.5, 0.95), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(0.5, 1.15), d.refVol->blackVol(0.5, 1.15), tol);

    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 0.80), d.refVol->blackVol(1.5, 0.80), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 0.90), d.refVol->blackVol(1.5, 0.90), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 0.95), d.refVol->blackVol(1.5, 0.95), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 1.15), d.refVol->blackVol(1.5, 1.15), tol);

    BOOST_CHECK_CLOSE(dyn->blackVol(5.0, 0.80), d.refVol->blackVol(5.0, 0.80), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(5.0, 0.90), d.refVol->blackVol(5.0, 0.90), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(5.0, 0.95), d.refVol->blackVol(5.0, 0.95), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(5.0, 1.15), d.refVol->blackVol(5.0, 1.15), tol);

    // move forward in time, in time direction we expect a constant
    // surface, but the strike range is constant in log money now
    // instead of absolute strike

    Settings::instance().evaluationDate() = TARGET().advance(d.origRefDate, 6 * Months);

    Real atm0 = d.spot->value(); // original atm value
    d.spot->setValue(0.9);
    Real atm = d.spot->value(); // new atm value

    BOOST_CHECK_CLOSE(dyn->blackVol(0.7, atm * std::exp(-0.25)), d.refVol->blackVol(0.7, atm0 * std::exp(-0.25)), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(0.7, atm * std::exp(0.00)), d.refVol->blackVol(0.7, atm0 * std::exp(0.00)), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(0.7, atm * std::exp(0.25)), d.refVol->blackVol(0.7, atm0 * std::exp(0.25)), tol);

    BOOST_CHECK_CLOSE(dyn->blackVol(1.7, atm * std::exp(-0.25)), d.refVol->blackVol(1.7, atm0 * std::exp(-0.25)), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.7, atm * std::exp(0.00)), d.refVol->blackVol(1.7, atm0 * std::exp(0.00)), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.7, atm * std::exp(0.25)), d.refVol->blackVol(1.7, atm0 * std::exp(0.25)), tol);

    BOOST_CHECK_CLOSE(dyn->blackVol(3.0, atm * std::exp(-0.25)), d.refVol->blackVol(3.0, atm0 * std::exp(-0.25)), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(3.0, atm * std::exp(0.00)), d.refVol->blackVol(3.0, atm0 * std::exp(0.00)), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(3.0, atm * std::exp(0.25)), d.refVol->blackVol(3.0, atm0 * std::exp(0.25)), tol);

    Settings::instance().evaluationDate() = TARGET().advance(d.origRefDate, 18 * Months);
    d.rate->setValue(0.01);
    // new atm for t=1.8
    atm = d.spot->value() / d.riskfreeTs->discount(1.8) * d.dividendTs->discount(1.8);

    BOOST_CHECK_CLOSE(dyn->blackVol(1.8, atm * std::exp(-0.25)), d.refVol->blackVol(1.8, atm0 * std::exp(-0.25)), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.8, atm * std::exp(0.00)), d.refVol->blackVol(1.8, atm0 * std::exp(0.00)), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.8, atm * std::exp(0.25)), d.refVol->blackVol(1.8, atm0 * std::exp(0.25)), tol);

    Settings::instance().evaluationDate() = TARGET().advance(d.origRefDate, 3 * Years);
    d.div->setValue(0.03);
    // new atm for t=3.5
    atm = d.spot->value() / d.riskfreeTs->discount(3.5) * d.dividendTs->discount(3.5);

    BOOST_CHECK_CLOSE(dyn->blackVol(3.5, atm * std::exp(-0.25)), d.refVol->blackVol(3.5, atm0 * std::exp(-0.25)), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(3.5, atm * std::exp(0.00)), d.refVol->blackVol(3.5, atm0 * std::exp(0.00)), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(3.5, atm * std::exp(0.25)), d.refVol->blackVol(3.5, atm0 * std::exp(0.25)), tol);

} // testConstantVarianceStickyLogMoneyness

BOOST_AUTO_TEST_CASE(testForwardVarianceStickyStrike) {

    BOOST_TEST_MESSAGE("Testing forward-forward variance, sticky strike "
                       "dynamics of DynamicBlackVolTermStructure...");

    TestData d;

    Handle<DynamicBlackVolTermStructure<tag::surface> > dyn(
        boost::make_shared<DynamicBlackVolTermStructure<tag::surface> >(
            d.refVol, 0, TARGET(), ForwardForwardVariance, StickyStrike, d.riskfreeTs, d.dividendTs, d.spot_q));

    dyn->enableExtrapolation();

    Real tol = 1.0E-8;

    // initially we should get the same volatilities

    BOOST_CHECK_CLOSE(dyn->blackVol(0.5, 0.80), d.refVol->blackVol(0.5, 0.80), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(0.5, 0.90), d.refVol->blackVol(0.5, 0.90), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(0.5, 0.95), d.refVol->blackVol(0.5, 0.95), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(0.5, 1.15), d.refVol->blackVol(0.5, 1.15), tol);

    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 0.80), d.refVol->blackVol(1.5, 0.80), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 0.90), d.refVol->blackVol(1.5, 0.90), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 0.95), d.refVol->blackVol(1.5, 0.95), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 1.15), d.refVol->blackVol(1.5, 1.15), tol);

    BOOST_CHECK_CLOSE(dyn->blackVol(5.0, 0.80), d.refVol->blackVol(5.0, 0.80), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(5.0, 0.90), d.refVol->blackVol(5.0, 0.90), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(5.0, 0.95), d.refVol->blackVol(5.0, 0.95), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(5.0, 1.15), d.refVol->blackVol(5.0, 1.15), tol);

    // move forward in time, in time direction we expect to roll
    // down the curve (i.e. forward vols from the original vol ts
    // are realized), with the strike range held constant

    Settings::instance().evaluationDate() = TARGET().advance(d.origRefDate, 6 * Months);
    Real t = d.refVol->timeFromReference(Settings::instance().evaluationDate());
    d.spot->setValue(0.9);

    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 0.80), d.refVol->blackForwardVol(t, t + 1.5, 0.80), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 0.90), d.refVol->blackForwardVol(t, t + 1.5, 0.90), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 0.95), d.refVol->blackForwardVol(t, t + 1.5, 0.95), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 1.15), d.refVol->blackForwardVol(t, t + 1.5, 1.15), tol);

    Settings::instance().evaluationDate() = TARGET().advance(d.origRefDate, 18 * Months);
    t = d.refVol->timeFromReference(Settings::instance().evaluationDate());
    d.rate->setValue(0.01);

    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 0.80), d.refVol->blackForwardVol(t, t + 1.5, 0.80), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 0.90), d.refVol->blackForwardVol(t, t + 1.5, 0.90), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 0.95), d.refVol->blackForwardVol(t, t + 1.5, 0.95), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 1.15), d.refVol->blackForwardVol(t, t + 1.5, 1.15), tol);

    Settings::instance().evaluationDate() = TARGET().advance(d.origRefDate, 3 * Years);
    t = d.refVol->timeFromReference(Settings::instance().evaluationDate());
    d.div->setValue(0.03);

    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 0.80), d.refVol->blackForwardVol(t, t + 1.5, 0.80), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 0.90), d.refVol->blackForwardVol(t, t + 1.5, 0.90), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 0.95), d.refVol->blackForwardVol(t, t + 1.5, 0.95), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 1.15), d.refVol->blackForwardVol(t, t + 1.5, 1.15), tol);

} // testForwardVarianceStickyLogMoneyness

BOOST_AUTO_TEST_CASE(testForwardVarianceStickyLogMoneyness) {

    BOOST_TEST_MESSAGE("Testing forward-forward variance, sticky log-moneyness "
                       "dynamics of DynamicBlackVolTermStructure...");

    TestData d;

    Handle<DynamicBlackVolTermStructure<tag::surface> > dyn(
        boost::make_shared<DynamicBlackVolTermStructure<tag::surface> >(
            d.refVol, 0, TARGET(), ForwardForwardVariance, StickyLogMoneyness, d.riskfreeTs, d.dividendTs, d.spot_q));

    dyn->enableExtrapolation();

    Real tol = 1.0E-8;

    // initially we should get the same volatilities

    BOOST_CHECK_CLOSE(dyn->blackVol(0.5, 0.80), d.refVol->blackVol(0.5, 0.80), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(0.5, 0.90), d.refVol->blackVol(0.5, 0.90), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(0.5, 0.95), d.refVol->blackVol(0.5, 0.95), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(0.5, 1.15), d.refVol->blackVol(0.5, 1.15), tol);

    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 0.80), d.refVol->blackVol(1.5, 0.80), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 0.90), d.refVol->blackVol(1.5, 0.90), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 0.95), d.refVol->blackVol(1.5, 0.95), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(1.5, 1.15), d.refVol->blackVol(1.5, 1.15), tol);

    BOOST_CHECK_CLOSE(dyn->blackVol(5.0, 0.80), d.refVol->blackVol(5.0, 0.80), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(5.0, 0.90), d.refVol->blackVol(5.0, 0.90), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(5.0, 0.95), d.refVol->blackVol(5.0, 0.95), tol);
    BOOST_CHECK_CLOSE(dyn->blackVol(5.0, 1.15), d.refVol->blackVol(5.0, 1.15), tol);

    // move forward in time, in time direction we expect to roll down
    // the curve with the forward variance being taken at strikes
    // constant in moneyness

    Settings::instance().evaluationDate() = TARGET().advance(d.origRefDate, 18 * Months);
    Real t = d.refVol->timeFromReference(Settings::instance().evaluationDate());
    Real atm0 = d.spot->value(); // original atm value
    d.spot->setValue(0.9);
    Real atm = d.spot->value(); // new atm value

    BOOST_CHECK_CLOSE(dyn->blackVariance(1.5, atm * std::exp(-0.25)),
                      d.refVol->blackVariance(t + 1.5, atm0 * std::exp(-0.25)) -
                          d.refVol->blackVariance(t, atm0 * std::exp(-0.25)),
                      tol);
    BOOST_CHECK_CLOSE(
        dyn->blackVariance(1.5, atm * std::exp(0.0)),
        d.refVol->blackVariance(t + 1.5, atm0 * std::exp(0.0)) - d.refVol->blackVariance(t, atm0 * std::exp(0.0)), tol);
    BOOST_CHECK_CLOSE(dyn->blackVariance(1.5, atm * std::exp(0.25)),
                      d.refVol->blackVariance(t + 1.5, atm0 * std::exp(0.25)) -
                          d.refVol->blackVariance(t, atm0 * std::exp(0.25)),
                      tol);

} // testForwardVarianceStickyLogMoneyness
BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: mrslezak/Engine

max_issues_repo_name: mrslezak/Engine

max_forks_repo_name: mrslezak/Engine


text:
// Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
// Use of this source code is governed by an apache-2.0 license that can be
// found in the LICENSE file.

#include "common/step/filesystem/step_create_icons.h"

#include <boost/filesystem/operations.hpp>
#include <boost/system/error_code.hpp>
#include <pkgmgr-info.h>

#include "common/utils/glist_range.h"

namespace bf = boost::filesystem;
namespace bs = boost::system;

namespace common_installer {
namespace filesystem {

Step::Status StepCreateIcons::undo() {
  for (auto& icon : icons_) {
    bs::error_code error;
    bf::remove_all(icon, error);
  }
  return Status::OK;
}

Step::Status StepCreateIcons::process() {
  bf::path destination =
      getIconPath(context_->uid.get(), context_->is_preload_request.get());
  bs::error_code error;
  if (!bf::exists(destination)) {
    bf::create_directories(destination, error);
    if (error) {
      LOG(ERROR) << "Cannot create directory of application icons: "
                 << destination;
      return Status::ERROR;
    }
  }

  for (application_x* app :
      GListRange<application_x*>(context_->manifest_data.get()->application)) {
    // TODO(t.iwanek): this ignores icon locale as well in same way as other
    // steps -> icons should be localized
    if (app->icon) {
      icon_x* icon = reinterpret_cast<icon_x*>(app->icon->data);
      bf::path source(icon->text);
      if (bf::exists(source)) {
        bf::path destination_path = destination / app->appid;
        if (source.has_extension())
          destination_path += source.extension();
        else
          destination_path += ".png";
        bf::copy_file(source, destination_path, error);
        if (error) {
          LOG(ERROR) << "Cannot create package icon: " << destination_path
                     << " , error: " << error;
          return Status::ICON_ERROR;
        }
        icons_.push_back(destination_path);
      }
    }
  }
  LOG(DEBUG) << "Icon files created";
  return Status::OK;
}

}  // namespace filesystem
}  // namespace common_installer

ext: cc


text:
/* Copyright Institute of Sound and Vibration Research - All rights reserved */

#include "signal_routing_parameter.hpp"

#include <boost/bind.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/qi_uint.hpp>

#include <algorithm>
#include <ciso646>

namespace visr
{
namespace pml
{

/**
 * Provide definition for the static const class member in order to allow their address to be taken.
 * The value is taken from their declaration within the class.
 * @note Microsoft Visual Studio neither allows or requires this standard-compliant explicit definition.
 */
#ifndef _MSC_VER
/*static*/ const SignalRoutingParameter::IndexType SignalRoutingParameter::cInvalidIndex;
#endif

SignalRoutingParameter::SignalRoutingParameter( std::initializer_list<Entry> const & entries )
{
  for( auto e : entries )
  {
    bool result;
    std::tie( std::ignore, result ) = mRoutings.insert( e );
    if( not result )
    {
      throw std::invalid_argument( "Duplicated output indices are not allowed." );
    }
  }
}

SignalRoutingParameter::SignalRoutingParameter( const ParameterConfigBase & )
 : SignalRoutingParameter() // Call default constructor
{
  // TODO: Check whether the parameter is of type EmptyParameterConfig.
}

SignalRoutingParameter::~SignalRoutingParameter() = default;

void SignalRoutingParameter::swap( SignalRoutingParameter& rhs )
{
  mRoutings.swap( rhs.mRoutings );
}

void SignalRoutingParameter::addRouting( Entry const & newEntry )
{
  RoutingsType::const_iterator const findIt = mRoutings.find( newEntry );
  if( findIt != mRoutings.end() )
  {
    mRoutings.erase( findIt );
  }
  mRoutings.insert( newEntry );
}

bool SignalRoutingParameter::removeEntry( Entry const & entry )
{
  RoutingsType::const_iterator const findIt = mRoutings.find( entry );
  if( findIt != mRoutings.end() )
  {
    if( findIt->input == entry.input )
    {
      mRoutings.erase( findIt );
      return true;
    }
  }
  return false;
}

bool SignalRoutingParameter::removeEntry( IndexType outputIdx )
{
  RoutingsType::const_iterator const findIt = mRoutings.find( Entry{ cInvalidIndex, outputIdx } );
  if( findIt != mRoutings.end() )
  {
    mRoutings.erase( findIt );
    return true;
  }
  return false;
}

void SignalRoutingParameter::clear()
{
  mRoutings.clear();
}

SignalRoutingParameter::IndexType SignalRoutingParameter::getOutput( IndexType inputIdx ) const
{
  RoutingsType::const_iterator findIt = std::find_if( mRoutings.begin(), mRoutings.end(),
                                                     [&inputIdx]( const Entry & x ) { return x.input == inputIdx; } );
  return (findIt == mRoutings.end()) ? cInvalidIndex : findIt->output;
}

// Parsing of string representations for signal routings

bool SignalRoutingParameter::parse( std::string const & encoded )
{
  namespace qi = boost::spirit::qi;

  std::string::const_iterator first = encoded.begin();
  std::string::const_iterator last = encoded.end();

  struct ParseState
  {
  public:
    void setInIdx( pml::SignalRoutingParameter::IndexType const inIdx )
    {
      mInIdx = inIdx;
    }

    void setOutIdx( pml::SignalRoutingParameter::IndexType const outIdx )
    {
      retValue.addRouting( mInIdx, outIdx );
    }
    pml::SignalRoutingParameter::IndexType mInIdx;
    pml::SignalRoutingParameter retValue;
  };
  ParseState state;
  // This parses a sequence of number pairs of the form 'x=y', where the pairs are separated by whitespace or a comma.
  bool const parseRet = qi::phrase_parse( first, last,
                                         ((qi::uint_[boost::bind( &ParseState::setInIdx, &state, _1 )] >> '=' >> qi::uint_[boost::bind(&ParseState::setOutIdx, &state, _1)]) % (','|qi::blank) ),
   qi::ascii::space );

  if( (not parseRet) or( first != last ) )
  {
    return false;
  }
  swap( state.retValue );
  return true;
}

} // namespace pml
} // namespace visr


text:
/*
  MIT License

  Copyright (c) 2018 Nicolai Trandafil

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
*/

#pragma once

#include <yenxo/meta.hpp>
#include <yenxo/type_name.hpp>
#include <yenxo/variant_conversion.hpp>

#include <boost/hana.hpp>

#include <iomanip>
#include <ostream>

namespace yenxo {
namespace detail {

/// \ingroup group-details
/// Is `std::ostream& operator<<(std::ostream&, T)` defined.
constexpr auto const hasOStreamOperator = boost::hana::is_valid(
        [](auto t) -> decltype(operator<<(std::declval<std::ostream>(),
                                          std::declval<typename decltype(t)::type>())) {
        });
} // namespace detail

struct OStreamT {
    template <class T>
    void operator()(std::ostream& os, T const&) const;
};

inline constexpr OStreamT oStream;

template <class T, class = void>
struct OStreamImpl : OStreamImpl<T, When<true>> {};

template <class T, bool condition>
struct OStreamImpl<T, When<condition>> {
    void apply(std::ostream&, T const&) {
        static_assert(T::pay_attention_no_ostream_operator_defined_for);
    }
};

template <class T>
struct OStreamImpl<T,
                   When<!detail::hasOStreamOperator(boost::hana::type_c<T>)
                        && isOptional(boost::hana::type_c<T>)>> {
    static void apply(std::ostream& os, T const& val) {
        if (val.has_value()) {
            oStream(os, *val);
        } else {
            os << "None";
        }
    }
};

template <class T>
struct OStreamImpl<T,
                   When<!detail::hasOStreamOperator(boost::hana::type_c<T>)
                        && isContainer(boost::hana::type_c<T>)
                        && isPair(boost::hana::type_c<typename T::value_type>)>> {
    static void apply(std::ostream& os, T const& val) {
        auto const s = size(val);
        std::size_t i = 0;
        os << "{ ";
        for (auto const& x : val) {
            oStream(os, x);
            os << ((i++ == s - 1) ? ";" : "; ");
        }
        os << " }";
    }
};

template <class T>
struct OStreamImpl<T,
                   When<!detail::hasOStreamOperator(boost::hana::type_c<T>)
                        && isContainer(boost::hana::type_c<T>)
                        && !isPair(boost::hana::type_c<typename T::value_type>)>> {
    static void apply(std::ostream& os, T const& val) {
        auto const s = size(val);
        std::size_t i = 0;
        os << "[";
        for (auto const& x : val) {
            oStream(os, x);
            os << ((i++ == s - 1) ? "" : ", ");
        }
        os << "]";
    }
};

template <class T>
struct OStreamImpl<T,
                   When<!detail::hasOStreamOperator(boost::hana::type_c<T>)
                        && isPair(boost::hana::type_c<T>)>> {
    static void apply(std::ostream& os, T const& val) {
        oStream(os, val.first);
        os << ": ";
        oStream(os, val.second);
    }
};

#if YENXO_ENABLE_TYPE_SAFE
template <class T>
struct OStreamImpl<T,
                   When<!detail::hasOStreamOperator(boost::hana::type_c<T>)
                        && strongTypeDef(boost::hana::type_c<T>)>> {
    static void apply(std::ostream& os, T const& val) {
        oStream(os, static_cast<type_safe::underlying_type<decltype(val)>>(val));
    }
};
#endif

template <class T>
struct OStreamImpl<T,
                   When<!detail::hasOStreamOperator(boost::hana::type_c<T>)
                        && isStdVariant(boost::hana::type_c<T>)>> {
    static void apply(std::ostream& os, T const& val) {
        std::visit([&os](auto const& x) { oStream(os, x); }, val);
    }
};

template <class T>
struct OStreamImpl<T, When<detail::hasOStreamOperator(boost::hana::type_c<T>)>> {
    static std::ostream& apply(std::ostream& os, T const& val) {
        return os << val;
    }
};

template <class T>
void OStreamT::operator()(std::ostream& os, T const& val) const {
    OStreamImpl<T>::apply(os, val);
}

/// \pre `T` should be a Boost.Hana.Struct.
template <class T>
void ostreamImpl(std::ostream& os, T const& x) {
    os << typeName(boost::hana::type_c<T>) << " { ";
    boost::hana::for_each(x, boost::hana::fuse([&](auto name, auto value) {
                              os << boost::hana::to<char const*>(name) << ": ";
                              oStream(os, value);
                              os << "; ";
                          }));
    os << "}";
}

namespace trait {

/// Enables `std::ostream& operator<<(std::ostream&, Derived)` for `Derived`
/// \ingroup group-traits-opt-in
/// \pre `T` should be a Boost.Hana.Struct.
template <typename Derived>
struct OStream {
    friend std::ostream& operator<<(std::ostream& os, Derived const& x) {
        ostreamImpl(os, x);
        return os;
    }
};

} // namespace trait
} // namespace yenxo

/// Enables `std::ostream& operator<<(std::ostream&, T)` for `T`
/// \ingroup group-traits-opt-in
/// \pre `T` should be a Boost.Hana.Struct.
/// \see yenxo::trait::OStream.
#define YENXO_OSTREAM_OPERATOR(T)                                                        \
    friend std::ostream& operator<<(std::ostream& os, T const& x) {                      \
        yenxo::ostreamImpl(os, x);                                                       \
        return os;                                                                       \
    }

/// Enables `std::ostream& operator<<(std::ostream&, T)` for `T`
/// \ingroup group-traits-opt-in
/// \pre `T` should be `toVariantConvertible()`.
///
/// The ostream operator dumps the JSON of the value.
#define YENXO_JSON_OSTREAM_OPERATOR(T)                                                   \
    friend std::ostream& operator<<(std::ostream& os, T const& x) {                      \
        return os << yenxo::toVariant(x).toPrettyJson();                                 \
    }

max_stars_repo_name: nicktrandafil/serialize

max_issues_repo_name: nicktrandafil/yenxo

max_forks_repo_name: nicktrandafil/yenxo


text:
/*  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 *
 *  Gearmand client and server library.
 *
 *  Copyright (C) 2011 Data Differential, http://datadifferential.com/
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are
 *  met:
 *
 *      * Redistributions of source code must retain the above copyright
 *  notice, this list of conditions and the following disclaimer.
 *
 *      * Redistributions in binary form must reproduce the above
 *  copyright notice, this list of conditions and the following disclaimer
 *  in the documentation and/or other materials provided with the
 *  distribution.
 *
 *      * The names of its contributors may not be used to endorse or
 *  promote products derived from this software without specific prior
 *  written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 *  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 *  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include "gear_config.h"

#include <iostream>

#include <boost/program_options.hpp>

#include "libgearman-server/common.h"
#include <libgearman-server/queue.h>
#include <libgearman-server/plugins/queue/base.h>
#include <libgearman-server/queue.hpp>
#include <libgearman-server/log.h>

#include <assert.h>

gearmand_error_t gearman_queue_add(gearman_server_st *server,
                                   const char *unique,
                                   size_t unique_size,
                                   const char *function_name,
                                   size_t function_name_size,
                                   const void *data,
                                   size_t data_size,
                                   gearman_job_priority_t priority,
                                   int64_t when)
{
  assert(server->state.queue_startup == false);
  gearmand_error_t ret;
  if (server->queue_version == QUEUE_VERSION_NONE)
  {
    return GEARMAND_SUCCESS;
  }
  else if (server->queue_version == QUEUE_VERSION_FUNCTION)
  {
    assert(server->queue.functions->_add_fn);
    ret= (*(server->queue.functions->_add_fn))(server,
                                               (void *)server->queue.functions->_context,
                                               unique, unique_size,
                                               function_name,
                                               function_name_size,
                                               data, data_size, priority,
                                               when);
  }
  else
  {
    assert(server->queue.object);
    ret= server->queue.object->store(server,
                                     unique, unique_size,
                                     function_name,
                                     function_name_size,
                                     data, data_size, priority,
                                     when);
  }

  if (gearmand_success(ret))
  {
    ret= gearman_queue_flush(server);
  }

  return ret;
}

gearmand_error_t gearman_queue_flush(gearman_server_st *server)
{
  if (server->queue_version != QUEUE_VERSION_NONE)
  {
    if (server->queue_version == QUEUE_VERSION_FUNCTION)
    {
      assert(server->queue.functions->_flush_fn);
      return (*(server->queue.functions->_flush_fn))(server, (void *)server->queue.functions->_context);
    }

    assert(server->queue.object);
    return server->queue.object->flush(server);
  }

  return GEARMAND_SUCCESS;
}

gearmand_error_t gearman_queue_done(gearman_server_st *server,
                                    const char *unique,
                                    size_t unique_size,
                                    const char *function_name,
                                    size_t function_name_size)
{
  if (server->queue_version == QUEUE_VERSION_NONE)
  {
    return GEARMAND_SUCCESS;
  }
  else if (server->queue_version == QUEUE_VERSION_FUNCTION)
  {
    assert(server->queue.functions->_done_fn);
    return (*(server->queue.functions->_done_fn))(server,
                                                  (void *)server->queue.functions->_context,
                                                  unique, unique_size,
                                                  function_name,
                                                  function_name_size);
  }
  else
  {
    assert(server->queue.object);
    return server->queue.object->done(server,
                                      unique, unique_size,
                                      function_name,
                                      function_name_size);
  }
}

void gearman_server_save_job(gearman_server_st& server,
                             const gearman_server_job_st* server_job)
{
  if (server.queue_version == QUEUE_VERSION_CLASS)
  {
    assert(server.queue.object);
    server.queue.object->save_job(server, server_job);
  }
}

void gearman_server_set_queue(gearman_server_st& server,
                              void *context,
                              gearman_queue_add_fn *add,
                              gearman_queue_flush_fn *flush,
                              gearman_queue_done_fn *done,
                              gearman_queue_replay_fn *replay)
{
  delete server.queue.functions;
  server.queue.functions= NULL;
  delete server.queue.object;
  server.queue.object= NULL;

  if (add)
  {
    server.queue_version= QUEUE_VERSION_FUNCTION;
    server.queue.functions= new queue_st();
    if (server.queue.functions)
    {
      server.queue.functions->_context= context;
      server.queue.functions->_add_fn= add;
      server.queue.functions->_flush_fn= flush;
      server.queue.functions->_done_fn= done;
      server.queue.functions->_replay_fn= replay;
    }
    assert(server.queue.functions);
  }
  else
  {
    server.queue_version= QUEUE_VERSION_NONE;
  }
}

void gearman_server_set_queue(gearman_server_st& server,
                              gearmand::queue::Context* context)
{
  delete server.queue.functions;
  server.queue.functions= NULL;
  delete server.queue.object;
  server.queue.object= NULL;
  assert(context);
  {
    server.queue_version= QUEUE_VERSION_CLASS;
    server.queue.object= context;
  }
}

namespace gearmand {

namespace queue {

plugins::Queue::vector all_queue_modules;

void add(plugins::Queue* arg)
{
  all_queue_modules.push_back(arg);
}

void load_options(boost::program_options::options_description &all)
{
  for (plugins::Queue::vector::iterator iter= all_queue_modules.begin();
       iter != all_queue_modules.end();
       ++iter)
  {
    all.add((*iter)->command_line_options());
  }
}

gearmand_error_t initialize(gearmand_st *, std::string name)
{
  bool launched= false;

  if (name.empty())
  {
    return GEARMAND_SUCCESS;
  }

  std::transform(name.begin(), name.end(), name.begin(), ::tolower);

  for (plugins::Queue::vector::iterator iter= all_queue_modules.begin();
       iter != all_queue_modules.end();
       ++iter)
  {
    if ((*iter)->compare(name) == 0)
    {
      if (launched)
      {
        return gearmand_gerror("Attempt to initialize multiple queues", GEARMAND_UNKNOWN_OPTION);
      }

      gearmand_error_t rc;
      if (gearmand_failed(rc= (*iter)->initialize()))
      {
        return gearmand_log_gerror(GEARMAN_DEFAULT_LOG_PARAM, rc,
                                   "Failed to initialize %s: %s", name.c_str(), (*iter)->error_string().c_str());
      }

      launched= true;
    }
  }

  if (launched == false)
  {
    return gearmand_log_gerror(GEARMAN_DEFAULT_LOG_PARAM, GEARMAND_UNKNOWN_OPTION, "Unknown queue %s", name.c_str());
  }

  return GEARMAND_SUCCESS;
}

} // namespace queue
} // namespace gearmand

max_stars_repo_name: alionurdemetoglu/gearmand

max_issues_repo_name: alionurdemetoglu/gearmand

max_forks_repo_name: alionurdemetoglu/gearmand