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

/**
 * @file ets_airspeed.cpp
 * @author Simon Wilks
 *
 * Driver for the Eagle Tree Airspeed V3 connected via I2C.
 */

#include <nuttx/config.h>

#include <drivers/device/i2c.h>

#include <sys/types.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
#include <semaphore.h>
#include <string.h>
#include <fcntl.h>
#include <poll.h>
#include <errno.h>
#include <stdio.h>
#include <math.h>
#include <unistd.h>

#include <nuttx/arch.h>
#include <nuttx/wqueue.h>
#include <nuttx/clock.h>

#include <board_config.h>

#include <systemlib/airspeed.h>
#include <systemlib/err.h>
#include <systemlib/param/param.h>
#include <systemlib/perf_counter.h>

#include <drivers/drv_airspeed.h>
#include <drivers/drv_hrt.h>
#include <drivers/device/ringbuffer.h>

#include <uORB/uORB.h>
#include <uORB/topics/differential_pressure.h>
#include <uORB/topics/subsystem_info.h>
#include <drivers/airspeed/airspeed.h>

/* I2C bus address */
#define I2C_ADDRESS	0x75	/* 7-bit address. 8-bit address is 0xEA */
#define ETS_PATH	"/dev/ets_airspeed"

/* Register address */
#define READ_CMD	0x07	/* Read the data */

/**
 * The Eagle Tree Airspeed V3 cannot provide accurate reading below speeds of 15km/h.
 * You can set this value to 12 if you want a zero reading below 15km/h.
 */
#define MIN_ACCURATE_DIFF_PRES_PA 0

/* Measurement rate is 100Hz */
#define CONVERSION_INTERVAL	(1000000 / 100)	/* microseconds */

class ETSAirspeed : public Airspeed
{
public:
	ETSAirspeed(int bus, int address = I2C_ADDRESS, const char* path = ETS_PATH);

protected:

	/**
	* Perform a poll cycle; collect from the previous measurement
	* and start a new one.
	*/
	virtual void	cycle();
	virtual int	measure();
	virtual int	collect();

};

/*
 * Driver 'main' command.
 */
extern "C" __EXPORT int ets_airspeed_main(int argc, char *argv[]);

ETSAirspeed::ETSAirspeed(int bus, int address, const char* path) : Airspeed(bus, address,
	CONVERSION_INTERVAL, path)
{

}

int
ETSAirspeed::measure()
{
	int ret;

	/*
	 * Send the command to begin a measurement.
	 */
	uint8_t cmd = READ_CMD;
	ret = transfer(&cmd, 1, nullptr, 0);

	if (OK != ret) {
		perf_count(_comms_errors);
	}

	return ret;
}

int
ETSAirspeed::collect()
{
	int	ret = -EIO;

	/* read from the sensor */
	uint8_t val[2] = {0, 0};

	perf_begin(_sample_perf);

	ret = transfer(nullptr, 0, &val[0], 2);

	if (ret < 0) {
		perf_count(_comms_errors);
		return ret;
	}

	uint16_t diff_pres_pa_raw = val[1] << 8 | val[0];
        if (diff_pres_pa_raw == 0) {
		// a zero value means the pressure sensor cannot give us a
		// value. We need to return, and not report a value or the
		// caller could end up using this value as part of an
		// average
		perf_count(_comms_errors);
		log("zero value from sensor");
		return -1;
        }

	// The raw value still should be compensated for the known offset
	diff_pres_pa_raw -= _diff_pres_offset;

	// Track maximum differential pressure measured (so we can work out top speed).
	if (diff_pres_pa_raw > _max_differential_pressure_pa) {
		_max_differential_pressure_pa = diff_pres_pa_raw;
	}

	differential_pressure_s report;
	report.timestamp = hrt_absolute_time();
        report.error_count = perf_event_count(_comms_errors);

	// XXX we may want to smooth out the readings to remove noise.
	report.differential_pressure_filtered_pa = diff_pres_pa_raw;
	report.differential_pressure_raw_pa = diff_pres_pa_raw;
	report.temperature = -1000.0f;
	report.max_differential_pressure_pa = _max_differential_pressure_pa;

	if (_airspeed_pub > 0 && !(_pub_blocked)) {
		/* publish it */
		orb_publish(ORB_ID(differential_pressure), _airspeed_pub, &report);
	}

	new_report(report);

	/* notify anyone waiting for data */
	poll_notify(POLLIN);

	ret = OK;

	perf_end(_sample_perf);

	return ret;
}

void
ETSAirspeed::cycle()
{
	int ret;

	/* collection phase? */
	if (_collect_phase) {

		/* perform collection */
		ret = collect();
		if (OK != ret) {
			perf_count(_comms_errors);
			/* restart the measurement state machine */
			start();
			_sensor_ok = false;
			return;
		}

		/* next phase is measurement */
		_collect_phase = false;

		/*
		 * Is there a collect->measure gap?
		 */
		if (_measure_ticks > USEC2TICK(CONVERSION_INTERVAL)) {

			/* schedule a fresh cycle call when we are ready to measure again */
			work_queue(HPWORK,
				   &_work,
				   (worker_t)&Airspeed::cycle_trampoline,
				   this,
				   _measure_ticks - USEC2TICK(CONVERSION_INTERVAL));

			return;
		}
	}

	/* measurement phase */
	ret = measure();
	if (OK != ret) {
		debug("measure error");
	}

	_sensor_ok = (ret == OK);

	/* next phase is collection */
	_collect_phase = true;

	/* schedule a fresh cycle call when the measurement is done */
	work_queue(HPWORK,
		   &_work,
		   (worker_t)&Airspeed::cycle_trampoline,
		   this,
		   USEC2TICK(CONVERSION_INTERVAL));
}

/**
 * Local functions in support of the shell command.
 */
namespace ets_airspeed
{

/* oddly, ERROR is not defined for c++ */
#ifdef ERROR
# undef ERROR
#endif
const int ERROR = -1;

ETSAirspeed	*g_dev;

void	start(int i2c_bus);
void	stop();
void	test();
void	reset();
void	info();

/**
 * Start the driver.
 *
 * This function only returns if the sensor is up and running
 * or could not be detected successfully.
 */
void
start(int i2c_bus)
{
	int fd;

	if (g_dev != nullptr)
		errx(1, "already started");

	/* create the driver */
	g_dev = new ETSAirspeed(i2c_bus);

	if (g_dev == nullptr)
		goto fail;

	if (OK != g_dev->Airspeed::init())
		goto fail;

	/* set the poll rate to default, starts automatic data collection */
	fd = open(AIRSPEED0_DEVICE_PATH, O_RDONLY);

	if (fd < 0)
		goto fail;

	if (ioctl(fd, SENSORIOCSPOLLRATE, SENSOR_POLLRATE_DEFAULT) < 0)
		goto fail;

	exit(0);

fail:

	if (g_dev != nullptr) {
		delete g_dev;
		g_dev = nullptr;
	}

	errx(1, "no ETS airspeed sensor connected");
}

/**
 * Stop the driver
 */
void
stop()
{
	if (g_dev != nullptr) {
		delete g_dev;
		g_dev = nullptr;

	} else {
		errx(1, "driver not running");
	}

	exit(0);
}

/**
 * Perform some basic functional tests on the driver;
 * make sure we can collect data from the sensor in polled
 * and automatic modes.
 */
void
test()
{
	struct differential_pressure_s report;
	ssize_t sz;
	int ret;

	int fd = open(ETS_PATH, O_RDONLY);

	if (fd < 0)
		err(1, "%s open failed (try 'ets_airspeed start' if the driver is not running", ETS_PATH);

	/* do a simple demand read */
	sz = read(fd, &report, sizeof(report));

	if (sz != sizeof(report))
		err(1, "immediate read failed");

	warnx("single read");
	warnx("diff pressure: %f pa", (double)report.differential_pressure_filtered_pa);

	/* start the sensor polling at 2Hz */
	if (OK != ioctl(fd, SENSORIOCSPOLLRATE, 2))
		errx(1, "failed to set 2Hz poll rate");

	/* read the sensor 5x and report each value */
	for (unsigned i = 0; i < 5; i++) {
		struct pollfd fds;

		/* wait for data to be ready */
		fds.fd = fd;
		fds.events = POLLIN;
		ret = poll(&fds, 1, 2000);

		if (ret != 1)
			errx(1, "timed out waiting for sensor data");

		/* now go get it */
		sz = read(fd, &report, sizeof(report));

		if (sz != sizeof(report))
			err(1, "periodic read failed");

		warnx("periodic read %u", i);
		warnx("diff pressure: %f pa", (double)report.differential_pressure_filtered_pa);
	}

	/* reset the sensor polling to its default rate */
	if (OK != ioctl(fd, SENSORIOCSPOLLRATE, SENSOR_POLLRATE_DEFAULT))
		errx(1, "failed to set default rate");

	errx(0, "PASS");
}

/**
 * Reset the driver.
 */
void
reset()
{
	int fd = open(ETS_PATH, O_RDONLY);

	if (fd < 0)
		err(1, "failed ");

	if (ioctl(fd, SENSORIOCRESET, 0) < 0)
		err(1, "driver reset failed");

	if (ioctl(fd, SENSORIOCSPOLLRATE, SENSOR_POLLRATE_DEFAULT) < 0)
		err(1, "driver poll restart failed");

	exit(0);
}

/**
 * Print a little info about the driver.
 */
void
info()
{
	if (g_dev == nullptr)
		errx(1, "driver not running");

	printf("state @ %p\n", g_dev);
	g_dev->print_info();

	exit(0);
}

} // namespace

static void
ets_airspeed_usage()
{
	warnx("usage: ets_airspeed command [options]");
	warnx("options:");
	warnx("\t-b --bus i2cbus (%d)", PX4_I2C_BUS_DEFAULT);
	warnx("command:");
	warnx("\tstart|stop|reset|test|info");
}

int
ets_airspeed_main(int argc, char *argv[])
{
	int i2c_bus = PX4_I2C_BUS_DEFAULT;

	int i;

	for (i = 1; i < argc; i++) {
		if (strcmp(argv[i], "-b") == 0 || strcmp(argv[i], "--bus") == 0) {
			if (argc > i + 1) {
				i2c_bus = atoi(argv[i + 1]);
			}
		}
	}

	/*
	 * Start/load the driver.
	 */
	if (!strcmp(argv[1], "start"))
		ets_airspeed::start(i2c_bus);

	/*
	 * Stop the driver
	 */
	if (!strcmp(argv[1], "stop"))
		ets_airspeed::stop();

	/*
	 * Test the driver/device.
	 */
	if (!strcmp(argv[1], "test"))
		ets_airspeed::test();

	/*
	 * Reset the driver.
	 */
	if (!strcmp(argv[1], "reset"))
		ets_airspeed::reset();

	/*
	 * Print driver information.
	 */
	if (!strcmp(argv[1], "info") || !strcmp(argv[1], "status"))
		ets_airspeed::info();

	ets_airspeed_usage();
	exit(0);
}
<commit_msg>Airspeed ETS: fix code style<commit_after>/****************************************************************************
 *
 *   Copyright (c) 2013, 2014 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/**
 * @file ets_airspeed.cpp
 * @author Simon Wilks
 *
 * Driver for the Eagle Tree Airspeed V3 connected via I2C.
 */

