<commit_before>/*
 * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
 * All rights reserved.
 *
 * This library/application is free software; you can redistribute and/or modify it under the terms of
 * the license that is included with this library/application in the file license.txt.
 */

//--- interface include --------------------------------------------------------
#include "LDAPDAICachePolicyModule.h"

//--- standard modules used ----------------------------------------------------
#include "Dbg.h"
#include "System.h"
#include "SysLog.h"
#include "DataAccess.h"
#include "Action.h"

//--- c-modules used -----------------------------------------------------------

//---- LDAPDAICachePolicyModule -----------------------------------------------------------
RegisterModule(LDAPDAICachePolicyModule);

LDAPDAICachePolicyModule *LDAPDAICachePolicyModule::fgLDAPDAICachePolicyModule = 0;

LDAPDAICachePolicyModule::LDAPDAICachePolicyModule(const char *name) : WDModule(name)
{
	StartTrace(LDAPDAICachePolicyModule.LDAPDAICachePolicyModule);
}

LDAPDAICachePolicyModule::~LDAPDAICachePolicyModule()
{
	StartTrace(LDAPDAICachePolicyModule.~LDAPDAICachePolicyModule);
}

bool LDAPDAICachePolicyModule::Init(const ROAnything config)
{
	StartTrace(LDAPDAICachePolicyModule.Init);
	ROAnything LDAPDAICachePolicyModuleConfig;
	config.LookupPath(LDAPDAICachePolicyModuleConfig, "LDAPDAICachePolicyModule");
	TraceAny(LDAPDAICachePolicyModuleConfig, "LDAPDAICachePolicyModule:");

	ROAnything dataAccesses(config["LDAPDAICachePolicyModule"]["LDAPDAIDataAccess"]);
	ROAnything dataAccessActions(config["LDAPDAICachePolicyModule"]["LDAPDAIDataAccessAction"]);
	if ( dataAccesses.GetSize() == 0 && dataAccessActions.GetSize() == 0 ) {
		SysLog::WriteToStderr("\tLDAPDAICachePolicyModule::Init can't read needed configuration data.\n");
		return false;
	}
	if ( InitialLoad(dataAccesses, LDAPDAICachePolicyModule::dataaccess, config.DeepClone()) 	== false ||
		 InitialLoad(dataAccessActions, LDAPDAICachePolicyModule::action, config.DeepClone()) 	== false ) {
		return false;
	}
	String failedDataAccesses;
	CheckContractIsFulfilled(failedDataAccesses, dataAccesses);
	CheckContractIsFulfilled(failedDataAccesses, dataAccessActions);
	if (failedDataAccesses.Length() != 0 ) {
		SysLog::WriteToStderr(String("\tLDAPDAICachePolicyModule::LDAP Query: ") << failedDataAccesses <<
							  String(" returned no data.\n"));
		return false;
	}
	SysLog::WriteToStderr("\tLDAPDAICachePolicyModule done\n");
	return true;
}

bool LDAPDAICachePolicyModule::InitialLoad(const ROAnything dataAccesses, LDAPDAICachePolicyModule::EDataAccessType daType, const Anything &config )
{
	StartTrace(LDAPDAICachePolicyModule.InitialLoad);
	CacheHandler *cache = CacheHandler::Get();
	bool ret(true);
	if (cache) {
		LDAPDAIDataAcccessLoader ldl(config);
		LDAPDAIActionLoader lal(config);
		Anything tmp;
		for (int i = 0; i < dataAccesses.GetSize(); i++) {
			String toDo(dataAccesses[i].AsString());
			if ( daType == dataaccess ) {
				Trace("Loading ldl with: " << toDo);
				cache->Load("LdapDAIGetter", toDo, &ldl);
			}
			if ( daType == action ) {
				Trace("Loading lal with: " << toDo);
				cache->Load("LdapDAIGetter", toDo, &lal);
			}
		}
	} else {
		SysLog::WriteToStderr("\tLDAPDAICachePolicyModule::InitialLoad: NoCacheHandlerFound\n");
		ret = false;
	}
	return ret;
}

bool LDAPDAICachePolicyModule::CheckContractIsFulfilled(String &failedDataAccesses, const ROAnything dataAccesses)
{
	StartTrace(LDAPDAICachePolicyModule.CheckContractIsFulfilled);
	bool ret(true);
	for (int i = 0; i < dataAccesses.GetSize(); i++) {
		String daToDo(dataAccesses[i].AsString());
		Trace("Checking with: " << daToDo);

		ROAnything result(LDAPDAICacheGetter::GetAll(daToDo));
		// broke contract: specified LDAP-query must return data
		if (result.IsNull()) {
			failedDataAccesses.Append(daToDo);
			failedDataAccesses.Append(" ");
			ret = false;
		}
	}
	return ret;
}

bool LDAPDAICachePolicyModule::Finis()
{
	StartTrace(LDAPDAICachePolicyModule.Finis);

	SysLog::WriteToStderr("\tTerminating LDAPDAICachePolicyModule done\n");
	return true;
}

//--- LDAPDAIDataAcccessLoader -----------------------------------------------
LDAPDAIDataAcccessLoader::LDAPDAIDataAcccessLoader() { }
LDAPDAIDataAcccessLoader::LDAPDAIDataAcccessLoader(Anything config) : fConfig(config) { }
LDAPDAIDataAcccessLoader::~LDAPDAIDataAcccessLoader() { }
Anything LDAPDAIDataAcccessLoader::Load(const char *ldapDa)
{
	StartTrace(LDAPDAIDataAcccessLoader.Load);
	Anything theResult(Storage::Global());
	Context ctx;
	Context::PushPopEntry aEntry(ctx, "LdapLoader", fConfig);

	if (ldapDa != "") {
		DataAccess da(ldapDa);
		bool retCode = da.StdExec(ctx);
		Anything tmpStore(ctx.GetTmpStore());

		if (retCode && tmpStore["LDAPResult"][ldapDa]["NumberOfEntries"].AsLong() > 0) {
			theResult = tmpStore["LDAPResult"][ldapDa]["Entries"];
		} else {
			String msg;
			msg << "\tLDAPDAICachePolicyModule::Load Unable to exec LDAP query for: " << ldapDa << "\n";
			SysLog::WriteToStderr(msg);
		}
	}

	TraceAny(theResult, "LDAP-Result for " << ldapDa << " cache.");
	return theResult;
}

//--- LDAPDAIDataAcccessLoader -----------------------------------------------
LDAPDAIActionLoader::LDAPDAIActionLoader() { }
LDAPDAIActionLoader::LDAPDAIActionLoader(Anything config) : fConfig(config) { }
LDAPDAIActionLoader::~LDAPDAIActionLoader() { }

Anything LDAPDAIActionLoader::Load(const char *ldapDaAction)
{
	StartTrace(LDAPDAIActionLoader.Load);
	Anything theResult(Storage::Global());
	Context ctx;
	Context::PushPopEntry aEntry(ctx, "LdapLoader", fConfig);
	if (ldapDaAction != "") {
		Anything tmpStore = ctx.GetTmpStore();
		String transition;
		Anything config;
		// Default constructs an action config containing the name of the LDAPDAIDataAccess to execute
		// This may be overridden by the action implementing the DataAccess(es).
		config[ldapDaAction]["DataAccess"] = ldapDaAction;
		bool retCode = Action::ExecAction(transition, ctx, config);
		Trace("Result of DataAccess " << ldapDaAction << " is: " << retCode);
		// Called Action *must* return results in slot ["LDAPResult"][ldapDaAction]
		TraceAny(tmpStore["LDAPResult"][ldapDaAction], "Returned: " << ldapDaAction);
		if (retCode && tmpStore["LDAPResult"][ldapDaAction]["NumberOfEntries"].AsLong() > 0) {
			theResult = tmpStore["LDAPResult"][ldapDaAction]["Entries"];
			TraceAny(theResult, "Result of Load()");
		} else {
			String msg;
			msg << "\tLDAPDAICachePolicyModule::Load Unable to exec LDAP query for: " << ldapDaAction << "\n";
			SysLog::WriteToStderr(msg);
		}
	}
	return (theResult);
}

//---- LDAPDAICacheGetter ---------------------------------------------------------
LDAPDAICacheGetter::LDAPDAICacheGetter(const String &dataAccess)
	: fDA(dataAccess)
{
	StartTrace("LDAPDAICacheGetter.LDAPDAICacheGetter");
}

LDAPDAICacheGetter::~LDAPDAICacheGetter()
{
	StartTrace(LDAPDAICacheGetter.~LDAPDAICacheGetter);
}

bool LDAPDAICacheGetter::DoLookup(const char *key, ROAnything &result, char delim, char indexdelim) const
{
	StartTrace(LDAPDAICacheGetter.DoLookup);

	return Get(result, fDA, key, delim, indexdelim);
}

ROAnything LDAPDAICacheGetter::GetAll(const String &dataAccess)
{
	StartTrace1(LDAPDAICacheGetter.GetAll, dataAccess);

	CacheHandler *cache = CacheHandler::Get();
	return cache->Get("LdapDAIGetter", dataAccess);
}

bool LDAPDAICacheGetter::Get(ROAnything &result, const String &dataAccess, const String &key, char sepS, char sepI)
{
	StartTrace1(LDAPDAICacheGetter.Get, key);

	bool ret = GetAll(dataAccess).LookupPath(result, key, sepS, sepI);
	TraceAny(result, "Result:");
	return ret;
}
<commit_msg>changed PushPopEntry signature<commit_after>/*
 * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
 * All rights reserved.
 *
 * This library/application is free software; you can redistribute and/or modify it under the terms of
 * the license that is included with this library/application in the file license.txt.
 */

//--- interface include --------------------------------------------------------
#include "LDAPDAICachePolicyModule.h"

//--- standard modules used ----------------------------------------------------
#include "Dbg.h"
#include "System.h"
#include "SysLog.h"
#include "DataAccess.h"
#include "Action.h"

//--- c-modules used -----------------------------------------------------------

//---- LDAPDAICachePolicyModule -----------------------------------------------------------
RegisterModule(LDAPDAICachePolicyModule);

LDAPDAICachePolicyModule *LDAPDAICachePolicyModule::fgLDAPDAICachePolicyModule = 0;

LDAPDAICachePolicyModule::LDAPDAICachePolicyModule(const char *name) : WDModule(name)
{
	StartTrace(LDAPDAICachePolicyModule.LDAPDAICachePolicyModule);
}

LDAPDAICachePolicyModule::~LDAPDAICachePolicyModule()
{
	StartTrace(LDAPDAICachePolicyModule.~LDAPDAICachePolicyModule);
}

bool LDAPDAICachePolicyModule::Init(const ROAnything config)
{
	StartTrace(LDAPDAICachePolicyModule.Init);
	ROAnything LDAPDAICachePolicyModuleConfig;
	config.LookupPath(LDAPDAICachePolicyModuleConfig, "LDAPDAICachePolicyModule");
	TraceAny(LDAPDAICachePolicyModuleConfig, "LDAPDAICachePolicyModule:");

	ROAnything dataAccesses(config["LDAPDAICachePolicyModule"]["LDAPDAIDataAccess"]);
	ROAnything dataAccessActions(config["LDAPDAICachePolicyModule"]["LDAPDAIDataAccessAction"]);
	if ( dataAccesses.GetSize() == 0 && dataAccessActions.GetSize() == 0 ) {
		SysLog::WriteToStderr("\tLDAPDAICachePolicyModule::Init can't read needed configuration data.\n");
		return false;
	}
	if ( InitialLoad(dataAccesses, LDAPDAICachePolicyModule::dataaccess, config.DeepClone()) 	== false ||
		 InitialLoad(dataAccessActions, LDAPDAICachePolicyModule::action, config.DeepClone()) 	== false ) {
		return false;
	}
	String failedDataAccesses;
	CheckContractIsFulfilled(failedDataAccesses, dataAccesses);
	CheckContractIsFulfilled(failedDataAccesses, dataAccessActions);
	if (failedDataAccesses.Length() != 0 ) {
		SysLog::WriteToStderr(String("\tLDAPDAICachePolicyModule::LDAP Query: ") << failedDataAccesses <<
							  String(" returned no data.\n"));
		return false;
	}
	SysLog::WriteToStderr("\tLDAPDAICachePolicyModule done\n");
	return true;
}

