<commit_before>#include "queueable.h"

#include <list>
#include <map>
#include <stdio.h>
#include <stdlib.h>
#include <sstream>
#include <string>
#include <string.h>
#include <stdint.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <vector>

void Queueable::run_tests(std::map<std::string, std::string> options)
{
    this->options = options;
    int max_msg_size = get_max_msg_size();
    int max_threads = get_max_threads();

    for (int i = 1; i <= max_threads; i *= 2)
    {
        for (int j = 1; j <= max_msg_size; j *= 2)
        {
            threads = i;
            msg_size = j;
            run_test();
        }
    }
}

// Run a single test with this backend
void Queueable::run_test()
{

    // Set default options
    child = false;
    parent = false;
    children.clear();

    D fprintf(stderr, "before_fork()\n");
    before_fork();

    D fprintf(stderr, "perform_fork()\n");
    perform_fork();

    D fprintf(stderr, "after_fork(), parent = %d, child = %d\n", parent, child);
    after_fork();

    D fprintf(stderr, "finished after_fork(), parent = %d, child = %d\n", parent, child);

    // Start timer, run test, stop timer
    std::string msg = "enqueue ";
    msg.append(options["items"]);
    msg.append(" items of size ");
    std::stringstream ss("");
    ss << msg_size;
    msg.append(ss.str());

    start_test(msg);
    if (parent == true)
    {
        test_enqueue(get_items(), msg_size);
    }
    else if (child == true)
    {
        test_dequeue();
    }

    D fprintf(stderr, "cleanup, parent = %d, child = %d\n", parent, child);
    cleanup();
    perform_wait();
    stop_test();
}

void Queueable::perform_fork()
{
    for (int i = 0; i < threads; ++i)
    {
        child = false;
        parent = false;
        pid_t pid = fork();

        if (pid == 0) // child
        {
            child = true;
            thread_id = i;
            break;
        }
        else if (pid > 0) // parent
        {
            parent = true;
            children.push_back((int) pid);
        }
        else // error
        {
            parent = false;
            child = false;
            perror("fork failed");
        }
    }
}

void Queueable::start_test(std::string msg)
{
    test_message = msg;
    gettimeofday(&start_tv, NULL);
}

void Queueable::stop_test()
{
    gettimeofday(&stop_tv, NULL);

    timersub(&stop_tv, &start_tv, &duration);

    print_results();
}

void Queueable::print_results()
{
    printf("<test>");
    printf("<type>%s</type>", backend_name());
    printf("<name>%d-thread</name>", threads);
    printf("<seconds>%ld.%06ld</seconds>", duration.tv_sec, duration.tv_usec);
    printf("<msg_size>%d</msg_size>", msg_size);
    printf("</test>\n");
}

void Queueable::test_enqueue(int num_items, uint32_t msg_size)
{
    std::vector<std::string> items;
    char * buffer = NULL;
    items.reserve(1000);

    buffer = (char *) malloc(msg_size);

    // Build 1000 item vector with desired message size
    for (int i = 0; i < 1000; ++i)
    {
        std::string str;
        str.reserve(msg_size);
        str.append(buffer, msg_size);
        items.push_back(str);
    }
    free(buffer);

    for (int i = 0; i < num_items/1000; ++i)
    {
        enqueue(&items);
    }
}

void Queueable::test_dequeue()
{
    std::vector<std::string> items;

    do
    {
        items.clear();
        dequeue(&items);
    }
    while (items.size() > 0);
}

void Queueable::perform_wait()
{
    int status = 0;
    std::list<int>::iterator it;

    if (parent == true)
    {
        for (it = children.begin(); it != children.end(); ++it)
        {
            D fprintf(stderr, "waiting for pid %d\n", *it);
            if (waitpid(*it, &status, 0) < 0)
                perror("waitpid fail");
        }
    }
    else if (child == true)
    {
        exit(0);
    }
}

int Queueable::get_max_threads()
{
    std::stringstream ss(options["max_threads"]);
    int tmp;
    ss >> tmp;

    return tmp;
}

int Queueable::get_items()
{
    std::stringstream ss(options["items"]);
    int items;
    ss >> items;

    return items;
}

int Queueable::get_port()
{
    std::stringstream ss(options["port"]);
    int port;
    ss >> port;

    return port;
}

int Queueable::get_max_msg_size()
{
    std::stringstream ss(options["max_msg_size"]);
    int size;
    ss >> size;

    return size;
}
<commit_msg>Change 'name' to 'threads' in output<commit_after>#include "queueable.h"

#include <list>
#include <map>
#include <stdio.h>
#include <stdlib.h>
#include <sstream>
#include <string>
#include <string.h>
#include <stdint.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <vector>

void Queueable::run_tests(std::map<std::string, std::string> options)
{
    this->options = options;
    int max_msg_size = get_max_msg_size();
    int max_threads = get_max_threads();

    for (int i = 1; i <= max_threads; i *= 2)
    {
        for (int j = 1; j <= max_msg_size; j *= 2)
        {
            threads = i;
            msg_size = j;
            run_test();
        }
    }
}

// Run a single test with this backend
void Queueable::run_test()
{

    // Set default options
    child = false;
    parent = false;
    children.clear();

    D fprintf(stderr, "before_fork()\n");
    before_fork();

    D fprintf(stderr, "perform_fork()\n");
    perform_fork();

    D fprintf(stderr, "after_fork(), parent = %d, child = %d\n", parent, child);
    after_fork();

    D fprintf(stderr, "finished after_fork(), parent = %d, child = %d\n", parent, child);

    // Start timer, run test, stop timer
    std::string msg = "enqueue ";
    msg.append(options["items"]);
    msg.append(" items of size ");
    std::stringstream ss("");
    ss << msg_size;
    msg.append(ss.str());

    start_test(msg);
    if (parent == true)
    {
        test_enqueue(get_items(), msg_size);
    }
    else if (child == true)
    {
        test_dequeue();
    }

    D fprintf(stderr, "cleanup, parent = %d, child = %d\n", parent, child);
    cleanup();
    perform_wait();
    stop_test();
}

void Queueable::perform_fork()
{
    for (int i = 0; i < threads; ++i)
    {
        child = false;
        parent = false;
        pid_t pid = fork();

        if (pid == 0) // child
        {
            child = true;
            thread_id = i;
            break;
        }
        else if (pid > 0) // parent
        {
            parent = true;
            children.push_back((int) pid);
        }
        else // error
        {
            parent = false;
            child = false;
            perror("fork failed");
        }
    }
}

void Queueable::start_test(std::string msg)
{
    test_message = msg;
    gettimeofday(&start_tv, NULL);
}

void Queueable::stop_test()
{
    gettimeofday(&stop_tv, NULL);

    timersub(&stop_tv, &start_tv, &duration);

    print_results();
}

void Queueable::print_results()
{
    printf("<test>");
    printf("<type>%s</type>", backend_name());
    printf("<threads>%d</threads>", threads);
    printf("<seconds>%ld.%06ld</seconds>", duration.tv_sec, duration.tv_usec);
    printf("<msg_size>%d</msg_size>", msg_size);
    printf("</test>\n");
}

void Queueable::test_enqueue(int num_items, uint32_t msg_size)
{
    std::vector<std::string> items;
    char * buffer = NULL;
    items.reserve(1000);

    buffer = (char *) malloc(msg_size);

    // Build 1000 item vector with desired message size
    for (int i = 0; i < 1000; ++i)
    {
        std::string str;
        str.reserve(msg_size);
        str.append(buffer, msg_size);
        items.push_back(str);
    }
    free(buffer);

    for (int i = 0; i < num_items/1000; ++i)
    {
        enqueue(&items);
    }
}

void Queueable::test_dequeue()
{
    std::vector<std::string> items;

    do
    {
        items.clear();
        dequeue(&items);
    }
    while (items.size() > 0);
}

void Queueable::perform_wait()
{
    int status = 0;
    std::list<int>::iterator it;

    if (parent == true)
    {
        for (it = children.begin(); it != children.end(); ++it)
        {
            D fprintf(stderr, "waiting for pid %d\n", *it);
            if (waitpid(*it, &status, 0) < 0)
                perror("waitpid fail");
        }
    }
    else if (child == true)
    {
        exit(0);
    }
}

int Queueable::get_max_threads()
{
    std::stringstream ss(options["max_threads"]);
    int tmp;
    ss >> tmp;

    return tmp;
}

int Queueable::get_items()
{
    std::stringstream ss(options["items"]);
    int items;
    ss >> items;

    return items;
}

int Queueable::get_port()
{
    std::stringstream ss(options["port"]);
    int port;
    ss >> port;

    return port;
}