#include <nuttx/config.h>

#include <drivers/device/i2c.h>

#include <sys/types.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
#include <semaphore.h>
#include <string.h>
#include <fcntl.h>
#include <poll.h>
#include <errno.h>
#include <stdio.h>
#include <math.h>
#include <unistd.h>

#include <nuttx/arch.h>
#include <nuttx/wqueue.h>
#include <nuttx/clock.h>

#include <board_config.h>

#include <systemlib/airspeed.h>
#include <systemlib/err.h>
#include <systemlib/param/param.h>
#include <systemlib/perf_counter.h>

#include <drivers/drv_airspeed.h>
#include <drivers/drv_hrt.h>
#include <drivers/device/ringbuffer.h>

#include <uORB/uORB.h>
#include <uORB/topics/differential_pressure.h>
#include <uORB/topics/subsystem_info.h>
#include <drivers/airspeed/airspeed.h>

/* I2C bus address */
#define I2C_ADDRESS	0x75	/* 7-bit address. 8-bit address is 0xEA */
#define ETS_PATH	"/dev/ets_airspeed"

/* Register address */
#define READ_CMD	0x07	/* Read the data */

/**
 * The Eagle Tree Airspeed V3 cannot provide accurate reading below speeds of 15km/h.
 * You can set this value to 12 if you want a zero reading below 15km/h.
 */
#define MIN_ACCURATE_DIFF_PRES_PA 0

/* Measurement rate is 100Hz */
#define CONVERSION_INTERVAL	(1000000 / 100)	/* microseconds */

class ETSAirspeed : public Airspeed
{
public:
	ETSAirspeed(int bus, int address = I2C_ADDRESS, const char *path = ETS_PATH);

protected:

	/**
	* Perform a poll cycle; collect from the previous measurement
	* and start a new one.
	*/
	virtual void	cycle();
	virtual int	measure();
	virtual int	collect();

};

/*
 * Driver 'main' command.
 */
extern "C" __EXPORT int ets_airspeed_main(int argc, char *argv[]);

ETSAirspeed::ETSAirspeed(int bus, int address, const char *path) : Airspeed(bus, address,
			CONVERSION_INTERVAL, path)
{

}

int
ETSAirspeed::measure()
{
	int ret;

	/*
	 * Send the command to begin a measurement.
	 */
	uint8_t cmd = READ_CMD;
	ret = transfer(&cmd, 1, nullptr, 0);

	if (OK != ret) {
		perf_count(_comms_errors);
	}

	return ret;
}

int
ETSAirspeed::collect()
{
	int	ret = -EIO;

	/* read from the sensor */
	uint8_t val[2] = {0, 0};

	perf_begin(_sample_perf);

	ret = transfer(nullptr, 0, &val[0], 2);

	if (ret < 0) {
		perf_count(_comms_errors);
		return ret;
	}

	uint16_t diff_pres_pa_raw = val[1] << 8 | val[0];

	if (diff_pres_pa_raw == 0) {
		// a zero value means the pressure sensor cannot give us a
		// value. We need to return, and not report a value or the
		// caller could end up using this value as part of an
		// average
		perf_count(_comms_errors);
		log("zero value from sensor");
		return -1;
	}

	// The raw value still should be compensated for the known offset
	diff_pres_pa_raw -= _diff_pres_offset;

	// Track maximum differential pressure measured (so we can work out top speed).
	if (diff_pres_pa_raw > _max_differential_pressure_pa) {
		_max_differential_pressure_pa = diff_pres_pa_raw;
	}

	differential_pressure_s report;
	report.timestamp = hrt_absolute_time();
	report.error_count = perf_event_count(_comms_errors);

	// XXX we may want to smooth out the readings to remove noise.
	report.differential_pressure_filtered_pa = diff_pres_pa_raw;
	report.differential_pressure_raw_pa = diff_pres_pa_raw;
	report.temperature = -1000.0f;
	report.max_differential_pressure_pa = _max_differential_pressure_pa;

	if (_airspeed_pub > 0 && !(_pub_blocked)) {
		/* publish it */
		orb_publish(ORB_ID(differential_pressure), _airspeed_pub, &report);
	}

	new_report(report);

	/* notify anyone waiting for data */
	poll_notify(POLLIN);

	ret = OK;

	perf_end(_sample_perf);

	return ret;
}

void
ETSAirspeed::cycle()
{
	int ret;

	/* collection phase? */
	if (_collect_phase) {

		/* perform collection */
		ret = collect();

		if (OK != ret) {
			perf_count(_comms_errors);
			/* restart the measurement state machine */
			start();
			_sensor_ok = false;
			return;
		}

		/* next phase is measurement */
		_collect_phase = false;

		/*
		 * Is there a collect->measure gap?
		 */
		if (_measure_ticks > USEC2TICK(CONVERSION_INTERVAL)) {

			/* schedule a fresh cycle call when we are ready to measure again */
			work_queue(HPWORK,
				   &_work,
				   (worker_t)&Airspeed::cycle_trampoline,
				   this,
				   _measure_ticks - USEC2TICK(CONVERSION_INTERVAL));

			return;
		}
	}

	/* measurement phase */
	ret = measure();

	if (OK != ret) {
		debug("measure error");
	}

	_sensor_ok = (ret == OK);

	/* next phase is collection */
	_collect_phase = true;

	/* schedule a fresh cycle call when the measurement is done */
	work_queue(HPWORK,
		   &_work,
		   (worker_t)&Airspeed::cycle_trampoline,
		   this,
		   USEC2TICK(CONVERSION_INTERVAL));
}

/**
 * Local functions in support of the shell command.
 */
namespace ets_airspeed
{

/* oddly, ERROR is not defined for c++ */
#ifdef ERROR
# undef ERROR
#endif
const int ERROR = -1;

ETSAirspeed	*g_dev;

void	start(int i2c_bus);
void	stop();
void	test();
void	reset();
void	info();

/**
 * Start the driver.
 *
 * This function only returns if the sensor is up and running
 * or could not be detected successfully.
 */
void
start(int i2c_bus)
{
	int fd;

	if (g_dev != nullptr) {
		errx(1, "already started");
	}

	/* create the driver */
	g_dev = new ETSAirspeed(i2c_bus);

	if (g_dev == nullptr) {
		goto fail;
	}

	if (OK != g_dev->Airspeed::init()) {
		goto fail;
	}

	/* set the poll rate to default, starts automatic data collection */
	fd = open(AIRSPEED0_DEVICE_PATH, O_RDONLY);

	if (fd < 0) {
		goto fail;
	}

	if (ioctl(fd, SENSORIOCSPOLLRATE, SENSOR_POLLRATE_DEFAULT) < 0) {
		goto fail;
	}

	exit(0);

fail:

	if (g_dev != nullptr) {
		delete g_dev;
		g_dev = nullptr;
	}

	errx(1, "no ETS airspeed sensor connected");
}

/**
 * Stop the driver
 */
void
stop()
{
	if (g_dev != nullptr) {
		delete g_dev;
		g_dev = nullptr;

	} else {
		errx(1, "driver not running");
	}

	exit(0);
}

/**
 * Perform some basic functional tests on the driver;
 * make sure we can collect data from the sensor in polled
 * and automatic modes.
 */
void
test()
{
	struct differential_pressure_s report;
	ssize_t sz;
	int ret;

	int fd = open(ETS_PATH, O_RDONLY);

	if (fd < 0) {
		err(1, "%s open failed (try 'ets_airspeed start' if the driver is not running", ETS_PATH);
	}

	/* do a simple demand read */
	sz = read(fd, &report, sizeof(report));

	if (sz != sizeof(report)) {
		err(1, "immediate read failed");
	}

	warnx("single read");
	warnx("diff pressure: %f pa", (double)report.differential_pressure_filtered_pa);

	/* start the sensor polling at 2Hz */
	if (OK != ioctl(fd, SENSORIOCSPOLLRATE, 2)) {
		errx(1, "failed to set 2Hz poll rate");
	}

	/* read the sensor 5x and report each value */
	for (unsigned i = 0; i < 5; i++) {
		struct pollfd fds;

		/* wait for data to be ready */
		fds.fd = fd;
		fds.events = POLLIN;
		ret = poll(&fds, 1, 2000);

		if (ret != 1) {
			errx(1, "timed out waiting for sensor data");
		}

		/* now go get it */
		sz = read(fd, &report, sizeof(report));

		if (sz != sizeof(report)) {
			err(1, "periodic read failed");
		}

		warnx("periodic read %u", i);
		warnx("diff pressure: %f pa", (double)report.differential_pressure_filtered_pa);
	}

	/* reset the sensor polling to its default rate */
	if (OK != ioctl(fd, SENSORIOCSPOLLRATE, SENSOR_POLLRATE_DEFAULT)) {
		errx(1, "failed to set default rate");
	}

	errx(0, "PASS");
}

/**
 * Reset the driver.
 */
void
reset()
{
	int fd = open(ETS_PATH, O_RDONLY);

	if (fd < 0) {
		err(1, "failed ");
	}

	if (ioctl(fd, SENSORIOCRESET, 0) < 0) {
		err(1, "driver reset failed");
	}

	if (ioctl(fd, SENSORIOCSPOLLRATE, SENSOR_POLLRATE_DEFAULT) < 0) {
		err(1, "driver poll restart failed");
	}

	exit(0);
}

/**
 * Print a little info about the driver.
 */
void
info()
{
	if (g_dev == nullptr) {
		errx(1, "driver not running");
	}

	printf("state @ %p\n", g_dev);
	g_dev->print_info();

	exit(0);
}

} // namespace

static void
ets_airspeed_usage()
{
	warnx("usage: ets_airspeed command [options]");
	warnx("options:");
	warnx("\t-b --bus i2cbus (%d)", PX4_I2C_BUS_DEFAULT);
	warnx("command:");
	warnx("\tstart|stop|reset|test|info");
}

int
ets_airspeed_main(int argc, char *argv[])
{
	int i2c_bus = PX4_I2C_BUS_DEFAULT;

	int i;

	for (i = 1; i < argc; i++) {
		if (strcmp(argv[i], "-b") == 0 || strcmp(argv[i], "--bus") == 0) {
			if (argc > i + 1) {
				i2c_bus = atoi(argv[i + 1]);
			}
		}
	}

	/*
	 * Start/load the driver.
	 */
	if (!strcmp(argv[1], "start")) {
		ets_airspeed::start(i2c_bus);
	}

	/*
	 * Stop the driver
	 */
	if (!strcmp(argv[1], "stop")) {
		ets_airspeed::stop();
	}

	/*
	 * Test the driver/device.
	 */
	if (!strcmp(argv[1], "test")) {
		ets_airspeed::test();
	}

	/*
	 * Reset the driver.
	 */
	if (!strcmp(argv[1], "reset")) {
		ets_airspeed::reset();
	}

	/*
	 * Print driver information.
	 */
	if (!strcmp(argv[1], "info") || !strcmp(argv[1], "status")) {
		ets_airspeed::info();
	}

	ets_airspeed_usage();
	exit(0);
}
<|endoftext|>