bool LDAPDAICachePolicyModule::InitialLoad(const ROAnything dataAccesses, LDAPDAICachePolicyModule::EDataAccessType daType, const Anything &config )
{
	StartTrace(LDAPDAICachePolicyModule.InitialLoad);
	CacheHandler *cache = CacheHandler::Get();
	bool ret(true);
	if (cache) {
		LDAPDAIDataAcccessLoader ldl(config);
		LDAPDAIActionLoader lal(config);
		Anything tmp;
		for (int i = 0; i < dataAccesses.GetSize(); i++) {
			String toDo(dataAccesses[i].AsString());
			if ( daType == dataaccess ) {
				Trace("Loading ldl with: " << toDo);
				cache->Load("LdapDAIGetter", toDo, &ldl);
			}
			if ( daType == action ) {
				Trace("Loading lal with: " << toDo);
				cache->Load("LdapDAIGetter", toDo, &lal);
			}
		}
	} else {
		SysLog::WriteToStderr("\tLDAPDAICachePolicyModule::InitialLoad: NoCacheHandlerFound\n");
		ret = false;
	}
	return ret;
}

bool LDAPDAICachePolicyModule::CheckContractIsFulfilled(String &failedDataAccesses, const ROAnything dataAccesses)
{
	StartTrace(LDAPDAICachePolicyModule.CheckContractIsFulfilled);
	bool ret(true);
	for (int i = 0; i < dataAccesses.GetSize(); i++) {
		String daToDo(dataAccesses[i].AsString());
		Trace("Checking with: " << daToDo);

		ROAnything result(LDAPDAICacheGetter::GetAll(daToDo));
		// broke contract: specified LDAP-query must return data
		if (result.IsNull()) {
			failedDataAccesses.Append(daToDo);
			failedDataAccesses.Append(" ");
			ret = false;
		}
	}
	return ret;
}

bool LDAPDAICachePolicyModule::Finis()
{
	StartTrace(LDAPDAICachePolicyModule.Finis);

	SysLog::WriteToStderr("\tTerminating LDAPDAICachePolicyModule done\n");
	return true;
}

//--- LDAPDAIDataAcccessLoader -----------------------------------------------
LDAPDAIDataAcccessLoader::LDAPDAIDataAcccessLoader() { }
LDAPDAIDataAcccessLoader::LDAPDAIDataAcccessLoader(Anything config) : fConfig(config) { }
LDAPDAIDataAcccessLoader::~LDAPDAIDataAcccessLoader() { }
Anything LDAPDAIDataAcccessLoader::Load(const char *ldapDa)
{
	StartTrace(LDAPDAIDataAcccessLoader.Load);
	Anything theResult(Storage::Global());
	Context ctx;
	Context::PushPopEntry<Anything> aEntry(ctx, "LdapLoader", fConfig);

	if (ldapDa != "") {
		DataAccess da(ldapDa);
		bool retCode = da.StdExec(ctx);
		Anything tmpStore(ctx.GetTmpStore());

		if (retCode && tmpStore["LDAPResult"][ldapDa]["NumberOfEntries"].AsLong() > 0) {
			theResult = tmpStore["LDAPResult"][ldapDa]["Entries"];
		} else {
			String msg;
			msg << "\tLDAPDAICachePolicyModule::Load Unable to exec LDAP query for: " << ldapDa << "\n";
			SysLog::WriteToStderr(msg);
		}
	}

	TraceAny(theResult, "LDAP-Result for " << ldapDa << " cache.");
	return theResult;
}

//--- LDAPDAIDataAcccessLoader -----------------------------------------------
LDAPDAIActionLoader::LDAPDAIActionLoader() { }
LDAPDAIActionLoader::LDAPDAIActionLoader(Anything config) : fConfig(config) { }
LDAPDAIActionLoader::~LDAPDAIActionLoader() { }

Anything LDAPDAIActionLoader::Load(const char *ldapDaAction)
{
	StartTrace(LDAPDAIActionLoader.Load);
	Anything theResult(Storage::Global());
	Context ctx;
	Context::PushPopEntry<Anything> aEntry(ctx, "LdapLoader", fConfig);
	if (ldapDaAction != "") {
		Anything tmpStore = ctx.GetTmpStore();
		String transition;
		Anything config;
		// Default constructs an action config containing the name of the LDAPDAIDataAccess to execute
		// This may be overridden by the action implementing the DataAccess(es).
		config[ldapDaAction]["DataAccess"] = ldapDaAction;
		bool retCode = Action::ExecAction(transition, ctx, config);
		Trace("Result of DataAccess " << ldapDaAction << " is: " << retCode);
		// Called Action *must* return results in slot ["LDAPResult"][ldapDaAction]
		TraceAny(tmpStore["LDAPResult"][ldapDaAction], "Returned: " << ldapDaAction);
		if (retCode && tmpStore["LDAPResult"][ldapDaAction]["NumberOfEntries"].AsLong() > 0) {
			theResult = tmpStore["LDAPResult"][ldapDaAction]["Entries"];
			TraceAny(theResult, "Result of Load()");
		} else {
			String msg;
			msg << "\tLDAPDAICachePolicyModule::Load Unable to exec LDAP query for: " << ldapDaAction << "\n";
			SysLog::WriteToStderr(msg);
		}
	}
	return (theResult);
}

//---- LDAPDAICacheGetter ---------------------------------------------------------
LDAPDAICacheGetter::LDAPDAICacheGetter(const String &dataAccess)
	: fDA(dataAccess)
{
	StartTrace("LDAPDAICacheGetter.LDAPDAICacheGetter");
}

LDAPDAICacheGetter::~LDAPDAICacheGetter()
{
	StartTrace(LDAPDAICacheGetter.~LDAPDAICacheGetter);
}

bool LDAPDAICacheGetter::DoLookup(const char *key, ROAnything &result, char delim, char indexdelim) const
{
	StartTrace(LDAPDAICacheGetter.DoLookup);

	return Get(result, fDA, key, delim, indexdelim);
}

ROAnything LDAPDAICacheGetter::GetAll(const String &dataAccess)
{
	StartTrace1(LDAPDAICacheGetter.GetAll, dataAccess);

	CacheHandler *cache = CacheHandler::Get();
	return cache->Get("LdapDAIGetter", dataAccess);
}

bool LDAPDAICacheGetter::Get(ROAnything &result, const String &dataAccess, const String &key, char sepS, char sepI)
{
	StartTrace1(LDAPDAICacheGetter.Get, key);

	bool ret = GetAll(dataAccess).LookupPath(result, key, sepS, sepI);
	TraceAny(result, "Result:");
	return ret;
}
<|endoftext|>


<commit_before>#ifndef HMLIB_ODEINT_INTERFERE_BOUNDARY_INC
#
namespace hmLib {
	namespace odeint {

		template<typename state_type_>
		struct sigmoid_boundary_diff{
			template<typename functor>
			double sigmoid_zero_boundary(double x, functor dx, double boundary_error, double abs_error) {
				if (boundary_error < x)return dx(x);

				double v = dx(boundary_error);
				double dv = (dx(boundary_error + abs_error) - dx(boundary_error - abs_error)) / (2 * abs_error);

				double vk = v * 2;
				double va = dv * 4 / (vk + std::numeric_limits<double>::min());

				if (v>0) {
					//				double ans = vk / (1 + std::exp(-va*(x - boundary_error)));
					return vk / (1 + std::exp(-va*(x - boundary_error)));
				}

				double ba = std::log(1 / boundary_error + 1) / boundary_error;
				double bk = -(vk / (1 + std::exp(-va*(0.0 - boundary_error)))) / (0.5 - (1 / (1 + std::exp(ba*(boundary_error)))));
				double bv = -bk / (1 + std::exp(ba*boundary_error));

				//			double ans = vk / (1 + std::exp(-va*(x - boundary_error))) + bk / (1 + std::exp(ba*x)) + bv;

				return vk / (1 + std::exp(-va*(x - boundary_error))) + bk / (1 + std::exp(ba*x)) + bv;
			}
		};
		struct float_lower_boundary {
			using state_type = double;
		private:
			state_type val;
			bool prev;
		public:
			float_lower_boundary(const state_type& val_) :val(val_) {}
			float_lower_boundary(state_type&& val_) :val(val_) {}
		public:
			void ready(const state_type& x) { prev = check(x); }
			bool valid_step(const state_type& x)const { return prev || !check(x); }
			bool validate(const state_type& x, state_type& vx) const {
				if (check(x)) {
					vx = val;
					return true;
				}
				return false;
			}
		private:
			bool check(const state_type& x) const { return val >= x; }
		};

		template<typename boundary_type_>
		struct boundary {
			using state_type = state_type_;
			using time_type = time_type_;
		private:
			boundary_category bcat;
		public:
			void ready(const state_type& x) {
				bcat.ready(x);
			}
			bool valid_step(const state_type& x) {
				return bcat.valid_step(x, t);
			}
			bool validate(const state_type& x, state_type& vx) {

			}
			bool on_boundary() {

			}
			template<typename fn>
			void operator()(const state_type& x, state_type& dx, fn&& Fn) {

			}
		};
	}
}
#
#endif
<commit_msg>Fix boundary<commit_after>#ifndef HMLIB_ODEINT_INTERFERE_BOUNDARY_INC
#
namespace hmLib {
	namespace odeint {
		struct bounadry_diff_mode {
			struct always{};
			struct step_base{};
			struct never {};
		};
		template<typename state_type_>
		struct sigmoid_boundary_diff{
			template<typename functor>
			double sigmoid_zero_boundary(double x, functor dx, double boundary_error, double abs_error) {
				if (boundary_error < x)return dx(x);

				double v = dx(boundary_error);
				double dv = (dx(boundary_error + abs_error) - dx(boundary_error - abs_error)) / (2 * abs_error);

				double vk = v * 2;
				double va = dv * 4 / (vk + std::numeric_limits<double>::min());

				if (v>0) {
					//				double ans = vk / (1 + std::exp(-va*(x - boundary_error)));
					return vk / (1 + std::exp(-va*(x - boundary_error)));
				}

				double ba = std::log(1 / boundary_error + 1) / boundary_error;
				double bk = -(vk / (1 + std::exp(-va*(0.0 - boundary_error)))) / (0.5 - (1 / (1 + std::exp(ba*(boundary_error)))));
				double bv = -bk / (1 + std::exp(ba*boundary_error));

				//			double ans = vk / (1 + std::exp(-va*(x - boundary_error))) + bk / (1 + std::exp(ba*x)) + bv;

				return vk / (1 + std::exp(-va*(x - boundary_error))) + bk / (1 + std::exp(ba*x)) + bv;
			}
		};
		template<typename diff_type_,typename diff_mode_>
		struct float_lower_boundary {
			using state_type = double;
		private:
			state_type val;
			bool prev;
		public:
			float_lower_boundary(const state_type& val_) :val(val_) {}
			float_lower_boundary(state_type&& val_) :val(val_) {}
		public:
			void ready(const state_type& x) { prev = check(x); }
			bool valid_step(const state_type& x)const { return prev || !check(x); }
			bool validate(const state_type& x, state_type& vx) const {
				if (check(x)) {
					vx = val;
					return true;
				}
				return false;
			}
		private:
			bool check(const state_type& x) const { return val >= x; }
		};

		template<typename boundary_type_>
		struct boundary {
			using state_type = state_type_;
			using time_type = time_type_;
		private:
			boundary_category bcat;
		public:
			void ready(const state_type& x) {
				bcat.ready(x);
			}
			bool valid_step(const state_type& x) {
				return bcat.valid_step(x, t);
			}
			bool validate(const state_type& x, state_type& vx) {

			}
			bool on_boundary() {

			}
			template<typename fn>
			void operator()(const state_type& x, state_type& dx, fn&& Fn) {

			}
		};
	}
}
#
#endif
<|endoftext|>


<commit_before>#ifndef CELL_AUTOMATA_OPENGLWRAPPER_DRAWFIELD
#define CELL_AUTOMATA_OPENGLWRAPPER_DRAWFIELD

#include <string>
#include <GL/glut.h>

template<typename window_traits>
void setWindow(int& argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitWindowSize(window_traits::window_x_size,
		       window_traits::window_y_size);
    glutCreateWindow(window_traits::window_name);
    return;
}

void setBackground()
{
    glutInitDisplayMode(GLUT_RGBA);
    glClearColor(1.0, 1.0, 1.0, 1.0);
    return;
}

