<commit_before>//C++ source file - Open Producer - Copyright (C) 2002 Don Burns
//Distributed under the terms of the GNU LIBRARY GENERAL PUBLIC LICENSE (LGPL)
//as published by the Free Software Foundation.

// Simple example of use of Producer::RenderSurface
// The myGraphics class is a simple sample of how one would implement
// graphics drawing with Producer::RenderSurface

#include <osgUtil/UpdateVisitor>

#include <osgDB/ReadFile>

#include <osg/ShapeDrawable>
#include <osg/PositionAttitudeTransform>

#include <osgProducer/Viewer>

#include "DepthPartitionNode.h"

const double r_earth = 6378.137;
const double r_sun = 695990.0;
const double AU = 149697900.0;

osg::Node* createScene()
{
    // Create the Earth, in blue
    osg::ShapeDrawable *earth_sd = new osg::ShapeDrawable;
    osg::Sphere* earth_sphere = new osg::Sphere;
    earth_sphere->setRadius(r_earth);
    earth_sd->setShape(earth_sphere);
    earth_sd->setColor(osg::Vec4(0, 0, 1.0, 1.0));

    osg::Geode* earth = new osg::Geode;
    earth->setName("earth");
    earth->addDrawable(earth_sd);

    // Create the Sun, in yellow
    osg::ShapeDrawable *sun_sd = new osg::ShapeDrawable;
    osg::Sphere* sun_sphere = new osg::Sphere;
    sun_sphere->setRadius(r_sun);
    sun_sd->setShape(sun_sphere);
    sun_sd->setColor(osg::Vec4(1.0, 0.0, 0.0, 1.0));

    osg::Geode* sun = new osg::Geode;
    sun->setName("sun");
    sun->addDrawable(sun_sd);

    // Move the sun behind the earth
    osg::PositionAttitudeTransform *pat = new osg::PositionAttitudeTransform;
    pat->setPosition(osg::Vec3d(0.0, AU, 0.0));

    osg::Group* scene = new osg::Group;
    scene->addChild(earth);
    scene->addChild(pat);
    pat->addChild(sun);

    return scene;
}

int main( int argc, char **argv )
{

    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard example of using osgProducer::CameraGroup.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] ...");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");

    // construct the viewer.
    osgProducer::Viewer viewer(arguments);

    // set up the value with sensible default event handlers.
    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    bool needToSetHomePosition = false;

    // read the scene from the list of file specified commandline args.
    osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments);

    // if one hasn't been loaded create an earth and sun test model.
    if (!scene)
    {
        scene = createScene();
        needToSetHomePosition = true;
    }

    // Create a DepthPartitionNode to manage partitioning of the scene
    osg::ref_ptr<DepthPartitionNode> dpn = new DepthPartitionNode;
    dpn->addChild(scene.get());
    dpn->setActive(true); // Control whether the node analyzes the scene

    // pass the loaded scene graph to the viewer.
    viewer.setSceneData(dpn.get());

    if (needToSetHomePosition)
    {
        viewer.getKeySwitchMatrixManipulator()->setHomePosition(osg::Vec3d(0.0,-5.0*r_earth,0.0),osg::Vec3d(0.0,0.0,0.0),osg::Vec3d(0.0,0.0,1.0));
    }

    // create the windows and run the threads.
    viewer.realize();

    while( !viewer.done() )
    {
        // wait for all cull and draw threads to complete.
        viewer.sync();

        // update the scene by traversing it with the the update visitor which will
        // call all node update callbacks and animations.
        viewer.update();

        // fire off the cull and draw traversals of the scene.
        viewer.frame();

    }

    // wait for all cull and draw threads to complete before exit.
    viewer.sync();

    // run a clean up frame to delete all OpenGL objects.
    viewer.cleanup_frame();

    // wait for all the clean up frame to complete.
    viewer.sync();

    return 0;
}

<commit_msg>From Keith Steffen, changed instance of sun to sun_geode to avoid Solaris10 build issue with it defining "sun"?#!<commit_after>//C++ source file - Open Producer - Copyright (C) 2002 Don Burns
//Distributed under the terms of the GNU LIBRARY GENERAL PUBLIC LICENSE (LGPL)
//as published by the Free Software Foundation.

// Simple example of use of Producer::RenderSurface
// The myGraphics class is a simple sample of how one would implement
// graphics drawing with Producer::RenderSurface

#include <osgUtil/UpdateVisitor>

#include <osgDB/ReadFile>

#include <osg/ShapeDrawable>
#include <osg/PositionAttitudeTransform>

#include <osgProducer/Viewer>

#include "DepthPartitionNode.h"

const double r_earth = 6378.137;
const double r_sun = 695990.0;
const double AU = 149697900.0;

osg::Node* createScene()
{
    // Create the Earth, in blue
    osg::ShapeDrawable *earth_sd = new osg::ShapeDrawable;
    osg::Sphere* earth_sphere = new osg::Sphere;
    earth_sphere->setRadius(r_earth);
    earth_sd->setShape(earth_sphere);
    earth_sd->setColor(osg::Vec4(0, 0, 1.0, 1.0));

    osg::Geode* earth = new osg::Geode;
    earth->setName("earth");
    earth->addDrawable(earth_sd);

    // Create the Sun, in yellow
    osg::ShapeDrawable *sun_sd = new osg::ShapeDrawable;
    osg::Sphere* sun_sphere = new osg::Sphere;
    sun_sphere->setRadius(r_sun);
    sun_sd->setShape(sun_sphere);
    sun_sd->setColor(osg::Vec4(1.0, 0.0, 0.0, 1.0));

    osg::Geode* sun_geode = new osg::Geode;
    sun_geode->setName("sun");
    sun_geode->addDrawable(sun_sd);

    // Move the sun behind the earth
    osg::PositionAttitudeTransform *pat = new osg::PositionAttitudeTransform;
    pat->setPosition(osg::Vec3d(0.0, AU, 0.0));

    osg::Group* scene = new osg::Group;
    scene->addChild(earth);
    scene->addChild(pat);
    pat->addChild(sun_geode);

    return scene;
}

int main( int argc, char **argv )
{

    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard example of using osgProducer::CameraGroup.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] ...");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");

    // construct the viewer.
    osgProducer::Viewer viewer(arguments);

    // set up the value with sensible default event handlers.
    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    bool needToSetHomePosition = false;

    // read the scene from the list of file specified commandline args.
    osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments);

    // if one hasn't been loaded create an earth and sun test model.
    if (!scene)
    {
        scene = createScene();
        needToSetHomePosition = true;
    }

    // Create a DepthPartitionNode to manage partitioning of the scene
    osg::ref_ptr<DepthPartitionNode> dpn = new DepthPartitionNode;
    dpn->addChild(scene.get());
    dpn->setActive(true); // Control whether the node analyzes the scene

    // pass the loaded scene graph to the viewer.
    viewer.setSceneData(dpn.get());

    if (needToSetHomePosition)
    {
        viewer.getKeySwitchMatrixManipulator()->setHomePosition(osg::Vec3d(0.0,-5.0*r_earth,0.0),osg::Vec3d(0.0,0.0,0.0),osg::Vec3d(0.0,0.0,1.0));
    }

    // create the windows and run the threads.
    viewer.realize();

    while( !viewer.done() )
    {
        // wait for all cull and draw threads to complete.
        viewer.sync();

        // update the scene by traversing it with the the update visitor which will
        // call all node update callbacks and animations.
        viewer.update();

        // fire off the cull and draw traversals of the scene.
        viewer.frame();

    }

    // wait for all cull and draw threads to complete before exit.
    viewer.sync();

    // run a clean up frame to delete all OpenGL objects.
    viewer.cleanup_frame();

    // wait for all the clean up frame to complete.
    viewer.sync();

    return 0;
}

<|endoftext|>


<commit_before>#include <xpcc/architecture/platform.hpp>
#include "../stm32f4_discovery.hpp"

#include <xpcc/processing/timeout.hpp>
#include <xpcc/processing/protothread.hpp>
#include <xpcc/driver/temperature/tmp102.hpp>

struct DeviceConfiguration
{
	// shared memory for both devices as a cheap way
	// to `tag` the current configuration of the peripheral
	// so we do not need to configure it unnecessarily.
	static char tag;

	/// 100kHz I2C configuration
	static void
	standard_configuration()
	{
		if (tag != 's') {
			I2cMaster1::initialize<defaultSystemClock, 100000>();
			tag = 's';
		}
	}

	/// 400kHz I2C configuration
	static void
	fast_configuration()
	{
		if (tag != 'f') {
			I2cMaster1::initialize<defaultSystemClock, 400000>();
			tag = 'f';
		}
	}
};
char DeviceConfiguration::tag = 0;

class ProtofaceTemperatureOne : public xpcc::pt::Protothread
{
public:
	ProtofaceTemperatureOne()
	:	temperature(temperatureData, 0x48)
	{
		// this i2c device will be driven with only 100kHz
		temperature.attachPeripheralConfiguration(DeviceConfiguration::standard_configuration);
	}

	bool
	update()
	{
		PT_BEGIN();

		// we need to configure the device before we can use it
		// so we wait until the task started
		PT_WAIT_UNTIL(temperature.startConfigure());
		// and we wait until it finished
		PT_WAIT_UNTIL(temperature.runConfigure());

		while (true)
		{
			// lets wait until we can read out the device
			PT_WAIT_UNTIL(temperature.startReadTemperature());
			// and until this task finishes
			PT_WAIT_UNTIL(temperature.runReadTemperature());
			// did we succeed with the readout?
			if (temperature.isSuccessful()) {
				tf = temperature.getTemperature();
			} else {
				tf = NAN;
			}

			this->timer.restart(200);
			PT_WAIT_UNTIL(this->timer.isExpired());
		}

		PT_END();
	}

private:
	float tf;
	xpcc::Timeout<> timer;
	uint8_t temperatureData[2];
	xpcc::Tmp102<I2cMaster1> temperature;
};

class ProtofaceTemperatureTwo : public xpcc::pt::Protothread
{
public:
	ProtofaceTemperatureTwo()
	:	temperature(temperatureData, 0x49)
	{
		// this device will be clocked at 400kHz
		temperature.attachPeripheralConfiguration(DeviceConfiguration::fast_configuration);
	}

	bool
	update()
	{
		PT_BEGIN();

		//
		PT_WAIT_UNTIL(temperature.startConfigure());
		PT_WAIT_UNTIL(temperature.runConfigure());

		while (true)
		{
			PT_WAIT_UNTIL(temperature.startReadTemperature());
			PT_WAIT_UNTIL(temperature.runReadTemperature());
			if (temperature.isSuccessful()) {
				tf = temperature.getTemperature();
			} else {
				tf = NAN;
			}

			this->timer.restart(500);
			PT_WAIT_UNTIL(this->timer.isExpired());
		}

		PT_END();
	}

private:
	float tf;
	xpcc::Timeout<> timer;
	uint8_t temperatureData[2];
	xpcc::Tmp102<I2cMaster1> temperature;
};

ProtofaceTemperatureOne one;
ProtofaceTemperatureTwo two;

// ----------------------------------------------------------------------------
MAIN_FUNCTION
{
	defaultSystemClock::enable();

	LedOrange::setOutput(xpcc::Gpio::High);
	LedGreen::setOutput(xpcc::Gpio::Low);
	LedRed::setOutput(xpcc::Gpio::High);
	LedBlue::setOutput(xpcc::Gpio::High);

	while (1)
	{
		one.update();
		two.update();
	}

	return 0;
}
<commit_msg>Update Protoface example with debug transaction and master. This is tested in hardware and worked.<commit_after>#include <xpcc/architecture/platform.hpp>
#include "../stm32f4_discovery.hpp"

#include <xpcc/processing/timeout.hpp>
#include <xpcc/processing/protothread.hpp>
#include <xpcc/driver/temperature/tmp102.hpp>

#include <xpcc/io/iostream.hpp>

xpcc::IODeviceWrapper<Usart2> device;
xpcc::IOStream stream(device);

// example of a debug transaction, which outputs the wrapped transactions choices.
class CustomI2cTransaction : public xpcc::I2cTransaction
{
	xpcc::I2cTransaction *transaction;

public:
	CustomI2cTransaction()
			:	transaction(nullptr)
	{}