int Queueable::get_max_msg_size()
{
    std::stringstream ss(options["max_msg_size"]);
    int size;
    ss >> size;

    return size;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012-2016 Justin Karneges
 *
 * 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.
 */

#include "qzmqvalve.h"

#include <QPointer>
#include "qzmqsocket.h"

namespace QZmq {

class Valve::Private : public QObject
{
	Q_OBJECT

public:
	Valve *q;
	QZmq::Socket *sock;
	bool isOpen;
	bool pendingRead;
	int maxReadsPerEvent;

	Private(Valve *_q) :
		QObject(_q),
		q(_q),
		sock(0),
		isOpen(false),
		pendingRead(false),
		maxReadsPerEvent(100)
	{
	}

	void setup(QZmq::Socket *_sock)
	{
		sock = _sock;
		connect(sock, SIGNAL(readyRead()), SLOT(sock_readyRead()));
	}

	void queueRead()
	{
		if(pendingRead)
			return;

		pendingRead = true;
		QMetaObject::invokeMethod(this, "queuedRead", Qt::QueuedConnection);
	}

	void tryRead()
	{
		QPointer<QObject> self = this;

		int count = 0;
		while(isOpen && sock->canRead())
		{
			if(count >= maxReadsPerEvent)
			{
				queueRead();
				return;
			}

			QList<QByteArray> msg = sock->read();
			emit q->readyRead(msg);
			if(!self)
				return;

			++count;
		}
	}

private slots:
	void sock_readyRead()
	{
		if(pendingRead)
			return;

		tryRead();
	}

	void queuedRead()
	{
		pendingRead = false;
		tryRead();
	}
};

Valve::Valve(QZmq::Socket *sock, QObject *parent) :
	QObject(parent)
{
	d = new Private(this);
	d->setup(sock);
}

Valve::~Valve()
{
	delete d;
}

bool Valve::isOpen() const
{
	return d->isOpen;
}

void Valve::setMaxReadsPerEvent(int max)
{
	d->maxReadsPerEvent = max;
}

void Valve::open()
{
	if(!d->isOpen)
	{
		d->isOpen = true;
		if(!d->pendingRead && d->sock->canRead())
			d->queueRead();
	}
}

void Valve::close()
{
	d->isOpen = false;
}

}

#include "qzmqvalve.moc"
<commit_msg>valve: empty reads are errors, ignore them<commit_after>/*
 * Copyright (C) 2012-2020 Justin Karneges
 *
 * 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.
 */

#include "qzmqvalve.h"

#include <QPointer>
#include "qzmqsocket.h"

namespace QZmq {

class Valve::Private : public QObject
{
	Q_OBJECT

public:
	Valve *q;
	QZmq::Socket *sock;
	bool isOpen;
	bool pendingRead;
	int maxReadsPerEvent;

	Private(Valve *_q) :
		QObject(_q),
		q(_q),
		sock(0),
		isOpen(false),
		pendingRead(false),
		maxReadsPerEvent(100)
	{
	}

	void setup(QZmq::Socket *_sock)
	{
		sock = _sock;
		connect(sock, SIGNAL(readyRead()), SLOT(sock_readyRead()));
	}

	void queueRead()
	{
		if(pendingRead)
			return;

		pendingRead = true;
		QMetaObject::invokeMethod(this, "queuedRead", Qt::QueuedConnection);
	}

	void tryRead()
	{
		QPointer<QObject> self = this;

		int count = 0;
		while(isOpen && sock->canRead())
		{
			if(count >= maxReadsPerEvent)
			{
				queueRead();
				return;
			}

			QList<QByteArray> msg = sock->read();

			if(!msg.isEmpty())
			{
				emit q->readyRead(msg);
				if(!self)
					return;
			}

			++count;
		}
	}

private slots:
	void sock_readyRead()
	{
		if(pendingRead)
			return;

		tryRead();
	}

	void queuedRead()
	{
		pendingRead = false;
		tryRead();
	}
};

Valve::Valve(QZmq::Socket *sock, QObject *parent) :
	QObject(parent)
{
	d = new Private(this);
	d->setup(sock);
}

Valve::~Valve()
{
	delete d;
}

bool Valve::isOpen() const
{
	return d->isOpen;
}

void Valve::setMaxReadsPerEvent(int max)
{
	d->maxReadsPerEvent = max;
}

void Valve::open()
{
	if(!d->isOpen)
	{
		d->isOpen = true;
		if(!d->pendingRead && d->sock->canRead())
			d->queueRead();
	}
}

void Valve::close()
{
	d->isOpen = false;
}

}

#include "qzmqvalve.moc"
<|endoftext|>


<commit_before>#include <cmath>
#include <exception>
#include <iostream>
#include <fstream>
#include <memory>
#include <vector>

#include <json/src/json.hpp>

#include <common_types.hpp>
#include <cell.hpp>
#include <cell_group.hpp>
#include <communication/communicator.hpp>
#include <communication/global_policy.hpp>
#include <fvm_cell.hpp>
#include <io/exporter_spike_file.hpp>
#include <mechanism_catalogue.hpp>
#include <model.hpp>
#include <profiling/profiler.hpp>
#include <threading/threading.hpp>
#include <util/ioutil.hpp>
#include <util/nop.hpp>
#include <util/optional.hpp>

#include "io.hpp"
#include "miniapp_recipes.hpp"
#include "trace_sampler.hpp"

using namespace nest::mc;

using global_policy = communication::global_policy;
using lowered_cell = fvm::fvm_cell<double, cell_local_size_type>;
using model_type = model<lowered_cell>;
using time_type = model_type::time_type;
using sample_trace_type = sample_trace<time_type, model_type::value_type>;
using file_export_type = io::exporter_spike_file<time_type, global_policy>;
void banner();
std::unique_ptr<recipe> make_recipe(const io::cl_options&, const probe_distribution&);
std::unique_ptr<sample_trace_type> make_trace(cell_member_type probe_id, probe_spec probe);
std::pair<cell_gid_type, cell_gid_type> distribute_cells(cell_size_type ncells);
using communicator_type = communication::communicator<time_type, communication::global_policy>;
using spike_type = typename communicator_type::spike_type;

void write_trace_json(const sample_trace_type& trace, const std::string& prefix = "trace_");

int main(int argc, char** argv) {
    nest::mc::communication::global_policy_guard global_guard(argc, argv);

    try {
        std::cout << util::mask_stream(global_policy::id()==0);
        banner();

        // read parameters
        io::cl_options options = io::read_options(argc, argv);
        std::cout << options << "\n";
        std::cout << "\n";
        std::cout << ":: simulation to " << options.tfinal << " ms in "
                  << std::ceil(options.tfinal / options.dt) << " steps of "
                  << options.dt << " ms" << std::endl;

        // determine what to attach probes to
        probe_distribution pdist;
        pdist.proportion = options.probe_ratio;
        pdist.all_segments = !options.probe_soma_only;

        auto recipe = make_recipe(options, pdist);
        auto cell_range = distribute_cells(recipe->num_cells());

        model_type m(*recipe, cell_range.first, cell_range.second);

        auto register_exporter = [] (const io::cl_options& options) {
            return
                util::make_unique<file_export_type>(
                    options.file_name, options.output_path,
                    options.file_extension, options.over_write);
        };

        // File output is depending on the input arguments
        std::unique_ptr<file_export_type> file_exporter;
        if (options.spike_file_output) {
            auto id = communication::global_policy::id();
            if (options.single_file_per_rank) {
                file_exporter = register_exporter(options);
                m.set_local_spike_callback(
                    [&](const std::vector<spike_type>& spikes) {
                        file_exporter->output(spikes);
                    });
            }
            else if(communication::global_policy::id()==0) {
                file_exporter = register_exporter(options);
                m.set_global_spike_callback(
                    [&](const std::vector<spike_type>& spikes) {
                       file_exporter->output(spikes);
                    });
            }
        }

        // inject some artificial spikes, 1 per 20 neurons.
        cell_gid_type spike_cell = 20*((cell_range.first+19)/20);
        for (; spike_cell<cell_range.second; spike_cell+=20) {
            m.add_artificial_spike({spike_cell,0u});
        }

        // attach samplers to all probes
        std::vector<std::unique_ptr<sample_trace_type>> traces;
        const model_type::time_type sample_dt = 0.1;
        for (auto probe: m.probes()) {
            if (options.trace_max_gid && probe.id.gid>*options.trace_max_gid) {
                continue;
            }

            traces.push_back(make_trace(probe.id, probe.probe));
            m.attach_sampler(probe.id, make_trace_sampler(traces.back().get(),sample_dt));
        }

        // run model
        m.run(options.tfinal, options.dt);
        util::profiler_output(0.001);

        std::cout << "there were " << m.num_spikes() << " spikes\n";

        // save traces
        for (const auto& trace: traces) {
            write_trace_json(*trace.get(), options.trace_prefix);
        }
    }
    catch (io::usage_error& e) {
        // only print usage/startup errors on master
        std::cerr << util::mask_stream(global_policy::id()==0);
        std::cerr << e.what() << "\n";
        return 1;
    }
    catch (std::exception& e) {
        std::cerr << e.what() << "\n";
        return 2;
    }
    return 0;
}

std::pair<cell_gid_type, cell_gid_type> distribute_cells(cell_size_type num_cells) {
    // Crude load balancing:
    // divide [0, num_cells) into num_domains non-overlapping, contiguous blocks
    // of size as close to equal as possible.

    auto num_domains = communication::global_policy::size();
    auto domain_id = communication::global_policy::id();

    cell_gid_type cell_from = (cell_gid_type)(num_cells*(domain_id/(double)num_domains));
    cell_gid_type cell_to = (cell_gid_type)(num_cells*((domain_id+1)/(double)num_domains));

    return {cell_from, cell_to};
}

void banner() {
    std::cout << "====================\n";
    std::cout << "  starting miniapp\n";
    std::cout << "  - " << threading::description() << " threading support\n";
    std::cout << "  - communication policy: " << global_policy::name() << "\n";
    std::cout << "====================\n";
}

std::unique_ptr<recipe> make_recipe(const io::cl_options& options, const probe_distribution& pdist) {
    basic_recipe_param p;

    p.num_compartments = options.compartments_per_segment;
    p.num_synapses = options.all_to_all? options.cells-1: options.synapses_per_cell;
    p.synapse_type = options.syn_type;

    if (options.all_to_all) {
        return make_basic_kgraph_recipe(options.cells, p, pdist);
    }
    else {
        return make_basic_rgraph_recipe(options.cells, p, pdist);
    }
}

std::unique_ptr<sample_trace_type> make_trace(cell_member_type probe_id, probe_spec probe) {
    std::string name = "";
    std::string units = "";

    switch (probe.kind) {
    case probeKind::membrane_voltage:
        name = "v";
        units = "mV";
        break;
    case probeKind::membrane_current:
        name = "i";
        units = "mA/cm²";
        break;
    default: ;
    }
    name += probe.location.segment? "dend" : "soma";

    return util::make_unique<sample_trace_type>(probe_id, name, units);
}

void write_trace_json(const sample_trace_type& trace, const std::string& prefix) {
    auto path = prefix + std::to_string(trace.probe_id.gid) +
                "." + std::to_string(trace.probe_id.index) + "_" + trace.name + ".json";

    nlohmann::json jrep;
    jrep["name"] = trace.name;
    jrep["units"] = trace.units;
    jrep["cell"] = trace.probe_id.gid;
    jrep["probe"] = trace.probe_id.index;

    auto& jt = jrep["data"]["time"];
    auto& jy = jrep["data"][trace.name];

    for (const auto& sample: trace.samples) {
        jt.push_back(sample.time);
        jy.push_back(sample.value);
    }
    std::ofstream file(path);
    file << std::setw(1) << jrep << std::endl;
}
<commit_msg>remove unused variable<commit_after>#include <cmath>
#include <exception>
#include <iostream>
#include <fstream>
#include <memory>
#include <vector>

#include <json/src/json.hpp>

#include <common_types.hpp>
#include <cell.hpp>
#include <cell_group.hpp>
#include <communication/communicator.hpp>
#include <communication/global_policy.hpp>
#include <fvm_cell.hpp>
#include <io/exporter_spike_file.hpp>
#include <mechanism_catalogue.hpp>
#include <model.hpp>
#include <profiling/profiler.hpp>
#include <threading/threading.hpp>
#include <util/ioutil.hpp>
#include <util/nop.hpp>
#include <util/optional.hpp>

#include "io.hpp"
#include "miniapp_recipes.hpp"
#include "trace_sampler.hpp"

using namespace nest::mc;

using global_policy = communication::global_policy;
using lowered_cell = fvm::fvm_cell<double, cell_local_size_type>;
using model_type = model<lowered_cell>;
using time_type = model_type::time_type;
using sample_trace_type = sample_trace<time_type, model_type::value_type>;
using file_export_type = io::exporter_spike_file<time_type, global_policy>;
void banner();
std::unique_ptr<recipe> make_recipe(const io::cl_options&, const probe_distribution&);
std::unique_ptr<sample_trace_type> make_trace(cell_member_type probe_id, probe_spec probe);
std::pair<cell_gid_type, cell_gid_type> distribute_cells(cell_size_type ncells);
using communicator_type = communication::communicator<time_type, communication::global_policy>;
using spike_type = typename communicator_type::spike_type;

void write_trace_json(const sample_trace_type& trace, const std::string& prefix = "trace_");

int main(int argc, char** argv) {
    nest::mc::communication::global_policy_guard global_guard(argc, argv);

    try {
        std::cout << util::mask_stream(global_policy::id()==0);
        banner();

        // read parameters
        io::cl_options options = io::read_options(argc, argv);
        std::cout << options << "\n";
        std::cout << "\n";
        std::cout << ":: simulation to " << options.tfinal << " ms in "
                  << std::ceil(options.tfinal / options.dt) << " steps of "
                  << options.dt << " ms" << std::endl;

        // determine what to attach probes to
        probe_distribution pdist;
        pdist.proportion = options.probe_ratio;
        pdist.all_segments = !options.probe_soma_only;

        auto recipe = make_recipe(options, pdist);
        auto cell_range = distribute_cells(recipe->num_cells());

        model_type m(*recipe, cell_range.first, cell_range.second);

        auto register_exporter = [] (const io::cl_options& options) {
            return
                util::make_unique<file_export_type>(
                    options.file_name, options.output_path,
                    options.file_extension, options.over_write);
        };

        // File output is depending on the input arguments
        std::unique_ptr<file_export_type> file_exporter;
        if (options.spike_file_output) {
            if (options.single_file_per_rank) {
                file_exporter = register_exporter(options);
                m.set_local_spike_callback(
                    [&](const std::vector<spike_type>& spikes) {
                        file_exporter->output(spikes);
                    });
            }
            else if(communication::global_policy::id()==0) {
                file_exporter = register_exporter(options);
                m.set_global_spike_callback(
                    [&](const std::vector<spike_type>& spikes) {
                       file_exporter->output(spikes);
                    });
            }
        }

        // inject some artificial spikes, 1 per 20 neurons.
        cell_gid_type spike_cell = 20*((cell_range.first+19)/20);
        for (; spike_cell<cell_range.second; spike_cell+=20) {
            m.add_artificial_spike({spike_cell,0u});
        }

        // attach samplers to all probes
        std::vector<std::unique_ptr<sample_trace_type>> traces;
        const model_type::time_type sample_dt = 0.1;
        for (auto probe: m.probes()) {
            if (options.trace_max_gid && probe.id.gid>*options.trace_max_gid) {
                continue;
            }

            traces.push_back(make_trace(probe.id, probe.probe));
            m.attach_sampler(probe.id, make_trace_sampler(traces.back().get(),sample_dt));
        }

        // run model
        m.run(options.tfinal, options.dt);
        util::profiler_output(0.001);

        std::cout << "there were " << m.num_spikes() << " spikes\n";

        // save traces
        for (const auto& trace: traces) {
            write_trace_json(*trace.get(), options.trace_prefix);
        }
    }
    catch (io::usage_error& e) {
        // only print usage/startup errors on master
        std::cerr << util::mask_stream(global_policy::id()==0);
        std::cerr << e.what() << "\n";
        return 1;
    }
    catch (std::exception& e) {
        std::cerr << e.what() << "\n";
        return 2;
    }
    return 0;
}

std::pair<cell_gid_type, cell_gid_type> distribute_cells(cell_size_type num_cells) {
    // Crude load balancing:
    // divide [0, num_cells) into num_domains non-overlapping, contiguous blocks
    // of size as close to equal as possible.

    auto num_domains = communication::global_policy::size();
    auto domain_id = communication::global_policy::id();

    cell_gid_type cell_from = (cell_gid_type)(num_cells*(domain_id/(double)num_domains));
    cell_gid_type cell_to = (cell_gid_type)(num_cells*((domain_id+1)/(double)num_domains));

    return {cell_from, cell_to};
}

void banner() {
    std::cout << "====================\n";
    std::cout << "  starting miniapp\n";
    std::cout << "  - " << threading::description() << " threading support\n";
    std::cout << "  - communication policy: " << global_policy::name() << "\n";
    std::cout << "====================\n";
}

std::unique_ptr<recipe> make_recipe(const io::cl_options& options, const probe_distribution& pdist) {
    basic_recipe_param p;

    p.num_compartments = options.compartments_per_segment;
    p.num_synapses = options.all_to_all? options.cells-1: options.synapses_per_cell;
    p.synapse_type = options.syn_type;

    if (options.all_to_all) {
        return make_basic_kgraph_recipe(options.cells, p, pdist);
    }
    else {
        return make_basic_rgraph_recipe(options.cells, p, pdist);
    }
}

std::unique_ptr<sample_trace_type> make_trace(cell_member_type probe_id, probe_spec probe) {
    std::string name = "";
    std::string units = "";

    switch (probe.kind) {
    case probeKind::membrane_voltage:
        name = "v";
        units = "mV";
        break;
    case probeKind::membrane_current:
        name = "i";
        units = "mA/cm²";
        break;
    default: ;
    }
    name += probe.location.segment? "dend" : "soma";

    return util::make_unique<sample_trace_type>(probe_id, name, units);
}

void write_trace_json(const sample_trace_type& trace, const std::string& prefix) {
    auto path = prefix + std::to_string(trace.probe_id.gid) +
                "." + std::to_string(trace.probe_id.index) + "_" + trace.name + ".json";

    nlohmann::json jrep;
    jrep["name"] = trace.name;
    jrep["units"] = trace.units;
    jrep["cell"] = trace.probe_id.gid;
    jrep["probe"] = trace.probe_id.index;

    auto& jt = jrep["data"]["time"];
    auto& jy = jrep["data"][trace.name];

    for (const auto& sample: trace.samples) {
        jt.push_back(sample.time);
        jy.push_back(sample.value);
    }
    std::ofstream file(path);
    file << std::setw(1) << jrep << std::endl;
}
<|endoftext|>


<commit_before>#include "reduction.hpp"
#include <algorithm>
#include <iostream>

using namespace std;

int getV(int n, int x){ return x > 0 ? x-1 : n-x-1; }
int sgn(int x){ return x == 0 ? 0 : (x > 0 ? 1 : -1); }

void rmMEMaxcut(wgraph &g){
	for(int i = 0; i < g.size(); i++){
		sort(g[i].begin(), g[i].end(),
			[](const edge &a, const edge &b){ return a.dst < b.dst; });
		for(int j = g[i].size()-1; j >= 0; j--){
			if(g[i][j].dst == g[i][j+1].dst){
				g[i][j].cst += g[i][j+1].cst;
				g[i][j+1].cst = 0;
			}
		}
		g[i].erase(remove_if(g[i].begin(), g[i].end(), [](const edge &a){ return a.cst == 0;}), g[i].end());
	}
}
void sat_indset(int n, const vector<vector<int> > &cnf, graph &g){
	g = graph(2*n);
	for(int i = 0; i < n; i++){ // variable gadget
		g[i].push_back(n+i);
		g[n+i].push_back(i);
	}
	int v = 2*n; // # of verteces
	for(int i = 0; i < cnf.size(); i++){
		for(int j = 0; j < cnf[i].size(); j++){
			int x = cnf[i][j];
			x = (x > 0 ? x-1 : n-x-1);
			g.push_back(vertex());
			// edge between variable gadget and CNF gadget
			g[x].push_back(v+j);
			g[v+j].push_back(x);
			for(int k = 0; k < j; k++){ // CNF gadget
				g[v+j].push_back(v+k);
				g[v+k].push_back(v+j);
			}
		}
	}
}

void naesat3_maxcut(int n, const vector<vector<int> > &cnf, wgraph &g, bool maximize){
	g = wgraph(2*n);
	for(int i = 0; i < cnf.size(); i++){
		int x[3];
		for(int j = 0; j < 3; j++) x[j] = getV(n, cnf[i][j]);
		for(int j = 0; j < 3; j++){
			int j2 = (j+1)%3;
			g[x[j]].push_back((edge){1, x[j2]});
			g[x[j2]].push_back((edge){1, x[j]});
		}
	}
	int w = 1;
	if(maximize){
		for(int i = 0; i < n; i++){
			w = max(w, min<int>(g[i].size(), g[n+i].size())+1);
		}
	}
	for(int i = 0; i < n; i++){
		g[i].push_back((edge){w, n+i});
		g[n+i].push_back((edge){w, i});
	}
	rmMEMaxcut(g);
}

void naesat3_maxcut2(int n, const vector<vector<int> > &cnf, wgraph &g){
	g = wgraph(n);
	for(int i = 0; i < cnf.size(); i++){
		int x[3];
		for(int j = 0; j < 3; j++) x[j] = abs(cnf[i][j])-1;
		for(int j = 0; j < 3; j++){
			int j2 = (j+1)%3;
			int ew = sgn(cnf[i][j])*sgn(cnf[i][j2]);
			g[x[j]].push_back((edge){ew, x[j2]});
			g[x[j2]].push_back((edge){ew, x[j]});
		}
	}
	rmMEMaxcut(g);
}

void sat_naesat(int n, const vector<vector<int> > &cnf, int &n2, vector<vector<int> > &cnf2){
	n2 = n+1;
	cnf2 = vector<vector<int> >(cnf);
	for(int i = 0; i < cnf2.size(); i++){
		cnf2[i].push_back(n2);
	}
}

void sat_sat3(int n, const vector<vector<int> > &cnf, int &n2, vector<vector<int> > &cnf2){
	n2 = n;
	cnf2.clear();
	for(int i = 0; i < n; i++){
		int l = cnf[i].size();
		if(l <= 3){
			cnf2.push_back(cnf[i]);
			while(l++ < 3) cnf2.back().push_back(cnf[i][0]);
			continue;
		}
		cnf2.push_back((vector<int>){cnf[i][0], cnf[i][1], n2+1});
		n2++;
		for(int j = 2; j < l-2; j++, n2++){
			cnf2.push_back((vector<int>){-n2, cnf[i][j], n2+1});
		}
		cnf2.push_back((vector<int>){-n2, cnf[i][l-2], cnf[i][l-1]});
	}
}

void indset_maxcut(const graph &g, wgraph &g2){
	int n = g.size();
	int n2 = n+1;
	g2 = wgraph(n2);
	for(int i = 0; i < n; i++){
		if(g[i].size() != 2){
			g2[i].push_back((edge){2-g[i].size(), n});
			g2[n].push_back((edge){2-g[i].size(), i});
		}
		for(int j = 0; j < g[i].size(); j++){
			g2[i].push_back((edge){1, g[i][j]});
		}
	}
}

void maxcut_isingModel(const wgraph &g, igraph &g2){
	int n = g.size();
	g2 = igraph(n);
	for(int i = 0; i < n; i++){
		for(int j = 0; j < g[i].size(); j++){
			g2[i].push_back((iedge){g[i][j].cst/2.0, g[i][j].dst});
		}
	}
}

<commit_msg>Fix style<commit_after>#include "reduction.hpp"
#include <algorithm>
#include <iostream>

using namespace std;

int getV(int n, int x){ return x > 0 ? x-1 : n-x-1; }
int sgn(int x){ return x == 0 ? 0 : (x > 0 ? 1 : -1); }

void rmMEMaxcut(wgraph &g){
	for(int i = 0; i < g.size(); i++){
		sort(g[i].begin(), g[i].end(),
			[](const edge &a, const edge &b){ return a.dst < b.dst; });
		for(int j = g[i].size()-1; j >= 0; j--){
			if(g[i][j].dst == g[i][j+1].dst){
				g[i][j].cst += g[i][j+1].cst;
				g[i][j+1].cst = 0;
			}
		}
		g[i].erase(remove_if(g[i].begin(), g[i].end(), [](const edge &a){ return a.cst == 0;}), g[i].end());
	}
}

void sat_indset(int n, const vector<vector<int> > &cnf, graph &g){
	g = graph(2*n);
	for(int i = 0; i < n; i++){ // variable gadget
		g[i].push_back(n+i);
		g[n+i].push_back(i);
	}
	int v = 2*n; // # of verteces
	for(int i = 0; i < cnf.size(); i++){
		for(int j = 0; j < cnf[i].size(); j++){
			int x = cnf[i][j];
			x = (x > 0 ? x-1 : n-x-1);
			g.push_back(vertex());
			// edge between variable gadget and CNF gadget
			g[x].push_back(v+j);
			g[v+j].push_back(x);
			for(int k = 0; k < j; k++){ // CNF gadget
				g[v+j].push_back(v+k);
				g[v+k].push_back(v+j);
			}
		}
	}
}

void naesat3_maxcut(int n, const vector<vector<int> > &cnf, wgraph &g, bool maximize){
	g = wgraph(2*n);
	for(int i = 0; i < cnf.size(); i++){
		int x[3];
		for(int j = 0; j < 3; j++) x[j] = getV(n, cnf[i][j]);
		for(int j = 0; j < 3; j++){
			int j2 = (j+1)%3;
			g[x[j]].push_back((edge){1, x[j2]});
			g[x[j2]].push_back((edge){1, x[j]});
		}
	}
	int w = 1;
	if(maximize){
		for(int i = 0; i < n; i++){
			w = max(w, min<int>(g[i].size(), g[n+i].size())+1);
		}
	}
	for(int i = 0; i < n; i++){
		g[i].push_back((edge){w, n+i});
		g[n+i].push_back((edge){w, i});
	}
	rmMEMaxcut(g);
}

void naesat3_maxcut2(int n, const vector<vector<int> > &cnf, wgraph &g){
	g = wgraph(n);
	for(int i = 0; i < cnf.size(); i++){
		int x[3];
		for(int j = 0; j < 3; j++) x[j] = abs(cnf[i][j])-1;
		for(int j = 0; j < 3; j++){
			int j2 = (j+1)%3;
			int ew = sgn(cnf[i][j])*sgn(cnf[i][j2]);
			g[x[j]].push_back((edge){ew, x[j2]});
			g[x[j2]].push_back((edge){ew, x[j]});
		}
	}
	rmMEMaxcut(g);
}

void sat_naesat(int n, const vector<vector<int> > &cnf, int &n2, vector<vector<int> > &cnf2){
	n2 = n+1;
	cnf2 = vector<vector<int> >(cnf);
	for(int i = 0; i < cnf2.size(); i++){
		cnf2[i].push_back(n2);
	}
}

void sat_sat3(int n, const vector<vector<int> > &cnf, int &n2, vector<vector<int> > &cnf2){
	n2 = n;
	cnf2.clear();
	for(int i = 0; i < n; i++){
		int l = cnf[i].size();
		if(l <= 3){
			cnf2.push_back(cnf[i]);
			while(l++ < 3) cnf2.back().push_back(cnf[i][0]);
			continue;
		}
		cnf2.push_back((vector<int>){cnf[i][0], cnf[i][1], n2+1});
		n2++;
		for(int j = 2; j < l-2; j++, n2++){
			cnf2.push_back((vector<int>){-n2, cnf[i][j], n2+1});
		}
		cnf2.push_back((vector<int>){-n2, cnf[i][l-2], cnf[i][l-1]});
	}
}

void indset_maxcut(const graph &g, wgraph &g2){
	int n = g.size();
	int n2 = n+1;
	g2 = wgraph(n2);
	for(int i = 0; i < n; i++){
		if(g[i].size() != 2){
			g2[i].push_back((edge){2-g[i].size(), n});
			g2[n].push_back((edge){2-g[i].size(), i});
		}
		for(int j = 0; j < g[i].size(); j++){
			g2[i].push_back((edge){1, g[i][j]});
		}
	}
}

void maxcut_isingModel(const wgraph &g, igraph &g2){
	int n = g.size();
	g2 = igraph(n);
	for(int i = 0; i < n; i++){
		for(int j = 0; j < g[i].size(); j++){
			g2[i].push_back((iedge){g[i][j].cst/2.0, g[i][j].dst});
		}
	}
}
<|endoftext|>


<commit_before>/***********************************************
 * Author: Jun Jiang - jiangjun4@sina.com
 * Create: 2017-09-05 16:04
 * Last modified : 2017-09-06 14:42
 * Filename	  : Layer.cpp
 * Description   : RNN network Layer
 **********************************************/
#include "rnn/Layer.h"

namespace abcdl{
namespace rnn{

void Layer::farward(const abcdl::algebra::Mat& train_seq_data,
					const abcdl::algebra::Mat& weight,
					const abcdl::algebra::Mat& pre_weight,
					const abcdl::algebra::Mat& act_weight,
					abcdl::algebra::Mat& state,
					abcdl::algebra::Mat& activation){

	size_t seq_rows = train_seq_data.rows();
	size_t seq_cols = train_seq_data.cols();
	state.reset(0, seq_rows, _hidden_dim);
	activation.reset(0, seq_rows, seq_cols);

	abcdl::algebra::Mat s_t;
	for(size_t t = 0; t != seq_rows; t++){
		//s[t] = tanh(U*x[t] + W*s[t-1])
		//o[t] = softmax(V* s[t])
		if(t > 0){
			s_t = (helper.dot(weight, train_seq_data.get_row(t).transpose()) + helper.dot(pre_weight, state.get_row(t - 1).transpose())).tanh();
		}else{
			s_t = helper.dot(weight, train_seq_data.get_row(t).transpose()).tanh();
		}

		state.set_row(t, s_t.Ts());
		activation.set_row(t, helper.dot(act_weight, s_t).softmax().transpose());
	}
}

void Layer::backward(const abcdl::algebra::Mat& train_seq_data,
					 const abcdl::algebra::Mat& train_seq_label,
					 abcdl::algebra::Mat& weight,
					 abcdl::algebra::Mat& pre_weight,
					 abcdl::algebra::Mat& act_weight,
					 const abcdl::algebra::Mat& state,
					 const abcdl::algebra::Mat& activation,
					 abcdl::algebra::Mat& derivate_weight,
					 abcdl::algebra::Mat& derivate_pre_weight,
					 abcdl::algebra::Mat& derivate_act_weight){
	abcdl::algebra::Mat derivate_output;
	_cost->delta(derivate_output, activation,train_seq_label);

	size_t seq_size = train_seq_data.rows();
	for(size_t s = seq_size; s != 0 ; s--){
		size_t t = s - 1;
		auto derivate_output_t = derivate_output.get_row(t).transpose();
		auto state_t = state.get_row(t).transpose();

        //update derivate_act_weight
		derivate_act_weight += helper.outer(derivate_output_t, state_t);

        //calc derivate_t
		abcdl::algebra::Mat state_derivate;
		helper.sigmoid_derivative(state_derivate, state_t);
		auto derivate_t = helper.dot(act_weight.Ts(), derivate_output_t) * state_derivate;

		//back_propagation steps
		for(size_t step = 0; step < _bptt_truncate && step <= t; step++){
			size_t bptt_step = t - step;
			abcdl::algebra::Mat derivate_state_t;
			if(bptt_step > 0){
				state.get_row(&derivate_state_t, bptt_step - 1);
			}else{
				derivate_state_t.reset(0, state.cols(), 1);
			}

            //update derivate_pre_weight
			derivate_pre_weight += helper.outer(derivate_t, derivate_state_t.transpose());

            //update derivate_weight
			auto train_data_t = train_seq_data.get_row(bptt_step).transpose();
            auto derivate_weight_t = helper.dot(derivate_weight, train_data_t) + derivate_t;

            size_t idx = train_data_t.argmax(0, abcdl::algebra::Axis_type::ROW);
            derivate_weight.set_col(idx, derivate_weight.get_col(idx) + derivate_weight_t);

			//update delta
			if(bptt_step > 0){
				helper.sigmoid_derivative(derivate_state_t, derivate_state_t);
				derivate_t = pre_weight.Ts().dot(derivate_t) * derivate_state_t;
			}
		}
	}
}

}//namespace rnn
}//namespace abcdl
<commit_msg>code style<commit_after>/***********************************************
 * Author: Jun Jiang - jiangjun4@sina.com
 * Create: 2017-09-05 16:04
 * Last modified : 2017-09-06 14:42
 * Filename	  : Layer.cpp
 * Description   : RNN network Layer
 **********************************************/
#include "rnn/Layer.h"

namespace abcdl{
namespace rnn{

void Layer::farward(const abcdl::algebra::Mat& train_seq_data,
					const abcdl::algebra::Mat& weight,
					const abcdl::algebra::Mat& pre_weight,
					const abcdl::algebra::Mat& act_weight,
					abcdl::algebra::Mat& state,
					abcdl::algebra::Mat& activation){

	size_t seq_rows = train_seq_data.rows();
	size_t seq_cols = train_seq_data.cols();
	state.reset(0, seq_rows, _hidden_dim);
	activation.reset(0, seq_rows, seq_cols);

	abcdl::algebra::Mat s_t;
	for(size_t t = 0; t != seq_rows; t++){
		//s[t] = tanh(U*x[t] + W*s[t-1])
		//o[t] = softmax(V* s[t])
		if(t > 0){
			s_t = (helper.dot(weight, train_seq_data.get_row(t).transpose()) + helper.dot(pre_weight, state.get_row(t - 1).transpose())).tanh();
		}else{
			s_t = helper.dot(weight, train_seq_data.get_row(t).transpose()).tanh();
		}

		state.set_row(t, s_t.Ts());
		activation.set_row(t, helper.dot(act_weight, s_t).softmax().transpose());
	}
}

void Layer::backward(const abcdl::algebra::Mat& train_seq_data,
					 const abcdl::algebra::Mat& train_seq_label,
					 abcdl::algebra::Mat& weight,
					 abcdl::algebra::Mat& pre_weight,
					 abcdl::algebra::Mat& act_weight,
					 const abcdl::algebra::Mat& state,
					 const abcdl::algebra::Mat& activation,
					 abcdl::algebra::Mat& derivate_weight,
					 abcdl::algebra::Mat& derivate_pre_weight,
					 abcdl::algebra::Mat& derivate_act_weight){
	abcdl::algebra::Mat derivate_output;
	_cost->delta(derivate_output, activation, train_seq_label);

	size_t seq_size = train_seq_data.rows();
	for(size_t s = seq_size; s != 0 ; s--){
		size_t t = s - 1;
		auto derivate_output_t = derivate_output.get_row(t).transpose();
		auto state_t = state.get_row(t).transpose();

        //update derivate_act_weight
		derivate_act_weight += helper.outer(derivate_output_t, state_t);

        //calc derivate_t
		abcdl::algebra::Mat state_derivate;
		helper.sigmoid_derivative(state_derivate, state_t);
		auto derivate_t = helper.dot(act_weight.Ts(), derivate_output_t) * state_derivate;

		//back_propagation steps
		for(size_t step = 0; step < _bptt_truncate && step <= t; step++){
			size_t bptt_step = t - step;
			abcdl::algebra::Mat derivate_state_t;
			if(bptt_step > 0){
				state.get_row(&derivate_state_t, bptt_step - 1);
			}else{
				derivate_state_t.reset(0, state.cols(), 1);
			}

            //update derivate_pre_weight
			derivate_pre_weight += helper.outer(derivate_t, derivate_state_t.transpose());

            //update derivate_weight
			auto train_data_t = train_seq_data.get_row(bptt_step).transpose();
            auto derivate_weight_t = helper.dot(derivate_weight, train_data_t) + derivate_t;

            size_t idx = train_data_t.argmax(0, abcdl::algebra::Axis_type::ROW);
            derivate_weight.set_col(idx, derivate_weight.get_col(idx) + derivate_weight_t);

			//update delta
			if(bptt_step > 0){
				helper.sigmoid_derivative(derivate_state_t, derivate_state_t);
				derivate_t = pre_weight.Ts().dot(derivate_t) * derivate_state_t;
			}
		}
	}
}

}//namespace rnn
}//namespace abcdl
<|endoftext|>


<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "rpcclient.h"
#include "rpcserver.h"
#include "rpcprotocol.h"
#include "protocol.h"
#include "util.h"
#include "ui_interface.h"

#include <stdint.h>

#include <boost/algorithm/string.hpp>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/shared_ptr.hpp>
#include "json/json_spirit_writer_template.h"

using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;

Object CallRPC(const string& strMethod, const Array& params)
{
    if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
        throw runtime_error(strprintf(
            _("You must set rpcpassword=<password> in the configuration file:\n%s\n"
              "If the file does not exist, create it with owner-readable-only file permissions."),
                GetConfigFile().string().c_str()));

    // Connect to localhost
    bool fUseSSL = GetBoolArg("-rpcssl", false);
    asio::io_service io_service;
    ssl::context context(io_service, ssl::context::sslv23);
    context.set_options(ssl::context::no_sslv2);
    asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
    SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
    iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);

    bool fWait = GetBoolArg("-rpcwait", false); // -rpcwait means try until server has started
    do {
        bool fConnected = d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetBoolArg("-testnet", false) ? TESTNET_RPC_PORT : RPC_PORT)));
        if (fConnected) break;
        if (fWait)
            MilliSleep(1000);
        else
            throw runtime_error("couldn't connect to server");
    } while (fWait);

    // HTTP basic authentication
    string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
    map<string, string> mapRequestHeaders;
    mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;

    // Send request
    string strRequest = JSONRPCRequest(strMethod, params, 1);
    string strPost = HTTPPost(strRequest, mapRequestHeaders);
    stream << strPost << std::flush;

    // Receive HTTP reply status
    int nProto = 0;
    int nStatus = ReadHTTPStatus(stream, nProto);

    // Receive HTTP reply message headers and body
    map<string, string> mapHeaders;
    string strReply;
    ReadHTTPMessage(stream, mapHeaders, strReply, nProto);

    if (nStatus == HTTP_UNAUTHORIZED)
        throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
    else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
        throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
    else if (strReply.empty())
        throw runtime_error("no response from server");

    // Parse reply
    Value valReply;
    if (!read_string(strReply, valReply))
        throw runtime_error("couldn't parse reply from server");
    const Object& reply = valReply.get_obj();
    if (reply.empty())
        throw runtime_error("expected reply to have result, error and id properties");

    return reply;
}