#endif /* CELL_AUTOMATA_OPENGLWRAPPER_DRAWFIELD */
<commit_msg>edit to use glutSwapBuffers().<commit_after>#ifndef CELL_AUTOMATA_OPENGLWRAPPER_DRAWFIELD
#define CELL_AUTOMATA_OPENGLWRAPPER_DRAWFIELD

#include <string>
#include <GL/glut.h>

template<typename window_traits>
void setWindow(int& argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitWindowSize(window_traits::window_x_size,
		       window_traits::window_y_size);
    glutCreateWindow(window_traits::window_name);
    return;
}

void setBackground()
{
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
    glClearColor(1.0, 1.0, 1.0, 1.0);
    return;
}

#endif /* CELL_AUTOMATA_OPENGLWRAPPER_DRAWFIELD */
<|endoftext|>


<commit_before>#include <cstdlib>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>

const char game_name[] = "barley-break";
const int screen_width = 640;
const int screen_height = 480;
const int tile_size = 64;
const int font_size = 32;
const int pole_size = 4;
const int two_pole_size = pole_size * pole_size;
const int tile_shift_x = ( screen_width - pole_size * tile_size ) / 2;
const int tile_shift_y = ( screen_height - pole_size * tile_size ) / 2;
const short moves[8] = { -1, +0, +1, +0, +0, -1, +0, +1 };
bool quit_flag = false;

SDL_Window *window = NULL;
SDL_Renderer *render = NULL;
SDL_Event event;
SDL_Texture *tile = NULL, *font = NULL;

short pole[pole_size][pole_size];

void send_error( int code )
{
    std::cout << SDL_GetError() << std::endl;
    exit( code );
}

void tile_draw( SDL_Renderer *r, SDL_Texture *tex, short id, int p )
{
    SDL_Rect wnd = { 0, 0, tile_size, tile_size };
    SDL_Rect pos = { 0, 0, tile_size, tile_size };
    short x = p % pole_size;
    short y = p / pole_size;

    id = id != 16 ? 1 : 0;
    pos.x = x * tile_size + tile_shift_x;
    pos.y = y * tile_size + tile_shift_y;
    wnd.x = id * tile_size;
    SDL_RenderCopy( r, tex, &wnd, &pos );
}

void font_color( SDL_Texture *tex, Uint32 color )
{
    SDL_SetTextureColorMod( tex, color >> 16, ( color >> 8 ) & 0xFF, color & 0xFF );
}

void font_draw( SDL_Renderer *r, SDL_Texture *tex, short text, int p )
{
    SDL_Rect wnd = { 0, 0, font_size, font_size };
    SDL_Rect pos = { 0, 0, font_size, font_size };
    short x = p % pole_size;
    short y = p / pole_size;

    if ( text == 16 ) {
        return;
    }
    pos.x = x * tile_size + tile_shift_x + font_size / 2;
    pos.y = y * tile_size + tile_shift_y + font_size / 2;
    wnd.x = (text - 1) * font_size;
    SDL_RenderCopy( r, tex, &wnd, &pos );
}

void game_restart( void )
{
    for ( short i = 0; i < two_pole_size; i++ ) {
        *( *pole + i ) = i+1;
    }
    for ( short i = 0; i < two_pole_size; i++ ) {
        short rnd_1 = rand() % two_pole_size;
        short rnd_2 = rand() % two_pole_size;
        if ( rnd_1 == rnd_2 ) {
            rnd_2 = (rnd_1 + 1) % two_pole_size;
        }
        std::swap( *(*pole + rnd_1), *(*pole + rnd_2) );
    }
    short incorrect = 0;
    for (short i = 0; i < two_pole_size; i++) {
        for (short j = i+1; j < two_pole_size; j++) {
            if (*(*pole + i) > *(*pole + j)) {
                incorrect ^= 1;
            }
        }
    }
    if (incorrect) {
        std::cout << "OMG!!!" << std::endl;
        game_restart();
    }
}

void game_event( SDL_Event *event )
{
    SDL_PollEvent( event );
    switch ( event->type ) {
        case SDL_QUIT:
            quit_flag = true;
            break;
        case SDL_MOUSEBUTTONDOWN:
            switch ( event->button.button ) {
                case SDL_BUTTON_LEFT:
                    short x = ( event->button.x - tile_shift_x ) / tile_size;
                    short y = ( event->button.y - tile_shift_y ) / tile_size;
                    for ( short i = 0; i < 8; i += 2 ) {
                        short it_move = pole[y+moves[i+1]][x+moves[i+0]] == 16 &&
                            x + moves[i+0] < pole_size && x + moves[i+0] >= 0 &&
                            y + moves[i+1] < pole_size && y + moves[i+1] >= 0;
                        if ( it_move ) {
                            pole[y+moves[i+1]][x+moves[i+0]] = pole[y][x];
                            pole[y][x] = 16;
                        }
                    }
                    break;
            }
            break;
        case SDL_KEYDOWN:
            short id = 0;
            for ( int i = 0; i < two_pole_size; i++ ) {
                if ( *(*pole + i) == 16 ) {
                    id = i;
                }
            }
            short x = id % pole_size;
            short y = id / pole_size;
            switch ( event->key.keysym.sym ) {
                case SDLK_UP:
                case SDLK_w:
                    if (y < 3) {
                        pole[y][x] = pole[y+1][x];
                        pole[y+1][x] = 16;
                    }
                    break;
                case SDLK_DOWN:
                case SDLK_s:
                    if (y > 0) {
                        pole[y][x] = pole[y-1][x];
                        pole[y-1][x] = 16;
                    }
                    break;
                case SDLK_LEFT:
                case SDLK_a:
                    if (x < 3) {
                        pole[y][x] = pole[y][x+1];
                        pole[y][x+1] = 16;
                    }
                    break;
                case SDLK_RIGHT:
                case SDLK_d:
                    if (x > 0) {
                        pole[y][x] = pole[y][x-1];
                        pole[y][x-1] = 16;
                    }
                    break;
                case SDLK_r:
                    game_restart();
                    break;
            }
            break;
    }
    event->button.button = 0;
    event->key.keysym.sym = 0;
}

void game_loop( void )
{
    short count = 0;

    for ( short i = 0; i < two_pole_size; i++ ) {
        if ( *( *pole + i ) == i+1 ) {
            count++;
        }
    }
    if ( count == two_pole_size ) {
        std::cout << "GAME OVER: WIN!\n";
        game_restart();
    }
}

void game_render( void )
{
    SDL_RenderClear( render );
    for ( short i = 0; i < two_pole_size; i++ ) {
        tile_draw( render, tile, *( *pole + i ), i );
        font_draw( render, font, *( *pole + i ), i );
    }
    SDL_RenderPresent( render );
}

void game_destroy( void )
{
    SDL_DestroyTexture( tile );
    SDL_DestroyTexture( font );
    SDL_DestroyRenderer( render );
    SDL_DestroyWindow( window );
    SDL_Quit();
}

void game_init( void )
{
    window = SDL_CreateWindow( game_name, SDL_WINDOWPOS_CENTERED,
        SDL_WINDOWPOS_CENTERED, screen_width, screen_height, SDL_WINDOW_SHOWN );
    if ( window == NULL ) {
        send_error( EXIT_FAILURE );
    }
    render = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED |
        SDL_RENDERER_PRESENTVSYNC );
    if ( render == NULL ) {
        send_error( EXIT_FAILURE );
    }
    tile = IMG_LoadTexture( render, "./images/tiles.png" );
    font = IMG_LoadTexture( render, "./images/font.png" );
    font_color( font, 0xf0c090 );
    srand( time( NULL ) );
    game_restart();
}

int main( int argc, char *argv[] )
{
    Uint32 FPS_MAX = 1000 / 31; // 30 fps

    game_init();
    while ( quit_flag == false ) {
        game_event( &event );
        game_loop();
        game_render();
        SDL_Delay( FPS_MAX );
    }
    game_destroy();
    return EXIT_SUCCESS;
}<commit_msg>[add] exit key<commit_after>#include <cstdlib>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>

const char game_name[] = "barley-break";
const int screen_width = 640;
const int screen_height = 480;
const int tile_size = 64;
const int font_size = 32;
const int pole_size = 4;
const int two_pole_size = pole_size * pole_size;
const int tile_shift_x = ( screen_width - pole_size * tile_size ) / 2;
const int tile_shift_y = ( screen_height - pole_size * tile_size ) / 2;
const short moves[8] = { -1, +0, +1, +0, +0, -1, +0, +1 };
bool quit_flag = false;

SDL_Window *window = NULL;
SDL_Renderer *render = NULL;
SDL_Event event;
SDL_Texture *tile = NULL, *font = NULL;

short pole[pole_size][pole_size];

void send_error( int code )
{
    std::cout << SDL_GetError() << std::endl;
    exit( code );
}

void tile_draw( SDL_Renderer *r, SDL_Texture *tex, short id, int p )
{
    SDL_Rect wnd = { 0, 0, tile_size, tile_size };
    SDL_Rect pos = { 0, 0, tile_size, tile_size };
    short x = p % pole_size;
    short y = p / pole_size;

    id = id != 16 ? 1 : 0;
    pos.x = x * tile_size + tile_shift_x;
    pos.y = y * tile_size + tile_shift_y;
    wnd.x = id * tile_size;
    SDL_RenderCopy( r, tex, &wnd, &pos );
}

void font_color( SDL_Texture *tex, Uint32 color )
{
    SDL_SetTextureColorMod( tex, color >> 16, ( color >> 8 ) & 0xFF, color & 0xFF );
}

void font_draw( SDL_Renderer *r, SDL_Texture *tex, short text, int p )
{
    SDL_Rect wnd = { 0, 0, font_size, font_size };
    SDL_Rect pos = { 0, 0, font_size, font_size };
    short x = p % pole_size;
    short y = p / pole_size;

    if ( text == 16 ) {
        return;
    }
    pos.x = x * tile_size + tile_shift_x + font_size / 2;
    pos.y = y * tile_size + tile_shift_y + font_size / 2;
    wnd.x = (text - 1) * font_size;
    SDL_RenderCopy( r, tex, &wnd, &pos );
}

void game_restart( void )
{
    for ( short i = 0; i < two_pole_size; i++ ) {
        *( *pole + i ) = i+1;
    }
    for ( short i = 0; i < two_pole_size; i++ ) {
        short rnd_1 = rand() % two_pole_size;
        short rnd_2 = rand() % two_pole_size;
        if ( rnd_1 == rnd_2 ) {
            rnd_2 = (rnd_1 + 1) % two_pole_size;
        }
        std::swap( *(*pole + rnd_1), *(*pole + rnd_2) );
    }
    short incorrect = 0;
    for (short i = 0; i < two_pole_size; i++) {
        for (short j = i+1; j < two_pole_size; j++) {
            if (*(*pole + i) > *(*pole + j)) {
                incorrect ^= 1;
            }
        }
    }
    if (incorrect) {
        std::cout << "OMG!!!" << std::endl;
        game_restart();
    }
}

void game_event( SDL_Event *event )
{
    SDL_PollEvent( event );
    switch ( event->type ) {
        case SDL_QUIT:
            quit_flag = true;
            break;
        case SDL_MOUSEBUTTONDOWN:
            switch ( event->button.button ) {
                case SDL_BUTTON_LEFT:
                    short x = ( event->button.x - tile_shift_x ) / tile_size;
                    short y = ( event->button.y - tile_shift_y ) / tile_size;
                    for ( short i = 0; i < 8; i += 2 ) {
                        short it_move = pole[y+moves[i+1]][x+moves[i+0]] == 16 &&
                            x + moves[i+0] < pole_size && x + moves[i+0] >= 0 &&
                            y + moves[i+1] < pole_size && y + moves[i+1] >= 0;
                        if ( it_move ) {
                            pole[y+moves[i+1]][x+moves[i+0]] = pole[y][x];
                            pole[y][x] = 16;
                        }
                    }
                    break;
            }
            break;
        case SDL_KEYDOWN:
            short id = 0;
            for ( int i = 0; i < two_pole_size; i++ ) {
                if ( *(*pole + i) == 16 ) {
                    id = i;
                }
            }
            short x = id % pole_size;
            short y = id / pole_size;
            switch ( event->key.keysym.sym ) {
                case SDLK_ESCAPE:
                case SDLK_q:
                    quit_flag = true;
                    break;
                case SDLK_UP:
                case SDLK_w:
                    if (y < 3) {
                        pole[y][x] = pole[y+1][x];
                        pole[y+1][x] = 16;
                    }
                    break;
                case SDLK_DOWN:
                case SDLK_s:
                    if (y > 0) {
                        pole[y][x] = pole[y-1][x];
                        pole[y-1][x] = 16;
                    }
                    break;
                case SDLK_LEFT:
                case SDLK_a:
                    if (x < 3) {
                        pole[y][x] = pole[y][x+1];
                        pole[y][x+1] = 16;
                    }
                    break;
                case SDLK_RIGHT:
                case SDLK_d:
                    if (x > 0) {
                        pole[y][x] = pole[y][x-1];
                        pole[y][x-1] = 16;
                    }
                    break;
                case SDLK_r:
                    game_restart();
                    break;
            }
            break;
    }
    event->button.button = 0;
    event->key.keysym.sym = 0;
}