<commit_before>#include "view.h"
#include "shader.h"

#include <SDL.h>
#include "gl.h"
#include <glm/gtx/transform.hpp>

#include <stdexcept>

namespace te
{
    const static GLfloat Z = 100;

    static void checkViewport(const FloatRect& viewport)
    {
        if (viewport.x < 0 ||
            viewport.y < 0 ||
            viewport.w > 1 ||
            viewport.y > 1)
        {
            throw std::runtime_error("View: Viewport must be in range [0,1].");
        }
    }

    View::View()
        : View(FloatRect(0,0,0,0))
    {}

    View::View(const FloatRect& lens)
        : mLens(lens)
        , mViewport(0, 0, 1, 1)
    {}

    FloatRect View::getLens() const
    {
        return mLens;
    }

    FloatRect View::getViewport() const
    {
        return mViewport;
    }

    void View::reset(const FloatRect& lens)
    {
        mLens = lens;
    }

    void View::setViewport(const FloatRect& viewport)
    {
        checkViewport(viewport);
        mViewport = viewport;
    }

    View::Lock View::activate(const View& view, const std::shared_ptr<Shader>& pShader, SDL_Window& window)
    {
        if (!pShader) { throw std::runtime_error("View::activate: Shader required."); }

        int width = 0, height = 0;
        SDL_GetWindowSize(&window, &width, &height);
        return activate(view, pShader, width, height);
    }

    View::Lock View::activate(const View& view, const std::shared_ptr<Shader>& pShader, int width, int height)
    {
        if (!pShader) { throw std::runtime_error("View::activate: Shader required."); }

        GLint originalViewport[4];
        glGetIntegerv(GL_VIEWPORT, originalViewport);

        FloatRect viewport = view.mViewport;
        glViewport((int)(viewport.x * width),
                   (int)(height - (height * (viewport.h + viewport.y))),
                   (int)(viewport.w * width),
                   (int)(viewport.h * height));

        glm::mat4 originalProjection = pShader->getProjection();
        pShader->setProjection(glm::ortho<GLfloat>(view.mLens.x, view.mLens.x + view.mLens.w, view.mLens.y + view.mLens.h, view.mLens.y, -Z, Z));

        return View::Lock(pShader, originalProjection, { originalViewport[0],
                                                         originalViewport[1],
                                                         originalViewport[2],
                                                         originalViewport[3] });
    }

    View::Lock::Lock(const std::shared_ptr<Shader>& pShader,
                     const glm::mat4& originalProjection,
                     const IntRect& originalViewport)
        : mpShader(pShader)
        , mProjection(originalProjection)
        , mViewport(originalViewport)
    {
        assert(pShader);
    }

    View::Lock& View::Lock::operator=(Lock&& o)
    {
        mpShader = o.mpShader;
        mProjection = o.mProjection;
        mViewport = o.mViewport;

        o.mpShader = nullptr;

        return *this;
    }

    View::Lock::Lock(Lock&& o)
        : mpShader(o.mpShader)
        , mProjection(o.mProjection)
        , mViewport(o.mViewport)
    {
        o.mpShader = nullptr;
    }

    View::Lock::~Lock()
    {
        // Null mpShader indicates moved lock
        if (mpShader) {
            // Restore lens and viewport
            mpShader->setProjection(mProjection);
            glViewport(mViewport.x, mViewport.y, mViewport.w, mViewport.h);
        }
    }
}
<commit_msg>Modify Lock move assignment operator<commit_after>#include "view.h"
#include "shader.h"

#include <SDL.h>
#include "gl.h"
#include <glm/gtx/transform.hpp>

#include <stdexcept>

namespace te
{
    const static GLfloat Z = 100;

    static void checkViewport(const FloatRect& viewport)
    {
        if (viewport.x < 0 ||
            viewport.y < 0 ||
            viewport.w > 1 ||
            viewport.y > 1)
        {
            throw std::runtime_error("View: Viewport must be in range [0,1].");
        }
    }

    View::View()
        : View(FloatRect(0,0,0,0))
    {}

    View::View(const FloatRect& lens)
        : mLens(lens)
        , mViewport(0, 0, 1, 1)
    {}

    FloatRect View::getLens() const
    {
        return mLens;
    }

    FloatRect View::getViewport() const
    {
        return mViewport;
    }

    void View::reset(const FloatRect& lens)
    {
        mLens = lens;
    }

    void View::setViewport(const FloatRect& viewport)
    {
        checkViewport(viewport);
        mViewport = viewport;
    }

    View::Lock View::activate(const View& view, const std::shared_ptr<Shader>& pShader, SDL_Window& window)
    {
        if (!pShader) { throw std::runtime_error("View::activate: Shader required."); }

        int width = 0, height = 0;
        SDL_GetWindowSize(&window, &width, &height);
        return activate(view, pShader, width, height);
    }

    View::Lock View::activate(const View& view, const std::shared_ptr<Shader>& pShader, int width, int height)
    {
        if (!pShader) { throw std::runtime_error("View::activate: Shader required."); }

        GLint originalViewport[4];
        glGetIntegerv(GL_VIEWPORT, originalViewport);

        FloatRect viewport = view.mViewport;
        glViewport((int)(viewport.x * width),
                   (int)(height - (height * (viewport.h + viewport.y))),
                   (int)(viewport.w * width),
                   (int)(viewport.h * height));

        glm::mat4 originalProjection = pShader->getProjection();
        pShader->setProjection(glm::ortho<GLfloat>(view.mLens.x, view.mLens.x + view.mLens.w, view.mLens.y + view.mLens.h, view.mLens.y, -Z, Z));

        return View::Lock(pShader, originalProjection, { originalViewport[0],
                                                         originalViewport[1],
                                                         originalViewport[2],
                                                         originalViewport[3] });
    }

    View::Lock::Lock(const std::shared_ptr<Shader>& pShader,
                     const glm::mat4& originalProjection,
                     const IntRect& originalViewport)
        : mpShader(pShader)
        , mProjection(originalProjection)
        , mViewport(originalViewport)
    {
        assert(pShader);
    }

    View::Lock& View::Lock::operator=(Lock&& o)
    {
        mpShader = o.mpShader;
        // Projection and viewport should not change

        o.mpShader = nullptr;

        return *this;
    }

    View::Lock::Lock(Lock&& o)
        : mpShader(o.mpShader)
        , mProjection(o.mProjection)
        , mViewport(o.mViewport)
    {
        o.mpShader = nullptr;
    }

    View::Lock::~Lock()
    {
        // Null mpShader indicates moved lock
        if (mpShader) {
            // Restore lens and viewport
            mpShader->setProjection(mProjection);
            glViewport(mViewport.x, mViewport.y, mViewport.w, mViewport.h);
        }
    }
}
<|endoftext|>