	void
	setTransaction(xpcc::I2cTransaction *transaction)
	{
		this->transaction = transaction;
	}

protected:
	virtual bool
	attaching()
	{
		bool result = transaction->attaching();
		stream << "T: attaching: " << result << xpcc::endl;
		return result;
	}

	virtual Starting
	starting()
	{
		xpcc::I2cTransaction::Starting result = transaction->starting();
		stream << "T: starting: addr=" << result.address << " next=" << (int)result.next << xpcc::endl;
		return result;
	}

	virtual Writing
	writing()
	{
		xpcc::I2cTransaction::Writing result = transaction->writing();
		stream << "T: writing: length=" << result.length << " next=" << (int)result.next << xpcc::endl;
		return result;
	}

	virtual Reading
	reading()
	{
		xpcc::I2cTransaction::Reading result = transaction->reading();
		stream << "T: reading: length=" << result.length << " next=" << (int)result.next << xpcc::endl;
		return result;
	}

	virtual void
	detaching(DetachCause cause)
	{
		transaction->detaching(cause);
		stream << "T: detaching: cause=" << (int)cause << xpcc::endl;
	}
};
static CustomI2cTransaction myTransaction;

// this custom I2c Master wraps the original transaction into the above debug transaction.
class MyI2cMaster2 : public I2cMaster1
{
public:
	static bool
	start(xpcc::I2cTransaction *transaction, xpcc::I2c::Configuration_t configuration = nullptr)
	{
		myTransaction.setTransaction(transaction);
		stream << "st" << xpcc::endl;
		return I2cMaster1::start(&myTransaction, configuration);
	}

	static bool
	startBlocking(xpcc::I2cTransaction *transaction, xpcc::I2c::Configuration_t configuration = nullptr)
	{
		myTransaction.setTransaction(transaction);
		stream << "stBl" << xpcc::endl;
		return I2cMaster1::start(&myTransaction, configuration);
	}
};

typedef I2cMaster1 MyI2cMaster;

struct DeviceConfiguration
{
	// shared memory for both devices as a cheap way
	// to `tag` the current configuration of the peripheral
	// so we do not need to configure it unnecessarily.
	static char tag;

	/// 100kHz I2C configuration
	static void
	standard_configuration()
	{
		if (tag != 's') {
			stream << "config: 20kHz" << xpcc::endl;
			MyI2cMaster::initialize<defaultSystemClock,  20000>();
			tag = 's';
		}
	}

	/// 400kHz I2C configuration
	static void
	fast_configuration()
	{
		if (tag != 'f') {
			stream << "config: 100kHz" << xpcc::endl;
			MyI2cMaster::initialize<defaultSystemClock, 100000>();
			tag = 'f';
		}
	}
};
char DeviceConfiguration::tag = 0;

class ProtofaceTemperatureOne : public xpcc::pt::Protothread
{
public:
	ProtofaceTemperatureOne()
	:	temperature(temperatureData, 0x48)
	{
		// this i2c device will be driven with only 20kHz
		temperature.attachPeripheralConfiguration(DeviceConfiguration::standard_configuration);
	}

	bool
	update()
	{
		PT_BEGIN();

		// we need to configure the device before we can use it
		// so we wait until the task started
		PT_WAIT_UNTIL(temperature.startConfigure());
		// and we wait until it finished
		PT_WAIT_UNTIL(temperature.runConfigure());

		while (true)
		{
			// lets wait until we can read out the device
			PT_WAIT_UNTIL(temperature.startReadTemperature());
			// and until this task finishes
			PT_WAIT_UNTIL(temperature.runReadTemperature());
			// did we succeed with the readout?
			if (temperature.isSuccessful()) {
				tf = temperature.getTemperature();
				stream << "t1: " << (int)tf << xpcc::endl;
			} else {
				tf = NAN;
				stream << "t1: NACK"<< xpcc::endl;
			}

			this->timer.restart(200);
			PT_WAIT_UNTIL(this->timer.isExpired());
			LedRed::toggle();
		}

		PT_END();
	}

private:
	float tf;
	xpcc::Timeout<> timer;
	uint8_t temperatureData[2];
	xpcc::Tmp102<MyI2cMaster> temperature;
};

class ProtofaceTemperatureTwo : public xpcc::pt::Protothread
{
public:
	ProtofaceTemperatureTwo()
	:	temperature(temperatureData, 0x48)
	{
		// this device will be clocked at 100kHz
		temperature.attachPeripheralConfiguration(DeviceConfiguration::fast_configuration);
	}

	bool
	update()
	{
		PT_BEGIN();

		PT_WAIT_UNTIL(temperature.startConfigure());
		PT_WAIT_UNTIL(temperature.runConfigure());

		while (true)
		{
			PT_WAIT_UNTIL(temperature.startReadTemperature());
			PT_WAIT_UNTIL(temperature.runReadTemperature());
			if (temperature.isSuccessful()) {
				tf = temperature.getTemperature();
				stream << "t2: " << (int)tf << xpcc::endl;
			} else {
				tf = NAN;
				stream << "t2: NACK"<< xpcc::endl;
			}

			this->timer.restart(500);
			PT_WAIT_UNTIL(this->timer.isExpired());
			LedGreen::toggle();
		}

		PT_END();
	}

private:
	float tf;
	xpcc::Timeout<> timer;
	uint8_t temperatureData[2];
	xpcc::Tmp102<MyI2cMaster> temperature;
};

ProtofaceTemperatureOne one;
ProtofaceTemperatureTwo two;