void game_loop( void )
{
    short count = 0;

    for ( short i = 0; i < two_pole_size; i++ ) {
        if ( *( *pole + i ) == i+1 ) {
            count++;
        }
    }
    if ( count == two_pole_size ) {
        std::cout << "GAME OVER: WIN!\n";
        game_restart();
    }
}

void game_render( void )
{
    SDL_RenderClear( render );
    for ( short i = 0; i < two_pole_size; i++ ) {
        tile_draw( render, tile, *( *pole + i ), i );
        font_draw( render, font, *( *pole + i ), i );
    }
    SDL_RenderPresent( render );
}

void game_destroy( void )
{
    SDL_DestroyTexture( tile );
    SDL_DestroyTexture( font );
    SDL_DestroyRenderer( render );
    SDL_DestroyWindow( window );
    SDL_Quit();
}

void game_init( void )
{
    window = SDL_CreateWindow( game_name, SDL_WINDOWPOS_CENTERED,
        SDL_WINDOWPOS_CENTERED, screen_width, screen_height, SDL_WINDOW_SHOWN );
    if ( window == NULL ) {
        send_error( EXIT_FAILURE );
    }
    render = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED |
        SDL_RENDERER_PRESENTVSYNC );
    if ( render == NULL ) {
        send_error( EXIT_FAILURE );
    }
    tile = IMG_LoadTexture( render, "./images/tiles.png" );
    font = IMG_LoadTexture( render, "./images/font.png" );
    font_color( font, 0xf0c090 );
    srand( time( NULL ) );
    game_restart();
}

int main( int argc, char *argv[] )
{
    Uint32 FPS_MAX = 1000 / 31; // 30 fps

    game_init();
    while ( quit_flag == false ) {
        game_event( &event );
        game_loop();
        game_render();
        SDL_Delay( FPS_MAX );
    }
    game_destroy();
    return EXIT_SUCCESS;
}<|endoftext|>


<commit_before>#include <iostream>
#include <vector>

using std::vector; using std::cout; using std::endl; using std::cin;

int main()
{
    vector<int> ivec;
    for (int i; cin >> i; ivec.push_back(i));

    if (ivec.empty())
    {
        cout << "input at least one integer." << endl;
        return -1;
    }

    if (ivec.size() == 1)
    {
        cout << "only one integer " << ivec[0] << ", it doesn't have any adjacent elements." << endl;
        return -1;
    }

    for (int i = 0; i != ivec.size() - 1; ++i)
        cout << ivec[i] + ivec[i + 1] << " ";
    cout << endl;

    return 0;
}
<commit_msg>Changed condition for clarity<commit_after>#include <iostream>
#include <vector>

using std::vector; using std::cout; using std::endl; using std::cin;

int main()
{
    vector<int> ivec;
    for (int i; cin >> i; ivec.push_back(i));

    if (ivec.empty())
    {
        cout << "input at least one integer." << endl;
        return -1;
    }

    if (ivec.size() == 1)
    {
        cout << "only one integer " << ivec[0] << ", it doesn't have any adjacent elements." << endl;
        return -1;
    }

    for (int i = 0; i < ivec.size() - 1; ++i)
        cout << ivec[i] + ivec[i + 1] << " ";
    cout << endl;

    return 0;
}
<|endoftext|>


<commit_before>//
// @author @Yue Wang @shbling @Soyn @Yue Wang
//
// Exercise 10.24:
// Use bind and check_size to find the first element in a vector of ints that has a value greater
// than the length of a specified string value.
//
//  Discussion over this exercise on StackOverflow
//  http://stackoverflow.com/questions/20539406/what-type-does-stdfind-if-not-return
//

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

using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::find_if;
using std::bind;
using std::size_t;

auto check_size(string const& str, size_t sz)
{
    return str.size() < sz;
}

auto find_first_greater(vector<int> const& v, string const& str)
{
    auto predicate = [&](int i){ return bind(check_size, str, i)(); };
    return find_if(v.cbegin(), v.cend(), predicate);
}

int main()
{
    vector<int> vec{ 0, 1, 2, 3, 4, 5, 6, 7 };
    string str("123456");
    auto result = find_first_greater(vec, str);
    if (result != vec.cend())
        cout << *result << endl;
    else
        cout << "Not found" << endl;

    return 0;
}
<commit_msg>Update ex10_24.cpp<commit_after>//
// @author @Yue Wang @shbling @Soyn @Yue Wang
//
// Exercise 10.24:
// Use bind and check_size to find the first element in a vector of ints that has a value greater
// than the length of a specified string value.
//
//  Discussion over this exercise on StackOverflow
//  http://stackoverflow.com/questions/20539406/what-type-does-stdfind-if-not-return
//

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

using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::find_if;
using std::bind;
using std::size_t;

auto check_size(string const& str, size_t sz)
{
    return str.size() < sz;
}

int main()
{
    vector<int> vec{ 0, 1, 2, 3, 4, 5, 6, 7 };
    string str("123456");
    auto result = find_if(vec.begin(), vec.end(), bind(check_size, str, _1));
    if (result != vec.cend())
        cout << *result << endl;
    else
        cout << "Not found" << endl;

    return 0;
}
<|endoftext|>


<commit_before>//
//  ex11_38.cpp
//  Exercise 11.38
//
//  Created by pezy on 12/18/14.
//  Copyright (c) 2014 pezy. All rights reserved.
//
//  Rewrite the word-counting (11.1, p. 421) and word-transformation (11.3.6, p.
//  440) programs to use an unordered_map.

#include <unordered_map>
#include <set>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>

using std::string;

void wordCounting()
{
    std::unordered_map<string, size_t> word_count;
    for (string word; std::cin >> word; ++word_count[word])
        ;
    for (const auto& w : word_count)
        std::cout << w.first << " occurs " << w.second
                  << (w.second > 1 ? "times" : "time") << std::endl;
}

void wordTransformation()
{
    std::ifstream ifs_map("../data/word_transformation.txt"),
        ifs_content("../data/given_to_transform.txt");
    if (!ifs_map || !ifs_content) {
        std::cerr << "can't find the documents." << std::endl;
        return;
    }

    std::unordered_map<string, string> trans_map;
    for (string key, value; ifs_map >> key && getline(ifs_map, value);)
        if (value.size() > 1)
            trans_map[key] =
                value.substr(1).substr(0, value.find_last_not_of(' '));

    for (string text, word; getline(ifs_content, text); std::cout << std::endl)
        for (std::istringstream iss(text); iss >> word;) {
            auto map_it = trans_map.find(word);
            std::cout << (map_it == trans_map.cend() ? word : map_it->second)
                      << " ";
        }
}

int main()
{
    // wordCounting();
    wordTransformation();
}<commit_msg>Update ex11_38.cpp<commit_after>//
//  ex11_38.cpp
//  Exercise 11.38
//
//  Created by pezy on 12/18/14.
//  Copyright (c) 2014 pezy. All rights reserved.
//
//  Rewrite the word counting (11.1, p. 421) and word transformation (11.3.6, p. 440) programs to use an unordered_map.

#include <iostream>
#include <string>
#include <cstddef>
#include <fstream>
#include <sstream>
#include <unordered_map>

using namespace std;

void wordCounting()
{
    unordered_map<string, size_t> word_count;
    for(string word; cin>>word; ++word_count[word])
        ;
    for(const auto &w:word_count)
        cout<<w.first<<" occurs "<<w.second<<((w.second>1)?" times":" time")<<endl;
}

void wordTransformation()
{
    ifstream ifs_map("E:\\1.txt"), ifs_content("E:\\2.txt");
    if(!ifs_map||!ifs_content)
    {
        cerr<<"can't find the documents"<<endl;
        return;
    }

    unordered_map<string, string> trans_map;
    for(string key, value; ifs_map>>key&&getline(ifs_map, value); )
        if(value.size()>1)
            trans_map[key]=value.substr(1).substr(0, value.find_last_not_of(' '));

    for(string text, word; getline(ifs_content, text); cout<<endl)
        for(istringstream iss(text); iss>>word; )
        {
            auto map_it=trans_map.find(word);
            cout<<((map_it==trans_map.cend()) ? word : map_it->second)<<" ";
        }
}

int main()
{
    //wordCounting();
    wordTransformation();
}
<|endoftext|>


<commit_before>#include "Arduino.h"

#include "mt8880.h"

void mt8880_init() {
  //Prepare chip select and register select
  pinMode(CS, OUTPUT);
  digitalWrite(CS, HIGH);
  pinMode(RS, OUTPUT);
  digitalWrite(RS, HIGH);

  //Wait until 100ms after power on
  while(millis() < 100);

  //Creepy initialization magic from the datasheet
  mt8880_read(true);
  mt8880_write(0b0000, true);
  mt8880_write(0b0000, true);
  mt8880_write(0b1000, true);
  mt8880_write(0b0000, true);
  mt8880_read(true);
}

char mt8880_read(bool rs) {
  //Data pins should be inputs
  pinMode(D0, INPUT);
  pinMode(D1, INPUT);
  pinMode(D2, INPUT);
  pinMode(D3, INPUT);

  //Select chip
  digitalWrite(CS, LOW);

  //Select status/control registers (based on rs value)
  digitalWrite(RS, rs);

  //Read register
  digitalWrite(RW, HIGH);

  //Clock pulse (so the chip updates)
  digitalWrite(O2, HIGH);
  delay(5);

  //Storage
  char data = 0;

  //Fun bitwise stuff to read and combine the binary values
  data |= digitalRead(D3);
  data <<= 1;
  data |= digitalRead(D2);
  data <<= 1;
  data |= digitalRead(D1);
  data <<= 1;
  data |= digitalRead(D0);

  //Clock pulse
  digitalWrite(O2, LOW);
  delay(5);

  //Deselect chip
  digitalWrite(CS, HIGH);

  return data;
}

void mt8880_write(char data, bool rs) {
  //Data pins should be outputs
  pinMode(D0, OUTPUT);
  pinMode(D1, OUTPUT);
  pinMode(D2, OUTPUT);
  pinMode(D3, OUTPUT);

  //Select chip
  digitalWrite(CS, LOW);

  //Select status/control registers (based on rs value)
  digitalWrite(RS, rs);

  //Write register
  digitalWrite(RW, LOW);

  //Fun bitwise stuff to separate and write the binary values
  digitalWrite(D0, data & 1);
  data >>= 1;
  digitalWrite(D1, data & 1);
  data >>= 1;
  digitalWrite(D2, data & 1);
  data >>= 1;
  digitalWrite(D3, data & 1);
  data >>= 1;

  //Clock pulse (so the chip updates)
  digitalWrite(O2, HIGH);
  delay(5);

  //Clock pulse
  digitalWrite(O2, LOW);
  delay(5);

  //Deselect chip
  digitalWrite(CS, HIGH);
}
<commit_msg>fix some initialization values for mt8880<commit_after>#include "Arduino.h"

#include "mt8880.h"

void mt8880_init() {
  //Prepare interrupt input with pull-up
  pinMode(IRQ, INPUT);
  digitalWrite(IRQ, HIGH);

  //Prepare chip select, register select, read/write, and clock
  pinMode(CS, OUTPUT);
  digitalWrite(CS, HIGH);
  pinMode(RS, OUTPUT);
  digitalWrite(RS, HIGH);
  pinMode(RW, OUTPUT);
  digitalWrite(RW, HIGH);
  pinMode(O2, OUTPUT);
  digitalWrite(O2, LOW);

  //Wait until 100ms after power on
  while(millis() < 100);

  //Creepy initialization magic from the datasheet
  mt8880_read(true);
  mt8880_write(0b0000, true);
  mt8880_write(0b0000, true);
  mt8880_write(0b1000, true);
  mt8880_write(0b0000, true);
  mt8880_read(true);
}