<commit_before>/*
 Copyright 2014 Arjan van der Velde, vandervelde.ag [at] gmail

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

#pragma once

#include <vector>
#include <string>
#include <iostream>

namespace TwoBit
{
class SequenceMeta;
class TwoBitFile;
}

std::ostream& operator<<(std::ostream& s, const TwoBit::SequenceMeta& x);

namespace TwoBit
{

class SequenceMeta
{

	// Contains enough information to open a two-bit file and read a specific
	// sequence, without having to read in any meta data.

private:
	class Region
	{
	public:
		uint32_t pos_;
		int action_; // start or end
		Region() :
				pos_(0), action_(0)
		{
		}
		Region(const uint32_t& pos, const int& action) :
				pos_(pos), action_(action)
		{
		}
	};

	friend class TwoBitFile;

	// make it "printable"
	friend std::ostream& ::operator<<(std::ostream& s, const SequenceMeta& x);

public:
	std::string name_;
	uint32_t offset_;
	std::string filename_;
	bool swapped_;
	uint32_t dnaSize_;
	uint32_t dnaBytes_;
	uint32_t packedPos_;
	std::vector<Region> nRegions; // N-s
	std::vector<Region> mRegions; // Masked

	SequenceMeta(const std::string& name, const uint32_t offset,
			const std::string& filename, const bool swapped)
	{
		name_ = name;
		offset_ = offset;
		filename_ = filename;
		swapped_ = swapped;
		dnaSize_ = 0;
		dnaBytes_ = 0;
		packedPos_ = 0;
	}
	SequenceMeta()
	{
		name_ = "";
		offset_ = 0;
		filename_ = "";
		swapped_ = false;
		dnaSize_ = 0;
		dnaBytes_ = 0;
		packedPos_ = 0;
	}
//	SequenceMeta(const SequenceMeta& other) {
//		name_ = other.name_;
//		offset_ = other.offset_;
//		filename_ = other.filename_;
//		swapped_ = other.swapped_;
//		dnaSize_ = other.dnaSize_;
//		dnaBytes_ = other.dnaBytes_;
//		packedPos_ = other.packedPos_;
//	}

};

} // namespace TwoBit

<commit_msg>remove comments.<commit_after>/*
 Copyright 2014 Arjan van der Velde, vandervelde.ag [at] gmail

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

#pragma once

#include <vector>
#include <string>
#include <iostream>

namespace TwoBit
{
class SequenceMeta;
class TwoBitFile;
}

std::ostream& operator<<(std::ostream& s, const TwoBit::SequenceMeta& x);

namespace TwoBit
{

class SequenceMeta
{

	// Contains enough information to open a two-bit file and read a specific
	// sequence, without having to read in any meta data.

private:
	class Region
	{
	public:
		uint32_t pos_;
		int action_; // start or end
		Region() :
				pos_(0), action_(0)
		{
		}
		Region(const uint32_t& pos, const int& action) :
				pos_(pos), action_(action)
		{
		}
	};

	friend class TwoBitFile;

	// make it "printable"
	friend std::ostream& ::operator<<(std::ostream& s, const SequenceMeta& x);

public:
	std::string name_;
	uint32_t offset_;
	std::string filename_;
	bool swapped_;
	uint32_t dnaSize_;
	uint32_t dnaBytes_;
	uint32_t packedPos_;
	std::vector<Region> nRegions; // N-s
	std::vector<Region> mRegions; // Masked

	SequenceMeta(const std::string& name, const uint32_t offset,
			const std::string& filename, const bool swapped)
	{
		name_ = name;
		offset_ = offset;
		filename_ = filename;
		swapped_ = swapped;
		dnaSize_ = 0;
		dnaBytes_ = 0;
		packedPos_ = 0;
	}
	SequenceMeta()
	{
		name_ = "";
		offset_ = 0;
		filename_ = "";
		swapped_ = false;
		dnaSize_ = 0;
		dnaBytes_ = 0;
		packedPos_ = 0;
	}
};

} // namespace TwoBit

<|endoftext|>


<commit_before>#include <acquire_release.h>
#include <static_image.h>
#include <math.h>
#include <stdio.h>
#include <HalideRuntime.h>
#include <assert.h>
#include <string.h>

const int W = 256, H = 256;

#if defined(TEST_OPENCL)
// Implement OpenCL custom context.

#ifdef __APPLE__
#include <OpenCL/cl.h>
#else
#include <CL/cl.h>
#endif

// Just use a global context and queue, created and destroyed by main.
cl_context cl_ctx = NULL;
cl_command_queue cl_q = NULL;

// Create the global context. This is just a helper function not called by Halide.
int init_context() {
    cl_int err = 0;

    const cl_uint maxPlatforms = 4;
    cl_platform_id platforms[maxPlatforms];
    cl_uint platformCount = 0;

    err = clGetPlatformIDs( maxPlatforms, platforms, &platformCount );
    if (err != CL_SUCCESS) {
        printf("clGetPlatformIDs failed (%d)\n", err);
        return err;
    }

    cl_platform_id platform = NULL;

    // Find the requested platform, or the first if none specified.
    const char * name = getenv("HL_OCL_PLATFORM");
    if (name != NULL) {
        for (cl_uint i = 0; i < platformCount; ++i) {
            const cl_uint maxPlatformName = 256;
            char platformName[maxPlatformName];
            err = clGetPlatformInfo( platforms[i], CL_PLATFORM_NAME, maxPlatformName, platformName, NULL );
            if (err != CL_SUCCESS) continue;

            // A platform matches the request if it is a substring of the platform name.
            if (strstr(platformName, name)) {
                platform = platforms[i];
                break;
            }
        }
    } else if (platformCount > 0) {
        platform = platforms[0];
    }
    if (platform == NULL){
        printf("Failed to find platform\n");
        return CL_INVALID_PLATFORM;
    }

    cl_device_type device_type = 0;
    // Find the device types requested.
    const char * dev_type = getenv("HL_OCL_DEVICE");
    if (dev_type != NULL) {
        if (strstr("cpu", dev_type)) {
            device_type |= CL_DEVICE_TYPE_CPU;
        }
        if (strstr("gpu", dev_type)) {
            device_type |= CL_DEVICE_TYPE_GPU;
        }
    }
    // If no devices are specified yet, just use all.
    if (device_type == 0) {
        device_type = CL_DEVICE_TYPE_ALL;
    }

    // Make sure we have a device
    const cl_uint maxDevices = 4;
    cl_device_id devices[maxDevices];
    cl_uint deviceCount = 0;
    err = clGetDeviceIDs( platform, device_type, maxDevices, devices, &deviceCount );
    if (err != CL_SUCCESS) {
        printf("clGetDeviceIDs failed (%d)\n", err);
        return err;
    }
    if (deviceCount == 0) {
        printf("Failed to get device\n");
        return CL_DEVICE_NOT_FOUND;
    }

    cl_device_id dev = devices[deviceCount-1];

    // Create context and command queue.
    cl_context_properties properties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platform, 0 };
    cl_ctx = clCreateContext(properties, 1, &dev, NULL, NULL, &err);
    if (err != CL_SUCCESS) {
        printf("clCreateContext failed (%d)\n", err);
        return err;
    }

    cl_q = clCreateCommandQueue(cl_ctx, dev, 0, &err);
    if (err != CL_SUCCESS) {
        printf("clCreateCommandQueue failed (%d)\n", err);
        return err;
    }
    printf("Created CL context %p\n", cl_ctx);
    return 0;
}

void destroy_context() {
    printf("Destroying CL context %p\n", cl_ctx);
    clReleaseCommandQueue(cl_q);
    clReleaseContext(cl_ctx);
    cl_q = NULL;
    cl_ctx = NULL;
}

// These functions replace the acquire/release implementation in src/runtime/opencl.cpp.
// Since we don't parallelize access to the GPU in the schedule, we don't need synchronization
// in our implementation of these functions.
extern "C" int halide_acquire_cl_context(void *user_context, cl_context *ctx, cl_command_queue *q) {
    printf("Acquired CL context %p\n", cl_ctx);
    *ctx = cl_ctx;
    *q = cl_q;
    return 0;
}

extern "C" int halide_release_cl_context(void *user_context) {
    printf("Releasing CL context %p\n", cl_ctx);
    return 0;
}
#elif defined(TEST_PTX)
// Implement CUDA custom context.
#include <cuda.h>

CUcontext cuda_ctx = NULL;

int init_context() {
    // Initialize CUDA
    CUresult err = cuInit(0);
    if (err != CUDA_SUCCESS) {
        printf("cuInit failed (%d)\n", err);
        return err;
    }

    // Make sure we have a device
    int deviceCount = 0;
    err = cuDeviceGetCount(&deviceCount);
    if (err != CUDA_SUCCESS) {
        printf("cuGetDeviceCount failed (%d)\n", err);
        return err;
    }
    if (deviceCount <= 0) {
        printf("No CUDA devices available\n");
        return CUDA_ERROR_NO_DEVICE;
    }

    char *device_str = getenv("HL_GPU_DEVICE");

    CUdevice dev;
    // Get device
    CUresult status;
    if (device_str) {
        status = cuDeviceGet(&dev, atoi(device_str));
    } else {
        // Try to get a device >0 first, since 0 should be our display device
        // For now, don't try devices > 2 to maintain compatibility with previous behavior.
        if (deviceCount > 2)
            deviceCount = 2;
        for (int id = deviceCount - 1; id >= 0; id--) {
            status = cuDeviceGet(&dev, id);
            if (status == CUDA_SUCCESS) break;
        }
    }
    if (status != CUDA_SUCCESS) {
        printf("Failed to get CUDA device\n");
        return status;
    }

    // Create context
    err = cuCtxCreate(&cuda_ctx, 0, dev);
    if (err != CUDA_SUCCESS) {
        printf("cuCtxCreate failed (%d)\n", err);
        return err;
    }
    printf("Created CUDA context %p\n", cuda_ctx);

    return 0;
}

void destroy_context() {
    printf("Destroying CUDA context %p\n", cuda_ctx);
    cuCtxDestroy(cuda_ctx);
    cuda_ctx = NULL;
}

// These functions replace the acquire/release implementation in src/runtime/cuda.cpp.
// Since we don't parallelize access to the GPU in the schedule, we don't need synchronization
// in our implementation of these functions.
extern "C" int halide_acquire_cuda_context(void *user_context, CUcontext *ctx) {
    printf("Acquired CUDA context %p\n", cuda_ctx);
    *ctx = cuda_ctx;
    return 0;
}

extern "C" int halide_release_cuda_context(void *user_context) {
    printf("Releasing CUDA context %p\n", cuda_ctx);
    return 0;
}
#else
// Just use the default implementation of acquire/release.
int init_context() {
    printf("Using default implementation of acquire/release\n");
    return 0;
}
void destroy_context() {
}
#endif

int main(int argc, char **argv) {
    // Initialize the runtime specific GPU context.
    int ret = init_context();
    if (ret != 0) {
        return ret;
    }

    // Everything else is a normal Halide program. The GPU runtime will call
    // the above acquire/release functions to get the context instead of using
    // its own internal context.
    Image<float> input(W, H);
    for (int y = 0; y < input.height(); y++) {
        for (int x = 0; x < input.width(); x++) {
            input(x, y) = (float)(x * y);
        }
    }

    input.set_host_dirty();

    Image<float> output(W, H);

    acquire_release(input, output);

    output.copy_to_host();

    for (int y = 0; y < output.height(); y++) {
        for (int x = 0; x < output.width(); x++) {
            if (input(x, y) * 2.0f + 1.0f != output(x, y)) {
                printf("Error at (%d, %d): %f != %f\n", x, y, input(x, y) * 2.0f + 1.0f, output(x, y));
                return -1;
            }
        }
    }

    // We need to free our GPU buffers before destroying the context.
    input.dev_free();
    output.dev_free();

    // Free the context we created.
    destroy_context();

    printf("Success!\n");
    return 0;
}
<commit_msg>Removed environment variables from acquire/release test.<commit_after>#include <acquire_release.h>
#include <static_image.h>
#include <math.h>
#include <stdio.h>
#include <HalideRuntime.h>
#include <assert.h>
#include <string.h>

const int W = 256, H = 256;

#if defined(TEST_OPENCL)
// Implement OpenCL custom context.

#ifdef __APPLE__
#include <OpenCL/cl.h>
#else
#include <CL/cl.h>
#endif

// Just use a global context and queue, created and destroyed by main.
cl_context cl_ctx = NULL;
cl_command_queue cl_q = NULL;

// Create the global context. This is just a helper function not called by Halide.
int init_context() {
    cl_int err = 0;

    const cl_uint maxPlatforms = 4;
    cl_platform_id platforms[maxPlatforms];
    cl_uint platformCount = 0;

    err = clGetPlatformIDs( maxPlatforms, platforms, &platformCount );
    if (err != CL_SUCCESS) {
        printf("clGetPlatformIDs failed (%d)\n", err);
        return err;
    }

    cl_platform_id platform = NULL;

    if (platformCount > 0) {
        platform = platforms[0];
    }
    if (platform == NULL){
        printf("Failed to get platform\n");
        return CL_INVALID_PLATFORM;
    }

    cl_device_type device_type = CL_DEVICE_TYPE_ALL;

    // Make sure we have a device
    const cl_uint maxDevices = 4;
    cl_device_id devices[maxDevices];
    cl_uint deviceCount = 0;
    err = clGetDeviceIDs( platform, device_type, maxDevices, devices, &deviceCount );
    if (err != CL_SUCCESS) {
        printf("clGetDeviceIDs failed (%d)\n", err);
        return err;
    }
    if (deviceCount == 0) {
        printf("Failed to get device\n");
        return CL_DEVICE_NOT_FOUND;
    }

    cl_device_id dev = devices[deviceCount-1];

    // Create context and command queue.
    cl_context_properties properties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platform, 0 };
    cl_ctx = clCreateContext(properties, 1, &dev, NULL, NULL, &err);
    if (err != CL_SUCCESS) {
        printf("clCreateContext failed (%d)\n", err);
        return err;
    }

    cl_q = clCreateCommandQueue(cl_ctx, dev, 0, &err);
    if (err != CL_SUCCESS) {
        printf("clCreateCommandQueue failed (%d)\n", err);
        return err;
    }
    printf("Created CL context %p\n", cl_ctx);
    return 0;
}

void destroy_context() {
    printf("Destroying CL context %p\n", cl_ctx);
    clReleaseCommandQueue(cl_q);
    clReleaseContext(cl_ctx);
    cl_q = NULL;
    cl_ctx = NULL;
}

// These functions replace the acquire/release implementation in src/runtime/opencl.cpp.
// Since we don't parallelize access to the GPU in the schedule, we don't need synchronization
// in our implementation of these functions.
extern "C" int halide_acquire_cl_context(void *user_context, cl_context *ctx, cl_command_queue *q) {
    printf("Acquired CL context %p\n", cl_ctx);
    *ctx = cl_ctx;
    *q = cl_q;
    return 0;
}

extern "C" int halide_release_cl_context(void *user_context) {
    printf("Releasing CL context %p\n", cl_ctx);
    return 0;
}
#elif defined(TEST_PTX)
// Implement CUDA custom context.
#include <cuda.h>

CUcontext cuda_ctx = NULL;

int init_context() {
    // Initialize CUDA
    CUresult err = cuInit(0);
    if (err != CUDA_SUCCESS) {
        printf("cuInit failed (%d)\n", err);
        return err;
    }

    // Make sure we have a device
    int deviceCount = 0;
    err = cuDeviceGetCount(&deviceCount);
    if (err != CUDA_SUCCESS) {
        printf("cuGetDeviceCount failed (%d)\n", err);
        return err;
    }
    if (deviceCount <= 0) {
        printf("No CUDA devices available\n");
        return CUDA_ERROR_NO_DEVICE;
    }

    CUdevice dev;
    // Get device
    CUresult status;
    // Try to get a device >0 first, since 0 should be our display device
    // For now, don't try devices > 2 to maintain compatibility with previous behavior.
    if (deviceCount > 2)
        deviceCount = 2;
    for (int id = deviceCount - 1; id >= 0; id--) {
        status = cuDeviceGet(&dev, id);
        if (status == CUDA_SUCCESS) break;
    }

    if (status != CUDA_SUCCESS) {
        printf("Failed to get CUDA device\n");
        return status;
    }

    // Create context
    err = cuCtxCreate(&cuda_ctx, 0, dev);
    if (err != CUDA_SUCCESS) {
        printf("cuCtxCreate failed (%d)\n", err);
        return err;
    }
    printf("Created CUDA context %p\n", cuda_ctx);

    return 0;
}

void destroy_context() {
    printf("Destroying CUDA context %p\n", cuda_ctx);
    cuCtxDestroy(cuda_ctx);
    cuda_ctx = NULL;
}

// These functions replace the acquire/release implementation in src/runtime/cuda.cpp.
// Since we don't parallelize access to the GPU in the schedule, we don't need synchronization
// in our implementation of these functions.
extern "C" int halide_acquire_cuda_context(void *user_context, CUcontext *ctx) {
    printf("Acquired CUDA context %p\n", cuda_ctx);
    *ctx = cuda_ctx;
    return 0;
}

extern "C" int halide_release_cuda_context(void *user_context) {
    printf("Releasing CUDA context %p\n", cuda_ctx);
    return 0;
}
#else
// Just use the default implementation of acquire/release.
int init_context() {
    printf("Using default implementation of acquire/release\n");
    return 0;
}
void destroy_context() {
}
#endif

int main(int argc, char **argv) {
    // Initialize the runtime specific GPU context.
    int ret = init_context();
    if (ret != 0) {
        return ret;
    }

    // Everything else is a normal Halide program. The GPU runtime will call
    // the above acquire/release functions to get the context instead of using
    // its own internal context.
    Image<float> input(W, H);
    for (int y = 0; y < input.height(); y++) {
        for (int x = 0; x < input.width(); x++) {
            input(x, y) = (float)(x * y);
        }
    }

    input.set_host_dirty();

    Image<float> output(W, H);

    acquire_release(input, output);

    output.copy_to_host();

    for (int y = 0; y < output.height(); y++) {
        for (int x = 0; x < output.width(); x++) {
            if (input(x, y) * 2.0f + 1.0f != output(x, y)) {
                printf("Error at (%d, %d): %f != %f\n", x, y, input(x, y) * 2.0f + 1.0f, output(x, y));
                return -1;
            }
        }
    }

    // We need to free our GPU buffers before destroying the context.
    input.dev_free();
    output.dev_free();

    // Free the context we created.
    destroy_context();

    printf("Success!\n");
    return 0;
}
<|endoftext|>


<commit_before>#include <agency/future.hpp>
#include <agency/new_executor_traits.hpp>
#include <iostream>
#include <cassert>
#include <algorithm>
#include <numeric>
#include <mutex>

#include "test_executors.hpp"

template<class Executor>
void test()
{
  using executor_type = Executor;

  {
    // execute returning user-specified container

    executor_type exec;

    size_t n = 100;

    std::vector<int> result = agency::new_executor_traits<executor_type>::template execute<std::vector<int>>(exec, [](size_t idx)
    {
      return idx;
    },
    n);

    std::vector<int> ref(n);
    std::iota(ref.begin(), ref.end(), 0);

    assert(std::equal(ref.begin(), ref.end(), result.begin()));
    assert(exec.valid());
  }

  {
    // execute returning default container

    executor_type exec;

    size_t n = 100;

    auto result = agency::new_executor_traits<executor_type>::execute(exec, [](size_t idx)
    {
      return idx;
    },
    n);

    std::vector<int> ref(n);
    std::iota(ref.begin(), ref.end(), 0);

    assert(std::equal(ref.begin(), ref.end(), result.begin()));
    assert(exec.valid());
  }

  {
    // execute returning void

    executor_type exec;

    size_t n = 100;

    int increment_me = 0;
    std::mutex mut;
    agency::new_executor_traits<executor_type>::execute(exec, [&](size_t idx)
    {
      mut.lock();
      increment_me += 13;
      mut.unlock();
    },
    n);

    assert(increment_me == n * 13);
    assert(exec.valid());
  }
}

int main()
{
  using namespace test_executors;

  test<empty_executor>();
  test<single_agent_when_all_execute_and_select_executor>();
  test<multi_agent_when_all_execute_and_select_executor>();
  test<single_agent_then_execute_executor>();

  test<multi_agent_execute_returning_user_defined_container_executor>();
  test<multi_agent_execute_returning_default_container_executor>();
  test<multi_agent_execute_returning_void_executor>();

  test<multi_agent_async_execute_returning_user_defined_container_executor>();
  test<multi_agent_async_execute_returning_default_container_executor>();
  test<multi_agent_async_execute_returning_void_executor>();

  std::cout << "OK" << std::endl;

  return 0;
}

<commit_msg>Test multi_agent_execute_with_shared_inits_returning_user_specified_container_executor with test_multi_agent_execute.cpp<commit_after>#include <agency/future.hpp>
#include <agency/new_executor_traits.hpp>
#include <iostream>
#include <cassert>
#include <algorithm>
#include <numeric>
#include <mutex>

#include "test_executors.hpp"

template<class Executor>
void test()
{
  using executor_type = Executor;

  {
    // execute returning user-specified container

    executor_type exec;

    size_t n = 100;

    std::vector<int> result = agency::new_executor_traits<executor_type>::template execute<std::vector<int>>(exec, [](size_t idx)
    {
      return idx;
    },
    n);

    std::vector<int> ref(n);
    std::iota(ref.begin(), ref.end(), 0);

    assert(std::equal(ref.begin(), ref.end(), result.begin()));
    assert(exec.valid());
  }

  {
    // execute returning default container

    executor_type exec;

    size_t n = 100;

    auto result = agency::new_executor_traits<executor_type>::execute(exec, [](size_t idx)
    {
      return idx;
    },
    n);

    std::vector<int> ref(n);
    std::iota(ref.begin(), ref.end(), 0);

    assert(std::equal(ref.begin(), ref.end(), result.begin()));
    assert(exec.valid());
  }

  {
    // execute returning void

    executor_type exec;

    size_t n = 100;

    int increment_me = 0;
    std::mutex mut;
    agency::new_executor_traits<executor_type>::execute(exec, [&](size_t idx)
    {
      mut.lock();
      increment_me += 13;
      mut.unlock();
    },
    n);

    assert(increment_me == n * 13);
    assert(exec.valid());
  }
}

int main()
{
  using namespace test_executors;

  test<empty_executor>();
  test<single_agent_when_all_execute_and_select_executor>();
  test<multi_agent_when_all_execute_and_select_executor>();
  test<single_agent_then_execute_executor>();

  test<multi_agent_execute_returning_user_defined_container_executor>();
  test<multi_agent_execute_returning_default_container_executor>();
  test<multi_agent_execute_returning_void_executor>();

  test<multi_agent_async_execute_returning_user_defined_container_executor>();
  test<multi_agent_async_execute_returning_default_container_executor>();
  test<multi_agent_async_execute_returning_void_executor>();

  test<multi_agent_execute_with_shared_inits_returning_user_defined_container_executor>();

  std::cout << "OK" << std::endl;

  return 0;
}

<|endoftext|>


<commit_before>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// This needs to go away.  The p4est namespace should not be used directly.
#include <p4est.h>

#include "amr_forestclaw.H"
#include "amr_utils.H"
#include "amr_options.h"
#include "no_solver_user.H"

int
main (int argc, char **argv)
{
  int		        lp;
  MPI_Comm              mpicomm;
  sc_options_t          *options;
  fclaw2d_domain_t	*domain;
  amr_options_t         *gparms;

  lp = SC_LP_PRODUCTION;
  mpicomm = MPI_COMM_WORLD;
  fclaw_mpi_init (&argc, &argv, mpicomm, lp);

  /* ---------------------------------------------------------------
     Read parameters from .ini file, parse command line, and
     do parameter checking.
     -------------------------------------------------------------- */
  options = sc_options_new(argv[0]);

  /* Register default parameters and any solver parameters */
  gparms = amr_options_new(options);

  /* Parse any command line arguments.  Argument gparms is no longer needed
     as an input since the array conversion is now done in 'postprocess' */