template<typename T>
void ConvertTo(Value& value, bool fAllowNull=false)
{
    if (fAllowNull && value.type() == null_type)
        return;
    if (value.type() == str_type)
    {
        // reinterpret string as unquoted json value
        Value value2;
        string strJSON = value.get_str();
        if (!read_string(strJSON, value2))
            throw runtime_error(string("Error parsing JSON:")+strJSON);
        ConvertTo<T>(value2, fAllowNull);
        value = value2;
    }
    else
    {
        value = value.get_value<T>();
    }
}

// Convert strings to command-specific RPC representation
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
    Array params;
    BOOST_FOREACH(const std::string &param, strParams)
        params.push_back(param);

    int n = params.size();

    //
    // Special case non-string parameter types
    //
    if (strMethod == "stop"                   && n > 0) ConvertTo<bool>(params[0]);
    if (strMethod == "getaddednodeinfo"       && n > 0) ConvertTo<bool>(params[0]);
    if (strMethod == "setgenerate"            && n > 0) ConvertTo<bool>(params[0]);
    if (strMethod == "setgenerate"            && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "getnetworkhashps"       && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "getnetworkhashps"       && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "sendtoaddress"          && n > 1) ConvertTo<double>(params[1]);
    if (strMethod == "settxfee"               && n > 0) ConvertTo<double>(params[0]);
    if (strMethod == "getreceivedbyaddress"   && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "getreceivedbyaccount"   && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "listreceivedbyaddress"  && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "listreceivedbyaddress"  && n > 1) ConvertTo<bool>(params[1]);
    if (strMethod == "listreceivedbyaccount"  && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "listreceivedbyaccount"  && n > 1) ConvertTo<bool>(params[1]);
    if (strMethod == "getbalance"             && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "getblockhash"           && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "move"                   && n > 2) ConvertTo<double>(params[2]);
    if (strMethod == "move"                   && n > 3) ConvertTo<boost::int64_t>(params[3]);
    if (strMethod == "sendfrom"               && n > 2) ConvertTo<double>(params[2]);
    if (strMethod == "sendfrom"               && n > 3) ConvertTo<boost::int64_t>(params[3]);
    if (strMethod == "listtransactions"       && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "listtransactions"       && n > 2) ConvertTo<boost::int64_t>(params[2]);
    if (strMethod == "listaccounts"           && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "walletpassphrase"       && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "walletpassphrase"       && n > 2) ConvertTo<bool>(params[2]);
    if (strMethod == "getblocktemplate"       && n > 0) ConvertTo<Object>(params[0]);
    if (strMethod == "listsinceblock"         && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "sendmany"               && n > 1) ConvertTo<Object>(params[1]);
    if (strMethod == "sendmany"               && n > 2) ConvertTo<boost::int64_t>(params[2]);
    if (strMethod == "addmultisigaddress"     && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "addmultisigaddress"     && n > 1) ConvertTo<Array>(params[1]);
    if (strMethod == "createmultisig"         && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "createmultisig"         && n > 1) ConvertTo<Array>(params[1]);
    if (strMethod == "listunspent"            && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "listunspent"            && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "listunspent"            && n > 2) ConvertTo<Array>(params[2]);
    if (strMethod == "getblock"               && n > 1) ConvertTo<bool>(params[1]);
    if (strMethod == "getrawtransaction"      && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "createrawtransaction"   && n > 0) ConvertTo<Array>(params[0]);
    if (strMethod == "createrawtransaction"   && n > 1) ConvertTo<Object>(params[1]);
    if (strMethod == "signrawtransaction"     && n > 1) ConvertTo<Array>(params[1], true);
    if (strMethod == "signrawtransaction"     && n > 2) ConvertTo<Array>(params[2], true);
    if (strMethod == "sendrawtransaction"     && n > 1) ConvertTo<bool>(params[1], true);
    if (strMethod == "gettxout"               && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "gettxout"               && n > 2) ConvertTo<bool>(params[2]);
    if (strMethod == "lockunspent"            && n > 0) ConvertTo<bool>(params[0]);
    if (strMethod == "lockunspent"            && n > 1) ConvertTo<Array>(params[1]);
    if (strMethod == "importprivkey"          && n > 2) ConvertTo<bool>(params[2]);
    if (strMethod == "listminting"            && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "listminting"            && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "verifychain"            && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "verifychain"            && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "keypoolrefill"          && n > 0) ConvertTo<boost::int64_t>(params[0]);

    return params;
}