char mt8880_read(bool rs) {
  //Data pins should be inputs
  pinMode(D0, INPUT);
  pinMode(D1, INPUT);
  pinMode(D2, INPUT);
  pinMode(D3, INPUT);

  //Select chip
  digitalWrite(CS, LOW);

  //Select status/control registers (based on rs value)
  digitalWrite(RS, rs);

  //Read register
  digitalWrite(RW, HIGH);

  //Clock pulse (so the chip updates)
  digitalWrite(O2, HIGH);
  delay(5);

  //Storage
  char data = 0;

  //Fun bitwise stuff to read and combine the binary values
  data |= digitalRead(D3);
  data <<= 1;
  data |= digitalRead(D2);
  data <<= 1;
  data |= digitalRead(D1);
  data <<= 1;
  data |= digitalRead(D0);

  //Clock pulse
  digitalWrite(O2, LOW);
  delay(5);

  //Deselect chip
  digitalWrite(CS, HIGH);

  return data;
}

void mt8880_write(char data, bool rs) {
  //Data pins should be outputs
  pinMode(D0, OUTPUT);
  pinMode(D1, OUTPUT);
  pinMode(D2, OUTPUT);
  pinMode(D3, OUTPUT);

  //Select chip
  digitalWrite(CS, LOW);

  //Select status/control registers (based on rs value)
  digitalWrite(RS, rs);

  //Write register
  digitalWrite(RW, LOW);

  //Fun bitwise stuff to separate and write the binary values
  digitalWrite(D0, data & 1);
  data >>= 1;
  digitalWrite(D1, data & 1);
  data >>= 1;
  digitalWrite(D2, data & 1);
  data >>= 1;
  digitalWrite(D3, data & 1);
  data >>= 1;

  //Clock pulse (so the chip updates)
  digitalWrite(O2, HIGH);
  delay(5);

  //Clock pulse
  digitalWrite(O2, LOW);
  delay(5);

  //Deselect chip
  digitalWrite(CS, HIGH);
}
<|endoftext|>


<commit_before>#include <fftw3.h>
#include <boost/timer/timer.hpp>
#include <boost/chrono.hpp>
#include <cmath>
#include <iostream>
#include <complex>
#include <Eigen/Dense>
#include <vector>
#include <unsupported/Eigen/FFT>
#include <fstream>
#include "chirpz.h"

using namespace Eigen;
namespace chirpz {

void hello(fc32_t c) {
    std::cout << "Hello World : " << c << std::endl;

}

template class ChirpZ<c32_t>;
template class ChirpZ<c64_t>;
template class ChirpZ2d<c32_t>;
template class ChirpZ2d<c64_t>;

}

<commit_msg>unneded dependency<commit_after>#include <fftw3.h>
#include <boost/timer/timer.hpp>
#include <boost/chrono.hpp>
#include <cmath>
#include <iostream>
#include <complex>
#include <Eigen/Dense>
#include <vector>
#include <fstream>
#include "chirpz.h"

using namespace Eigen;
namespace chirpz {

void hello(fc32_t c) {
    std::cout << "Hello World : " << c << std::endl;

}

template class ChirpZ<c32_t>;
template class ChirpZ<c64_t>;
template class ChirpZ2d<c32_t>;
template class ChirpZ2d<c64_t>;

}

<|endoftext|>


<commit_before>// Copyright 2004-present Facebook. All Rights Reserved.

#include <glog/logging.h>

#include "osquery/core.h"
#include "osquery/flags.h"
#include "osquery/filesystem.h"
#include "osquery/registry.h"

namespace osquery {

#define __GFLAGS_NAMESPACE google

const std::string kDescription =
    "your operating system as a high-performance "
    "relational database";
const std::string kEpilog = "osquery project page <http://osquery.io>.";

DEFINE_osquery_flag(bool, debug, false, "Enable debug messages.");

DEFINE_osquery_flag(bool,
                    verbose_debug,
                    false,
                    "Enable verbose debug messages.")

DEFINE_osquery_flag(bool,
                    disable_logging,
                    false,
                    "Disable ERROR/INFO logging.");

DEFINE_osquery_flag(string,
                    osquery_log_dir,
                    "/var/log/osquery/",
                    "Directory to store ERROR/INFO and results logging.");

static const char* basename(const char* filename) {
  const char* sep = strrchr(filename, '/');
  return sep ? sep + 1 : filename;
}

void initOsquery(int argc, char* argv[], int tool) {
  std::string binary(basename(argv[0]));
  std::string first_arg = (argc > 1) ? std::string(argv[1]) : "";

  if ((first_arg == "--help" || first_arg == "-h" || first_arg == "-help") &&
      tool != OSQUERY_TOOL_TEST) {
    // Parse help options before gflags. Only display osquery-related options.
    fprintf(stdout, "osquery " OSQUERY_VERSION ", %s\n", kDescription.c_str());
    if (tool == OSQUERY_TOOL_SHELL) {
      // The shell allows a caller to run a single SQL statement and exit.
      fprintf(
          stdout, "Usage: %s [OPTION]... [SQL STATEMENT]\n\n", binary.c_str());
    } else {
      fprintf(stdout, "Usage: %s [OPTION]...\n\n", binary.c_str());
    }
    fprintf(stdout,
            "The following options control the osquery "
            "daemon and shell.\n\n");

    Flag::printFlags(Flag::get().flags());

    if (tool == OSQUERY_TOOL_SHELL) {
      // Print shell flags.
      fprintf(stdout, "\nThe following options control the osquery shell.\n\n");
      Flag::printFlags(Flag::get().shellFlags());
    }

    fprintf(stdout, "\n%s\n", kEpilog.c_str());

    ::exit(0);
  }

  FLAGS_alsologtostderr = true;
  FLAGS_logbufsecs = 0; // flush the log buffer immediately
  FLAGS_stop_logging_if_full_disk = true;
  FLAGS_max_log_size = 10; // max size for individual log file is 10MB

  // Set version string from CMake build
  __GFLAGS_NAMESPACE::SetVersionString(OSQUERY_VERSION);

  // Let gflags parse the non-help options/flags.
  __GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, false);

  // The log dir is used for glogging and the filesystem results logs.
  if (isWritable(FLAGS_osquery_log_dir.c_str()).ok()) {
    FLAGS_log_dir = FLAGS_osquery_log_dir;
  }

  if (FLAGS_verbose_debug) {
    FLAGS_debug = true;
    FLAGS_v = 1;
  }

  if (!FLAGS_debug) {
    FLAGS_minloglevel = 1; // WARNING
  }

  if (FLAGS_disable_logging) {
    FLAGS_logtostderr = true;
    FLAGS_minloglevel = 2;
  }

  google::InitGoogleLogging(argv[0]);
  osquery::InitRegistry::get().run();
}
}
<commit_msg>More appropriate logging controls<commit_after>// Copyright 2004-present Facebook. All Rights Reserved.

#include <glog/logging.h>

#include "osquery/core.h"
#include "osquery/flags.h"
#include "osquery/filesystem.h"
#include "osquery/registry.h"

namespace osquery {

#define __GFLAGS_NAMESPACE google

const std::string kDescription =
    "your operating system as a high-performance "
    "relational database";
const std::string kEpilog = "osquery project page <http://osquery.io>.";

DEFINE_osquery_flag(bool, debug, false, "Enable debug messages.");

DEFINE_osquery_flag(bool,
                    verbose_debug,
                    false,
                    "Enable verbose debug messages.")

DEFINE_osquery_flag(bool,
                    disable_logging,
                    false,
                    "Disable ERROR/INFO logging.");

DEFINE_osquery_flag(string,
                    osquery_log_dir,
                    "/var/log/osquery/",
                    "Directory to store ERROR/INFO and results logging.");

static const char* basename(const char* filename) {
  const char* sep = strrchr(filename, '/');
  return sep ? sep + 1 : filename;
}

void initOsquery(int argc, char* argv[], int tool) {
  std::string binary(basename(argv[0]));
  std::string first_arg = (argc > 1) ? std::string(argv[1]) : "";

  if ((first_arg == "--help" || first_arg == "-h" || first_arg == "-help") &&
      tool != OSQUERY_TOOL_TEST) {
    // Parse help options before gflags. Only display osquery-related options.
    fprintf(stdout, "osquery " OSQUERY_VERSION ", %s\n", kDescription.c_str());
    if (tool == OSQUERY_TOOL_SHELL) {
      // The shell allows a caller to run a single SQL statement and exit.
      fprintf(
          stdout, "Usage: %s [OPTION]... [SQL STATEMENT]\n\n", binary.c_str());
    } else {
      fprintf(stdout, "Usage: %s [OPTION]...\n\n", binary.c_str());
    }
    fprintf(stdout,
            "The following options control the osquery "
            "daemon and shell.\n\n");

    Flag::printFlags(Flag::get().flags());

    if (tool == OSQUERY_TOOL_SHELL) {
      // Print shell flags.
      fprintf(stdout, "\nThe following options control the osquery shell.\n\n");
      Flag::printFlags(Flag::get().shellFlags());
    }

    fprintf(stdout, "\n%s\n", kEpilog.c_str());

    ::exit(0);
  }

  FLAGS_alsologtostderr = true;
  FLAGS_logbufsecs = 0; // flush the log buffer immediately
  FLAGS_stop_logging_if_full_disk = true;
  FLAGS_max_log_size = 10; // max size for individual log file is 10MB

  // Set version string from CMake build
  __GFLAGS_NAMESPACE::SetVersionString(OSQUERY_VERSION);

  // Let gflags parse the non-help options/flags.
  __GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, false);

  // The log dir is used for glogging and the filesystem results logs.
  if (isWritable(FLAGS_osquery_log_dir.c_str()).ok()) {
    FLAGS_log_dir = FLAGS_osquery_log_dir;
  }

  if (FLAGS_verbose_debug) {
    // Turn verbosity up to 1.
    // Do log DEBUG, INFO, WARNING, ERROR to their log files.
    // Do log the above and verbose=1 to stderr.
    FLAGS_debug = true;
    FLAGS_v = 1;
  }

  if (!FLAGS_debug) {
    // Do NOT log INFO, WARNING, ERROR to stderr.
    // Do log to their log files.
    FLAGS_minloglevel = 0; // INFO
    FLAGS_alsologtostderr = false;
  }

  if (FLAGS_disable_logging) {
    // Do log ERROR to stderr.
    // Do NOT log INFO, WARNING, ERROR to their log files.
    FLAGS_logtostderr = true;
    FLAGS_minloglevel = 2; // ERROR
  }

  google::InitGoogleLogging(argv[0]);
  osquery::InitRegistry::get().run();
}
}
<|endoftext|>


<commit_before>/**
 *  Copyright (c) 2014-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under both the Apache 2.0 license (found in the
 *  LICENSE file in the root directory of this source tree) and the GPLv2 (found
 *  in the COPYING file in the root directory of this source tree).
 *  You may select, at your option, one of the above-listed licenses.
 */

#include <poll.h>

#include <osquery/events.h>
#include <osquery/filesystem.h>
#include <osquery/logger.h>
#include <osquery/registry_factory.h>

#include "osquery/events/linux/udev.h"