#if 0
  amr_options_parse(options, gparms, argc, argv, lp);
#endif
  amr_options_parse(options,argc,argv,lp);

  /* Any arrays are converted here */
  amr_postprocess_parms(gparms);

  /* Check final state of parameters */
  amr_checkparms(gparms);

  /* ---------------------------------------------------------------
     Domain geometry
     -------------------------------------------------------------- */
  domain = fclaw2d_domain_new_unitsquare (mpicomm, gparms->minlevel);

  fclaw2d_domain_list_levels(domain, lp);
  fclaw2d_domain_list_neighbors(domain, lp);

  /* ---------------------------------------------------------------
     Set domain data.
     --------------------------------------------------------------- */
  init_domain_data(domain);
  set_domain_parms(domain,gparms);

  /* ---------------------------------------------------------------
     Don't do any solve or run.  This is just to test that we can
     compile without any solver routines.
     --------------------------------------------------------------- */
  link_problem_setup(domain,no_solver_setprob);

  /* Initialize data but don't do anything */
  fclaw2d_solver_functions_t* sf = get_solver_functions(domain);
  sf->f_patch_initialize = &no_solver_patch_initialize;

  link_regrid_functions(domain,no_solver_patch_tag4refinement,
                        no_solver_patch_tag4coarsening);

  /* ---------------------------------------------------------------
     Initialize and run (but with out updating anything)
     --------------------------------------------------------------- */
  amrinit(&domain);
  amrrun(&domain);  /* Nothing should happen */
  amrreset(&domain);

  /* ---------------------------------------------------------------
     Clean up
     --------------------------------------------------------------- */

  sc_options_destroy(options);         /* this could be moved up */
  amr_options_destroy(gparms);

  fclaw_mpi_finalize ();

  return 0;
}
<commit_msg>All function pointers are now assigned in a user defined linker routine<commit_after>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// This needs to go away.  The p4est namespace should not be used directly.
#include <p4est.h>