int CommandLineRPC(int argc, char *argv[])
{
    string strPrint;
    int nRet = 0;
    try
    {
        // Skip switches
        while (argc > 1 && IsSwitchChar(argv[1][0]))
        {
            argc--;
            argv++;
        }

        // Method
        if (argc < 2)
            throw runtime_error("too few parameters");
        string strMethod = argv[1];

        // Parameters default to strings
        std::vector<std::string> strParams(&argv[2], &argv[argc]);
        Array params = RPCConvertValues(strMethod, strParams);

        // Execute
        Object reply = CallRPC(strMethod, params);

        // Parse reply
        const Value& result = find_value(reply, "result");
        const Value& error  = find_value(reply, "error");

        if (error.type() != null_type)
        {
            // Error
            strPrint = "error: " + write_string(error, false);
            int code = find_value(error.get_obj(), "code").get_int();
            nRet = abs(code);
        }
        else
        {
            // Result
            if (result.type() == null_type)
                strPrint = "";
            else if (result.type() == str_type)
                strPrint = result.get_str();
            else
                strPrint = write_string(result, true);
        }
    }
    catch (boost::thread_interrupted) {
        throw;
    }
    catch (std::exception& e) {
        strPrint = string("error: ") + e.what();
        nRet = 87;
    }
    catch (...) {
        PrintException(NULL, "CommandLineRPC()");
    }

    if (strPrint != "")
    {
        fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
    }
    return nRet;
}