// ----------------------------------------------------------------------------
MAIN_FUNCTION
{
	defaultSystemClock::enable();
	xpcc::cortex::SysTickTimer::enable();

	LedOrange::setOutput(xpcc::Gpio::High);
	LedGreen::setOutput(xpcc::Gpio::Low);
	LedRed::setOutput(xpcc::Gpio::High);
	LedBlue::setOutput(xpcc::Gpio::High);

	GpioOutputA2::connect(Usart2::Tx);
	Usart2::initialize<defaultSystemClock, xpcc::Uart::B38400>(10);

	GpioB7::connect(MyI2cMaster::Sda);
	GpioB8::connect(MyI2cMaster::Scl);
	GpioB7::configure(Gpio::InputType::PullUp);
	GpioB8::configure(Gpio::InputType::PullUp);

	stream << "\n\nRESTART\n\n";

	while (1)
	{
		one.update();
		two.update();
		LedOrange::toggle();
	}

	return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2007 Digital Bazaar, Inc.  All rights reserved.
 */
#include <iostream>

#include "Base64Coder.h"
#include "Object.h"
#include "Runnable.h"
#include "Thread.h"
#include "System.h"
#include "TcpSocket.h"
#include "InternetAddress.h"

using namespace std;
using namespace db::net;
using namespace db::rt;
using namespace db::util;

void runBase64Test()
{
	cout << "Running Base64 Test" << endl << endl;

	char data[] = {'a', 'b', 'c', 'd'};
	string encoded = Base64Coder::encode(data, 0, 4);
	cout << "encoded=" << encoded << endl;

	char* decoded = Base64Coder::decode(encoded);
   int length = sizeof(decoded);

	cout << "decoded bytes=" << length << endl;
   for(int i = 0; i < length; i++)
   {
      cout << "decoded[" << i << "]=" << decoded[i] << endl;
   }

	string encoded2 = Base64Coder::encode(decoded, 0, 4);
	cout << "encoded again=" << encoded2 << endl;

   if(decoded != NULL)
   {
	   delete [] decoded;
   }
}

void runTimeTest()
{
   cout << "Running Time Test" << endl << endl;

   unsigned long long start = System::getCurrentMilliseconds();

   cout << "Time start=" << start << endl;

   unsigned long long end = System::getCurrentMilliseconds();

   cout << "Time end=" << end << endl;
}

class TestRunnable : public virtual Object, public Runnable
{
   virtual void run()
   {
      string name = Thread::currentThread()->getName();
      cout << name << ": This is a TestRunnable thread." << endl;

      if(name == "Thread 1")
      {
         cout << "Thread 1 Waiting for Thread 5..." << endl;

         lock();
         {
            lock();
            lock();
            lock();
            wait();
         }
         unlock();

         cout << "Thread 1 Finished." << endl;
      }
      else if(name == "Thread 3")
      {
         cout << "Thread 3 Waiting for Thread 5..." << endl;

         lock();
         lock();
         lock();
         lock();
         {
            wait();
         }
         unlock();

         cout << "Thread 3 Finished." << endl;
      }
      else if(name == "Thread 5")
      {
         cout << "Thread 5 waking up threads..." << endl;

         lock();
         lock();
         lock();
         lock();
         {
            notifyAll();
         }
         unlock();
      }
   }
};

void runThreadTest()
{
   cout << "Running Thread Test" << endl << endl;

   TestRunnable r1;
   Thread t1(&r1, "Thread 1");

   //TestRunnable r2;
   Thread t2(&r1, "Thread 2");

   //TestRunnable r3;
   Thread t3(&r1, "Thread 3");

   //TestRunnable r4;
   Thread t4(&r1, "Thread 4");

   //TestRunnable r5;
   Thread t5(&r1, "Thread 5");

   t1.start();
   t2.start();
   t3.start();
   t4.start();
   t5.start();

   t1.join();
   t2.join();
   t3.join();
   t4.join();
   t5.join();
}

void runWindowsSocketTest()
{
   // initialize winsock
#ifdef WIN32
   WSADATA wsaData;
   if(WSAStartup(MAKEWORD(2, 0), &wsaData) < 0)
   {
      cout << "ERROR!!!" << endl;
   }
#endif

   // create tcp socket
   TcpSocket socket;

   // create address
   // "www.google.com"
   InternetAddress address("64.233.161.99", 80);

   // connect
   socket.connect(&address);

   // close
   socket.close();

   cout << "DONE!" << endl;

   // cleanup winsock
#ifdef WIN32
   WSACleanup();
#endif
}

void runLinuxSocketTest()
{
   // create tcp socket
   TcpSocket socket;

   // create address
   // "www.google.com"
   //InternetAddress address("64.233.161.99", 80);
   InternetAddress address("127.0.0.1", 80);
   cout << address.getAddress() << endl;

   // connect
   socket.connect(&address);

   char request[] = "GET / HTTP/1.0\r\nContent-Length: 0\r\n\r\n";
   socket.send(request, 0, sizeof(request));

   char response[2048];
   int numBytes = socket.receive(response, 0, 2048);

   cout << "numBytes received: " << numBytes << endl;

   // close
   socket.close();

   cout << "DONE!" << endl;
}

int main()
{
   cout << "Tests starting..." << endl << endl;

   try
   {
      //runBase64Test();
      //runTimeTest();
      //runThreadTest();
      //runWindowsSocketTest();
      runLinuxSocketTest();
   }
   catch(SocketException& e)
   {
      cout << "SocketException caught!" << endl;
      cout << "message: " << e.getMessage() << endl;
      cout << "code: " << e.getCode() << endl;
   }
   catch(...)
   {
      cout << "Exception caught!" << endl;
   }

   cout << endl << "Tests finished." << endl;
}
<commit_msg>Updated socket test.<commit_after>/*
 * Copyright (c) 2007 Digital Bazaar, Inc.  All rights reserved.
 */
#include <iostream>

#include "Base64Coder.h"
#include "Object.h"
#include "Runnable.h"
#include "Thread.h"
#include "System.h"
#include "TcpSocket.h"
#include "InternetAddress.h"

using namespace std;
using namespace db::net;
using namespace db::rt;
using namespace db::util;

void runBase64Test()
{
	cout << "Running Base64 Test" << endl << endl;

	char data[] = {'a', 'b', 'c', 'd'};
	string encoded = Base64Coder::encode(data, 0, 4);
	cout << "encoded=" << encoded << endl;

	char* decoded = Base64Coder::decode(encoded);
   int length = sizeof(decoded);

	cout << "decoded bytes=" << length << endl;
   for(int i = 0; i < length; i++)
   {
      cout << "decoded[" << i << "]=" << decoded[i] << endl;
   }

	string encoded2 = Base64Coder::encode(decoded, 0, 4);
	cout << "encoded again=" << encoded2 << endl;

   if(decoded != NULL)
   {
	   delete [] decoded;
   }
}

void runTimeTest()
{
   cout << "Running Time Test" << endl << endl;

   unsigned long long start = System::getCurrentMilliseconds();

   cout << "Time start=" << start << endl;

   unsigned long long end = System::getCurrentMilliseconds();

   cout << "Time end=" << end << endl;
}

class TestRunnable : public virtual Object, public Runnable
{
   virtual void run()
   {
      string name = Thread::currentThread()->getName();
      cout << name << ": This is a TestRunnable thread." << endl;

      if(name == "Thread 1")
      {
         cout << "Thread 1 Waiting for Thread 5..." << endl;

         lock();
         {
            lock();
            lock();
            lock();
            wait();
         }
         unlock();

         cout << "Thread 1 Finished." << endl;
      }
      else if(name == "Thread 3")
      {
         cout << "Thread 3 Waiting for Thread 5..." << endl;

         lock();
         lock();
         lock();
         lock();
         {
            wait();
         }
         unlock();

         cout << "Thread 3 Finished." << endl;
      }
      else if(name == "Thread 5")
      {
         cout << "Thread 5 waking up threads..." << endl;

         lock();
         lock();
         lock();
         lock();
         {
            notifyAll();
         }
         unlock();
      }
   }
};

void runThreadTest()
{
   cout << "Running Thread Test" << endl << endl;

   TestRunnable r1;
   Thread t1(&r1, "Thread 1");

   //TestRunnable r2;
   Thread t2(&r1, "Thread 2");

   //TestRunnable r3;
   Thread t3(&r1, "Thread 3");

   //TestRunnable r4;
   Thread t4(&r1, "Thread 4");

   //TestRunnable r5;
   Thread t5(&r1, "Thread 5");

   t1.start();
   t2.start();
   t3.start();
   t4.start();
   t5.start();

   t1.join();
   t2.join();
   t3.join();
   t4.join();
   t5.join();
}

void runWindowsSocketTest()
{
   // initialize winsock
#ifdef WIN32
   WSADATA wsaData;
   if(WSAStartup(MAKEWORD(2, 0), &wsaData) < 0)
   {
      cout << "ERROR!!!" << endl;
   }
#endif

   // create tcp socket
   TcpSocket socket;

   // create address
   // "www.google.com"
   InternetAddress address("64.233.161.99", 80);

   // connect
   socket.connect(&address);

   // close
   socket.close();

   cout << "DONE!" << endl;

   // cleanup winsock
#ifdef WIN32
   WSACleanup();
#endif
}

void runLinuxSocketTest()
{
   // create tcp socket
   TcpSocket socket;

   // create address
   // "www.google.com"
   //InternetAddress address("64.233.161.99", 80);
   InternetAddress address("127.0.0.1", 80);
   cout << address.getAddress() << endl;

   // connect
   socket.connect(&address);

   char request[] =
      "GET / HTTP/1.0\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
   socket.send(request, 0, sizeof(request));

   char response[2048];
   int numBytes = 0;
   string str = "";
   while((numBytes = socket.receive(response, 0, 2048)) != -1)
   {
      cout << "numBytes received: " << numBytes << endl;
      str.append(response, numBytes);
   }

   // close
   socket.close();

   cout << "Socket connection closed." << endl;
   cout << "Response:" << endl << str << endl;

   cout << endl << "Socket test complete." << endl;
}

int main()
{
   cout << "Tests starting..." << endl << endl;

   try
   {
      //runBase64Test();
      //runTimeTest();
      //runThreadTest();
      //runWindowsSocketTest();
      runLinuxSocketTest();
   }
   catch(SocketException& e)
   {
      cout << "SocketException caught!" << endl;
      cout << "message: " << e.getMessage() << endl;
      cout << "code: " << e.getCode() << endl;
   }
   catch(...)
   {
      cout << "Exception caught!" << endl;
   }

   cout << endl << "Tests finished." << endl;
}
<|endoftext|>


<commit_before>/**********************************************************************************
 * NAN - Native Abstractions for Node.js
 *
 * Copyright (c) 2014 NAN contributors
 *
 * MIT +no-false-attribs License <https://github.com/rvagg/nan/blob/master/LICENSE>
 **********************************************************************************/

#include <nan.h>
#include <string>

static int magic = 1337;

NAN_METHOD(NewNumber) {
  NanScope();
  NanReturnValue(NanNew<v8::Number>(0.5));
}

NAN_METHOD(NewNegativeInteger) {
  NanScope();
  NanReturnValue(NanNew<v8::Integer>(-1));
}

NAN_METHOD(NewPositiveInteger) {
  NanScope();
  NanReturnValue(NanNew<v8::Integer>(1));
}

NAN_METHOD(NewInt32FromPositive) {
  NanScope();
  NanReturnValue(NanNew<v8::Int32>(0xFFFFFFFF));
}

NAN_METHOD(NewInt32FromNegative) {
  NanScope();
  NanReturnValue(NanNew<v8::Int32>(-1));
}

NAN_METHOD(NewUint32FromPositive) {
  NanScope();
  NanReturnValue(NanNew<v8::Uint32>(0xFFFFFFFF));
}

NAN_METHOD(NewUint32FromNegative) {
  NanScope();
  NanReturnValue(NanNew<v8::Uint32>(-1));
}

NAN_METHOD(NewUtf8String) {
  NanScope();
  const char s[] = "strïng";
  NanReturnValue(NanNew<v8::String>(s));
}

NAN_METHOD(NewLatin1String) {
  NanScope();
  const uint8_t s[] = "str\xefng";
  NanReturnValue(NanNew<v8::String>(s));
}

NAN_METHOD(NewUcs2String) {
  NanScope();
  const uint16_t s[] = {'s', 't', 'r', 0xef, 'n', 'g', '\0'};
  NanReturnValue(NanNew(s));
}

NAN_METHOD(NewStdString) {
  NanScope();
  const std::string s = "strïng";
  NanReturnValue(NanNew<v8::String>(s));
}

NAN_METHOD(NewRegExp) {
  NanScope();
  NanReturnValue(NanNew<v8::RegExp>(NanNew("foo"), v8::RegExp::kNone));
}

NAN_METHOD(NewStringObject) {
  NanScope();
  NanReturnValue(NanNew<v8::StringObject>(NanNew<v8::String>("foo")));
}

NAN_METHOD(NewNumberObject) {
  NanScope();
  NanReturnValue(NanNew<v8::NumberObject>(0.5));
}

NAN_METHOD(NewBooleanObject) {
  NanScope();
  NanReturnValue(NanNew<v8::BooleanObject>(true));
}

NAN_METHOD(NewExternal) {
  NanScope();
  v8::Local<v8::External> ext = NanNew<v8::External>(&magic);
  assert(*static_cast<int *>(ext->Value()) == 1337);
  NanReturnValue(NanNew<v8::String>("passed"));
}

NAN_METHOD(NewSignature) {
  NanScope();
  v8::Local<v8::FunctionTemplate> tmpl =
      NanNew<v8::FunctionTemplate>(NewSignature);
  v8::Local<v8::Signature> sig = NanNew<v8::Signature>(tmpl, 1, &tmpl);
  tmpl = NanNew<v8::FunctionTemplate>(
      NewSignature, v8::Handle<v8::Value>(), sig);
  NanReturnValue(NanNew<v8::String>("string"));
}

NAN_METHOD(NewScript) {
  NanScope();
  v8::Local<NanUnboundScript> script = NanNew<NanUnboundScript>(NanNew("2+4"));
  NanReturnValue(NanRunScript(script)->ToInt32());
}

NAN_METHOD(NewScript2) {
  NanScope();
  v8::ScriptOrigin origin(NanNew<v8::String>("x"));
  v8::Local<NanUnboundScript> script =
      NanNew<NanUnboundScript>(NanNew("2+4"), origin);
  NanReturnValue(NanRunScript(script)->ToInt32());
}

NAN_METHOD(CompileScript) {
  NanScope();
  v8::Local<NanBoundScript> script = NanCompileScript(NanNew("2+4"));
  NanReturnValue(NanRunScript(script)->ToInt32());
}

NAN_METHOD(CompileScript2) {
  NanScope();
  v8::ScriptOrigin origin(NanNew<v8::String>("x"));
  v8::Local<NanBoundScript> script = NanCompileScript(NanNew("2+4"), origin);
  NanReturnValue(NanRunScript(script)->ToInt32());
}

NAN_METHOD(NewDate) {
  NanScope();
  NanReturnValue(NanNew<v8::Date>(1337));
}

NAN_METHOD(NewArray) {
  NanScope();
  NanReturnValue(NanNew<v8::Array>());
}

void Init(v8::Handle<v8::Object> target) {
  target->Set(
      NanNew<v8::String>("newNumber")
    , NanNew<v8::FunctionTemplate>(NewNumber)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newNegativeInteger")
    , NanNew<v8::FunctionTemplate>(NewNegativeInteger)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newPositiveInteger")
    , NanNew<v8::FunctionTemplate>(NewPositiveInteger)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newInt32FromPositive")
    , NanNew<v8::FunctionTemplate>(NewInt32FromPositive)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newInt32FromNegative")
    , NanNew<v8::FunctionTemplate>(NewInt32FromNegative)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newUint32FromPositive")
    , NanNew<v8::FunctionTemplate>(NewUint32FromPositive)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newUint32FromNegative")
    , NanNew<v8::FunctionTemplate>(NewUint32FromNegative)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newUtf8String")
    , NanNew<v8::FunctionTemplate>(NewUtf8String)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newLatin1String")
    , NanNew<v8::FunctionTemplate>(NewLatin1String)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newUcs2String")
    , NanNew<v8::FunctionTemplate>(NewUcs2String)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newStdString")
    , NanNew<v8::FunctionTemplate>(NewUcs2String)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newRegExp")
    , NanNew<v8::FunctionTemplate>(NewRegExp)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newStringObject")
    , NanNew<v8::FunctionTemplate>(NewStringObject)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newNumberObject")
    , NanNew<v8::FunctionTemplate>(NewNumberObject)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newBooleanObject")
    , NanNew<v8::FunctionTemplate>(NewBooleanObject)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newExternal")
    , NanNew<v8::FunctionTemplate>(NewExternal)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newSignature")
    , NanNew<v8::FunctionTemplate>(NewSignature)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newScript")
    , NanNew<v8::FunctionTemplate>(NewScript)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newScript2")
    , NanNew<v8::FunctionTemplate>(NewScript2)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("compileScript")
    , NanNew<v8::FunctionTemplate>(CompileScript)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("compileScript2")
    , NanNew<v8::FunctionTemplate>(CompileScript2)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newDate")
    , NanNew<v8::FunctionTemplate>(NewDate)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newArray")
    , NanNew<v8::FunctionTemplate>(NewArray)->GetFunction()
  );
}

NODE_MODULE(news, Init)
<commit_msg>Fix std::string test<commit_after>/**********************************************************************************
 * NAN - Native Abstractions for Node.js
 *
 * Copyright (c) 2014 NAN contributors
 *
 * MIT +no-false-attribs License <https://github.com/rvagg/nan/blob/master/LICENSE>
 **********************************************************************************/

#include <nan.h>
#include <string>

static int magic = 1337;

NAN_METHOD(NewNumber) {
  NanScope();
  NanReturnValue(NanNew<v8::Number>(0.5));
}

NAN_METHOD(NewNegativeInteger) {
  NanScope();
  NanReturnValue(NanNew<v8::Integer>(-1));
}

NAN_METHOD(NewPositiveInteger) {
  NanScope();
  NanReturnValue(NanNew<v8::Integer>(1));
}

NAN_METHOD(NewInt32FromPositive) {
  NanScope();
  NanReturnValue(NanNew<v8::Int32>(0xFFFFFFFF));
}

NAN_METHOD(NewInt32FromNegative) {
  NanScope();
  NanReturnValue(NanNew<v8::Int32>(-1));
}

NAN_METHOD(NewUint32FromPositive) {
  NanScope();
  NanReturnValue(NanNew<v8::Uint32>(0xFFFFFFFF));
}

NAN_METHOD(NewUint32FromNegative) {
  NanScope();
  NanReturnValue(NanNew<v8::Uint32>(-1));
}

NAN_METHOD(NewUtf8String) {
  NanScope();
  const char s[] = "strïng";
  NanReturnValue(NanNew<v8::String>(s));
}

NAN_METHOD(NewLatin1String) {
  NanScope();
  const uint8_t s[] = "str\xefng";
  NanReturnValue(NanNew<v8::String>(s));
}

NAN_METHOD(NewUcs2String) {
  NanScope();
  const uint16_t s[] = {'s', 't', 'r', 0xef, 'n', 'g', '\0'};
  NanReturnValue(NanNew(s));
}

NAN_METHOD(NewStdString) {
  NanScope();
  const std::string s = "strïng";
  NanReturnValue(NanNew<v8::String>(s));
}

NAN_METHOD(NewRegExp) {
  NanScope();
  NanReturnValue(NanNew<v8::RegExp>(NanNew("foo"), v8::RegExp::kNone));
}

NAN_METHOD(NewStringObject) {
  NanScope();
  NanReturnValue(NanNew<v8::StringObject>(NanNew<v8::String>("foo")));
}

NAN_METHOD(NewNumberObject) {
  NanScope();
  NanReturnValue(NanNew<v8::NumberObject>(0.5));
}

NAN_METHOD(NewBooleanObject) {
  NanScope();
  NanReturnValue(NanNew<v8::BooleanObject>(true));
}

NAN_METHOD(NewExternal) {
  NanScope();
  v8::Local<v8::External> ext = NanNew<v8::External>(&magic);
  assert(*static_cast<int *>(ext->Value()) == 1337);
  NanReturnValue(NanNew<v8::String>("passed"));
}

NAN_METHOD(NewSignature) {
  NanScope();
  v8::Local<v8::FunctionTemplate> tmpl =
      NanNew<v8::FunctionTemplate>(NewSignature);
  v8::Local<v8::Signature> sig = NanNew<v8::Signature>(tmpl, 1, &tmpl);
  tmpl = NanNew<v8::FunctionTemplate>(
      NewSignature, v8::Handle<v8::Value>(), sig);
  NanReturnValue(NanNew<v8::String>("string"));
}

NAN_METHOD(NewScript) {
  NanScope();
  v8::Local<NanUnboundScript> script = NanNew<NanUnboundScript>(NanNew("2+4"));
  NanReturnValue(NanRunScript(script)->ToInt32());
}

NAN_METHOD(NewScript2) {
  NanScope();
  v8::ScriptOrigin origin(NanNew<v8::String>("x"));
  v8::Local<NanUnboundScript> script =
      NanNew<NanUnboundScript>(NanNew("2+4"), origin);
  NanReturnValue(NanRunScript(script)->ToInt32());
}

NAN_METHOD(CompileScript) {
  NanScope();
  v8::Local<NanBoundScript> script = NanCompileScript(NanNew("2+4"));
  NanReturnValue(NanRunScript(script)->ToInt32());
}

NAN_METHOD(CompileScript2) {
  NanScope();
  v8::ScriptOrigin origin(NanNew<v8::String>("x"));
  v8::Local<NanBoundScript> script = NanCompileScript(NanNew("2+4"), origin);
  NanReturnValue(NanRunScript(script)->ToInt32());
}

NAN_METHOD(NewDate) {
  NanScope();
  NanReturnValue(NanNew<v8::Date>(1337));
}

NAN_METHOD(NewArray) {
  NanScope();
  NanReturnValue(NanNew<v8::Array>());
}

void Init(v8::Handle<v8::Object> target) {
  target->Set(
      NanNew<v8::String>("newNumber")
    , NanNew<v8::FunctionTemplate>(NewNumber)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newNegativeInteger")
    , NanNew<v8::FunctionTemplate>(NewNegativeInteger)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newPositiveInteger")
    , NanNew<v8::FunctionTemplate>(NewPositiveInteger)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newInt32FromPositive")
    , NanNew<v8::FunctionTemplate>(NewInt32FromPositive)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newInt32FromNegative")
    , NanNew<v8::FunctionTemplate>(NewInt32FromNegative)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newUint32FromPositive")
    , NanNew<v8::FunctionTemplate>(NewUint32FromPositive)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newUint32FromNegative")
    , NanNew<v8::FunctionTemplate>(NewUint32FromNegative)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newUtf8String")
    , NanNew<v8::FunctionTemplate>(NewUtf8String)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newLatin1String")
    , NanNew<v8::FunctionTemplate>(NewLatin1String)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newUcs2String")
    , NanNew<v8::FunctionTemplate>(NewUcs2String)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newStdString")
    , NanNew<v8::FunctionTemplate>(NewStdString)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newRegExp")
    , NanNew<v8::FunctionTemplate>(NewRegExp)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newStringObject")
    , NanNew<v8::FunctionTemplate>(NewStringObject)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newNumberObject")
    , NanNew<v8::FunctionTemplate>(NewNumberObject)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newBooleanObject")
    , NanNew<v8::FunctionTemplate>(NewBooleanObject)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newExternal")
    , NanNew<v8::FunctionTemplate>(NewExternal)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newSignature")
    , NanNew<v8::FunctionTemplate>(NewSignature)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newScript")
    , NanNew<v8::FunctionTemplate>(NewScript)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newScript2")
    , NanNew<v8::FunctionTemplate>(NewScript2)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("compileScript")
    , NanNew<v8::FunctionTemplate>(CompileScript)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("compileScript2")
    , NanNew<v8::FunctionTemplate>(CompileScript2)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newDate")
    , NanNew<v8::FunctionTemplate>(NewDate)->GetFunction()
  );
  target->Set(
      NanNew<v8::String>("newArray")
    , NanNew<v8::FunctionTemplate>(NewArray)->GetFunction()
  );
}

NODE_MODULE(news, Init)
<|endoftext|>


<commit_before>#include "download.h"

#include "test-helpers.h"

using namespace podboat;

TEST_CASE("Require-view-update callback gets called when download progress or status changes", "[Download]")
{
	GIVEN("A Download object") {
		bool got_called = false;
		std::function<void()> callback = [&got_called]() {
			got_called = true;
		};

		Download d(callback);

		REQUIRE(d.status() == DlStatus::QUEUED);

		WHEN("its progress is updated (increased)") {
			got_called = false;
			d.set_progress(1.0, 1.0);

			THEN("the require-view-update callback gets called") {
				REQUIRE(got_called);
			}
		}

		WHEN("its progress has not changed") {
			got_called = false;
			d.set_progress(0.0, 1.0);

			THEN("the require-view-update callback does not get called") {
				REQUIRE_FALSE(got_called);
			}
		}

		WHEN("its status is changed") {
			got_called = false;
			d.set_status(DlStatus::DOWNLOADING);

			THEN("the require-view-update callback gets called") {
				REQUIRE(got_called);
			}
		}

		WHEN("when its status is not changed") {
			got_called = false;
			d.set_status(DlStatus::QUEUED);

			THEN("the require-view-update callback does not get called") {
				REQUIRE_FALSE(got_called);
			}
		}
	}
}
<commit_msg>Add test for Download::filename<commit_after>#include "download.h"

#include "test-helpers.h"

using namespace podboat;

TEST_CASE("Require-view-update callback gets called when download progress or status changes", "[Download]")
{
	GIVEN("A Download object") {
		bool got_called = false;
		std::function<void()> callback = [&got_called]() {
			got_called = true;
		};

		Download d(callback);

		REQUIRE(d.status() == DlStatus::QUEUED);

		WHEN("its progress is updated (increased)") {
			got_called = false;
			d.set_progress(1.0, 1.0);

			THEN("the require-view-update callback gets called") {
				REQUIRE(got_called);
			}
		}

		WHEN("its progress has not changed") {
			got_called = false;
			d.set_progress(0.0, 1.0);

			THEN("the require-view-update callback does not get called") {
				REQUIRE_FALSE(got_called);
			}
		}

		WHEN("its status is changed") {
			got_called = false;
			d.set_status(DlStatus::DOWNLOADING);

			THEN("the require-view-update callback gets called") {
				REQUIRE(got_called);
			}
		}

		WHEN("when its status is not changed") {
			got_called = false;
			d.set_status(DlStatus::QUEUED);

			THEN("the require-view-update callback does not get called") {
				REQUIRE_FALSE(got_called);
			}
		}
	}
}

TEST_CASE("Filename returns configured filename", "[Download]")
{
	auto emptyCallback = [](){};

	Download d(emptyCallback);

	SECTION("filename returns empty string by default") {
		REQUIRE(d.filename() == "");
	}

	SECTION("filename returns same string which is set via set_filename") {
		d.set_filename("abc");
		REQUIRE(d.filename() == "abc");
	}

	SECTION("filename will return the latest configured filename") {
		d.set_filename("abc");
		d.set_filename("def");

		REQUIRE(d.filename() == "def");
	}
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "basetexteditmodifier.h"

#include <qmljs/qmljsmodelmanagerinterface.h>
#include <qmljseditor/qmljseditor.h>
#include <qmljseditor/qmljseditordocument.h>
#include <texteditor/tabsettings.h>
#include <utils/changeset.h>

using namespace QmlDesigner;

BaseTextEditModifier::BaseTextEditModifier(TextEditor::BaseTextEditorWidget *textEdit):
        PlainTextEditModifier(textEdit)
{
}

void BaseTextEditModifier::indent(int offset, int length)
{
    if (length == 0 || offset < 0 || offset + length >= text().length())
        return;

    if (TextEditor::BaseTextEditorWidget *bte = qobject_cast<TextEditor::BaseTextEditorWidget*>(plainTextEdit())) {
        TextEditor::BaseTextDocument *btd = bte->baseTextDocument();
        // find the applicable block:
        QTextDocument *doc = btd->document();
        QTextCursor tc(doc);
        tc.beginEditBlock();
        tc.setPosition(offset);
        tc.setPosition(offset + length, QTextCursor::KeepAnchor);
        btd->autoIndent(tc);
        tc.endEditBlock();
    }
}

int BaseTextEditModifier::indentDepth() const
{
    if (TextEditor::BaseTextEditorWidget *bte = qobject_cast<TextEditor::BaseTextEditorWidget*>(plainTextEdit()))
        return bte->baseTextDocument()->tabSettings().m_indentSize;
    else
        return 0;
}

bool BaseTextEditModifier::renameId(const QString &oldId, const QString &newId)
{
    if (QmlJSEditor::QmlJSTextEditorWidget *qmljse = qobject_cast<QmlJSEditor::QmlJSTextEditorWidget*>(plainTextEdit())) {
        Utils::ChangeSet changeSet;
        foreach (const QmlJS::AST::SourceLocation &loc,
                 qmljse->qmlJsEditorDocument()->semanticInfo().idLocations.value(oldId)) {
            changeSet.replace(loc.begin(), loc.end(), newId);
        }
        QTextCursor tc = qmljse->textCursor();
        changeSet.apply(&tc);
        return true;
    } else {
        return false;
    }
}

QmlJS::Snapshot BaseTextEditModifier::getSnapshot() const
{
    QmlJS::ModelManagerInterface *modelManager = QmlJS::ModelManagerInterface::instance();
    if (modelManager)
        return modelManager->snapshot();
    else
        return QmlJS::Snapshot();
}

QStringList BaseTextEditModifier::importPaths() const
{
    QmlJS::ModelManagerInterface *modelManager = QmlJS::ModelManagerInterface::instance();
    if (modelManager)
        return modelManager->importPaths();
    else
        return QStringList();
}
<commit_msg>QmlDesigner: Use QmlJSEditorDocument instead of widget<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "basetexteditmodifier.h"

#include <qmljs/qmljsmodelmanagerinterface.h>
#include <qmljseditor/qmljseditordocument.h>
#include <texteditor/tabsettings.h>
#include <utils/changeset.h>

using namespace QmlDesigner;

BaseTextEditModifier::BaseTextEditModifier(TextEditor::BaseTextEditorWidget *textEdit):
        PlainTextEditModifier(textEdit)
{
}

void BaseTextEditModifier::indent(int offset, int length)
{
    if (length == 0 || offset < 0 || offset + length >= text().length())
        return;

    if (TextEditor::BaseTextEditorWidget *bte = qobject_cast<TextEditor::BaseTextEditorWidget*>(plainTextEdit())) {
        TextEditor::BaseTextDocument *btd = bte->baseTextDocument();
        // find the applicable block:
        QTextDocument *doc = btd->document();
        QTextCursor tc(doc);
        tc.beginEditBlock();
        tc.setPosition(offset);
        tc.setPosition(offset + length, QTextCursor::KeepAnchor);
        btd->autoIndent(tc);
        tc.endEditBlock();
    }
}

int BaseTextEditModifier::indentDepth() const
{
    if (TextEditor::BaseTextEditorWidget *bte = qobject_cast<TextEditor::BaseTextEditorWidget*>(plainTextEdit()))
        return bte->baseTextDocument()->tabSettings().m_indentSize;
    else
        return 0;
}

bool BaseTextEditModifier::renameId(const QString &oldId, const QString &newId)
{
    if (TextEditor::BaseTextEditorWidget *bte = qobject_cast<TextEditor::BaseTextEditorWidget*>(plainTextEdit())) {
        if (QmlJSEditor::QmlJSEditorDocument *document
                = qobject_cast<QmlJSEditor::QmlJSEditorDocument *>(bte->baseTextDocument())) {
            Utils::ChangeSet changeSet;
            foreach (const QmlJS::AST::SourceLocation &loc,
                    document->semanticInfo().idLocations.value(oldId)) {
                changeSet.replace(loc.begin(), loc.end(), newId);
            }
            QTextCursor tc = bte->textCursor();
            changeSet.apply(&tc);
            return true;
        }
    }
    return false;
}

QmlJS::Snapshot BaseTextEditModifier::getSnapshot() const
{
    QmlJS::ModelManagerInterface *modelManager = QmlJS::ModelManagerInterface::instance();
    if (modelManager)
        return modelManager->snapshot();
    else
        return QmlJS::Snapshot();
}

QStringList BaseTextEditModifier::importPaths() const
{
    QmlJS::ModelManagerInterface *modelManager = QmlJS::ModelManagerInterface::instance();
    if (modelManager)
        return modelManager->importPaths();
    else
        return QStringList();
}
<|endoftext|>


<commit_before>
#pragma once

#include <utility>
#include <functional>
#include <cassert>

#include <glbinding/Value.h>
#include <glbinding/FunctionCall.h>
#include <glbinding/CallbackMask.h>
#include <glbinding/Boolean8.h>

namespace glbinding
{

template <typename ReturnType, typename... Arguments>
struct BasicCallHelper
{
    inline static ReturnType call(const glbinding::Function<ReturnType, Arguments...> * function, Arguments&&... arguments)
    {
        return reinterpret_cast<typename glbinding::Function<ReturnType, Arguments...>::Signature>(function->address())(std::forward<Arguments>(arguments)...);
    }
};

// Special case for booleans because of MSVC differing behavior

template <typename... Arguments>
struct BasicCallHelper<glbinding::Boolean8, Arguments...>
{
    inline static glbinding::Boolean8 call(const glbinding::Function<glbinding::Boolean8, Arguments...> * function, Arguments&&... arguments)
    {
        return reinterpret_cast<typename glbinding::Function<glbinding::Boolean8::underlying_type, Arguments...>::Signature>(function->address())(std::forward<Arguments>(arguments)...);
    }
};

template <typename ReturnType, typename... Arguments>
struct FunctionHelper
{
    inline static ReturnType call(const glbinding::Function<ReturnType, Arguments...> * function, Arguments&&... arguments)
    {
        glbinding::FunctionCall functionCall(function);

        if (function->isAnyEnabled(glbinding::CallbackMask::Parameters))
        {
            functionCall.parameters = glbinding::createValues(std::forward<Arguments>(arguments)...);
        }

        if (function->isEnabled(glbinding::CallbackMask::Before))
        {
            AbstractFunction::before(functionCall);

            if (function->beforeCallback())
            {
                function->beforeCallback()(std::forward<Arguments>(arguments)...);
            }
        }

        auto value = BasicCallHelper<ReturnType, Arguments ...>::call(function, std::forward<Arguments>(arguments)...);

        if (function->isAnyEnabled(glbinding::CallbackMask::ReturnValue))
        {
            functionCall.returnValue = glbinding::createValue(value);
        }

        if (function->isEnabled(glbinding::CallbackMask::After))
        {
            AbstractFunction::after(functionCall);

            if (function->afterCallback())
            {
                function->afterCallback()(value, std::forward<Arguments>(arguments)...);
            }
        }

        if (function->isEnabled(glbinding::CallbackMask::Logging))
        {
            AbstractFunction::log(std::move(functionCall));
        }

        return value;
    }
};

template <typename... Arguments>
struct FunctionHelper<void, Arguments...>
{
    inline static void call(const glbinding::Function<void, Arguments...> * function, Arguments&&... arguments)
    {
        glbinding::FunctionCall functionCall(function);

        if (function->isAnyEnabled(glbinding::CallbackMask::Parameters))
        {
            functionCall.parameters = glbinding::createValues(std::forward<Arguments>(arguments)...);
        }

        if (function->isEnabled(glbinding::CallbackMask::Before))
        {
            AbstractFunction::before(functionCall);

            if (function->beforeCallback())
            {
                function->beforeCallback()(std::forward<Arguments>(arguments)...);
            }
        }

        BasicCallHelper<void, Arguments ...>::call(function, std::forward<Arguments>(arguments)...);

        if (function->isEnabled(glbinding::CallbackMask::After))
        {
            AbstractFunction::after(functionCall);

            if (function->afterCallback())
            {
                function->afterCallback()(std::forward<Arguments>(arguments)...);
            }
        }

        if (function->isEnabled(glbinding::CallbackMask::Logging))
        {
            AbstractFunction::log(std::move(functionCall));
        }
    }
};

template <typename ReturnType, typename... Arguments>
Function<ReturnType, Arguments...>::Function(const char * _name)
: AbstractFunction{_name}
, m_beforeCallback{nullptr}
, m_afterCallback{nullptr}
{
}

template <typename ReturnType, typename... Arguments>
ReturnType Function<ReturnType, Arguments...>::operator()(Arguments&... arguments) const
{
    return call(arguments...);
}

template <typename ReturnType, typename... Arguments>
ReturnType Function<ReturnType, Arguments...>::call(Arguments&... arguments) const
{
    const auto myAddress = address();

    if (myAddress == nullptr)
    {
        if (isEnabled(CallbackMask::Unresolved))
        {
           AbstractFunction::unresolved(this);
        }

        return ReturnType();
    }

    if (isAnyEnabled(CallbackMask::Before | CallbackMask::After | CallbackMask::Logging))
    {
        return FunctionHelper<ReturnType, Arguments...>::call(this, std::forward<Arguments>(arguments)...);
    }
    else
    {
        return BasicCallHelper<ReturnType, Arguments...>::call(this, std::forward<Arguments>(arguments)...);
    }
}

template <typename ReturnType, typename... Arguments>
ReturnType Function<ReturnType, Arguments...>::directCall(Arguments... arguments) const
{
    if (address() == nullptr)
    {
        return ReturnType();
    }

    return BasicCallHelper<ReturnType, Arguments...>::call(this, std::forward<Arguments>(arguments)...);
}

template <typename ReturnType, typename... Arguments>
void Function<ReturnType, Arguments...>::setBeforeCallback(BeforeCallback callback)
{
    m_beforeCallback = std::move(callback);
}

template <typename ReturnType, typename... Arguments>
void Function<ReturnType, Arguments...>::clearBeforeCallback()
{
    m_beforeCallback = nullptr;
}

template <typename ReturnType, typename... Arguments>
void Function<ReturnType, Arguments...>::setAfterCallback(AfterCallback callback)
{
    m_afterCallback = std::move(callback);
}

template <typename ReturnType, typename... Arguments>
void Function<ReturnType, Arguments...>::clearAfterCallback()
{
    m_afterCallback = nullptr;
}

template <typename ReturnType, typename... Arguments>
typename Function<ReturnType, Arguments...>::BeforeCallback Function<ReturnType, Arguments...>::beforeCallback() const
{
    return m_beforeCallback;
}

template <typename ReturnType, typename... Arguments>
typename Function<ReturnType, Arguments...>::AfterCallback Function<ReturnType, Arguments...>::afterCallback() const
{
    return m_afterCallback;
}

template <typename ReturnType, typename... Arguments>
bool Function<ReturnType, Arguments...>::hasState() const
{
    return hasState(AbstractFunction::currentPos());
}

template <typename ReturnType, typename... Arguments>
bool Function<ReturnType, Arguments...>::hasState(const int pos) const
{
    return pos > -1 && AbstractFunction::maxPos() <= pos;
}

template <typename ReturnType, typename... Arguments>
AbstractState & Function<ReturnType, Arguments...>::state() const
{
    return state(AbstractFunction::currentPos());
}

template <typename ReturnType, typename... Arguments>
AbstractState & Function<ReturnType, Arguments...>::state(const int pos) const
{
    assert(AbstractFunction::maxPos() >= pos);
    assert(pos > -1);

    return m_states.at(pos);
}

template <typename ReturnType, typename... Arguments>
void Function<ReturnType, Arguments...>::resizeStates(int count)
{
    m_states.resize(static_cast<std::size_t>(count));
}

} // namespace glbinding
<commit_msg>Assert valid function pointer instead of silent failure (closes #262)<commit_after>
#pragma once

#include <utility>
#include <functional>
#include <cassert>

#include <glbinding/Value.h>
#include <glbinding/FunctionCall.h>
#include <glbinding/CallbackMask.h>
#include <glbinding/Boolean8.h>

namespace glbinding
{

template <typename ReturnType, typename... Arguments>
struct BasicCallHelper
{
    inline static ReturnType call(const glbinding::Function<ReturnType, Arguments...> * function, Arguments&&... arguments)
    {
        return reinterpret_cast<typename glbinding::Function<ReturnType, Arguments...>::Signature>(function->address())(std::forward<Arguments>(arguments)...);
    }
};

// Special case for booleans because of MSVC differing behavior

template <typename... Arguments>
struct BasicCallHelper<glbinding::Boolean8, Arguments...>
{
    inline static glbinding::Boolean8 call(const glbinding::Function<glbinding::Boolean8, Arguments...> * function, Arguments&&... arguments)
    {
        return reinterpret_cast<typename glbinding::Function<glbinding::Boolean8::underlying_type, Arguments...>::Signature>(function->address())(std::forward<Arguments>(arguments)...);
    }
};

template <typename ReturnType, typename... Arguments>
struct FunctionHelper
{
    inline static ReturnType call(const glbinding::Function<ReturnType, Arguments...> * function, Arguments&&... arguments)
    {
        glbinding::FunctionCall functionCall(function);

        if (function->isAnyEnabled(glbinding::CallbackMask::Parameters))
        {
            functionCall.parameters = glbinding::createValues(std::forward<Arguments>(arguments)...);
        }

        if (function->isEnabled(glbinding::CallbackMask::Before))
        {
            AbstractFunction::before(functionCall);

            if (function->beforeCallback())
            {
                function->beforeCallback()(std::forward<Arguments>(arguments)...);
            }
        }

        auto value = BasicCallHelper<ReturnType, Arguments ...>::call(function, std::forward<Arguments>(arguments)...);

        if (function->isAnyEnabled(glbinding::CallbackMask::ReturnValue))
        {
            functionCall.returnValue = glbinding::createValue(value);
        }

        if (function->isEnabled(glbinding::CallbackMask::After))
        {
            AbstractFunction::after(functionCall);

            if (function->afterCallback())
            {
                function->afterCallback()(value, std::forward<Arguments>(arguments)...);
            }
        }

        if (function->isEnabled(glbinding::CallbackMask::Logging))
        {
            AbstractFunction::log(std::move(functionCall));
        }

        return value;
    }
};

template <typename... Arguments>
struct FunctionHelper<void, Arguments...>
{
    inline static void call(const glbinding::Function<void, Arguments...> * function, Arguments&&... arguments)
    {
        glbinding::FunctionCall functionCall(function);

        if (function->isAnyEnabled(glbinding::CallbackMask::Parameters))
        {
            functionCall.parameters = glbinding::createValues(std::forward<Arguments>(arguments)...);
        }

        if (function->isEnabled(glbinding::CallbackMask::Before))
        {
            AbstractFunction::before(functionCall);

            if (function->beforeCallback())
            {
                function->beforeCallback()(std::forward<Arguments>(arguments)...);
            }
        }

        BasicCallHelper<void, Arguments ...>::call(function, std::forward<Arguments>(arguments)...);

        if (function->isEnabled(glbinding::CallbackMask::After))
        {
            AbstractFunction::after(functionCall);

            if (function->afterCallback())
            {
                function->afterCallback()(std::forward<Arguments>(arguments)...);
            }
        }

        if (function->isEnabled(glbinding::CallbackMask::Logging))
        {
            AbstractFunction::log(std::move(functionCall));
        }
    }
};

template <typename ReturnType, typename... Arguments>
Function<ReturnType, Arguments...>::Function(const char * _name)
: AbstractFunction{_name}
, m_beforeCallback{nullptr}
, m_afterCallback{nullptr}
{
}

template <typename ReturnType, typename... Arguments>
ReturnType Function<ReturnType, Arguments...>::operator()(Arguments&... arguments) const
{
    return call(arguments...);
}

template <typename ReturnType, typename... Arguments>
ReturnType Function<ReturnType, Arguments...>::call(Arguments&... arguments) const
{
    const auto myAddress = address();

    if (myAddress == nullptr)
    {
        if (isEnabled(CallbackMask::Unresolved))
        {
           AbstractFunction::unresolved(this);
        }
        else
        {
            // Trying to call a function without check if it is resolvable is considered a programming error.
            // You may try to call AbstractFunction::resolve first and check the address for validity (a pointer
            // unequal to nullptr is considered valid) or check the exposition of associated extensions.
            assert(false);
        }

        return ReturnType();
    }

    if (isAnyEnabled(CallbackMask::Before | CallbackMask::After | CallbackMask::Logging))
    {
        return FunctionHelper<ReturnType, Arguments...>::call(this, std::forward<Arguments>(arguments)...);
    }
    else
    {
        return BasicCallHelper<ReturnType, Arguments...>::call(this, std::forward<Arguments>(arguments)...);
    }
}

template <typename ReturnType, typename... Arguments>
ReturnType Function<ReturnType, Arguments...>::directCall(Arguments... arguments) const
{
    if (address() == nullptr)
    {
        return ReturnType();
    }

    return BasicCallHelper<ReturnType, Arguments...>::call(this, std::forward<Arguments>(arguments)...);
}

template <typename ReturnType, typename... Arguments>
void Function<ReturnType, Arguments...>::setBeforeCallback(BeforeCallback callback)
{
    m_beforeCallback = std::move(callback);
}

template <typename ReturnType, typename... Arguments>
void Function<ReturnType, Arguments...>::clearBeforeCallback()
{
    m_beforeCallback = nullptr;
}

template <typename ReturnType, typename... Arguments>
void Function<ReturnType, Arguments...>::setAfterCallback(AfterCallback callback)
{
    m_afterCallback = std::move(callback);
}

template <typename ReturnType, typename... Arguments>
void Function<ReturnType, Arguments...>::clearAfterCallback()
{
    m_afterCallback = nullptr;
}

template <typename ReturnType, typename... Arguments>
typename Function<ReturnType, Arguments...>::BeforeCallback Function<ReturnType, Arguments...>::beforeCallback() const
{
    return m_beforeCallback;
}

template <typename ReturnType, typename... Arguments>
typename Function<ReturnType, Arguments...>::AfterCallback Function<ReturnType, Arguments...>::afterCallback() const
{
    return m_afterCallback;
}

template <typename ReturnType, typename... Arguments>
bool Function<ReturnType, Arguments...>::hasState() const
{
    return hasState(AbstractFunction::currentPos());
}

template <typename ReturnType, typename... Arguments>
bool Function<ReturnType, Arguments...>::hasState(const int pos) const
{
    return pos > -1 && AbstractFunction::maxPos() <= pos;
}

template <typename ReturnType, typename... Arguments>
AbstractState & Function<ReturnType, Arguments...>::state() const
{
    return state(AbstractFunction::currentPos());
}

template <typename ReturnType, typename... Arguments>
AbstractState & Function<ReturnType, Arguments...>::state(const int pos) const
{
    assert(AbstractFunction::maxPos() >= pos);
    assert(pos > -1);

    return m_states.at(pos);
}

template <typename ReturnType, typename... Arguments>
void Function<ReturnType, Arguments...>::resizeStates(int count)
{
    m_states.resize(static_cast<std::size_t>(count));
}

} // namespace glbinding
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2010 Google Inc. All rights reserved.
 * Copyright (C) 2013 Samsung Electronics. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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 "config.h"
#include "modules/storage/InspectorDOMStorageAgent.h"

#include "bindings/core/v8/ExceptionState.h"
#include "core/InspectorFrontend.h"
#include "core/dom/DOMException.h"
#include "core/dom/Document.h"
#include "core/dom/ExceptionCode.h"
#include "core/frame/LocalDOMWindow.h"
#include "core/frame/LocalFrame.h"
#include "core/inspector/InspectorState.h"
#include "core/page/Page.h"
#include "modules/storage/Storage.h"
#include "modules/storage/StorageNamespace.h"
#include "modules/storage/StorageNamespaceController.h"
#include "platform/JSONValues.h"
#include "platform/weborigin/SecurityOrigin.h"

namespace blink {

#ifdef MINIBLINK_NOT_IMPLEMENTED

namespace DOMStorageAgentState {
static const char domStorageAgentEnabled[] = "domStorageAgentEnabled";
};

static bool hadException(ExceptionState& exceptionState, ErrorString* errorString)
{
    if (!exceptionState.hadException())
        return false;

    switch (exceptionState.code()) {
    case SecurityError:
        *errorString = "Security error";
        return true;
    default:
        *errorString = "Unknown DOM storage error";
        return true;
    }
}

InspectorDOMStorageAgent::InspectorDOMStorageAgent(Page* page)
    : InspectorBaseAgent<InspectorDOMStorageAgent, InspectorFrontend::DOMStorage>("DOMStorage")
    , m_page(page)
    , m_isEnabled(false)
{
}

InspectorDOMStorageAgent::~InspectorDOMStorageAgent()
{
}

DEFINE_TRACE(InspectorDOMStorageAgent)
{
    visitor->trace(m_page);
    InspectorBaseAgent::trace(visitor);
}

void InspectorDOMStorageAgent::restore()
{
    if (m_state->getBoolean(DOMStorageAgentState::domStorageAgentEnabled))
        enable(0);
}

void InspectorDOMStorageAgent::enable(ErrorString*)
{
    if (m_isEnabled)
        return;
    m_isEnabled = true;
    m_state->setBoolean(DOMStorageAgentState::domStorageAgentEnabled, true);
    if (StorageNamespaceController* controller = StorageNamespaceController::from(m_page))
        controller->setInspectorAgent(this);
}

void InspectorDOMStorageAgent::disable(ErrorString*)
{
    if (!m_isEnabled)
        return;
    m_isEnabled = false;
    m_state->setBoolean(DOMStorageAgentState::domStorageAgentEnabled, false);
    if (StorageNamespaceController* controller = StorageNamespaceController::from(m_page))
        controller->setInspectorAgent(nullptr);
}

void InspectorDOMStorageAgent::getDOMStorageItems(ErrorString* errorString, const RefPtr<JSONObject>& storageId, RefPtr<TypeBuilder::Array<TypeBuilder::Array<String>>>& items)
{
    LocalFrame* frame;
    StorageArea* storageArea = findStorageArea(errorString, storageId, frame);
    if (!storageArea)
        return;

    RefPtr<TypeBuilder::Array<TypeBuilder::Array<String>>> storageItems = TypeBuilder::Array<TypeBuilder::Array<String>>::create();

    TrackExceptionState exceptionState;
    for (unsigned i = 0; i < storageArea->length(exceptionState, frame); ++i) {
        String name(storageArea->key(i, exceptionState, frame));
        if (hadException(exceptionState, errorString))
            return;
        String value(storageArea->getItem(name, exceptionState, frame));
        if (hadException(exceptionState, errorString))
            return;
        RefPtr<TypeBuilder::Array<String>> entry = TypeBuilder::Array<String>::create();
        entry->addItem(name);
        entry->addItem(value);
        storageItems->addItem(entry);
    }
    items = storageItems.release();
}

static String toErrorString(ExceptionState& exceptionState)
{
    if (exceptionState.hadException())
        return DOMException::getErrorName(exceptionState.code());
    return "";
}

void InspectorDOMStorageAgent::setDOMStorageItem(ErrorString* errorString, const RefPtr<JSONObject>& storageId, const String& key, const String& value)
{
    LocalFrame* frame;
    StorageArea* storageArea = findStorageArea(0, storageId, frame);
    if (!storageArea) {
        *errorString = "Storage not found";
        return;
    }

    TrackExceptionState exceptionState;
    storageArea->setItem(key, value, exceptionState, frame);
    *errorString = toErrorString(exceptionState);
}

void InspectorDOMStorageAgent::removeDOMStorageItem(ErrorString* errorString, const RefPtr<JSONObject>& storageId, const String& key)
{
    LocalFrame* frame;
    StorageArea* storageArea = findStorageArea(0, storageId, frame);
    if (!storageArea) {
        *errorString = "Storage not found";
        return;
    }

    TrackExceptionState exceptionState;
    storageArea->removeItem(key, exceptionState, frame);
    *errorString = toErrorString(exceptionState);
}

PassRefPtr<TypeBuilder::DOMStorage::StorageId> InspectorDOMStorageAgent::storageId(SecurityOrigin* securityOrigin, bool isLocalStorage)
{
    return TypeBuilder::DOMStorage::StorageId::create()
        .setSecurityOrigin(securityOrigin->toRawString())
        .setIsLocalStorage(isLocalStorage).release();
}

void InspectorDOMStorageAgent::didDispatchDOMStorageEvent(const String& key, const String& oldValue, const String& newValue, StorageType storageType, SecurityOrigin* securityOrigin)
{
    if (!frontend())
        return;

    RefPtr<TypeBuilder::DOMStorage::StorageId> id = storageId(securityOrigin, storageType == LocalStorage);

    if (key.isNull())
        frontend()->domStorageItemsCleared(id);
    else if (newValue.isNull())
        frontend()->domStorageItemRemoved(id, key);
    else if (oldValue.isNull())
        frontend()->domStorageItemAdded(id, key, newValue);
    else
        frontend()->domStorageItemUpdated(id, key, oldValue, newValue);
}

static LocalFrame* findFrameWithSecurityOrigin(LocalFrame* inspectedFrame, const String& originRawString)
{
    for (Frame* frame = inspectedFrame; frame; frame = frame->tree().traverseNext(inspectedFrame)) {
        if (!frame->isLocalFrame())
            continue;
        RefPtr<SecurityOrigin> documentOrigin = toLocalFrame(frame)->document()->securityOrigin();
        if (documentOrigin->toRawString() == originRawString)
            return toLocalFrame(frame);
    }
    return nullptr;
}

StorageArea* InspectorDOMStorageAgent::findStorageArea(ErrorString* errorString, const RefPtr<JSONObject>& storageId, LocalFrame*& targetFrame)
{
    String securityOrigin;
    bool isLocalStorage = false;
    bool success = storageId->getString("securityOrigin", &securityOrigin);
    if (success)
        success = storageId->getBoolean("isLocalStorage", &isLocalStorage);
    if (!success) {
        if (errorString)
            *errorString = "Invalid storageId format";
        return nullptr;
    }

    if (!m_page->mainFrame()->isLocalFrame())
        return nullptr;

    LocalFrame* frame = findFrameWithSecurityOrigin(m_page->deprecatedLocalMainFrame(), securityOrigin);
    if (!frame) {
        if (errorString)
            *errorString = "LocalFrame not found for the given security origin";
        return nullptr;
    }
    targetFrame = frame;

    if (isLocalStorage)
        return StorageNamespace::localStorageArea(frame->document()->securityOrigin());
    return StorageNamespaceController::from(m_page)->sessionStorage()->storageArea(frame->document()->securityOrigin());
}

#else

void InspectorDOMStorageAgent::didDispatchDOMStorageEvent(const String& key, const String& oldValue, const String& newValue, StorageType storageType, SecurityOrigin* securityOrigin)
{
    ;
}

DEFINE_TRACE(InspectorDOMStorageAgent)
{
//     visitor->trace(m_page);
//     InspectorBaseAgent::trace(visitor);
    DebugBreak();
}

#endif // MINIBLINK_NOT_IMPLEMENTED

} // namespace blink
<commit_msg>* 打开devtools的storage<commit_after>/*
 * Copyright (C) 2010 Google Inc. All rights reserved.
 * Copyright (C) 2013 Samsung Electronics. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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 "config.h"
#include "modules/storage/InspectorDOMStorageAgent.h"

#include "bindings/core/v8/ExceptionState.h"
#include "core/InspectorFrontend.h"
#include "core/dom/DOMException.h"
#include "core/dom/Document.h"
#include "core/dom/ExceptionCode.h"
#include "core/frame/LocalDOMWindow.h"
#include "core/frame/LocalFrame.h"
#include "core/inspector/InspectorState.h"
#include "core/page/Page.h"
#include "modules/storage/Storage.h"
#include "modules/storage/StorageNamespace.h"
#include "modules/storage/StorageNamespaceController.h"
#include "platform/JSONValues.h"
#include "platform/weborigin/SecurityOrigin.h"

namespace blink {

#if 1 // def MINIBLINK_NOT_IMPLEMENTED

namespace DOMStorageAgentState {
static const char domStorageAgentEnabled[] = "domStorageAgentEnabled";
};

static bool hadException(ExceptionState& exceptionState, ErrorString* errorString)
{
    if (!exceptionState.hadException())
        return false;

    switch (exceptionState.code()) {
    case SecurityError:
        *errorString = "Security error";
        return true;
    default:
        *errorString = "Unknown DOM storage error";
        return true;
    }
}

InspectorDOMStorageAgent::InspectorDOMStorageAgent(Page* page)
    : InspectorBaseAgent<InspectorDOMStorageAgent, InspectorFrontend::DOMStorage>("DOMStorage")
    , m_page(page)
    , m_isEnabled(false)
{
}

InspectorDOMStorageAgent::~InspectorDOMStorageAgent()
{
}

DEFINE_TRACE(InspectorDOMStorageAgent)
{
    visitor->trace(m_page);
    InspectorBaseAgent::trace(visitor);
}

void InspectorDOMStorageAgent::restore()
{
    if (m_state->getBoolean(DOMStorageAgentState::domStorageAgentEnabled))
        enable(0);
}

void InspectorDOMStorageAgent::enable(ErrorString*)
{
    if (m_isEnabled)
        return;
    m_isEnabled = true;
    m_state->setBoolean(DOMStorageAgentState::domStorageAgentEnabled, true);
    if (StorageNamespaceController* controller = StorageNamespaceController::from(m_page))
        controller->setInspectorAgent(this);
}

void InspectorDOMStorageAgent::disable(ErrorString*)
{
    if (!m_isEnabled)
        return;
    m_isEnabled = false;
    m_state->setBoolean(DOMStorageAgentState::domStorageAgentEnabled, false);
    if (StorageNamespaceController* controller = StorageNamespaceController::from(m_page))
        controller->setInspectorAgent(nullptr);
}

void InspectorDOMStorageAgent::getDOMStorageItems(ErrorString* errorString, const RefPtr<JSONObject>& storageId, RefPtr<TypeBuilder::Array<TypeBuilder::Array<String>>>& items)
{
    LocalFrame* frame;
    StorageArea* storageArea = findStorageArea(errorString, storageId, frame);
    if (!storageArea)
        return;

    RefPtr<TypeBuilder::Array<TypeBuilder::Array<String>>> storageItems = TypeBuilder::Array<TypeBuilder::Array<String>>::create();

    TrackExceptionState exceptionState;
    for (unsigned i = 0; i < storageArea->length(exceptionState, frame); ++i) {
        String name(storageArea->key(i, exceptionState, frame));
        if (hadException(exceptionState, errorString))
            return;
        String value(storageArea->getItem(name, exceptionState, frame));
        if (hadException(exceptionState, errorString))
            return;
        RefPtr<TypeBuilder::Array<String>> entry = TypeBuilder::Array<String>::create();
        entry->addItem(name);
        entry->addItem(value);
        storageItems->addItem(entry);
    }
    items = storageItems.release();
}

static String toErrorString(ExceptionState& exceptionState)
{
    if (exceptionState.hadException())
        return DOMException::getErrorName(exceptionState.code());
    return "";
}

void InspectorDOMStorageAgent::setDOMStorageItem(ErrorString* errorString, const RefPtr<JSONObject>& storageId, const String& key, const String& value)
{
    LocalFrame* frame;
    StorageArea* storageArea = findStorageArea(0, storageId, frame);
    if (!storageArea) {
        *errorString = "Storage not found";
        return;
    }

    TrackExceptionState exceptionState;
    storageArea->setItem(key, value, exceptionState, frame);
    *errorString = toErrorString(exceptionState);
}

void InspectorDOMStorageAgent::removeDOMStorageItem(ErrorString* errorString, const RefPtr<JSONObject>& storageId, const String& key)
{
    LocalFrame* frame;
    StorageArea* storageArea = findStorageArea(0, storageId, frame);
    if (!storageArea) {
        *errorString = "Storage not found";
        return;
    }

    TrackExceptionState exceptionState;
    storageArea->removeItem(key, exceptionState, frame);
    *errorString = toErrorString(exceptionState);
}

PassRefPtr<TypeBuilder::DOMStorage::StorageId> InspectorDOMStorageAgent::storageId(SecurityOrigin* securityOrigin, bool isLocalStorage)
{
    return TypeBuilder::DOMStorage::StorageId::create()
        .setSecurityOrigin(securityOrigin->toRawString())
        .setIsLocalStorage(isLocalStorage).release();
}

void InspectorDOMStorageAgent::didDispatchDOMStorageEvent(const String& key, const String& oldValue, const String& newValue, StorageType storageType, SecurityOrigin* securityOrigin)
{
    if (!frontend())
        return;

    RefPtr<TypeBuilder::DOMStorage::StorageId> id = storageId(securityOrigin, storageType == LocalStorage);

    if (key.isNull())
        frontend()->domStorageItemsCleared(id);
    else if (newValue.isNull())
        frontend()->domStorageItemRemoved(id, key);
    else if (oldValue.isNull())
        frontend()->domStorageItemAdded(id, key, newValue);
    else
        frontend()->domStorageItemUpdated(id, key, oldValue, newValue);
}

static LocalFrame* findFrameWithSecurityOrigin(LocalFrame* inspectedFrame, const String& originRawString)
{
    for (Frame* frame = inspectedFrame; frame; frame = frame->tree().traverseNext(inspectedFrame)) {
        if (!frame->isLocalFrame())
            continue;
        RefPtr<SecurityOrigin> documentOrigin = toLocalFrame(frame)->document()->securityOrigin();
        if (documentOrigin->toRawString() == originRawString)
            return toLocalFrame(frame);
    }
    return nullptr;
}

StorageArea* InspectorDOMStorageAgent::findStorageArea(ErrorString* errorString, const RefPtr<JSONObject>& storageId, LocalFrame*& targetFrame)
{
    String securityOrigin;
    bool isLocalStorage = false;
    bool success = storageId->getString("securityOrigin", &securityOrigin);
    if (success)
        success = storageId->getBoolean("isLocalStorage", &isLocalStorage);
    if (!success) {
        if (errorString)
            *errorString = "Invalid storageId format";
        return nullptr;
    }

    if (!m_page->mainFrame()->isLocalFrame())
        return nullptr;

    LocalFrame* frame = findFrameWithSecurityOrigin(m_page->deprecatedLocalMainFrame(), securityOrigin);
    if (!frame) {
        if (errorString)
            *errorString = "LocalFrame not found for the given security origin";
        return nullptr;
    }
    targetFrame = frame;

    if (isLocalStorage)
        return StorageNamespace::localStorageArea(frame->document()->securityOrigin());
    return StorageNamespaceController::from(m_page)->sessionStorage()->storageArea(frame->document()->securityOrigin());
}

#else

void InspectorDOMStorageAgent::didDispatchDOMStorageEvent(const String& key, const String& oldValue, const String& newValue, StorageType storageType, SecurityOrigin* securityOrigin)
{
    ;
}

DEFINE_TRACE(InspectorDOMStorageAgent)
{
//     visitor->trace(m_page);
//     InspectorBaseAgent::trace(visitor);
    DebugBreak();
}

#endif // MINIBLINK_NOT_IMPLEMENTED

} // namespace blink
<|endoftext|>


<commit_before>// Copyright 2014 BVLC and contributors.

#include <vector>

#include "cuda_runtime.h"
#include "gtest/gtest.h"
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/filler.hpp"
#include "caffe/vision_layers.hpp"
#include "caffe/test/test_gradient_check_util.hpp"

#include "caffe/test/test_caffe_main.hpp"

namespace caffe {

extern cudaDeviceProp CAFFE_TEST_CUDA_PROP;

template <typename Dtype>
class ArgMaxLayerTest : public ::testing::Test {
 protected:
  ArgMaxLayerTest()
      : blob_bottom_(new Blob<Dtype>(20, 10, 1, 1)),
        blob_top_(new Blob<Dtype>()) {
    Caffe::set_random_seed(this->seed_);
    // fill the values
    FillerParameter filler_param;
    GaussianFiller<Dtype> filler(filler_param);
    filler.Fill(this->blob_bottom_);
    blob_bottom_vec_.push_back(blob_bottom_);
    blob_top_vec_.push_back(blob_top_);
  }
  virtual ~ArgMaxLayerTest() { delete blob_bottom_; delete blob_top_; }
  Blob<Dtype>* const blob_bottom_;
  Blob<Dtype>* const blob_top_;
  vector<Blob<Dtype>*> blob_bottom_vec_;
  vector<Blob<Dtype>*> blob_top_vec_;
};

typedef ::testing::Types<float, double> Dtypes;
TYPED_TEST_CASE(ArgMaxLayerTest, Dtypes);

TYPED_TEST(ArgMaxLayerTest, TestSetup) {
  LayerParameter layer_param;
  ArgMaxLayer<TypeParam> layer(layer_param);
  layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));
  EXPECT_EQ(this->blob_top_->num(), this->blob_bottom_->num());
  EXPECT_EQ(this->blob_top_->channels(), 1);
}

TYPED_TEST(ArgMaxLayerTest, TestSetupMaxVal) {
  LayerParameter layer_param;
  ArgMaxParameter* argmax_param = layer_param.mutable_argmax_param();
  argmax_param->set_out_max_val(true);
  ArgMaxLayer<TypeParam> layer(layer_param);
  layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));
  EXPECT_EQ(this->blob_top_->num(), this->blob_bottom_->num());
  EXPECT_EQ(this->blob_top_->channels(), 2);
}

TYPED_TEST(ArgMaxLayerTest, TestCPU) {
  LayerParameter layer_param;
  Caffe::set_mode(Caffe::CPU);
  ArgMaxLayer<TypeParam> layer(layer_param);
  layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));
  layer.Forward(this->blob_bottom_vec_, &(this->blob_top_vec_));
  // Now, check values
  const TypeParam* bottom_data = this->blob_bottom_->cpu_data();
  const TypeParam* top_data = this->blob_top_->cpu_data();
  int max_ind;
  TypeParam max_val;
  int num = this->blob_bottom_->num();
  int dim = this->blob_bottom_->count() / num;
  for (int i = 0; i < num; ++i) {
    EXPECT_GE(top_data[i], 0);
    EXPECT_LE(top_data[i], dim);
    max_ind = top_data[i];
    max_val = bottom_data[i * dim + max_ind];
    for (int j = 0; j < dim; ++j) {
      EXPECT_LE(bottom_data[i * dim + j], max_val);
    }
  }
}

TYPED_TEST(ArgMaxLayerTest, TestCPUMaxVal) {
  LayerParameter layer_param;
  Caffe::set_mode(Caffe::CPU);
  ArgMaxParameter* argmax_param = layer_param.mutable_argmax_param();
  argmax_param->set_out_max_val(true);
  ArgMaxLayer<TypeParam> layer(layer_param);
  layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));
  layer.Forward(this->blob_bottom_vec_, &(this->blob_top_vec_));
  // Now, check values
  const TypeParam* bottom_data = this->blob_bottom_->cpu_data();
  const TypeParam* top_data = this->blob_top_->cpu_data();
  int max_ind;
  TypeParam max_val;
  int num = this->blob_bottom_->num();
  int dim = this->blob_bottom_->count() / num;
  for (int i = 0; i < num; ++i) {
    EXPECT_GE(top_data[i], 0);
    EXPECT_LE(top_data[i], dim);
    max_ind = top_data[i * 2];
    max_val = top_data[i * 2 + 1];
    EXPECT_EQ(bottom_data[i * dim + max_ind], max_val);
    for (int j = 0; j < dim; ++j) {
      EXPECT_LE(bottom_data[i * dim + j], max_val);
    }
  }
}

}  // namespace caffe
<commit_msg>Revert "setting canonical random seed"<commit_after>// Copyright 2014 BVLC and contributors.

#include <vector>

#include "cuda_runtime.h"
#include "gtest/gtest.h"
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/filler.hpp"
#include "caffe/vision_layers.hpp"
#include "caffe/test/test_gradient_check_util.hpp"

#include "caffe/test/test_caffe_main.hpp"

namespace caffe {

extern cudaDeviceProp CAFFE_TEST_CUDA_PROP;

template <typename Dtype>
class ArgMaxLayerTest : public ::testing::Test {
 protected:
  ArgMaxLayerTest()
      : blob_bottom_(new Blob<Dtype>(20, 10, 1, 1)),
        blob_top_(new Blob<Dtype>()) {
    Caffe::set_random_seed(1701);
    // fill the values
    FillerParameter filler_param;
    GaussianFiller<Dtype> filler(filler_param);
    filler.Fill(this->blob_bottom_);
    blob_bottom_vec_.push_back(blob_bottom_);
    blob_top_vec_.push_back(blob_top_);
  }
  virtual ~ArgMaxLayerTest() { delete blob_bottom_; delete blob_top_; }
  Blob<Dtype>* const blob_bottom_;
  Blob<Dtype>* const blob_top_;
  vector<Blob<Dtype>*> blob_bottom_vec_;
  vector<Blob<Dtype>*> blob_top_vec_;
};

typedef ::testing::Types<float, double> Dtypes;
TYPED_TEST_CASE(ArgMaxLayerTest, Dtypes);

TYPED_TEST(ArgMaxLayerTest, TestSetup) {
  LayerParameter layer_param;
  ArgMaxLayer<TypeParam> layer(layer_param);
  layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));
  EXPECT_EQ(this->blob_top_->num(), this->blob_bottom_->num());
  EXPECT_EQ(this->blob_top_->channels(), 1);
}

TYPED_TEST(ArgMaxLayerTest, TestSetupMaxVal) {
  LayerParameter layer_param;
  ArgMaxParameter* argmax_param = layer_param.mutable_argmax_param();
  argmax_param->set_out_max_val(true);
  ArgMaxLayer<TypeParam> layer(layer_param);
  layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));
  EXPECT_EQ(this->blob_top_->num(), this->blob_bottom_->num());
  EXPECT_EQ(this->blob_top_->channels(), 2);
}

TYPED_TEST(ArgMaxLayerTest, TestCPU) {
  LayerParameter layer_param;
  Caffe::set_mode(Caffe::CPU);
  ArgMaxLayer<TypeParam> layer(layer_param);
  layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));
  layer.Forward(this->blob_bottom_vec_, &(this->blob_top_vec_));
  // Now, check values
  const TypeParam* bottom_data = this->blob_bottom_->cpu_data();
  const TypeParam* top_data = this->blob_top_->cpu_data();
  int max_ind;
  TypeParam max_val;
  int num = this->blob_bottom_->num();
  int dim = this->blob_bottom_->count() / num;
  for (int i = 0; i < num; ++i) {
    EXPECT_GE(top_data[i], 0);
    EXPECT_LE(top_data[i], dim);
    max_ind = top_data[i];
    max_val = bottom_data[i * dim + max_ind];
    for (int j = 0; j < dim; ++j) {
      EXPECT_LE(bottom_data[i * dim + j], max_val);
    }
  }
}

TYPED_TEST(ArgMaxLayerTest, TestCPUMaxVal) {
  LayerParameter layer_param;
  Caffe::set_mode(Caffe::CPU);
  ArgMaxParameter* argmax_param = layer_param.mutable_argmax_param();
  argmax_param->set_out_max_val(true);
  ArgMaxLayer<TypeParam> layer(layer_param);
  layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));
  layer.Forward(this->blob_bottom_vec_, &(this->blob_top_vec_));
  // Now, check values
  const TypeParam* bottom_data = this->blob_bottom_->cpu_data();
  const TypeParam* top_data = this->blob_top_->cpu_data();
  int max_ind;
  TypeParam max_val;
  int num = this->blob_bottom_->num();
  int dim = this->blob_bottom_->count() / num;
  for (int i = 0; i < num; ++i) {
    EXPECT_GE(top_data[i], 0);
    EXPECT_LE(top_data[i], dim);
    max_ind = top_data[i * 2];
    max_val = top_data[i * 2 + 1];
    EXPECT_EQ(bottom_data[i * dim + max_ind], max_val);
    for (int j = 0; j < dim; ++j) {
      EXPECT_LE(bottom_data[i * dim + j], max_val);
    }
  }
}

}  // namespace caffe
<|endoftext|>


<commit_before>#include "mbed.h"
#include "test_env.h"

#if !DEVICE_CAN
#error [NOT_SUPPORTED] CAN not supported
#endif

#if defined(TARGET_LPC1549)
#define CAN_RD D9
#define CAN_TD D8
#elif defined(TARGET_LPC1768) || defined(TARGET_LPC4088)
#define CAN_RD p9
#define CAN_TD p10
#elif defined(TARGET_B96B_F446VE)
#define CAN_RD PD_0
#define CAN_TD PD_1
#elif defined(TARGET_VK_RZ_A1H)
#define CAN_RD P5_9
#define CAN_TD P5_10
#elif defined(TARGET_NUCLEO_F042K6) || \
      defined(TARGET_NUCLEO_F072RB) || \
      defined(TARGET_NUCLEO_F091RC) || \
      defined(TARGET_NUCLEO_F302R8) || \
      defined(TARGET_NUCLEO_F303RE) || \
      defined(TARGET_NUCLEO_F303K8) || \
      defined(TARGET_NUCLEO_F334R8) || \
      defined(TARGET_NUCLEO_F412ZG) || \
      defined(TARGET_DISCO_F429ZI)  || \
      defined(TARGET_NUCLEO_F446RE) || \
      defined(TARGET_NUCLEO_F746ZG) || \
      defined(TARGET_NUCLEO_L432KC) || \
      defined(TARGET_DISCO_L476VG)  || \
      defined(TARGET_NUCLEO_L476RG)
#define CAN_RD PA_11
#define CAN_TD PA_12
#elif defined(TARGET_NUCLEO_F103RB) || \
      defined(TARGET_NUCLEO_F207ZG) || \
      defined(TARGET_DISCO_F303VC)  || \
      defined(TARGET_NUCLEO_F303ZE) || \
      defined(TARGET_NUCLEO_F412ZG) || \
      defined(TARGET_NUCLEO_F429ZI) || \
      defined(TARGET_NUCLEO_F439ZI) || \
      defined(TARGET_NUCLEO_F446ZE) || \
      defined(TARGET_DISCO_F469NI)  || \
      defined(TARGET_DISCO_F746NG)  || \
      defined(TARGET_NUCLEO_F756ZG) || \
      defined(TARGET_NUCLEO_F767ZI) || \
      defined(TARGET_DISCO_F769NI)  || \
      defined(TARGET_NUCLEO_L486RG)
#define CAN_RD PB_8
#define CAN_TD PB_9
#endif

int result = true;

void Check_CAN_Frequency(int CanFrequency)
{
    printf("Init CAN at %d Hz\n", CanFrequency);

    CAN can_object(CAN_RD, CAN_TD, CanFrequency);

#if !defined(TARGET_VK_RZ_A1H)
    can_object.mode(CAN::Reset);
#endif

    if (!can_object.mode(CAN::LocalTest)) {
        printf("CAN MODE_TEST_LOCAL failed\n");
        result = false;
    }
}

int main()
{
    MBED_HOSTTEST_TIMEOUT(20);
    MBED_HOSTTEST_SELECT(dev_null);
    MBED_HOSTTEST_DESCRIPTION(CAN API at different frequency);
    MBED_HOSTTEST_START("MBED_A30");

    const int frequency_table[] = {10000, 50000, 100000, 500000, 1000000};
    for (uint32_t i = 0; i < sizeof(frequency_table)/sizeof(int); i++) {
        Check_CAN_Frequency(frequency_table[i]);
    }

    MBED_HOSTTEST_RESULT(result);
}
<commit_msg>Add header to the test main.cpp<commit_after>/* mbed Microcontroller Library
 * Copyright (c) 2017 ARM Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "mbed.h"
#include "test_env.h"

#if !DEVICE_CAN
#error [NOT_SUPPORTED] CAN not supported
#endif

#if defined(TARGET_LPC1549)
#define CAN_RD D9
#define CAN_TD D8
#elif defined(TARGET_LPC1768) || defined(TARGET_LPC4088)
#define CAN_RD p9
#define CAN_TD p10
#elif defined(TARGET_B96B_F446VE)
#define CAN_RD PD_0
#define CAN_TD PD_1
#elif defined(TARGET_VK_RZ_A1H)
#define CAN_RD P5_9
#define CAN_TD P5_10
#elif defined(TARGET_NUCLEO_F042K6) || \
      defined(TARGET_NUCLEO_F072RB) || \
      defined(TARGET_NUCLEO_F091RC) || \
      defined(TARGET_NUCLEO_F302R8) || \
      defined(TARGET_NUCLEO_F303RE) || \
      defined(TARGET_NUCLEO_F303K8) || \
      defined(TARGET_NUCLEO_F334R8) || \
      defined(TARGET_NUCLEO_F412ZG) || \
      defined(TARGET_DISCO_F429ZI)  || \
      defined(TARGET_NUCLEO_F446RE) || \
      defined(TARGET_NUCLEO_F746ZG) || \
      defined(TARGET_NUCLEO_L432KC) || \
      defined(TARGET_DISCO_L476VG)  || \
      defined(TARGET_NUCLEO_L476RG)
#define CAN_RD PA_11
#define CAN_TD PA_12
#elif defined(TARGET_NUCLEO_F103RB) || \
      defined(TARGET_NUCLEO_F207ZG) || \
      defined(TARGET_DISCO_F303VC)  || \
      defined(TARGET_NUCLEO_F303ZE) || \
      defined(TARGET_NUCLEO_F412ZG) || \
      defined(TARGET_NUCLEO_F429ZI) || \
      defined(TARGET_NUCLEO_F439ZI) || \
      defined(TARGET_NUCLEO_F446ZE) || \
      defined(TARGET_DISCO_F469NI)  || \
      defined(TARGET_DISCO_F746NG)  || \
      defined(TARGET_NUCLEO_F756ZG) || \
      defined(TARGET_NUCLEO_F767ZI) || \
      defined(TARGET_DISCO_F769NI)  || \
      defined(TARGET_NUCLEO_L486RG)
#define CAN_RD PB_8
#define CAN_TD PB_9
#endif

int result = true;

void Check_CAN_Frequency(int CanFrequency)
{
    printf("Init CAN at %d Hz\n", CanFrequency);

    CAN can_object(CAN_RD, CAN_TD, CanFrequency);

#if !defined(TARGET_VK_RZ_A1H)
    can_object.mode(CAN::Reset);
#endif

    if (!can_object.mode(CAN::LocalTest)) {
        printf("CAN MODE_TEST_LOCAL failed\n");
        result = false;
    }
}

int main()
{
    MBED_HOSTTEST_TIMEOUT(20);
    MBED_HOSTTEST_SELECT(dev_null);
    MBED_HOSTTEST_DESCRIPTION(CAN API at different frequency);
    MBED_HOSTTEST_START("MBED_A30");

    const int frequency_table[] = {10000, 50000, 100000, 500000, 1000000};
    for (uint32_t i = 0; i < sizeof(frequency_table)/sizeof(int); i++) {
        Check_CAN_Frequency(frequency_table[i]);
    }

    MBED_HOSTTEST_RESULT(result);
}
<|endoftext|>