#include "amr_forestclaw.H"
#include "amr_utils.H"
#include "amr_options.h"
#include "no_solver_user.H"

int
main (int argc, char **argv)
{
  int		        lp;
  MPI_Comm              mpicomm;
  sc_options_t          *options;
  fclaw2d_domain_t	*domain;
  amr_options_t         *gparms;

  lp = SC_LP_PRODUCTION;
  mpicomm = MPI_COMM_WORLD;
  fclaw_mpi_init (&argc, &argv, mpicomm, lp);

  /* ---------------------------------------------------------------
     Read parameters from .ini file, parse command line, and
     do parameter checking.
     -------------------------------------------------------------- */
  options = sc_options_new(argv[0]);

  /* Register default parameters and any solver parameters */
  gparms = amr_options_new(options);

  /* Parse any command line arguments.  Argument gparms is no longer needed
     as an input since the array conversion is now done in 'postprocess' */
#if 0
  amr_options_parse(options, gparms, argc, argv, lp);
#endif
  amr_options_parse(options,argc,argv,lp);

  /* Any arrays are converted here */
  amr_postprocess_parms(gparms);

  /* Check final state of parameters */
  amr_checkparms(gparms);

  /* ---------------------------------------------------------------
     Domain geometry
     -------------------------------------------------------------- */
  domain = fclaw2d_domain_new_unitsquare (mpicomm, gparms->minlevel);

  fclaw2d_domain_list_levels(domain, lp);
  fclaw2d_domain_list_neighbors(domain, lp);

  /* ---------------------------------------------------------------
     Set domain data.
     --------------------------------------------------------------- */
  init_domain_data(domain);
  set_domain_parms(domain,gparms);

  /* ---------------------------------------------------------------
     Don't do any solve or run.  This is just to test that we can
     compile without any solver routines.
     --------------------------------------------------------------- */

  no_solver_linker(domain);

  /* ---------------------------------------------------------------
     Initialize and run (but with out updating anything)
     --------------------------------------------------------------- */
  amrinit(&domain);
  amrrun(&domain);  /* Nothing should happen */
  amrreset(&domain);

  /* ---------------------------------------------------------------
     Clean up
     --------------------------------------------------------------- */

  sc_options_destroy(options);         /* this could be moved up */
  amr_options_destroy(gparms);

  fclaw_mpi_finalize ();

  return 0;
}
<|endoftext|>


<commit_before>// qpp.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"

#include <iostream>
#include "qpp.h"

int main()
{
	using namespace qpp;
	std::cout << "Hello, Quantum++!\nThis is the |0> state:\n";
	std::cout << disp(st.z0) << '\n';
	std::cin.get();
}
<commit_msg>Update qpp.cpp<commit_after>// qpp.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"

#include <iostream>
#include "qpp.h"

int main()
{
	using namespace qpp;
	std::cout << "Hello, Quantum++!\nThis is the |0> state:\n";
	std::cout << disp(st.z0) << '\n';
}
<|endoftext|>


<commit_before>#include "WinAPIUtils.h"

#include <algorithm>

// Does NOT synched.
const char* WinAPIUtils::getLogFileNameFromAppName() throw() {
  static auto* const LOG_FILE_EXT = ".txt";
  static const auto LOG_FILE_EXT_LEN = strlen(LOG_FILE_EXT); // use constexpr if possible
  static char appName[MAX_PATH + 1U + 8U - (MAX_PATH + 1U) % 8U]; // make 8 even
  static_assert(!(sizeof(appName) % 8U), "SHOULD be 8 even");

  if (!*appName) { // NOT yet determined
    auto len = GetModuleFileName(nullptr, appName, std::extent<decltype(appName)>::value - 1U);
    static const decltype(len) MAX_LEN = std::extent<decltype(appName)>::value - 1U - LOG_FILE_EXT_LEN;

    if (len && *appName) { // something received
      if (!appName[len - 1U]) { // there CAN be str. terminator OR NOT
        --len; // set to the str. terminator
      }
      const auto pos = std::min<>(MAX_LEN, len);
      strcat_s(appName + pos, LOG_FILE_EXT_LEN + 1U, LOG_FILE_EXT);
    } else return ""; // call GetLastError to get extended error information
  }
  return appName;
}

// Returns ptr. to the provided storage [!] which SHOULD NOT be larger than 64K bytes [!]
// Returns empty str. if NO error
// If 'fromLowerCase' flag is true - msg. will start from lower case letter
char* WinAPIUtils::getErrorMsg(char* const msgBuf, const size_t bufSize,
                               const DWORD errorCode, const bool fromLowerCase) throw() {
  if (!msgBuf || !bufSize) return nullptr;
  *msgBuf = '\0';
  if (ERROR_SUCCESS == errorCode) return msgBuf; // operation completed successfully

  static const DWORD FLAGS
    = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK;
  static const auto LANG = MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT); // en
  // Return value is the number of TCHARs stored in the output buffer,
  //  excluding the terminating null character
  const auto count = FormatMessage(FLAGS, nullptr, errorCode, LANG, msgBuf, bufSize, nullptr);
  if (!count || !*msgBuf) { // if the function fails, the return value is zero
    strncpy_s(msgBuf, bufSize, "unlocalized error", bufSize - 1U);
    return msgBuf; // to get extended error information, call 'GetLastError'
  }
  char* currCharPtr = msgBuf + (count - 1U);
  while (' ' == *currCharPtr || '.' == *currCharPtr)
    *currCharPtr-- = '\0'; // erase end spacers and point
  if (fromLowerCase) *msgBuf = tolower(*msgBuf);

  return msgBuf;
}

#include "Dbt.h"

// Returns nullptr if 'lpEventData' is NOT provided OR NOT required OR at ANY error
// [!] Do NOT forget to 'delete[]' the returned ptr. when data is NO longer needed [!]
void* WinAPIUtils::copyEventData(const DWORD dwControl, const DWORD dwEventType,
                                 LPVOID const lpEventData, bool& error) throw() {
  error = false;

  if (!lpEventData) return nullptr;
  auto dataSize = DWORD();

  switch (dwControl) {
    case SERVICE_CONTROL_SESSIONCHANGE: {
        auto const sessionData = reinterpret_cast<const WTSSESSION_NOTIFICATION*>(lpEventData);
        dataSize = std::max<>(sessionData->cbSize, static_cast<DWORD>(sizeof(*sessionData)));
      }
    break;

    case SERVICE_CONTROL_DEVICEEVENT: {
        auto const deviceData = reinterpret_cast<const DEV_BROADCAST_HDR*>(lpEventData);
        dataSize = std::max<>(deviceData->dbch_size, static_cast<DWORD>(sizeof(*deviceData)));
      }
    break;

    case SERVICE_CONTROL_POWEREVENT:
      if (PBT_POWERSETTINGCHANGE != dwEventType) return nullptr; // unused event, NOT required
      {
        auto const powerSettings = reinterpret_cast<const POWERBROADCAST_SETTING*>(lpEventData);
        dataSize = sizeof(*powerSettings) + powerSettings->DataLength - sizeof(powerSettings->Data);
      }
    break;

    case SERVICE_CONTROL_TIMECHANGE:
      dataSize = sizeof(SERVICE_TIMECHANGE_INFO);
    break;

    default: // unused control, NOT required
      return nullptr;
  }
  dataSize += 8U; // add a few bytes to the end (NOT really required, BUT let it be)
  auto const newData = new char[dataSize](); // zero (default) initialized

  if (newData) { // alocated
    memcpy_s(newData, dataSize, lpEventData, dataSize);
  } else error = true; // NOT allocated

  return newData;
}<commit_msg>'WinAPIUtils' module minor fix<commit_after>#include "WinAPIUtils.h"

#include <algorithm>

// Does NOT synched.
const char* WinAPIUtils::getLogFileNameFromAppName() throw() {
  static auto* const LOG_FILE_EXT = ".txt";
  static const auto LOG_FILE_EXT_LEN = strlen(LOG_FILE_EXT); // use constexpr if possible
  static char appName[MAX_PATH + 1U + 8U - (MAX_PATH + 1U) % 8U]; // make 8 even
  static_assert(!(sizeof(appName) % 8U), "SHOULD be 8 even");

  if (!*appName) { // NOT yet determined
    auto len = GetModuleFileName(nullptr, appName, std::extent<decltype(appName)>::value - 1U);
    static const decltype(len) MAX_LEN = std::extent<decltype(appName)>::value - 1U - LOG_FILE_EXT_LEN;

    if (len && *appName) { // something received
      if (!appName[len - 1U]) { // there CAN be str. terminator OR NOT
        --len; // set to the str. terminator
      }
      const auto pos = std::min<>(MAX_LEN, len);
      strcat_s(appName + pos, LOG_FILE_EXT_LEN + 1U, LOG_FILE_EXT);
    } else return ""; // call GetLastError to get extended error information
  }
  return appName;
}

// Returns ptr. to the provided storage [!] which SHOULD NOT be larger than 64K bytes [!]
// Returns empty str. if NO error
// If 'fromLowerCase' flag is true - msg. will start from lower case letter
char* WinAPIUtils::getErrorMsg(char* const msgBuf, const size_t bufSize,
                               const DWORD errorCode, const bool fromLowerCase) throw() {
  if (!msgBuf || !bufSize) return nullptr;
  *msgBuf = '\0';
  if (ERROR_SUCCESS == errorCode) return msgBuf; // operation completed successfully

  static const DWORD FLAGS
    = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK;
  static const auto LANG = MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT); // en
  // Return value is the number of TCHARs stored in the output buffer,
  //  excluding the terminating null character
  const auto count = FormatMessage(FLAGS, nullptr, errorCode, LANG, msgBuf, bufSize, nullptr);
  if (!count || !*msgBuf) { // if the function fails, the return value is zero
    strncpy_s(msgBuf, bufSize, "unlocalized error", bufSize - 1U);
    return msgBuf; // to get extended error information, call 'GetLastError'
  }
  char* currCharPtr = msgBuf + (count - 1U);
  while (' ' == *currCharPtr || '.' == *currCharPtr)
    *currCharPtr-- = '\0'; // erase end spacers and point
  if (fromLowerCase) *msgBuf = tolower(*msgBuf);

  return msgBuf;
}

#include "Dbt.h"