std::string HelpMessageCli(bool mainProgram)
{
    string strUsage;
    if(mainProgram)
    {
        strUsage += _("Options:") + "\n";
        strUsage += "  -?                     " + _("This help message") + "\n";
        strUsage += "  -conf=<file>           " + _("Specify configuration file (default: ppcoin.conf)") + "\n";
        strUsage += "  -datadir=<dir>         " + _("Specify data directory") + "\n";
        strUsage += "  -testnet               " + _("Use the test network") + "\n";
        strUsage += "  -regtest               " + _("Enter regression test mode, which uses a special chain in which blocks can be "
                                            "solved instantly. This is intended for regression testing tools and app development.") + "\n";
    } else {
        strUsage += _("RPC client options:") + "\n";
    }

    strUsage += "  -rpcconnect=<ip>       " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n";
    strUsage += "  -rpcport=<port>        " + _("Connect to JSON-RPC on <port> (default: 8332 or testnet: 18332)") + "\n";
    strUsage += "  -rpcwait               " + _("Wait for RPC server to start") + "\n";
    strUsage += "  -rpcuser=<user>        " + _("Username for JSON-RPC connections") + "\n";
    strUsage += "  -rpcpassword=<pw>      " + _("Password for JSON-RPC connections") + "\n";

    if(mainProgram)
    {
        strUsage += "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n";
        strUsage += "  -rpcssl                " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n";
    }

    return strUsage;
}

<commit_msg>fix rpc parameters after autotools merge<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "rpcclient.h"
#include "rpcserver.h"
#include "rpcprotocol.h"
#include "protocol.h"
#include "util.h"
#include "ui_interface.h"

#include <stdint.h>

#include <boost/algorithm/string.hpp>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/shared_ptr.hpp>
#include "json/json_spirit_writer_template.h"

using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;

Object CallRPC(const string& strMethod, const Array& params)
{
    if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
        throw runtime_error(strprintf(
            _("You must set rpcpassword=<password> in the configuration file:\n%s\n"
              "If the file does not exist, create it with owner-readable-only file permissions."),
                GetConfigFile().string().c_str()));

    // Connect to localhost
    bool fUseSSL = GetBoolArg("-rpcssl", false);
    asio::io_service io_service;
    ssl::context context(io_service, ssl::context::sslv23);
    context.set_options(ssl::context::no_sslv2);
    asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
    SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
    iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);

    bool fWait = GetBoolArg("-rpcwait", false); // -rpcwait means try until server has started
    do {
        bool fConnected = d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetBoolArg("-testnet", false) ? TESTNET_RPC_PORT : RPC_PORT)));
        if (fConnected) break;
        if (fWait)
            MilliSleep(1000);
        else
            throw runtime_error("couldn't connect to server");
    } while (fWait);

    // HTTP basic authentication
    string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
    map<string, string> mapRequestHeaders;
    mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;

    // Send request
    string strRequest = JSONRPCRequest(strMethod, params, 1);
    string strPost = HTTPPost(strRequest, mapRequestHeaders);
    stream << strPost << std::flush;

    // Receive HTTP reply status
    int nProto = 0;
    int nStatus = ReadHTTPStatus(stream, nProto);

    // Receive HTTP reply message headers and body
    map<string, string> mapHeaders;
    string strReply;
    ReadHTTPMessage(stream, mapHeaders, strReply, nProto);

    if (nStatus == HTTP_UNAUTHORIZED)
        throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
    else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
        throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
    else if (strReply.empty())
        throw runtime_error("no response from server");

    // Parse reply
    Value valReply;
    if (!read_string(strReply, valReply))
        throw runtime_error("couldn't parse reply from server");
    const Object& reply = valReply.get_obj();
    if (reply.empty())
        throw runtime_error("expected reply to have result, error and id properties");

    return reply;
}

template<typename T>
void ConvertTo(Value& value, bool fAllowNull=false)
{
    if (fAllowNull && value.type() == null_type)
        return;
    if (value.type() == str_type)
    {
        // reinterpret string as unquoted json value
        Value value2;
        string strJSON = value.get_str();
        if (!read_string(strJSON, value2))
            throw runtime_error(string("Error parsing JSON:")+strJSON);
        ConvertTo<T>(value2, fAllowNull);
        value = value2;
    }
    else
    {
        value = value.get_value<T>();
    }
}