namespace osquery {

static const int kUdevMLatency = 200;

REGISTER(UdevEventPublisher, "event_publisher", "udev");

Status UdevEventPublisher::setUp() {
  // The Setup and Teardown workflows should be protected against races.
  // Just in case let's protect the publisher's resources.
  WriteLock lock(mutex_);

  // Create the udev object.
  handle_ = udev_new();
  if (handle_ == nullptr) {
    return Status(1, "Could not create udev object.");
  }

  // Set up the udev monitor before scanning/polling.
  monitor_ = udev_monitor_new_from_netlink(handle_, "udev");
  if (monitor_ == nullptr) {
    udev_unref(handle_);
    handle_ = nullptr;
    return Status(1, "Could not create udev monitor.");
  }

  udev_monitor_enable_receiving(monitor_);
  return Status(0, "OK");
}

void UdevEventPublisher::tearDown() {
  WriteLock lock(mutex_);
  if (monitor_ != nullptr) {
    udev_monitor_unref(monitor_);
    monitor_ = nullptr;
  }

  if (handle_ != nullptr) {
    udev_unref(handle_);
    handle_ = nullptr;
  }
}

Status UdevEventPublisher::run() {
  int fd = 0;

  {
    WriteLock lock(mutex_);
    if (monitor_ == nullptr) {
      return Status(1);
    }
    fd = udev_monitor_get_fd(monitor_);
  }

  struct pollfd fds[1];
  fds[0].fd = fd;
  fds[0].events = POLLIN;

  int selector = ::poll(fds, 1, 1000);
  if (selector == -1 && errno != EINTR && errno != EAGAIN) {
    LOG(ERROR) << "Could not read udev monitor";
    return Status(1, "udev monitor failed.");
  }

  if (selector == 0 || !(fds[0].revents & POLLIN)) {
    // Read timeout.
    return Status(0, "Finished");
  }

  {
    WriteLock lock(mutex_);
    struct udev_device* device = udev_monitor_receive_device(monitor_);
    if (device == nullptr) {
      LOG(ERROR) << "udev monitor returned invalid device";
      return Status(1, "udev monitor failed.");
    }

    auto ec = createEventContextFrom(device);
    fire(ec);

    udev_device_unref(device);
  }

  pauseMilli(kUdevMLatency);
  return Status(0, "OK");
}

std::string UdevEventPublisher::getValue(struct udev_device* device,
                                         const std::string& property) {
  auto value = udev_device_get_property_value(device, property.c_str());
  if (value != nullptr) {
    return std::string(value);
  }
  return "";
}

std::string UdevEventPublisher::getAttr(struct udev_device* device,
                                        const std::string& attr) {
  auto value = udev_device_get_sysattr_value(device, attr.c_str());
  if (value != nullptr) {
    return std::string(value);
  }
  return "";
}

UdevEventContextRef UdevEventPublisher::createEventContextFrom(
    struct udev_device* device) {
  auto ec = createEventContext();
  ec->device = device;
  // Map the action string to the eventing enum.
  ec->action = UDEV_EVENT_ACTION_UNKNOWN;
  ec->action_string = std::string(udev_device_get_action(device));
  if (ec->action_string == "add") {
    ec->action = UDEV_EVENT_ACTION_ADD;
  } else if (ec->action_string == "remove") {
    ec->action = UDEV_EVENT_ACTION_REMOVE;
  } else if (ec->action_string == "change") {
    ec->action = UDEV_EVENT_ACTION_CHANGE;
  }

  // Set the subscription-aware variables for the event.
  auto value = udev_device_get_subsystem(device);
  if (value != nullptr) {
    ec->subsystem = std::string(value);
  }

  value = udev_device_get_devnode(device);
  if (value != nullptr) {
    ec->devnode = std::string(value);
  }

  value = udev_device_get_devtype(device);
  if (value != nullptr) {
    ec->devtype = std::string(value);
  }

  value = udev_device_get_driver(device);
  if (value != nullptr) {
    ec->driver = std::string(value);
  }