// Returns nullptr if 'lpEventData' is NOT provided OR NOT required OR at ANY error
// [!] Do NOT forget to 'delete[]' the returned ptr. when data is NO longer needed [!]
void* WinAPIUtils::copyEventData(const DWORD dwControl, const DWORD dwEventType,
                                 LPVOID const lpEventData, bool& error) throw() {
  error = false;

  if (!lpEventData) return nullptr;
  auto dataSize = DWORD();

  switch (dwControl) {
    case SERVICE_CONTROL_SESSIONCHANGE: {
        auto const sessionData = reinterpret_cast<const WTSSESSION_NOTIFICATION*>(lpEventData);
        dataSize = std::max<>(sessionData->cbSize, static_cast<DWORD>(sizeof(*sessionData)));
      }
    break;

    case SERVICE_CONTROL_DEVICEEVENT: {
        auto const deviceData = reinterpret_cast<const DEV_BROADCAST_HDR*>(lpEventData);
        dataSize = std::max<>(deviceData->dbch_size, static_cast<DWORD>(sizeof(*deviceData)));
      }
    break;

    case SERVICE_CONTROL_POWEREVENT:
      if (PBT_POWERSETTINGCHANGE != dwEventType) return nullptr; // unused event, NOT required
      {
        auto const powerSettings = reinterpret_cast<const POWERBROADCAST_SETTING*>(lpEventData);
        dataSize = sizeof(*powerSettings) + powerSettings->DataLength - sizeof(powerSettings->Data);
      }
    break;

    case SERVICE_CONTROL_TIMECHANGE:
      dataSize = sizeof(SERVICE_TIMECHANGE_INFO);
    break;

    default: // unused control, NOT required
      return nullptr;
  }
  dataSize += 8UL; // add a few bytes to the end (NOT really required, BUT let it be)
  auto const newData = new char[dataSize](); // zero (default) initialized

  if (newData) { // alocated
    memcpy_s(newData, dataSize, lpEventData, dataSize);
  } else error = true; // NOT allocated

  return newData;
}<|endoftext|>


<commit_before>/******************************************************************************\
* ATestModule.cpp                                                              *
* A Lua module as a shared library, created using Diluculum facilities.        *
*                                                                              *
*                                                                              *
* Copyright (C) 2005-2006 by Leandro Motta Barros.                             *
*                                                                              *
* 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 <Diluculum/LuaWrappers.hpp>

/** A class that will be exported by the Lua module. Does nothing interesting.
 *  It's just a test...
 */
class AClass
{
   public:
      /// Constructor. Takes a number and stores it in \c val_.
      AClass (const Diluculum::LuaValueList& params)
      {
         if (params.size() != 1 || params[0].type() != LUA_TNUMBER)
         {
            throw Diluculum::LuaError(
               "Constructor expected a single number parameter.");
         }
         val_ = params[0].asNumber();
      }

      /// A test method; returns val_.
      Diluculum::LuaValueList aMethod (const Diluculum::LuaValueList& params)
      {
         Diluculum::LuaValueList ret;
         ret.push_back (val_);
         return ret;
      }

   private:
      /** Just a value. If you want to read something with meaning, try
       *  Literature, instead of my test classes.
       */
      double val_;
};

/// A function that always returns two values: \c true and <tt>"Ahey!"</tt>.
Diluculum::LuaValueList AFunction (const Diluculum::LuaValueList& params)
{
   Diluculum::LuaValueList ret;
   ret.push_back (true);
   ret.push_back ("Ahey!");

   return ret;
}

DILUCULUM_BEGIN_CLASS (AClass);
   DILUCULUM_CLASS_METHOD (AClass, aMethod);
DILUCULUM_END_CLASS (AClass);

DILUCULUM_WRAP_FUNCTION (AFunction);

DILUCULUM_BEGIN_MODULE (ATestModule);
   DILUCULUM_MODULE_ADD_CLASS (AClass); // SQLite.SQLiteDB.new()
   DILUCULUM_MODULE_ADD_FUNCTION (AFunction, "AFunction");
DILUCULUM_END_MODULE();
<commit_msg>Removed a comment from 'Tests/ATestModule.cpp', which was reminiscent of some very early tests with modules.<commit_after>/******************************************************************************\
* ATestModule.cpp                                                              *
* A Lua module as a shared library, created using Diluculum facilities.        *
*                                                                              *
*                                                                              *
* Copyright (C) 2005-2006 by Leandro Motta Barros.                             *
*                                                                              *
* 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 <Diluculum/LuaWrappers.hpp>

/** A class that will be exported by the Lua module. Does nothing interesting.
 *  It's just a test...
 */
class AClass
{
   public:
      /// Constructor. Takes a number and stores it in \c val_.
      AClass (const Diluculum::LuaValueList& params)
      {
         if (params.size() != 1 || params[0].type() != LUA_TNUMBER)
         {
            throw Diluculum::LuaError(
               "Constructor expected a single number parameter.");
         }
         val_ = params[0].asNumber();
      }

      /// A test method; returns val_.
      Diluculum::LuaValueList aMethod (const Diluculum::LuaValueList& params)
      {
         Diluculum::LuaValueList ret;
         ret.push_back (val_);
         return ret;
      }

   private:
      /** Just a value. If you want to read something with meaning, try
       *  Literature, instead of my test classes.
       */
      double val_;
};

/// A function that always returns two values: \c true and <tt>"Ahey!"</tt>.
Diluculum::LuaValueList AFunction (const Diluculum::LuaValueList& params)
{
   Diluculum::LuaValueList ret;
   ret.push_back (true);
   ret.push_back ("Ahey!");

   return ret;
}

DILUCULUM_BEGIN_CLASS (AClass);
   DILUCULUM_CLASS_METHOD (AClass, aMethod);
DILUCULUM_END_CLASS (AClass);

DILUCULUM_WRAP_FUNCTION (AFunction);

DILUCULUM_BEGIN_MODULE (ATestModule);
   DILUCULUM_MODULE_ADD_CLASS (AClass);
   DILUCULUM_MODULE_ADD_FUNCTION (AFunction, "AFunction");
DILUCULUM_END_MODULE();
<|endoftext|>