// Convert strings to command-specific RPC representation
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
    Array params;
    BOOST_FOREACH(const std::string &param, strParams)
        params.push_back(param);

    int n = params.size();

    //
    // Special case non-string parameter types
    //
    if (strMethod == "stop"                   && n > 0) ConvertTo<bool>(params[0]);
    if (strMethod == "getaddednodeinfo"       && n > 0) ConvertTo<bool>(params[0]);
    if (strMethod == "setgenerate"            && n > 0) ConvertTo<bool>(params[0]);
    if (strMethod == "setgenerate"            && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "sendtoaddress"          && n > 1) ConvertTo<double>(params[1]);
    if (strMethod == "settxfee"               && n > 0) ConvertTo<double>(params[0]);
    if (strMethod == "getreceivedbyaddress"   && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "getreceivedbyaccount"   && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "listreceivedbyaddress"  && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "listreceivedbyaddress"  && n > 1) ConvertTo<bool>(params[1]);
    if (strMethod == "listreceivedbyaccount"  && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "listreceivedbyaccount"  && n > 1) ConvertTo<bool>(params[1]);
    if (strMethod == "getbalance"             && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "getblockhash"           && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "move"                   && n > 2) ConvertTo<double>(params[2]);
    if (strMethod == "move"                   && n > 3) ConvertTo<boost::int64_t>(params[3]);
    if (strMethod == "sendfrom"               && n > 2) ConvertTo<double>(params[2]);
    if (strMethod == "sendfrom"               && n > 3) ConvertTo<boost::int64_t>(params[3]);
    if (strMethod == "listtransactions"       && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "listtransactions"       && n > 2) ConvertTo<boost::int64_t>(params[2]);
    if (strMethod == "listaccounts"           && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "walletpassphrase"       && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "walletpassphrase"       && n > 2) ConvertTo<bool>(params[2]);
    if (strMethod == "getblocktemplate"       && n > 0) ConvertTo<Object>(params[0]);
    if (strMethod == "listsinceblock"         && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "sendmany"               && n > 1) ConvertTo<Object>(params[1]);
    if (strMethod == "sendmany"               && n > 2) ConvertTo<boost::int64_t>(params[2]);
    if (strMethod == "addmultisigaddress"     && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "addmultisigaddress"     && n > 1) ConvertTo<Array>(params[1]);
    if (strMethod == "createmultisig"         && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "createmultisig"         && n > 1) ConvertTo<Array>(params[1]);
    if (strMethod == "listunspent"            && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "listunspent"            && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "listunspent"            && n > 2) ConvertTo<Array>(params[2]);
    if (strMethod == "getblock"               && n > 1) ConvertTo<bool>(params[1]);
    if (strMethod == "getblock"               && n > 2) ConvertTo<bool>(params[2]);
    if (strMethod == "sendalert"              && n > 2) ConvertTo<boost::int64_t>(params[2]);
    if (strMethod == "sendalert"              && n > 3) ConvertTo<boost::int64_t>(params[3]);
    if (strMethod == "sendalert"              && n > 4) ConvertTo<boost::int64_t>(params[4]);
    if (strMethod == "sendalert"              && n > 5) ConvertTo<boost::int64_t>(params[5]);
    if (strMethod == "sendalert"              && n > 6) ConvertTo<boost::int64_t>(params[6]);
    if (strMethod == "enforcecheckpoint"      && n > 0) ConvertTo<bool>(params[0]);
    if (strMethod == "reservebalance"         && n > 0) ConvertTo<bool>(params[0]);
    if (strMethod == "reservebalance"         && n > 1) ConvertTo<double>(params[1]);
    if (strMethod == "getrawtransaction"      && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "createrawtransaction"   && n > 0) ConvertTo<Array>(params[0]);
    if (strMethod == "createrawtransaction"   && n > 1) ConvertTo<Object>(params[1]);
    if (strMethod == "signrawtransaction"     && n > 1) ConvertTo<Array>(params[1], true);
    if (strMethod == "signrawtransaction"     && n > 2) ConvertTo<Array>(params[2], true);
    if (strMethod == "sendrawtransaction"     && n > 1) ConvertTo<bool>(params[1], true);
    if (strMethod == "gettxout"               && n > 1) ConvertTo<boost::int64_t>(params[1]);
    if (strMethod == "gettxout"               && n > 2) ConvertTo<bool>(params[2]);
    if (strMethod == "lockunspent"            && n > 0) ConvertTo<bool>(params[0]);
    if (strMethod == "lockunspent"            && n > 1) ConvertTo<Array>(params[1]);
    if (strMethod == "importprivkey"          && n > 2) ConvertTo<bool>(params[2]);
    if (strMethod == "listminting"            && n > 0) ConvertTo<boost::int64_t>(params[0]);
    if (strMethod == "listminting"            && n > 1) ConvertTo<boost::int64_t>(params[1]);
#ifdef TESTING
    if (strMethod == "timetravel"             && n > 0) ConvertTo<boost::int64_t>(params[0]);
#endif
    return params;
}

int CommandLineRPC(int argc, char *argv[])
{
    string strPrint;
    int nRet = 0;
    try
    {
        // Skip switches
        while (argc > 1 && IsSwitchChar(argv[1][0]))
        {
            argc--;
            argv++;
        }

        // Method
        if (argc < 2)
            throw runtime_error("too few parameters");
        string strMethod = argv[1];

        // Parameters default to strings
        std::vector<std::string> strParams(&argv[2], &argv[argc]);
        Array params = RPCConvertValues(strMethod, strParams);

        // Execute
        Object reply = CallRPC(strMethod, params);

        // Parse reply
        const Value& result = find_value(reply, "result");
        const Value& error  = find_value(reply, "error");

        if (error.type() != null_type)
        {
            // Error
            strPrint = "error: " + write_string(error, false);
            int code = find_value(error.get_obj(), "code").get_int();
            nRet = abs(code);
        }
        else
        {
            // Result
            if (result.type() == null_type)
                strPrint = "";
            else if (result.type() == str_type)
                strPrint = result.get_str();
            else
                strPrint = write_string(result, true);
        }
    }
    catch (boost::thread_interrupted) {
        throw;
    }
    catch (std::exception& e) {
        strPrint = string("error: ") + e.what();
        nRet = 87;
    }
    catch (...) {
        PrintException(NULL, "CommandLineRPC()");
    }

    if (strPrint != "")
    {
        fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
    }
    return nRet;
}

std::string HelpMessageCli(bool mainProgram)
{
    string strUsage;
    if(mainProgram)
    {
        strUsage += _("Options:") + "\n";
        strUsage += "  -?                     " + _("This help message") + "\n";
        strUsage += "  -conf=<file>           " + _("Specify configuration file (default: ppcoin.conf)") + "\n";
        strUsage += "  -datadir=<dir>         " + _("Specify data directory") + "\n";
        strUsage += "  -testnet               " + _("Use the test network") + "\n";
        strUsage += "  -regtest               " + _("Enter regression test mode, which uses a special chain in which blocks can be "
                                            "solved instantly. This is intended for regression testing tools and app development.") + "\n";
    } else {
        strUsage += _("RPC client options:") + "\n";
    }

    strUsage += "  -rpcconnect=<ip>       " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n";
    strUsage += "  -rpcport=<port>        " + _("Connect to JSON-RPC on <port> (default: 8332 or testnet: 18332)") + "\n";
    strUsage += "  -rpcwait               " + _("Wait for RPC server to start") + "\n";
    strUsage += "  -rpcuser=<user>        " + _("Username for JSON-RPC connections") + "\n";
    strUsage += "  -rpcpassword=<pw>      " + _("Password for JSON-RPC connections") + "\n";

    if(mainProgram)
    {
        strUsage += "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n";
        strUsage += "  -rpcssl                " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n";
    }

    return strUsage;
}

<|endoftext|>


<commit_before>#include <unistd.h>
#include <getopt.h>
#include <dgtype/dgtype.hh>
#include "args.hh"
#include "file_io.hh"

Error_code read_args(int argc, char* argv[], Arguments* args) {
  int c;

  while (true) {
    static struct option long_options[] =
    {
      {"verbose", no_argument, NULL, 'v'},
      {"help", no_argument, NULL, 'h'},
      {"extract", no_argument, NULL, 'e'}, {"input", required_argument, NULL, 'i'},
      {"output", required_argument, NULL, 'o'},
      {"message", required_argument, NULL, 'm'},
      {0, 0, 0, 0}
    };

    int option_index = 0;
    c = getopt_long (argc, argv, "evhi:o:m:",
                     long_options, &option_index);
    if (c == -1) {
      break;
    }

    switch (c) {
    case 'v':
      args->verbose = true;
      break;
    case 'h':
      return Error_code::HELP_ARG;
    case 'e':
      args->extract = true;
      break;
    case 'i':
      args->input_fname = optarg;
      break;
    case 'o':
      args->output_fname = optarg;
      break;
    case 'm':
      args->message_fname = optarg;
      break;
    case ':':
      return Error_code::MISSING_ARG;
    case '?':
      return Error_code::UNKNOWN_ARG;
    }
  }
  if (file_type_of(args->input_fname) == File_type::UNKNOWN ||
      (!args->extract && file_type_of(args->output_fname) == File_type::UNKNOWN)) {
    return Error_code::UNKNOWN_TYPE;
  }
  if (args->input_fname.empty()) {
    return Error_code::MISSING_INPUT;
  }
  if (args->output_fname.empty()) {
    return Error_code::MISSING_OUTPUT;
  }
  if (!is_file_accessible(args->input_fname) ||
     (!args->extract && !is_file_accessible(args->message_fname))) {
    return Error_code::INACCESSIBLE_FILE;
  }
  return Error_code::SUCCESS;
}

void process_error_code(Error_code err_code) {
  switch (err_code) {
  case Error_code::MISSING_INPUT:
    std::cerr << "error: must specify an input file.\n";
    break;
  case Error_code::MISSING_OUTPUT:
    std::cerr << "error: must specify an output file.\n"
              << "(Note the output is a media file when embedding, "
              << "but a file containing a message when extracting)\n";
    break;
  case Error_code::INACCESSIBLE_FILE:
    std::cerr << "error: could not open file for reading.\n";
    break;
  case Error_code::HELP_ARG:
    print_help();
    exit(EXIT_SUCCESS);
  case Error_code::UNKNOWN_ARG:
  case Error_code::UNKNOWN_TYPE:
  case Error_code::MISSING_ARG:
    break;
  case Error_code::SUCCESS:
    return;
  }
  print_usage();
  exit(EXIT_FAILURE);
}

void print_help() {
  print_usage(true);
  std::cout << "Media types supported:\n  - Windows BMP\n  - PCM 16-bit WAV\n";
  std::cout << std::endl
            << "Long       short  desc\n"
            << "--extract  -e     extract a message instead of embedding\n"
            << "--help     -h     show this screen\n"
            << "--input    -i     location of input bmp/wav file to embed in or extract from\n"
            << "--message  -m     location of file containing the message to embed\n"
            << "--output   -o     location of output stego file or extracted message file\n"
            << "--verbose  -v     verbosely describe stego process\n\n";
}