  return ec;
}

bool UdevEventPublisher::shouldFire(const UdevSubscriptionContextRef& sc,
                                    const UdevEventContextRef& ec) const {
  if (sc->action != UDEV_EVENT_ACTION_ALL) {
    if (sc->action != ec->action) {
      return false;
    }
  }

  if (sc->subsystem.length() != 0 && sc->subsystem != ec->subsystem) {
    return false;
  } else if (sc->devnode.length() != 0 && sc->devnode != ec->devnode) {
    return false;
  } else if (sc->devtype.length() != 0 && sc->devtype != ec->devtype) {
    return false;
  } else if (sc->driver.length() != 0 && sc->driver != ec->driver) {
    return false;
  }

  return true;
}
}
<commit_msg>udev resource protection (#4599)<commit_after>/**
 *  Copyright (c) 2014-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under both the Apache 2.0 license (found in the
 *  LICENSE file in the root directory of this source tree) and the GPLv2 (found
 *  in the COPYING file in the root directory of this source tree).
 *  You may select, at your option, one of the above-listed licenses.
 */

#include <poll.h>

#include <osquery/events.h>
#include <osquery/filesystem.h>
#include <osquery/logger.h>
#include <osquery/registry_factory.h>

#include "osquery/events/linux/udev.h"

namespace osquery {

static const int kUdevMLatency = 200;

REGISTER(UdevEventPublisher, "event_publisher", "udev");

Status UdevEventPublisher::setUp() {
  // The Setup and Teardown workflows should be protected against races.
  // Just in case let's protect the publisher's resources.
  WriteLock lock(mutex_);

  // Create the udev object.
  handle_ = udev_new();
  if (handle_ == nullptr) {
    return Status(1, "Could not create udev object.");
  }

  // Set up the udev monitor before scanning/polling.
  monitor_ = udev_monitor_new_from_netlink(handle_, "udev");
  if (monitor_ == nullptr) {
    udev_unref(handle_);
    handle_ = nullptr;
    return Status(1, "Could not create udev monitor.");
  }

  udev_monitor_enable_receiving(monitor_);
  return Status(0, "OK");
}

void UdevEventPublisher::tearDown() {
  WriteLock lock(mutex_);
  if (monitor_ != nullptr) {
    udev_monitor_unref(monitor_);
    monitor_ = nullptr;
  }

  if (handle_ != nullptr) {
    udev_unref(handle_);
    handle_ = nullptr;
  }
}

Status UdevEventPublisher::run() {
  int fd = 0;

  {
    WriteLock lock(mutex_);
    if (monitor_ == nullptr) {
      return Status(1);
    }
    fd = udev_monitor_get_fd(monitor_);

    struct pollfd fds[1];
    fds[0].fd = fd;
    fds[0].events = POLLIN;

    int selector = ::poll(fds, 1, 1000);
    if (selector == -1 && errno != EINTR && errno != EAGAIN) {
      LOG(ERROR) << "Could not read udev monitor";
      return Status(1, "udev monitor failed.");
    }

    if (selector == 0 || !(fds[0].revents & POLLIN)) {
      // Read timeout.
      return Status(0, "Finished");
    }

    struct udev_device* device = udev_monitor_receive_device(monitor_);
    if (device == nullptr) {
      LOG(ERROR) << "udev monitor returned invalid device";
      return Status(1, "udev monitor failed.");
    }

    auto ec = createEventContextFrom(device);
    fire(ec);

    udev_device_unref(device);
  }

  pauseMilli(kUdevMLatency);
  return Status(0, "OK");
}

std::string UdevEventPublisher::getValue(struct udev_device* device,
                                         const std::string& property) {
  auto value = udev_device_get_property_value(device, property.c_str());
  if (value != nullptr) {
    return std::string(value);
  }
  return "";
}

std::string UdevEventPublisher::getAttr(struct udev_device* device,
                                        const std::string& attr) {
  auto value = udev_device_get_sysattr_value(device, attr.c_str());
  if (value != nullptr) {
    return std::string(value);
  }
  return "";
}

UdevEventContextRef UdevEventPublisher::createEventContextFrom(
    struct udev_device* device) {
  auto ec = createEventContext();
  ec->device = device;
  // Map the action string to the eventing enum.
  ec->action = UDEV_EVENT_ACTION_UNKNOWN;
  ec->action_string = std::string(udev_device_get_action(device));
  if (ec->action_string == "add") {
    ec->action = UDEV_EVENT_ACTION_ADD;
  } else if (ec->action_string == "remove") {
    ec->action = UDEV_EVENT_ACTION_REMOVE;
  } else if (ec->action_string == "change") {
    ec->action = UDEV_EVENT_ACTION_CHANGE;
  }

  // Set the subscription-aware variables for the event.
  auto value = udev_device_get_subsystem(device);
  if (value != nullptr) {
    ec->subsystem = std::string(value);
  }

  value = udev_device_get_devnode(device);
  if (value != nullptr) {
    ec->devnode = std::string(value);
  }

  value = udev_device_get_devtype(device);
  if (value != nullptr) {
    ec->devtype = std::string(value);
  }

  value = udev_device_get_driver(device);
  if (value != nullptr) {
    ec->driver = std::string(value);
  }

  return ec;
}

bool UdevEventPublisher::shouldFire(const UdevSubscriptionContextRef& sc,
                                    const UdevEventContextRef& ec) const {
  if (sc->action != UDEV_EVENT_ACTION_ALL) {
    if (sc->action != ec->action) {
      return false;
    }
  }

  if (sc->subsystem.length() != 0 && sc->subsystem != ec->subsystem) {
    return false;
  } else if (sc->devnode.length() != 0 && sc->devnode != ec->devnode) {
    return false;
  } else if (sc->devtype.length() != 0 && sc->devtype != ec->devtype) {
    return false;
  } else if (sc->driver.length() != 0 && sc->driver != ec->driver) {
    return false;
  }

  return true;
}
} // namespace osquery
<|endoftext|>


<commit_before>// Copyright (c) 2013-2014 Flowgrammable.org
//
// 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 <iostream>
#include <fstream>
#include <iterator>
#include <string>

#include <freeflow/sys/socket.hpp>
#include <freeflow/sys/json.hpp>

using namespace std;
using namespace freeflow;

// Holds a command-line flag. The flag is set when --flag_true is passed, and
// reset when --flag_false is passed. When used in CommandParser, the name
// and value act as a key-value pair. Upon construction, value will be set to
// the default value of the flag.
//
// Example usage:
//
// Flag("auto connect","auto-connect","no-auto-connect",true, "Whether to
//   automatically connect to the network");
//
// If the user typed "run --auto-connect", value for "auto connect" would
// be true, whereas is they typed "run --no-auto-connect", it would be false
struct Flag {
  string name;
  string flag_true;
  string flag_false;
  bool value;
  string help_text;

  Flag(string n,string f_true,string f_false,bool default_val,string help = "") :
    name(n), flag_true(f_true), flag_false(f_false), value(default_val),
    help_text(help){}
};

int main(){
  return 0;
}

<commit_msg>Added pattern matching functionality and initial framework for parsing command-line arguments<commit_after>// Copyright (c) 2013-2014 Flowgrammable.org
//
// 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 <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <vector>
#include <assert.h>

#include <freeflow/sys/socket.hpp>
#include <freeflow/sys/json.hpp>

using namespace std;
using namespace freeflow;

struct CLI_parser_exception {
  CLI_parser_exception(string err);
};

CLI_parser_exception::CLI_parser_exception(string err) {
  cout << "CLI parser exception: " << err << endl;
}

struct CLI_parser_rule {
  string format;

  bool match(string & str,vector<pair<string,string> > args);

  CLI_parser_rule(string rule);
};

CLI_parser_rule::CLI_parser_rule(string rule) : format(rule) {
  // Make sure all square brackets are closed
  bool in_bracket = false;

  for (char c : format) {
    if (c == '[') {
      if (not in_bracket) {
        in_bracket = true;
      }
      else {
        throw CLI_parser_exception("Too many opening square brackets ('[')"
          " in parser rule: " + format);
      }
    } else if (c == ']') {
      if (in_bracket) {
        in_bracket = false;
      }
      else {
        throw CLI_parser_exception("Too many closing square brackets (']')"
          " in parser rule: " + format);
      }
    }
  }

  if (in_bracket){
    throw CLI_parser_exception("Expected closing square bracket (']')"
      " in parser rule: " + format);
  }
}

bool CLI_parser_rule::match(string & str,vector<pair<string,string> > args) {
  int pos_f = 0;
  int pos_s = 0;
  string name;
  string var_value;
  bool var = false;

  while (pos_s < (int)str.length()) {
    if (!var) {
      if (format[pos_f] == '[') {
        pos_f++;
        name = "";
        var_value = "";
        var = true;

        bool matched = false;

        while (pos_f < (int)format.length()) {
          if (format[pos_f] == ']') {
            matched = true;
            pos_f++;
            break;
          }
          else{
            name += format[pos_f++];
          }
        }

        if (!matched) {
          throw "CLI_parser_rule Error: unmatched bracket in rule "+format;
        }

        cout << "Next: " << format[pos_f] << endl;

        //pos_f++;
      }
    }

    if (var) {
      //if(pos_f+1 < format.length()){
        if (str[pos_s] == format[pos_f]) {
          var = false;
          cout << "Var " << name << " = " << var_value << endl;
          args.push_back(pair<string,string>(name,var_value));
        }
        else {
          var_value += str[pos_s++];
        }
      //}
    }
    else {
      if (format[pos_f] != str[pos_s]) {
        return false;
      }

      pos_f++;
      pos_s++;
    }
  }

  if (var){
    cout << "Var " << name << " = " << var_value << endl;
    args.push_back(pair<string,string>(name,var_value));
  }

  if (pos_f < (int)format.length()) return false;
  else return true;
}

struct CLI_parser {
  vector<CLI_parser_rule> rules;
  vector<string> args;
  int arg_pos;

  void parse(int argc,char *argv[]);
  string & get_arg();
  bool next_arg();
  void set_arg_pos(int pos);

};

void CLI_parser::parse(int argc,char *argv[]) {
  // Probably a good idea to clear the args vector if this is called more than once
  args.clear();

  for (int i = 0; i < argc; i++) {
    args.push_back(argv[i]);
  }

  set_arg_pos(0);
}

// Gets the current argument
string & CLI_parser::get_arg() {
  assert(arg_pos < (int)args.size());

  return args[arg_pos];
}

// Advances to the next argument
// Returns whether there is another argument
bool CLI_parser::next_arg() {
  return ++arg_pos < (int)args.size();
}

// Sets the position of the current argument
void CLI_parser::set_arg_pos(int pos) {
  if (pos < (int)args.size())
    arg_pos = pos;
  else
    arg_pos = args.size();
}

int main(int argc,char *argv[]){
  CLI_parser parser;

  CLI_parser_rule("--[flag]=[value");

  parser.parse(argc,argv);

  do{
    cout << parser.get_arg() << endl;
  } while(parser.next_arg());
}

<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 3      *
*                (c) 2006-2008 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#ifndef SOFA_COMPONENT_MAPPING_CENTERPOINTMAPPING_INL
#define SOFA_COMPONENT_MAPPING_CENTERPOINTMAPPING_INL

#include "CenterPointMechanicalMapping.h"
#include <sofa/core/componentmodel/topology/BaseMeshTopology.h>

namespace sofa
{

namespace component
{

namespace mapping
{

template <class BaseMapping>
CenterPointMechanicalMapping<BaseMapping>::CenterPointMechanicalMapping(In* from, Out* to)
    : Inherit(from, to)
    , inputTopo(NULL)
    , outputTopo(NULL)
{
}

template <class BaseMapping>
CenterPointMechanicalMapping<BaseMapping>::~CenterPointMechanicalMapping()
{
}

template <class BaseMapping>
void CenterPointMechanicalMapping<BaseMapping>::init()
{
    inputTopo = this->fromModel->getContext()->getMeshTopology();
    outputTopo = this->toModel->getContext()->getMeshTopology();
    this->Inherit::init();
}

template <class BaseMapping>
void CenterPointMechanicalMapping<BaseMapping>::apply( typename Out::VecCoord& out, const typename In::VecCoord& in )
{
    const core::componentmodel::topology::BaseMeshTopology::SeqHexas& hexas = inputTopo->getHexas();

    if(out.size() < hexas.size())
        out.resize(hexas.size());

    for(unsigned int i = 0; i < hexas.size(); ++i)
    {
        out[i] =(in[ hexas[i][0] ]
                + in[ hexas[i][1] ]
                + in[ hexas[i][2] ]
                + in[ hexas[i][3] ]
                + in[ hexas[i][4] ]
                + in[ hexas[i][5] ]
                + in[ hexas[i][6] ]
                + in[ hexas[i][7] ]) * 0.125f;
    }
}

template <class BaseMapping>
void CenterPointMechanicalMapping<BaseMapping>::applyJ( typename Out::VecDeriv& out, const typename In::VecDeriv& in )
{
    const core::componentmodel::topology::BaseMeshTopology::SeqHexas& hexas = inputTopo->getHexas();

    if(out.size() < hexas.size())
        out.resize(hexas.size());

    for(unsigned int i = 0; i < hexas.size(); ++i)
    {
        out[i] =(in[ hexas[i][0] ]
                + in[ hexas[i][1] ]
                + in[ hexas[i][2] ]
                + in[ hexas[i][3] ]
                + in[ hexas[i][4] ]
                + in[ hexas[i][5] ]
                + in[ hexas[i][6] ]
                + in[ hexas[i][7] ]) * 0.125f;
    }
}

template <class BaseMapping>
void CenterPointMechanicalMapping<BaseMapping>::applyJT( typename In::VecDeriv& out, const typename Out::VecDeriv& in )
{
    const core::componentmodel::topology::BaseMeshTopology::SeqHexas& hexas = inputTopo->getHexas();

    for(unsigned int i = 0; i <hexas.size(); ++i)
    {
        typename Out::Deriv val = in[i] * 0.125f;

        out[ hexas[i][0] ] += val;
        out[ hexas[i][1] ] += val;
        out[ hexas[i][2] ] += val;
        out[ hexas[i][3] ] += val;
        out[ hexas[i][4] ] += val;
        out[ hexas[i][5] ] += val;
        out[ hexas[i][6] ] += val;
        out[ hexas[i][7] ] += val;
    }
}

template <class BaseMapping>
void CenterPointMechanicalMapping<BaseMapping>::applyJT( typename In::VecConst& /*out*/, const typename Out::VecConst& /*in*/ )
{
    // TODO

    return;
}

} // namespace mapping

} // namespace component

} // namespace sofa

#endif
<commit_msg>r3533/sofa-dev : FIX: not well understood bug with certain topologies<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 3      *
*                (c) 2006-2008 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                               SOFA :: Modules                               *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#ifndef SOFA_COMPONENT_MAPPING_CENTERPOINTMAPPING_INL
#define SOFA_COMPONENT_MAPPING_CENTERPOINTMAPPING_INL

#include "CenterPointMechanicalMapping.h"
#include <sofa/core/componentmodel/topology/BaseMeshTopology.h>

namespace sofa
{

namespace component
{

namespace mapping
{

template <class BaseMapping>
CenterPointMechanicalMapping<BaseMapping>::CenterPointMechanicalMapping(In* from, Out* to)
    : Inherit(from, to)
    , inputTopo(NULL)
    , outputTopo(NULL)
{
}

template <class BaseMapping>
CenterPointMechanicalMapping<BaseMapping>::~CenterPointMechanicalMapping()
{
}

template <class BaseMapping>
void CenterPointMechanicalMapping<BaseMapping>::init()
{
    inputTopo = this->fromModel->getContext()->getMeshTopology();
    outputTopo = this->toModel->getContext()->getMeshTopology();
    this->Inherit::init();
}

template <class BaseMapping>
void CenterPointMechanicalMapping<BaseMapping>::apply( typename Out::VecCoord& out, const typename In::VecCoord& in )
{
    const core::componentmodel::topology::BaseMeshTopology::SeqHexas& hexas = inputTopo->getHexas();

    if(out.size() < hexas.size())
        out.resize(hexas.size());

    for(unsigned int i = 0; i < hexas.size(); ++i)
    {
        out[i] =(in[ hexas[i][0] ]
                + in[ hexas[i][1] ]
                + in[ hexas[i][2] ]
                + in[ hexas[i][3] ]
                + in[ hexas[i][4] ]
                + in[ hexas[i][5] ]
                + in[ hexas[i][6] ]
                + in[ hexas[i][7] ]) * 0.125f;
    }
}

template <class BaseMapping>
void CenterPointMechanicalMapping<BaseMapping>::applyJ( typename Out::VecDeriv& out, const typename In::VecDeriv& in )
{
    const core::componentmodel::topology::BaseMeshTopology::SeqHexas& hexas = inputTopo->getHexas();

    if(out.size() < hexas.size())
        out.resize(hexas.size());

    for(unsigned int i = 0; i < hexas.size(); ++i)
    {
        out[i] =(in[ hexas[i][0] ]
                + in[ hexas[i][1] ]
                + in[ hexas[i][2] ]
                + in[ hexas[i][3] ]
                + in[ hexas[i][4] ]
                + in[ hexas[i][5] ]
                + in[ hexas[i][6] ]
                + in[ hexas[i][7] ]) * 0.125f;
    }
}

template <class BaseMapping>
void CenterPointMechanicalMapping<BaseMapping>::applyJT( typename In::VecDeriv& out, const typename Out::VecDeriv& in )
{
    const core::componentmodel::topology::BaseMeshTopology::SeqHexas& hexas = inputTopo->getHexas();

    for(unsigned int i = 0; i <hexas.size(); ++i)
    {
        if( in.size() <= i ) continue;

        typename Out::Deriv val = in[i] * 0.125f;

        out[ hexas[i][0] ] += val;
        out[ hexas[i][1] ] += val;
        out[ hexas[i][2] ] += val;
        out[ hexas[i][3] ] += val;
        out[ hexas[i][4] ] += val;
        out[ hexas[i][5] ] += val;
        out[ hexas[i][6] ] += val;
        out[ hexas[i][7] ] += val;
    }
}

template <class BaseMapping>
void CenterPointMechanicalMapping<BaseMapping>::applyJT( typename In::VecConst& /*out*/, const typename Out::VecConst& /*in*/ )
{
    // TODO

    return;
}

} // namespace mapping

} // namespace component

} // namespace sofa

#endif
<|endoftext|>


<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/websockets/websocket_handshake_stream_create_helper.h"

#include <string>
#include <vector>

#include "net/base/completion_callback.h"
#include "net/base/net_errors.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_request_info.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_response_info.h"
#include "net/socket/client_socket_handle.h"
#include "net/socket/socket_test_util.h"
#include "net/websockets/websocket_basic_handshake_stream.h"
#include "net/websockets/websocket_stream.h"
#include "net/websockets/websocket_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
#include "url/origin.h"

namespace net {
namespace {

// This class encapsulates the details of creating a mock ClientSocketHandle.
class MockClientSocketHandleFactory {
 public:
  MockClientSocketHandleFactory()
      : pool_(1, 1, socket_factory_maker_.factory()) {}

  // The created socket expects |expect_written| to be written to the socket,
  // and will respond with |return_to_read|. The test will fail if the expected
  // text is not written, or if all the bytes are not read.
  scoped_ptr<ClientSocketHandle> CreateClientSocketHandle(
      const std::string& expect_written,
      const std::string& return_to_read) {
    socket_factory_maker_.SetExpectations(expect_written, return_to_read);
    scoped_ptr<ClientSocketHandle> socket_handle(new ClientSocketHandle);
    socket_handle->Init(
        "a",
        scoped_refptr<MockTransportSocketParams>(),
        MEDIUM,
        CompletionCallback(),
        &pool_,
        BoundNetLog());
    return socket_handle.Pass();
  }

 private:
  WebSocketMockClientSocketFactoryMaker socket_factory_maker_;
  MockTransportClientSocketPool pool_;

  DISALLOW_COPY_AND_ASSIGN(MockClientSocketHandleFactory);
};

class TestConnectDelegate : public WebSocketStream::ConnectDelegate {
 public:
  ~TestConnectDelegate() override {}

  void OnSuccess(scoped_ptr<WebSocketStream> stream) override {}
  void OnFailure(const std::string& failure_message) override {}
  void OnStartOpeningHandshake(
      scoped_ptr<WebSocketHandshakeRequestInfo> request) override {}
  void OnFinishOpeningHandshake(
      scoped_ptr<WebSocketHandshakeResponseInfo> response) override {}
  void OnSSLCertificateError(
      scoped_ptr<WebSocketEventInterface::SSLErrorCallbacks>
          ssl_error_callbacks,
      const SSLInfo& ssl_info,
      bool fatal) override {}
};

class WebSocketHandshakeStreamCreateHelperTest : public ::testing::Test {
 protected:
  scoped_ptr<WebSocketStream> CreateAndInitializeStream(
      const std::string& socket_url,
      const std::string& socket_host,
      const std::string& socket_path,
      const std::vector<std::string>& sub_protocols,
      const std::string& origin,
      const std::string& extra_request_headers,
      const std::string& extra_response_headers) {
    WebSocketHandshakeStreamCreateHelper create_helper(&connect_delegate_,
                                                       sub_protocols);
    create_helper.set_failure_message(&failure_message_);

    scoped_ptr<ClientSocketHandle> socket_handle =
        socket_handle_factory_.CreateClientSocketHandle(
            WebSocketStandardRequest(socket_path, socket_host,
                                     url::Origin(GURL(origin)),
                                     extra_request_headers),
            WebSocketStandardResponse(extra_response_headers));

    scoped_ptr<WebSocketHandshakeStreamBase> handshake(
        create_helper.CreateBasicStream(socket_handle.Pass(), false));

    // If in future the implementation type returned by CreateBasicStream()
    // changes, this static_cast will be wrong. However, in that case the test
    // will fail and AddressSanitizer should identify the issue.
    static_cast<WebSocketBasicHandshakeStream*>(handshake.get())
        ->SetWebSocketKeyForTesting("dGhlIHNhbXBsZSBub25jZQ==");

    HttpRequestInfo request_info;
    request_info.url = GURL(socket_url);
    request_info.method = "GET";
    request_info.load_flags = LOAD_DISABLE_CACHE;
    int rv = handshake->InitializeStream(
        &request_info, DEFAULT_PRIORITY, BoundNetLog(), CompletionCallback());
    EXPECT_EQ(OK, rv);

    HttpRequestHeaders headers;
    headers.SetHeader("Host", "localhost");
    headers.SetHeader("Connection", "Upgrade");
    headers.SetHeader("Pragma", "no-cache");
    headers.SetHeader("Cache-Control", "no-cache");
    headers.SetHeader("Upgrade", "websocket");
    headers.SetHeader("Origin", origin);
    headers.SetHeader("Sec-WebSocket-Version", "13");
    headers.SetHeader("User-Agent", "");
    headers.SetHeader("Accept-Encoding", "gzip, deflate");
    headers.SetHeader("Accept-Language", "en-us,fr");

    HttpResponseInfo response;
    TestCompletionCallback dummy;

    rv = handshake->SendRequest(headers, &response, dummy.callback());

    EXPECT_EQ(OK, rv);

    rv = handshake->ReadResponseHeaders(dummy.callback());
    EXPECT_EQ(OK, rv);
    EXPECT_EQ(101, response.headers->response_code());
    EXPECT_TRUE(response.headers->HasHeaderValue("Connection", "Upgrade"));
    EXPECT_TRUE(response.headers->HasHeaderValue("Upgrade", "websocket"));
    return handshake->Upgrade();
  }

  MockClientSocketHandleFactory socket_handle_factory_;
  TestConnectDelegate connect_delegate_;
  std::string failure_message_;
};

// Confirm that the basic case works as expected.
TEST_F(WebSocketHandshakeStreamCreateHelperTest, BasicStream) {
  scoped_ptr<WebSocketStream> stream = CreateAndInitializeStream(
      "ws://localhost/", "localhost", "/", std::vector<std::string>(),
      "http://localhost", "", "");
  EXPECT_EQ("", stream->GetExtensions());
  EXPECT_EQ("", stream->GetSubProtocol());
}

// Verify that the sub-protocols are passed through.
TEST_F(WebSocketHandshakeStreamCreateHelperTest, SubProtocols) {
  std::vector<std::string> sub_protocols;
  sub_protocols.push_back("chat");
  sub_protocols.push_back("superchat");
  scoped_ptr<WebSocketStream> stream = CreateAndInitializeStream(
      "ws://localhost/", "localhost", "/", sub_protocols, "http://localhost",
      "Sec-WebSocket-Protocol: chat, superchat\r\n",
      "Sec-WebSocket-Protocol: superchat\r\n");
  EXPECT_EQ("superchat", stream->GetSubProtocol());
}

// Verify that extension name is available. Bad extension names are tested in
// websocket_stream_test.cc.
TEST_F(WebSocketHandshakeStreamCreateHelperTest, Extensions) {
  scoped_ptr<WebSocketStream> stream = CreateAndInitializeStream(
      "ws://localhost/", "localhost", "/", std::vector<std::string>(),
      "http://localhost", "",
      "Sec-WebSocket-Extensions: permessage-deflate\r\n");
  EXPECT_EQ("permessage-deflate", stream->GetExtensions());
}

// Verify that extension parameters are available. Bad parameters are tested in
// websocket_stream_test.cc.
TEST_F(WebSocketHandshakeStreamCreateHelperTest, ExtensionParameters) {
  scoped_ptr<WebSocketStream> stream = CreateAndInitializeStream(
      "ws://localhost/", "localhost", "/", std::vector<std::string>(),
      "http://localhost", "",
      "Sec-WebSocket-Extensions: permessage-deflate;"
      " client_max_window_bits=14; server_max_window_bits=14;"
      " server_no_context_takeover; client_no_context_takeover\r\n");

  EXPECT_EQ(
      "permessage-deflate;"
      " client_max_window_bits=14; server_max_window_bits=14;"
      " server_no_context_takeover; client_no_context_takeover",
      stream->GetExtensions());
}

}  // namespace
}  // namespace net
<commit_msg>Remove unused params in WebSocketHandshakeStreamCreateHelperTest<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/websockets/websocket_handshake_stream_create_helper.h"

#include <string>
#include <vector>

#include "net/base/completion_callback.h"
#include "net/base/net_errors.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_request_info.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_response_info.h"
#include "net/socket/client_socket_handle.h"
#include "net/socket/socket_test_util.h"
#include "net/websockets/websocket_basic_handshake_stream.h"
#include "net/websockets/websocket_stream.h"
#include "net/websockets/websocket_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
#include "url/origin.h"

namespace net {
namespace {

// This class encapsulates the details of creating a mock ClientSocketHandle.
class MockClientSocketHandleFactory {
 public:
  MockClientSocketHandleFactory()
      : pool_(1, 1, socket_factory_maker_.factory()) {}

  // The created socket expects |expect_written| to be written to the socket,
  // and will respond with |return_to_read|. The test will fail if the expected
  // text is not written, or if all the bytes are not read.
  scoped_ptr<ClientSocketHandle> CreateClientSocketHandle(
      const std::string& expect_written,
      const std::string& return_to_read) {
    socket_factory_maker_.SetExpectations(expect_written, return_to_read);
    scoped_ptr<ClientSocketHandle> socket_handle(new ClientSocketHandle);
    socket_handle->Init(
        "a",
        scoped_refptr<MockTransportSocketParams>(),
        MEDIUM,
        CompletionCallback(),
        &pool_,
        BoundNetLog());
    return socket_handle.Pass();
  }

 private:
  WebSocketMockClientSocketFactoryMaker socket_factory_maker_;
  MockTransportClientSocketPool pool_;

  DISALLOW_COPY_AND_ASSIGN(MockClientSocketHandleFactory);
};

class TestConnectDelegate : public WebSocketStream::ConnectDelegate {
 public:
  ~TestConnectDelegate() override {}

  void OnSuccess(scoped_ptr<WebSocketStream> stream) override {}
  void OnFailure(const std::string& failure_message) override {}
  void OnStartOpeningHandshake(
      scoped_ptr<WebSocketHandshakeRequestInfo> request) override {}
  void OnFinishOpeningHandshake(
      scoped_ptr<WebSocketHandshakeResponseInfo> response) override {}
  void OnSSLCertificateError(
      scoped_ptr<WebSocketEventInterface::SSLErrorCallbacks>
          ssl_error_callbacks,
      const SSLInfo& ssl_info,
      bool fatal) override {}
};

class WebSocketHandshakeStreamCreateHelperTest : public ::testing::Test {
 protected:
  scoped_ptr<WebSocketStream> CreateAndInitializeStream(
      const std::vector<std::string>& sub_protocols,
      const std::string& extra_request_headers,
      const std::string& extra_response_headers) {
    static const char kOrigin[] = "http://localhost";
    WebSocketHandshakeStreamCreateHelper create_helper(&connect_delegate_,
                                                       sub_protocols);
    create_helper.set_failure_message(&failure_message_);

    scoped_ptr<ClientSocketHandle> socket_handle =
        socket_handle_factory_.CreateClientSocketHandle(
            WebSocketStandardRequest("/", "localhost",
                                     url::Origin(GURL(kOrigin)),
                                     extra_request_headers),
            WebSocketStandardResponse(extra_response_headers));

    scoped_ptr<WebSocketHandshakeStreamBase> handshake(
        create_helper.CreateBasicStream(socket_handle.Pass(), false));

    // If in future the implementation type returned by CreateBasicStream()
    // changes, this static_cast will be wrong. However, in that case the test
    // will fail and AddressSanitizer should identify the issue.
    static_cast<WebSocketBasicHandshakeStream*>(handshake.get())
        ->SetWebSocketKeyForTesting("dGhlIHNhbXBsZSBub25jZQ==");

    HttpRequestInfo request_info;
    request_info.url = GURL("ws://localhost/");
    request_info.method = "GET";
    request_info.load_flags = LOAD_DISABLE_CACHE;
    int rv = handshake->InitializeStream(
        &request_info, DEFAULT_PRIORITY, BoundNetLog(), CompletionCallback());
    EXPECT_EQ(OK, rv);

    HttpRequestHeaders headers;
    headers.SetHeader("Host", "localhost");
    headers.SetHeader("Connection", "Upgrade");
    headers.SetHeader("Pragma", "no-cache");
    headers.SetHeader("Cache-Control", "no-cache");
    headers.SetHeader("Upgrade", "websocket");
    headers.SetHeader("Origin", kOrigin);
    headers.SetHeader("Sec-WebSocket-Version", "13");
    headers.SetHeader("User-Agent", "");
    headers.SetHeader("Accept-Encoding", "gzip, deflate");
    headers.SetHeader("Accept-Language", "en-us,fr");

    HttpResponseInfo response;
    TestCompletionCallback dummy;

    rv = handshake->SendRequest(headers, &response, dummy.callback());

    EXPECT_EQ(OK, rv);

    rv = handshake->ReadResponseHeaders(dummy.callback());
    EXPECT_EQ(OK, rv);
    EXPECT_EQ(101, response.headers->response_code());
    EXPECT_TRUE(response.headers->HasHeaderValue("Connection", "Upgrade"));
    EXPECT_TRUE(response.headers->HasHeaderValue("Upgrade", "websocket"));
    return handshake->Upgrade();
  }

  MockClientSocketHandleFactory socket_handle_factory_;
  TestConnectDelegate connect_delegate_;
  std::string failure_message_;
};

// Confirm that the basic case works as expected.
TEST_F(WebSocketHandshakeStreamCreateHelperTest, BasicStream) {
  scoped_ptr<WebSocketStream> stream =
      CreateAndInitializeStream(std::vector<std::string>(), "", "");
  EXPECT_EQ("", stream->GetExtensions());
  EXPECT_EQ("", stream->GetSubProtocol());
}

// Verify that the sub-protocols are passed through.
TEST_F(WebSocketHandshakeStreamCreateHelperTest, SubProtocols) {
  std::vector<std::string> sub_protocols;
  sub_protocols.push_back("chat");
  sub_protocols.push_back("superchat");
  scoped_ptr<WebSocketStream> stream = CreateAndInitializeStream(
      sub_protocols, "Sec-WebSocket-Protocol: chat, superchat\r\n",
      "Sec-WebSocket-Protocol: superchat\r\n");
  EXPECT_EQ("superchat", stream->GetSubProtocol());
}

// Verify that extension name is available. Bad extension names are tested in
// websocket_stream_test.cc.
TEST_F(WebSocketHandshakeStreamCreateHelperTest, Extensions) {
  scoped_ptr<WebSocketStream> stream = CreateAndInitializeStream(
      std::vector<std::string>(), "",
      "Sec-WebSocket-Extensions: permessage-deflate\r\n");
  EXPECT_EQ("permessage-deflate", stream->GetExtensions());
}

// Verify that extension parameters are available. Bad parameters are tested in
// websocket_stream_test.cc.
TEST_F(WebSocketHandshakeStreamCreateHelperTest, ExtensionParameters) {
  scoped_ptr<WebSocketStream> stream = CreateAndInitializeStream(
      std::vector<std::string>(), "",
      "Sec-WebSocket-Extensions: permessage-deflate;"
      " client_max_window_bits=14; server_max_window_bits=14;"
      " server_no_context_takeover; client_no_context_takeover\r\n");

  EXPECT_EQ(
      "permessage-deflate;"
      " client_max_window_bits=14; server_max_window_bits=14;"
      " server_no_context_takeover; client_no_context_takeover",
      stream->GetExtensions());
}

}  // namespace
}  // namespace net
<|endoftext|>