<commit_before>/*
	This file is part of the E_Rendering library.
	Copyright (C) 2009-2012 Benjamin Eikel <benjamin@eikel.org>
	Copyright (C) 2009-2012 Claudius Jähn <claudius@uni-paderborn.de>
	Copyright (C) 2009-2012 Ralf Petring <ralf@petring.net>

	This library is subject to the terms of the Mozilla Public License, v. 2.0.
	You should have received a copy of the MPL along with this library; see the
	file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "E_Texture.h"
#include "../E_RenderingContext.h"

#include <Rendering/Texture/Texture.h>
#include <E_Util/Graphics/E_Color.h>
#include <E_Util/E_FileName.h>
#include <EScript/Basics.h>
#include <EScript/StdObjects.h>
#include <sstream>

using namespace EScript;
using namespace Rendering;

namespace E_Rendering {

//! (static)
EScript::Type * E_Texture::getTypeObject() {
	// E_Texture ---|> Object
	static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject());
	return typeObject.get();
}

//! initMembers
void E_Texture::init(EScript::Namespace & lib) {
	EScript::Type * typeObject = getTypeObject();
	declareConstant(&lib,getClassName(),typeObject);

	//! thisEObj Texture.allocateLocalData()
	ES_MFUN(typeObject,Texture,"allocateLocalData",0,0,	(thisObj->allocateLocalData(),thisEObj))

	//! thisEObj Texture.createMipmaps(RenderingContext)
	ES_MFUN(typeObject,Texture,"createMipmaps",1,1, (thisObj->createMipmaps(parameter[0].to<RenderingContext&>(rt)),thisEObj))

	//! thisEObj Texture.dataChanged()
	ES_MFUN(typeObject,Texture,"dataChanged",0,0, (thisObj->dataChanged(),thisEObj))

	//! thisEObj Texture.download(RenderingContext)
	ES_MFUN(typeObject,Texture,"download",1,1, (thisObj->downloadGLTexture(parameter[0].to<RenderingContext&>(rt)),thisEObj))

	//! thisEObj Texture._upload(RenderingContext)
	ES_MFUN(typeObject,Texture,"_upload",1,1, (thisObj->_uploadGLTexture(parameter[0].to<RenderingContext&>(rt)),thisEObj))

	//! [ESMF] FileName Texture.getHasMipmaps()
	ES_MFUN(typeObject,const Texture,"getHasMipmaps",0,0, thisObj->getHasMipmaps())

	//! [ESMF] FileName Texture.getFileName()
	ES_MFUN(typeObject,const Texture,"getFileName",0,0,	thisObj->getFileName())

	//! Number Texture.getDataSize()
	ES_MFUN(typeObject,const Texture,"getDataSize",0,0,thisObj->getDataSize())

	//! Number Texture.getHeight()
	ES_MFUN(typeObject,const Texture,"getHeight",0,0, thisObj->getHeight())

	//! Number Texture.getNumLayers()
	ES_MFUN(typeObject,const Texture,"getNumLayers",0,0, thisObj->getNumLayers())

	//! Number Texture.getTextureType()
	ES_MFUN(typeObject,const Texture,"getTextureType",0,0, static_cast<uint32_t>(thisObj->getTextureType()))

	//! Number Texture.getWidth()
	ES_MFUN(typeObject,const Texture,"getWidth",0,0, thisObj->getWidth())

	//! Bool Texture.getUseLinearMinFilter()
	ES_MFUN(typeObject,const Texture,"getUseLinearMinFilter",0,0, thisObj->getUseLinearMinFilter())

	//! Bool Texture.getUseLinearMagFilter()
	ES_MFUN(typeObject,const Texture,"getUseLinearMagFilter",0,0, thisObj->getUseLinearMagFilter())

	//! self Texture.planMipmapCreation()
	ES_MFUN(typeObject,Texture,"planMipmapCreation",0,0, (thisObj->planMipmapCreation(),thisEObj))

	//! [ESMF] thisEObj FileName.setFileName([[FileName, String] name])
	ES_MFUNCTION(typeObject,Texture,"setFileName",0,1,{
				if(parameter.count() == 0){
					thisObj->setFileName(Util::FileName());
				}
				else{
					E_Util::E_FileName * t = dynamic_cast<E_Util::E_FileName *>(parameter[0].get());
					if(t){
						thisObj->setFileName(t->ref());
					}
					else{
						thisObj->setFileName(Util::FileName(parameter[0].toString()));
					}
				}
				return thisEObj;
	})

	EScript::declareConstant( typeObject, "TEXTURE_1D",				static_cast<uint32_t>(TextureType::TEXTURE_1D) );
	EScript::declareConstant( typeObject, "TEXTURE_1D_ARRAY",		static_cast<uint32_t>(TextureType::TEXTURE_1D_ARRAY) );
	EScript::declareConstant( typeObject, "TEXTURE_2D",				static_cast<uint32_t>(TextureType::TEXTURE_2D) );
	EScript::declareConstant( typeObject, "TEXTURE_2D_ARRAY",		static_cast<uint32_t>(TextureType::TEXTURE_2D_ARRAY) );
	EScript::declareConstant( typeObject, "TEXTURE_3D",				static_cast<uint32_t>(TextureType::TEXTURE_3D) );
	EScript::declareConstant( typeObject, "TEXTURE_CUBE_MAP",		static_cast<uint32_t>(TextureType::TEXTURE_CUBE_MAP) );
	EScript::declareConstant( typeObject, "TEXTURE_CUBE_MAP_ARRAY",	static_cast<uint32_t>(TextureType::TEXTURE_CUBE_MAP_ARRAY) );
	EScript::declareConstant( typeObject, "TEXTURE_BUFFER",			static_cast<uint32_t>(TextureType::TEXTURE_BUFFER) );
	EScript::declareConstant( typeObject, "TEXTURE_2D_MULTISAMPLE",	static_cast<uint32_t>(TextureType::TEXTURE_2D_MULTISAMPLE) );

}

E_Texture::E_Texture(Rendering::Texture * t) : ReferenceObject<Util::Reference<Rendering::Texture> >(t,getTypeObject()){}
E_Texture::E_Texture(const Util::Reference<Rendering::Texture> & t) : ReferenceObject<Util::Reference<Rendering::Texture> >(t,getTypeObject()){}
E_Texture::E_Texture(Util::Reference<Rendering::Texture> && t) : ReferenceObject<Util::Reference<Rendering::Texture> >(t,getTypeObject()){}

std::string E_Texture::toString() const {
	std::stringstream ss;
	ss << "#Texture:" << reinterpret_cast<void*>(this->get());
	return ss.str();
}

}
<commit_msg>bindings for Texture.clear<commit_after>/*
	This file is part of the E_Rendering library.
	Copyright (C) 2009-2012 Benjamin Eikel <benjamin@eikel.org>
	Copyright (C) 2009-2012 Claudius Jähn <claudius@uni-paderborn.de>
	Copyright (C) 2009-2012 Ralf Petring <ralf@petring.net>

	This library is subject to the terms of the Mozilla Public License, v. 2.0.
	You should have received a copy of the MPL along with this library; see the
	file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "E_Texture.h"
#include "../E_RenderingContext.h"

#include <Rendering/Texture/Texture.h>
#include <E_Util/Graphics/E_Color.h>
#include <E_Util/E_FileName.h>
#include <EScript/Basics.h>
#include <EScript/StdObjects.h>
#include <sstream>

using namespace EScript;
using namespace Rendering;

namespace E_Rendering {

//! (static)
EScript::Type * E_Texture::getTypeObject() {
	// E_Texture ---|> Object
	static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject());
	return typeObject.get();
}

//! initMembers
void E_Texture::init(EScript::Namespace & lib) {
	EScript::Type * typeObject = getTypeObject();
	declareConstant(&lib,getClassName(),typeObject);

	//! thisEObj Texture.allocateLocalData()
	ES_MFUN(typeObject,Texture,"allocateLocalData",0,0,	(thisObj->allocateLocalData(),thisEObj))

	//! thisEObj Texture.createMipmaps(RenderingContext)
	ES_MFUN(typeObject,Texture,"createMipmaps",1,1, (thisObj->createMipmaps(parameter[0].to<RenderingContext&>(rt)),thisEObj))

	//! thisEObj Texture.dataChanged()
	ES_MFUN(typeObject,Texture,"dataChanged",0,0, (thisObj->dataChanged(),thisEObj))

	//! thisEObj Texture.download(RenderingContext)
	ES_MFUN(typeObject,Texture,"download",1,1, (thisObj->downloadGLTexture(parameter[0].to<RenderingContext&>(rt)),thisEObj))

	//! thisEObj Texture._upload(RenderingContext)
	ES_MFUN(typeObject,Texture,"_upload",1,1, (thisObj->_uploadGLTexture(parameter[0].to<RenderingContext&>(rt)),thisEObj))

	//! thisEObj Texture.clear([Color])
	ES_MFUN(typeObject,Texture,"clear",0,1, (thisObj->clearGLData(parameter[0].to(rt,Util::Color4f())),thisEObj))

	//! [ESMF] FileName Texture.getHasMipmaps()
	ES_MFUN(typeObject,const Texture,"getHasMipmaps",0,0, thisObj->getHasMipmaps())

	//! [ESMF] FileName Texture.getFileName()
	ES_MFUN(typeObject,const Texture,"getFileName",0,0,	thisObj->getFileName())

	//! Number Texture.getDataSize()
	ES_MFUN(typeObject,const Texture,"getDataSize",0,0,thisObj->getDataSize())

	//! Number Texture.getHeight()
	ES_MFUN(typeObject,const Texture,"getHeight",0,0, thisObj->getHeight())

	//! Number Texture.getNumLayers()
	ES_MFUN(typeObject,const Texture,"getNumLayers",0,0, thisObj->getNumLayers())

	//! Number Texture.getTextureType()
	ES_MFUN(typeObject,const Texture,"getTextureType",0,0, static_cast<uint32_t>(thisObj->getTextureType()))

	//! Number Texture.getWidth()
	ES_MFUN(typeObject,const Texture,"getWidth",0,0, thisObj->getWidth())

	//! Bool Texture.getUseLinearMinFilter()
	ES_MFUN(typeObject,const Texture,"getUseLinearMinFilter",0,0, thisObj->getUseLinearMinFilter())

	//! Bool Texture.getUseLinearMagFilter()
	ES_MFUN(typeObject,const Texture,"getUseLinearMagFilter",0,0, thisObj->getUseLinearMagFilter())

	//! self Texture.planMipmapCreation()
	ES_MFUN(typeObject,Texture,"planMipmapCreation",0,0, (thisObj->planMipmapCreation(),thisEObj))

	//! [ESMF] thisEObj FileName.setFileName([[FileName, String] name])
	ES_MFUNCTION(typeObject,Texture,"setFileName",0,1,{
				if(parameter.count() == 0){
					thisObj->setFileName(Util::FileName());
				}
				else{
					E_Util::E_FileName * t = dynamic_cast<E_Util::E_FileName *>(parameter[0].get());
					if(t){
						thisObj->setFileName(t->ref());
					}
					else{
						thisObj->setFileName(Util::FileName(parameter[0].toString()));
					}
				}
				return thisEObj;
	})

	EScript::declareConstant( typeObject, "TEXTURE_1D",				static_cast<uint32_t>(TextureType::TEXTURE_1D) );
	EScript::declareConstant( typeObject, "TEXTURE_1D_ARRAY",		static_cast<uint32_t>(TextureType::TEXTURE_1D_ARRAY) );
	EScript::declareConstant( typeObject, "TEXTURE_2D",				static_cast<uint32_t>(TextureType::TEXTURE_2D) );
	EScript::declareConstant( typeObject, "TEXTURE_2D_ARRAY",		static_cast<uint32_t>(TextureType::TEXTURE_2D_ARRAY) );
	EScript::declareConstant( typeObject, "TEXTURE_3D",				static_cast<uint32_t>(TextureType::TEXTURE_3D) );
	EScript::declareConstant( typeObject, "TEXTURE_CUBE_MAP",		static_cast<uint32_t>(TextureType::TEXTURE_CUBE_MAP) );
	EScript::declareConstant( typeObject, "TEXTURE_CUBE_MAP_ARRAY",	static_cast<uint32_t>(TextureType::TEXTURE_CUBE_MAP_ARRAY) );
	EScript::declareConstant( typeObject, "TEXTURE_BUFFER",			static_cast<uint32_t>(TextureType::TEXTURE_BUFFER) );
	EScript::declareConstant( typeObject, "TEXTURE_2D_MULTISAMPLE",	static_cast<uint32_t>(TextureType::TEXTURE_2D_MULTISAMPLE) );

}

E_Texture::E_Texture(Rendering::Texture * t) : ReferenceObject<Util::Reference<Rendering::Texture> >(t,getTypeObject()){}
E_Texture::E_Texture(const Util::Reference<Rendering::Texture> & t) : ReferenceObject<Util::Reference<Rendering::Texture> >(t,getTypeObject()){}
E_Texture::E_Texture(Util::Reference<Rendering::Texture> && t) : ReferenceObject<Util::Reference<Rendering::Texture> >(t,getTypeObject()){}

std::string E_Texture::toString() const {
	std::stringstream ss;
	ss << "#Texture:" << reinterpret_cast<void*>(this->get());
	return ss.str();
}

}
<|endoftext|>


<commit_before>// RUN: cat %s | %cling -I%p | FileCheck %s

// This file should be used as regression test for the meta processing subsystem
// Reproducers of fixed bugs should be put here

// PR #93092
// Don't remove the spaces and tabs
.L     cling/Interpreter/Interpreter.h
.x ./DotXable.h(5)
// CHECK: 5
// End PR #93092
<commit_msg>Make sure that we have proper case preventing such scenario as from today.<commit_after>// RUN: cat %s | %cling -I%p | FileCheck %s

// This file should be used as regression test for the meta processing subsystem
// Reproducers of fixed bugs should be put here

// PR #93092
// Don't remove the spaces and tabs
.L     cling/Interpreter/Interpreter.h
.x ./DotXable.h(5)
// CHECK: 5
// End PR #93092

.X ./DotXable(10)
 // CHECK: 10
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// cache_test.cpp
//
// Identification: tests/common/cache_test.cpp
//
// Copyright (c) 201CACHE_SIZE, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "harness.h"
#include "backend/common/thread_manager.h"

namespace peloton {
namespace test {

//===--------------------------------------------------------------------===//
// Thread Manager Test
//===--------------------------------------------------------------------===//

class ThreadManagerTests : public PelotonTest {};

TEST_F(ThreadManagerTests, BasicTest) {

  auto& thread_manager = ThreadManager::GetInstance();
  std::shared_ptr<std::thread> t1(new std::thread);

  bool status = thread_manager.AttachThread(t1);
  EXPECT_EQ(status, true);

  status = thread_manager.AttachThread(t1);
  EXPECT_EQ(status, false);

  status = thread_manager.DetachThread(t1);
  EXPECT_EQ(status, true);

  status = thread_manager.DetachThread(t1);
  EXPECT_EQ(status, false);

}

}  // End test namespace
}  // End peloton namespace
<commit_msg>add thread_manager_test<commit_after>//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// cache_test.cpp
//
// Identification: tests/common/cache_test.cpp
//
// Copyright (c) 201CACHE_SIZE, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "harness.h"
#include "backend/common/thread_manager.h"

namespace peloton {
namespace test {

//===--------------------------------------------------------------------===//
// Thread Manager Test
//===--------------------------------------------------------------------===//

class ThreadManagerTests : public PelotonTest {};

/* this is the old test
TEST_F(ThreadManagerTests, BasicTest) {
  auto& thread_manager = ThreadManager::GetInstance();
  std::shared_ptr<std::thread> t1(new std::thread);
  bool status = thread_manager.AttachThread(t1);
  EXPECT_EQ(status, true);
  status = thread_manager.AttachThread(t1);
  EXPECT_EQ(status, false);
  status = thread_manager.DetachThread(t1);
  EXPECT_EQ(status, true);
  status = thread_manager.DetachThread(t1);
  EXPECT_EQ(status, false);
}
*/

TEST_F(ThreadManagerTests, BasicTest) {

  auto& server_thread_manager1 = ThreadManager::GetServerThreadPool();
  auto& server_thread_manager2 = ThreadManager::GetServerThreadPool();

  bool status = (&server_thread_manager1 == &server_thread_manager2);
  EXPECT_EQ(status, true);

  auto& client_thread_manager1 = ThreadManager::GetClientThreadPool();
  auto& client_thread_manager2 = ThreadManager::GetClientThreadPool();

  status = (&client_thread_manager1 == &client_thread_manager2);
  EXPECT_EQ(status, true);

  status = (&server_thread_manager1 == &client_thread_manager2);
  EXPECT_EQ(status, false);

}

}  // End test namespace
}  // End peloton namespace
<|endoftext|>