void print_usage(bool help) {
  std::cout << "usage: munchkinsteg [hv] [-i <wav|bmp file> -o <wav|bmp file> -m <message file>]\n"
            << "                    ~OR~ [-e -i <wav|bmp file> -o <message file>]\n\n";
  if (!help) {
    std::cout << "NOTE: The supported media types are:\n  - Windows BMP\n  - PCM 16-bit WAV\n";
  }
}

void print_if(std::string str, bool condition) {
  if (condition) {
    std::cout << str;
  }
}
<commit_msg>Added more to the help string of stego crypt main<commit_after>#include <unistd.h>
#include <getopt.h>
#include <dgtype/dgtype.hh>
#include "args.hh"
#include "file_io.hh"

Error_code read_args(int argc, char* argv[], Arguments* args) {int c;

  while (true) {
    static struct option long_options[] =
    {
      {"verbose", no_argument, NULL, 'v'},
      {"help", no_argument, NULL, 'h'},
      {"extract", no_argument, NULL, 'e'}, {"input", required_argument, NULL, 'i'},
      {"output", required_argument, NULL, 'o'},
      {"message", required_argument, NULL, 'm'},
      {0, 0, 0, 0}
    };

    int option_index = 0;
    c = getopt_long (argc, argv, "evhi:o:m:",
                     long_options, &option_index);
    if (c == -1) {
      break;
    }

    switch (c) {
    case 'v':
      args->verbose = true;
      break;
    case 'h':
      return Error_code::HELP_ARG;
    case 'e':
      args->extract = true;
      break;
    case 'i':
      args->input_fname = optarg;
      break;
    case 'o':
      args->output_fname = optarg;
      break;
    case 'm':
      args->message_fname = optarg;
      break;
    case ':':
      return Error_code::MISSING_ARG;
    case '?':
      return Error_code::UNKNOWN_ARG;
    }
  }
  if (file_type_of(args->input_fname) == File_type::UNKNOWN ||
      (!args->extract && file_type_of(args->output_fname) == File_type::UNKNOWN)) {
    return Error_code::UNKNOWN_TYPE;
  }
  if (args->input_fname.empty()) {
    return Error_code::MISSING_INPUT;
  }
  if (args->output_fname.empty()) {
    return Error_code::MISSING_OUTPUT;
  }
  if (!is_file_accessible(args->input_fname) ||
     (!args->extract && !is_file_accessible(args->message_fname))) {
    return Error_code::INACCESSIBLE_FILE;
  }
  return Error_code::SUCCESS;
}

void process_error_code(Error_code err_code) {
  switch (err_code) {
  case Error_code::MISSING_INPUT:
    std::cerr << "error: must specify an input file.\n";
    break;
  case Error_code::MISSING_OUTPUT:
    std::cerr << "error: must specify an output file.\n"
              << "(Note the output is a media file when embedding, "
              << "but a file containing a message when extracting)\n";
    break;
  case Error_code::INACCESSIBLE_FILE:
    std::cerr << "error: could not open file for reading.\n";
    break;
  case Error_code::HELP_ARG:
    print_help();
    exit(EXIT_SUCCESS);
  case Error_code::UNKNOWN_ARG:
  case Error_code::UNKNOWN_TYPE:
  case Error_code::MISSING_ARG:
    break;
  case Error_code::SUCCESS:
    return;
  }
  print_usage();
  exit(EXIT_FAILURE);
}

void print_help() {
  print_usage(true);
  std::cout << "-- Munchkinsteg help\n\n"
            << "Munchkinsteg is a BMP and WAV file steganography utility.\n"
            << "It can embed message files into music and image files as well as\n"
            << "extract messages that may be embedded in a music or image file and\n"
            << "store that message in a file.\n";
  std::cout << std::endl;
  std::cout << "Media types supported:\n  - Windows BMP\n  - PCM 16-bit WAV\n";
  std::cout << std::endl
            << "Long       short  desc\n"
            << "--extract  -e     extract a message instead of embedding\n"
            << "--help     -h     show this screen\n"
            << "--input    -i     location of input bmp/wav file to embed in or extract from\n"
            << "--message  -m     location of file containing the message to embed\n"
            << "--output   -o     location of output stego file or extracted message file\n"
            << "--verbose  -v     verbosely describe stego process\n\n";
}

void print_usage(bool help) {
  std::cout << "usage: munchkinsteg [hv] [-i <wav|bmp file> -o <wav|bmp file> -m <message file>]\n"
            << "                    ~OR~ [-e -i <wav|bmp file> -o <message file>]\n\n";
  if (!help) {
    std::cout << "NOTE: The supported media types are:\n  - Windows BMP\n  - PCM 16-bit WAV\n";
  }
}

void print_if(std::string str, bool condition) {
  if (condition) {
    std::cout << str;
  }
}
<|endoftext|>


<commit_before>#include "Slam.hh"

Slam::Slam(Agent *agent)
{
  this->_agent = agent;
  this->_landmarkDb = new Landmarks(agent->degreePerScan);
  this->_data = new DataAssociation(this->_landmarkDb);
  this->_state = new SystemStateMatrice(*agent);
  this->_covariance = new CovarianceMatrice(agent->getPos().x, agent->getPos().y, agent->getBearing());
}

Slam::~Slam()
{
  if (this->_data)
    delete this->_data;
  if (this->_landmarkDb)
    delete this->_landmarkDb;
  if (this->_state)
    delete this->_state;
  if (this->_covariance)
    delete this->_covariance;
}

void    Slam::updateState(pcl::PointCloud<pcl::PointXYZ> const &cloud, Agent &agent)
{
  //Update state using odometry
  this->_state->setRobotState(agent);
  //@TODO: update jacobian matrice
  //@TODO: update process noise matrice
  this->_covariance->setRobotPosition(agent);
  this->_covariance->calculationCovariance();

  //Update state using reobserved landmark
  std::vector<Landmarks::Landmark *> newLandmarks;
  std::vector<Landmarks::Landmark *> reobservedLandmarks;
  this->_data->validationGate(cloud, agent, newLandmarks, reobservedLandmarks);
  this->addLandmarks(newLandmarks);

  for (std::vector<Landmarks::Landmark *>::iterator it = reobservedLandmarks.begin(); it != reobservedLandmarks.end(); ++it)
  {
    //@TODO: Caculate kalman gain and uncertainity
    //@TODO: Update state using kalman gain and uncertainity
  }

  agent.setPos(this->_state->getRobotPos());
  //After all, remove abd landmarks
  this->_landmarkDb->removeBadLandmarks(cloud, agent);
}

void    Slam::addLandmarks(std::vector<Landmarks::Landmark *> const &newLandmarks)
{
  for (std::vector<Landmarks::Landmark *>::const_iterator it = newLandmarks.begin(); it != newLandmarks.end(); ++it)
  {
    int landmarkId = this->_landmarkDb->addToDB(**it);
    int slamId = this->_state->addLandmarkPosition((*it)->pos);
    this->_landmarkDb->addSlamId(landmarkId, slamId);
    //By default assume that landmark is perfectly observed
    this->_kg.addLandmark(std::make_pair(0.0, 0.0), std::make_pair(0.0, 0.0), slamId);
    this->_covariance->addLandmark((*it)->pos, slamId);
    this->_covariance->calculationCovariance();
  }
}
<commit_msg>Slam.cpp: Change todo format to be shown in doxygen documentation<commit_after>#include "Slam.hh"

Slam::Slam(Agent *agent)
{
  this->_agent = agent;
  this->_landmarkDb = new Landmarks(agent->degreePerScan);
  this->_data = new DataAssociation(this->_landmarkDb);
  this->_state = new SystemStateMatrice(*agent);
  this->_covariance = new CovarianceMatrice(agent->getPos().x, agent->getPos().y, agent->getBearing());
}

Slam::~Slam()
{
  if (this->_data)
    delete this->_data;
  if (this->_landmarkDb)
    delete this->_landmarkDb;
  if (this->_state)
    delete this->_state;
  if (this->_covariance)
    delete this->_covariance;
}

void    Slam::updateState(pcl::PointCloud<pcl::PointXYZ> const &cloud, Agent &agent)
{
  //Update state using odometry
  this->_state->setRobotState(agent);
  ///@todo: update jacobian matrice
  ///@todo: update process noise matrice
  this->_covariance->setRobotPosition(agent);
  this->_covariance->calculationCovariance();

  //Update state using reobserved landmark
  std::vector<Landmarks::Landmark *> newLandmarks;
  std::vector<Landmarks::Landmark *> reobservedLandmarks;
  this->_data->validationGate(cloud, agent, newLandmarks, reobservedLandmarks);
  this->addLandmarks(newLandmarks);

  for (std::vector<Landmarks::Landmark *>::iterator it = reobservedLandmarks.begin(); it != reobservedLandmarks.end(); ++it)
  {
    ///@todo: Caculate kalman gain and uncertainity
    ///@todo: Update state using kalman gain and uncertainity
  }

  agent.setPos(this->_state->getRobotPos());
  //After all, remove abd landmarks
  this->_landmarkDb->removeBadLandmarks(cloud, agent);
}

void    Slam::addLandmarks(std::vector<Landmarks::Landmark *> const &newLandmarks)
{
  for (std::vector<Landmarks::Landmark *>::const_iterator it = newLandmarks.begin(); it != newLandmarks.end(); ++it)
  {
    int landmarkId = this->_landmarkDb->addToDB(**it);
    int slamId = this->_state->addLandmarkPosition((*it)->pos);
    this->_landmarkDb->addSlamId(landmarkId, slamId);
    //By default assume that landmark is perfectly observed
    this->_kg.addLandmark(std::make_pair(0.0, 0.0), std::make_pair(0.0, 0.0), slamId);
    this->_covariance->addLandmark((*it)->pos, slamId);
    this->_covariance->calculationCovariance();
  }
}
<|endoftext|>


<commit_before>/*
 * Copyright 2007-2021 CM4all GmbH
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * 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.
 *
 * 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
 * FOUNDATION 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 "Basic.hxx"
#include "Config.hxx"
#include "ssl/Error.hxx"
#include "ssl/Ctx.hxx"

#include <openssl/err.h>
#include <openssl/opensslv.h>

#include <stdio.h>

static void
keylog(const SSL *, const char *line)
{
	const char *path = getenv("SSLKEYLOGFILE");
	if (path == nullptr)
		return;

	FILE *file = fopen(path, "a");
	if (file != nullptr) {
		  fprintf(file, "%s\n", line);
		  fclose(file);
	}
}

static void
SetupBasicSslCtx(SSL_CTX &ssl_ctx, bool server)
{
	long mode = SSL_MODE_ENABLE_PARTIAL_WRITE
		| SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER
		| SSL_MODE_RELEASE_BUFFERS;

	/* without this flag, OpenSSL attempts to verify the whole local
	   certificate chain for each connection, which is a waste of CPU
	   time */
	mode |= SSL_MODE_NO_AUTO_CHAIN;

	SSL_CTX_set_mode(&ssl_ctx, mode);

	if (server) {
		/* enable Elliptic curve Diffie-Hellman (ECDH) for perfect
		   forward secrecy; by default, it OpenSSL disables it */
		SSL_CTX_set_ecdh_auto(ssl_ctx, 1);

		/* no auto-clear, because LbInstance::compress_event will do
		   this every 10 minutes, which is more reliable */
		SSL_CTX_set_session_cache_mode(&ssl_ctx,
					       SSL_SESS_CACHE_SERVER|
					       SSL_SESS_CACHE_NO_AUTO_CLEAR);
	}

	/* disable protocols that are known to be insecure */
	SSL_CTX_set_min_proto_version(&ssl_ctx, TLS1_2_VERSION);

	/* disable weak ciphers */
	/* "!SHA1:!SHA256:!SHA384" disables insecure CBC ciphers */
	SSL_CTX_set_cipher_list(&ssl_ctx, "DEFAULT:!EXPORT:!LOW:!RC4:!SHA1:!SHA256:!SHA384");

	/* let us choose the cipher based on our own priority; so if a
	   client prefers to use a weak cipher (which would be rather
	   stupid, but oh well..), choose the strongest one supported by
	   the client; this call is only here to maximize our SSL/TLS
	   "score" in benchmarks which think following the client's
	   preferences is bad */
	SSL_CTX_set_options(&ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);

	/* support logging session secrets for Wireshark */
	if (getenv("SSLKEYLOGFILE") != nullptr)
		SSL_CTX_set_keylog_callback(&ssl_ctx, keylog);
}

SslCtx
CreateBasicSslCtx(bool server)
{
	ERR_clear_error();

	auto method = server
		? TLS_server_method()
		: TLS_client_method();

	SslCtx ssl_ctx(method);
	SetupBasicSslCtx(*ssl_ctx, server);
	return ssl_ctx;
}

static int
verify_callback(int ok, X509_STORE_CTX *) noexcept
{
	return ok;
}

void
ApplyServerConfig(SSL_CTX &ssl_ctx, const SslConfig &config)
{
	ERR_clear_error();

	if (!config.ca_cert_file.empty()) {
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
		if (SSL_CTX_load_verify_file(&ssl_ctx,
					     config.ca_cert_file.c_str()) != 1)
			throw SslError("Failed to load CA certificate file " +
				       config.ca_cert_file);
#else
		if (SSL_CTX_load_verify_locations(&ssl_ctx,
						  config.ca_cert_file.c_str(),
						  nullptr) != 1)
			throw SslError("Failed to load CA certificate file " +
				       config.ca_cert_file);
#endif

		/* send all certificates from this file to the client (list of
		   acceptable CA certificates) */

		STACK_OF(X509_NAME) *list =
			SSL_load_client_CA_file(config.ca_cert_file.c_str());
		if (list == nullptr)
			throw SslError("Failed to load CA certificate list from file " +
				       config.ca_cert_file);

		SSL_CTX_set_client_CA_list(&ssl_ctx, list);
	}

	if (config.verify != SslVerify::NO) {
		/* enable client certificates */
		int mode = SSL_VERIFY_PEER;

		if (config.verify == SslVerify::YES)
			mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;

		SSL_CTX_set_verify(&ssl_ctx, mode, verify_callback);
	}
}
<commit_msg>ssl/Basic: remove deprecated SSL_CTX_set_ecdh_auto() call<commit_after>/*
 * Copyright 2007-2021 CM4all GmbH
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * 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.
 *
 * 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
 * FOUNDATION 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 "Basic.hxx"
#include "Config.hxx"
#include "ssl/Error.hxx"
#include "ssl/Ctx.hxx"

#include <openssl/err.h>
#include <openssl/opensslv.h>

#include <stdio.h>

static void
keylog(const SSL *, const char *line)
{
	const char *path = getenv("SSLKEYLOGFILE");
	if (path == nullptr)
		return;

	FILE *file = fopen(path, "a");
	if (file != nullptr) {
		  fprintf(file, "%s\n", line);
		  fclose(file);
	}
}

static void
SetupBasicSslCtx(SSL_CTX &ssl_ctx, bool server)
{
	long mode = SSL_MODE_ENABLE_PARTIAL_WRITE
		| SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER
		| SSL_MODE_RELEASE_BUFFERS;

	/* without this flag, OpenSSL attempts to verify the whole local
	   certificate chain for each connection, which is a waste of CPU
	   time */
	mode |= SSL_MODE_NO_AUTO_CHAIN;

	SSL_CTX_set_mode(&ssl_ctx, mode);

	if (server) {
		/* no auto-clear, because LbInstance::compress_event will do
		   this every 10 minutes, which is more reliable */
		SSL_CTX_set_session_cache_mode(&ssl_ctx,
					       SSL_SESS_CACHE_SERVER|
					       SSL_SESS_CACHE_NO_AUTO_CLEAR);
	}

	/* disable protocols that are known to be insecure */
	SSL_CTX_set_min_proto_version(&ssl_ctx, TLS1_2_VERSION);

	/* disable weak ciphers */
	/* "!SHA1:!SHA256:!SHA384" disables insecure CBC ciphers */
	SSL_CTX_set_cipher_list(&ssl_ctx, "DEFAULT:!EXPORT:!LOW:!RC4:!SHA1:!SHA256:!SHA384");

	/* let us choose the cipher based on our own priority; so if a
	   client prefers to use a weak cipher (which would be rather
	   stupid, but oh well..), choose the strongest one supported by
	   the client; this call is only here to maximize our SSL/TLS
	   "score" in benchmarks which think following the client's
	   preferences is bad */
	SSL_CTX_set_options(&ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);

	/* support logging session secrets for Wireshark */
	if (getenv("SSLKEYLOGFILE") != nullptr)
		SSL_CTX_set_keylog_callback(&ssl_ctx, keylog);
}

SslCtx
CreateBasicSslCtx(bool server)
{
	ERR_clear_error();

	auto method = server
		? TLS_server_method()
		: TLS_client_method();

	SslCtx ssl_ctx(method);
	SetupBasicSslCtx(*ssl_ctx, server);
	return ssl_ctx;
}

static int
verify_callback(int ok, X509_STORE_CTX *) noexcept
{
	return ok;
}

void
ApplyServerConfig(SSL_CTX &ssl_ctx, const SslConfig &config)
{
	ERR_clear_error();

	if (!config.ca_cert_file.empty()) {
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
		if (SSL_CTX_load_verify_file(&ssl_ctx,
					     config.ca_cert_file.c_str()) != 1)
			throw SslError("Failed to load CA certificate file " +
				       config.ca_cert_file);
#else
		if (SSL_CTX_load_verify_locations(&ssl_ctx,
						  config.ca_cert_file.c_str(),
						  nullptr) != 1)
			throw SslError("Failed to load CA certificate file " +
				       config.ca_cert_file);
#endif

		/* send all certificates from this file to the client (list of
		   acceptable CA certificates) */

		STACK_OF(X509_NAME) *list =
			SSL_load_client_CA_file(config.ca_cert_file.c_str());
		if (list == nullptr)
			throw SslError("Failed to load CA certificate list from file " +
				       config.ca_cert_file);

		SSL_CTX_set_client_CA_list(&ssl_ctx, list);
	}

	if (config.verify != SslVerify::NO) {
		/* enable client certificates */
		int mode = SSL_VERIFY_PEER;

		if (config.verify == SslVerify::YES)
			mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;

		SSL_CTX_set_verify(&ssl_ctx, mode, verify_callback);
	}
}
<|endoftext|>


<commit_before>// RUN: %clang_cc1 -emit-llvm %s -o /dev/null -g
// XTARGET: darwin,linux
// XFAIL: *
template <typename T1,typename T2>
inline void f(const T1&,const T2&) { }

template <typename T1,typename T2,void F(const T1&,const T2&)>
struct A {
    template <typename T> void g(T& i) { }
};

int main() {
    int i;
    A<int,int,f> a;
    a.g(i);
}
<commit_msg>Try removing xfail and xtarget to see if this brings back a couple of bots.<commit_after>// RUN: %clang_cc1 -emit-llvm %s -o /dev/null -g

template <typename T1,typename T2>
inline void f(const T1&,const T2&) { }

template <typename T1,typename T2,void F(const T1&,const T2&)>
struct A {
    template <typename T> void g(T& i) { }
};

int main() {
    int i;
    A<int,int,f> a;
    a.g(i);
}
<|endoftext|>


<commit_before>// RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck %s

// CHECK: define i{{.*}} @main({{.*}}) #0
int main(int argc, char **argv) {
    return 1;
}

// CHECK: attributes #0 = { norecurse{{.*}} }
<commit_msg>Slacken the norecurse test slightly<commit_after>// RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck %s

// CHECK: define {{.*}} @main({{.*}}) #0
int main(int argc, char **argv) {
    return 1;
}

// CHECK: attributes #0 = { norecurse{{.*}} }
<|endoftext|>


<commit_before>#include "OSXIEEE1394Cam.h"

// constructor
OSXIEEE1394Cam::OSXIEEE1394Cam()
{
	// the string that we are going to pass to artoolkit
	char init_string [] = "-nodialog -width=640 -height=480 -pixelformat=24";
	//char init_string [] = "-nodialog -width=320 -height=240 -pixelformat=24";

	// attempt to open the camera
	this->artk_params = ar2VideoOpen( init_string );

	// check to see if the camera was opened okay
	if( this->artk_params == NULL )
	{
		gen_fatal( "Couldn't open camera. Is it plugged in?" );
	}

	// start the capturing.
	int started = ar2VideoCapStart( this->artk_params );

	// check that capturing was started okay
	if( started == -1 )
	{
		gen_fatal( "camera capturing could not be started" );
	}

	message( "create an OSXIEEE1394 object" );
}

// constructor that enables the user to enter the
// width and height of the image. The default colour
// space is RGB
OSXIEEE1394Cam::OSXIEEE1394Cam( int width, int height )
{
	message( "not implemented yet" );
}

// returns a frame from the camera.
unsigned char* OSXIEEE1394Cam::getFrame()
{

	while( ( this->image_buffer = ar2VideoGetImage( this->artk_params ) ) == NULL )
		;
/*
	unsigned char*  temp = image_buffer;
	for( int i = 0; i < 640 * 480; i++ )
	{
		*temp = 255 - *temp;
		temp++;
	}
*/
	return this->image_buffer;
}

OSXIEEE1394Cam::~OSXIEEE1394Cam() {}
<commit_msg>added the closing of the capturing to the destructor method. Also removed     some debug comments.<commit_after>#include "OSXIEEE1394Cam.h"

// constructor
OSXIEEE1394Cam::OSXIEEE1394Cam()
{
	// the string that we are going to pass to artoolkit
	char init_string [] = "-nodialog -width=640 -height=480 -pixelformat=24 -fps";
	//char init_string [] = "-nodialog -width=320 -height=240 -pixelformat=24";

	// attempt to open the camera
	this->artk_params = ar2VideoOpen( init_string );

	// check to see if the camera was opened okay
	if( this->artk_params == NULL )
	{
		gen_fatal( "Couldn't open camera. Is it plugged in?" );
	}

	// start the capturing.
	int started = ar2VideoCapStart( this->artk_params );

	// check that capturing was started okay
	if( started == -1 )
	{
		gen_fatal( "camera capturing could not be started" );
	}

	message( "create an OSXIEEE1394 object" );
}

// constructor that enables the user to enter the
// width and height of the image. The default colour
// space is RGB
OSXIEEE1394Cam::OSXIEEE1394Cam( int width, int height )
{
	message( "not implemented yet" );
}

// returns a frame from the camera.
unsigned char* OSXIEEE1394Cam::getFrame()
{
	while( ( this->image_buffer = ar2VideoGetImage( this->artk_params ) ) == NULL )
		;
/*
	unsigned char*  temp = image_buffer;
	for( int i = 0; i < 640 * 480; i++ )
	{
		*temp = 255 - *temp;
		temp++;
	}
*/
	return this->image_buffer;
}

OSXIEEE1394Cam::~OSXIEEE1394Cam()
{
	// close the image grabber
	int stopped = ar2VideoCapStop( this->artk_params );

	// check that capturing was stopped okay
	if( stopped == -1 )
	{
		gen_fatal( "camera capturing could not be stopped cleanly" );
	}
}
<|endoftext|>