<commit_before>/*******************************************************************************
Copyright (c) 2014, Jan Koester jan.koester@gmx.net
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

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

#include "os/os.h"
#include "utils.h"
#include "httpd.h"

#define KTKEY 0
#define KTSKEY 1

libhttppp::HTTPDCmd::HTTPDCmd() {
	_Key = NULL;
	_SKey = '\0';
	_Value = NULL;
	_Help = NULL;
	_Found = false;
	_Required = false;
	_nextHTTPDCmd = NULL;
}

const char *libhttppp::HTTPDCmd::getKey() {
	return _Key;
}

const char libhttppp::HTTPDCmd::getShortkey() {
	return _SKey;
}

const char *libhttppp::HTTPDCmd::getValue() {
	return _Value;
}

size_t libhttppp::HTTPDCmd::getValueSize_t() {
	return atoi(_Value);
}

int libhttppp::HTTPDCmd::getValueInt() {
	return atoi(_Value);
}

const char *libhttppp::HTTPDCmd::getHelp() {
	return _Help;
}

bool libhttppp::HTTPDCmd::getFound() {
	return _Found;
}

bool libhttppp::HTTPDCmd::getRequired() {
	return _Required;
}

libhttppp::HTTPDCmd *libhttppp::HTTPDCmd::nextHTTPDCmd() {
	return _nextHTTPDCmd;
}

libhttppp::HTTPDCmd::~HTTPDCmd() {
	delete[] _Key;
	delete[] _Value;
	delete[] _Help;
	delete _nextHTTPDCmd;
}

libhttppp::HTTPDCmdController::HTTPDCmdController() {
	_firstHTTPDCmd = NULL;
	_lastHTTPDCmd = NULL;
}

void libhttppp::HTTPDCmdController::registerCmd(const char *key, const char skey,bool required, const char *defaultvalue, const char *help) {
	if (!key || !skey || !help) {
		_httpexception[HTTPException::Critical] << "cmd parser key,skey or help not set!";
		throw _httpexception;
	}
	/*if key exist overwriting options*/
	for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd=curhttpdcmd->nextHTTPDCmd()) {
		if (strncmp(curhttpdcmd->getKey(), key, getlen(curhttpdcmd->getKey())) == 0) {
			/*set new shortkey*/
			curhttpdcmd->_SKey = skey;
			/*set reqirement flag*/
			curhttpdcmd->_Required = required;
			/*set new value*/
			delete[] curhttpdcmd->_Value;
			curhttpdcmd->_Value = new char[getlen(defaultvalue)+1];
			scopy(defaultvalue, defaultvalue+getlen(defaultvalue),curhttpdcmd->_Value);
			curhttpdcmd->_Value[getlen(defaultvalue)] = '\0';
			/*set new help*/
			delete[] curhttpdcmd->_Help;
			curhttpdcmd->_Help = new char[getlen(help) + 1];
			scopy(help, help + getlen(help), curhttpdcmd->_Help);
			curhttpdcmd->_Help[getlen(help)] = '\0';
			return;
		}
	}
	/*create new key value store*/
	if (!_firstHTTPDCmd) {
		_firstHTTPDCmd = new HTTPDCmd;
		_lastHTTPDCmd = _firstHTTPDCmd;
	}
	else {
		_lastHTTPDCmd->_nextHTTPDCmd = new HTTPDCmd;
		_lastHTTPDCmd = _lastHTTPDCmd->_nextHTTPDCmd;
	}
	/*set new key*/
	_lastHTTPDCmd->_Key = new char[getlen(key) + 1];
	scopy(key,key+getlen(key),_lastHTTPDCmd->_Key);
	_lastHTTPDCmd->_Key[getlen(key)] = '\0';
	/*set new shortkey*/
	_lastHTTPDCmd->_SKey = skey;
	/*set reqirement flag*/
	_lastHTTPDCmd->_Required = required;
	/*set new value*/
	if (defaultvalue) {
		_lastHTTPDCmd->_Value = new char[getlen(defaultvalue) + 1];
		scopy(defaultvalue, defaultvalue + getlen(defaultvalue), _lastHTTPDCmd->_Value);
		_lastHTTPDCmd->_Value[getlen(defaultvalue)] = '\0';
	}
	/*set new help*/
	_lastHTTPDCmd->_Help = new char[getlen(help) + 1];
	scopy(help, help + getlen(help), _lastHTTPDCmd->_Help);
	_lastHTTPDCmd->_Help[getlen(help)] = '\0';

}

void libhttppp::HTTPDCmdController::registerCmd(const char *key, const char skey, bool required, size_t defaultvalue, const char *help) {
	char buf[255];
	itoa(defaultvalue,buf);
	registerCmd(key,skey,required,buf,help);
}

void libhttppp::HTTPDCmdController::registerCmd(const char *key, const char skey, bool required, int defaultvalue, const char *help) {
	char buf[255];
	itoa(defaultvalue,buf);
	registerCmd(key, skey, required, buf, help);
}

void libhttppp::HTTPDCmdController::parseCmd(int argc, char** argv){
	for (int args = 1; args < argc; args++) {
		int keytype = -1;
		if (argv[args][0]=='-' && argv[args][1] == '-') {
			keytype = KTKEY;
		}else if (argv[args][0] == '-'){
			keytype = KTSKEY;
		}else {
			break;
		}

		size_t kendpos = getlen(argv[args]);
		for (size_t cmdpos = 0; cmdpos < getlen(argv[args])+1; cmdpos++) {
			switch (argv[args][cmdpos]) {
			  case '=': {
				  kendpos = cmdpos;
			  };
			}
		}

		char *key = NULL;
		char skey = '0';
		if (keytype == KTKEY) {
			key = new char[kendpos-1];
			scopy(argv[args] +2, argv[args] +kendpos, key);
			key[kendpos - 2] = '\0';
		} else if (keytype == KTSKEY){
			skey = argv[args][1];
		}

		for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) {
			if (keytype == KTKEY) {
				if (strncmp(curhttpdcmd->getKey(), key, getlen(curhttpdcmd->getKey())) == 0) {
					curhttpdcmd->_Found = true;
					int valuesize = (getlen(argv[args]) - (kendpos+1));
					if (valuesize > 0) {
						delete[] curhttpdcmd->_Value;
						curhttpdcmd->_Value = new char[valuesize+1];
						scopy(argv[args]+(kendpos+1), argv[args] + getlen(argv[args]),curhttpdcmd->_Value);
						curhttpdcmd->_Value[valuesize] = '\0';
					}
				}
			} else if (keytype == KTSKEY) {
				if (curhttpdcmd->getShortkey()== skey) {
					curhttpdcmd->_Found = true;
					int valuesize = getlen(argv[++args]);
					if (valuesize > 0) {
						delete[] curhttpdcmd->_Value;
						curhttpdcmd->_Value = new char[valuesize + 1];
						scopy(argv[args], argv[args] + getlen(argv[args]), curhttpdcmd->_Value);
						curhttpdcmd->_Value[valuesize] = '\0';
					}
				}
			}
		}

		delete[] key;
	}
}

bool libhttppp::HTTPDCmdController::checkRequired() {
	for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) {
		if (curhttpdcmd->getRequired() && !curhttpdcmd->_Found) {
			return false;
		}
	}
	return true;
}

void libhttppp::HTTPDCmdController::printHelp() {
	for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) {
        Console con;
        con << "--" << curhttpdcmd->getKey()
            << " -" << curhttpdcmd->getShortkey()
            << " "  << curhttpdcmd->getHelp() << Console::endl;
	}
}

libhttppp::HTTPDCmd *libhttppp::HTTPDCmdController::getHTTPDCmdbyKey(const char *key) {
	for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) {
		if (strncmp(curhttpdcmd->getKey(), key, getlen(curhttpdcmd->getKey())) == 0) {
			return curhttpdcmd;
		}
	}
	return NULL;
}

libhttppp::HTTPDCmdController::~HTTPDCmdController() {
	delete _firstHTTPDCmd;
	_lastHTTPDCmd = NULL;
}

libhttppp::HttpD::HttpD(int argc, char** argv){
    CmdController= new HTTPDCmdController;
	/*Register Parameters*/
	CmdController->registerCmd("help", 'h', false, (const char*) NULL, "Helpmenu");
    CmdController->registerCmd("httpaddr",'a', true,(const char*) NULL,"Address to listen");
    CmdController->registerCmd("httpport", 'p', false, 8080, "Port to listen");
    CmdController->registerCmd("maxconnections", 'm',false, MAXDEFAULTCONN, "Max connections that can connect");
    CmdController->registerCmd("httpscert", 'c',false,(const char*) NULL, "HTTPS Certfile");
    CmdController->registerCmd("httpskey", 'k',false, (const char*) NULL, "HTTPS Keyfile");
  /*Parse Parameters*/
    CmdController->parseCmd(argc,argv);
	if (!CmdController->checkRequired()) {
		CmdController->printHelp();
		_httpexception[HTTPException::Critical] << "cmd parser not enough arguments given";
		throw _httpexception;
	}

	if (CmdController->getHTTPDCmdbyKey("help") && CmdController->getHTTPDCmdbyKey("help")->getFound()) {
		CmdController->printHelp();
		throw _httpexception[HTTPException::Note]<< "^-libhttppp default args-^";
	}

	/*get port from console paramter*/
	int port = 0;
    bool portset=false;
	if(CmdController->getHTTPDCmdbyKey("httpport")){
	    port = CmdController->getHTTPDCmdbyKey("httpport")->getValueInt();
        portset = CmdController->getHTTPDCmdbyKey("httpport")->getFound();
    }

	/*get httpaddress from console paramter*/
	const char *httpaddr = NULL;
	if (CmdController->getHTTPDCmdbyKey("httpaddr"))
		httpaddr = CmdController->getHTTPDCmdbyKey("httpaddr")->getValue();

	/*get max connections from console paramter*/
	int maxconnections = 0;
	if (CmdController->getHTTPDCmdbyKey("maxconnections"))
		maxconnections = CmdController->getHTTPDCmdbyKey("maxconnections")->getValueInt();

	/*get httpaddress from console paramter*/
	const char *sslcertpath = NULL;
	if (CmdController->getHTTPDCmdbyKey("httpscert"))
		sslcertpath = CmdController->getHTTPDCmdbyKey("httpscert")->getValue();

	/*get httpaddress from console paramter*/
	const char *sslkeypath = NULL;
	if (CmdController->getHTTPDCmdbyKey("httpskey"))
		sslkeypath = CmdController->getHTTPDCmdbyKey("httpskey")->getValue();

  try {
#ifndef Windows
	  if (portset == true)
		  _ServerSocket = new ServerSocket(httpaddr, port, maxconnections);
	  else
		  _ServerSocket = new ServerSocket(httpaddr, maxconnections);
#else
      _ServerSocket = new ServerSocket(httpaddr, port, maxconnections);
#endif

      if (!_ServerSocket) {
		  throw _httpexception;
	  }

	  if (sslcertpath && sslkeypath) {
		  _ServerSocket->createContext();
		  _ServerSocket->loadCertfile(sslcertpath);
		  _ServerSocket->loadKeyfile(sslkeypath);
	  }
  }catch (HTTPException &e) {
        throw e;
  }
}

libhttppp::ServerSocket *libhttppp::HttpD::getServerSocket(){
  return _ServerSocket;
}

libhttppp::HttpD::~HttpD(){
  delete _ServerSocket;
  delete CmdController;
}
<commit_msg>corrected formating code<commit_after>/*******************************************************************************
Copyright (c) 2014, Jan Koester jan.koester@gmx.net
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

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

#include "os/os.h"
#include "utils.h"
#include "httpd.h"

#define KTKEY 0
#define KTSKEY 1

libhttppp::HTTPDCmd::HTTPDCmd() {
	_Key = NULL;
	_SKey = '\0';
	_Value = NULL;
	_Help = NULL;
	_Found = false;
	_Required = false;
	_nextHTTPDCmd = NULL;
}

const char *libhttppp::HTTPDCmd::getKey() {
	return _Key;
}

const char libhttppp::HTTPDCmd::getShortkey() {
	return _SKey;
}

const char *libhttppp::HTTPDCmd::getValue() {
	return _Value;
}

size_t libhttppp::HTTPDCmd::getValueSize_t() {
	return atoi(_Value);
}

int libhttppp::HTTPDCmd::getValueInt() {
	return atoi(_Value);
}

const char *libhttppp::HTTPDCmd::getHelp() {
	return _Help;
}

bool libhttppp::HTTPDCmd::getFound() {
	return _Found;
}

bool libhttppp::HTTPDCmd::getRequired() {
	return _Required;
}

libhttppp::HTTPDCmd *libhttppp::HTTPDCmd::nextHTTPDCmd() {
	return _nextHTTPDCmd;
}

libhttppp::HTTPDCmd::~HTTPDCmd() {
	delete[] _Key;
	delete[] _Value;
	delete[] _Help;
	delete _nextHTTPDCmd;
}

libhttppp::HTTPDCmdController::HTTPDCmdController() {
	_firstHTTPDCmd = NULL;
	_lastHTTPDCmd = NULL;
}

void libhttppp::HTTPDCmdController::registerCmd(const char *key, const char skey,bool required, const char *defaultvalue, const char *help) {
	if (!key || !skey || !help) {
		_httpexception[HTTPException::Critical] << "cmd parser key,skey or help not set!";
		throw _httpexception;
	}
	/*if key exist overwriting options*/
	for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd=curhttpdcmd->nextHTTPDCmd()) {
		if (strncmp(curhttpdcmd->getKey(), key, getlen(curhttpdcmd->getKey())) == 0) {
			/*set new shortkey*/
			curhttpdcmd->_SKey = skey;
			/*set reqirement flag*/
			curhttpdcmd->_Required = required;
			/*set new value*/
			delete[] curhttpdcmd->_Value;
			curhttpdcmd->_Value = new char[getlen(defaultvalue)+1];
			scopy(defaultvalue, defaultvalue+getlen(defaultvalue),curhttpdcmd->_Value);
			curhttpdcmd->_Value[getlen(defaultvalue)] = '\0';
			/*set new help*/
			delete[] curhttpdcmd->_Help;
			curhttpdcmd->_Help = new char[getlen(help) + 1];
			scopy(help, help + getlen(help), curhttpdcmd->_Help);
			curhttpdcmd->_Help[getlen(help)] = '\0';
			return;
		}
	}
	/*create new key value store*/
	if (!_firstHTTPDCmd) {
		_firstHTTPDCmd = new HTTPDCmd;
		_lastHTTPDCmd = _firstHTTPDCmd;
	}
	else {
		_lastHTTPDCmd->_nextHTTPDCmd = new HTTPDCmd;
		_lastHTTPDCmd = _lastHTTPDCmd->_nextHTTPDCmd;
	}
	/*set new key*/
	_lastHTTPDCmd->_Key = new char[getlen(key) + 1];
	scopy(key,key+getlen(key),_lastHTTPDCmd->_Key);
	_lastHTTPDCmd->_Key[getlen(key)] = '\0';
	/*set new shortkey*/
	_lastHTTPDCmd->_SKey = skey;
	/*set reqirement flag*/
	_lastHTTPDCmd->_Required = required;
	/*set new value*/
	if (defaultvalue) {
		_lastHTTPDCmd->_Value = new char[getlen(defaultvalue) + 1];
		scopy(defaultvalue, defaultvalue + getlen(defaultvalue), _lastHTTPDCmd->_Value);
		_lastHTTPDCmd->_Value[getlen(defaultvalue)] = '\0';
	}
	/*set new help*/
	_lastHTTPDCmd->_Help = new char[getlen(help) + 1];
	scopy(help, help + getlen(help), _lastHTTPDCmd->_Help);
	_lastHTTPDCmd->_Help[getlen(help)] = '\0';

}

void libhttppp::HTTPDCmdController::registerCmd(const char *key, const char skey, bool required, size_t defaultvalue, const char *help) {
	char buf[255];
	itoa(defaultvalue,buf);
	registerCmd(key,skey,required,buf,help);
}

void libhttppp::HTTPDCmdController::registerCmd(const char *key, const char skey, bool required, int defaultvalue, const char *help) {
	char buf[255];
	itoa(defaultvalue,buf);
	registerCmd(key, skey, required, buf, help);
}

void libhttppp::HTTPDCmdController::parseCmd(int argc, char** argv){
	for (int args = 1; args < argc; args++) {
		int keytype = -1;
		if (argv[args][0]=='-' && argv[args][1] == '-') {
			keytype = KTKEY;
		}else if (argv[args][0] == '-'){
			keytype = KTSKEY;
		}else {
			break;
		}

		size_t kendpos = getlen(argv[args]);
		for (size_t cmdpos = 0; cmdpos < getlen(argv[args])+1; cmdpos++) {
			switch (argv[args][cmdpos]) {
			  case '=': {
				  kendpos = cmdpos;
			  };
			}
		}

		char *key = NULL;
		char skey = '0';
		if (keytype == KTKEY) {
			key = new char[kendpos-1];
			scopy(argv[args] +2, argv[args] +kendpos, key);
			key[kendpos - 2] = '\0';
		} else if (keytype == KTSKEY){
			skey = argv[args][1];
		}

		for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) {
			if (keytype == KTKEY) {
				if (strncmp(curhttpdcmd->getKey(), key, getlen(curhttpdcmd->getKey())) == 0) {
					curhttpdcmd->_Found = true;
					int valuesize = (getlen(argv[args]) - (kendpos+1));
					if (valuesize > 0) {
						delete[] curhttpdcmd->_Value;
						curhttpdcmd->_Value = new char[valuesize+1];
						scopy(argv[args]+(kendpos+1), argv[args] + getlen(argv[args]),curhttpdcmd->_Value);
						curhttpdcmd->_Value[valuesize] = '\0';
					}
				}
			} else if (keytype == KTSKEY) {
				if (curhttpdcmd->getShortkey()== skey) {
					curhttpdcmd->_Found = true;
					int valuesize = getlen(argv[++args]);
					if (valuesize > 0) {
						delete[] curhttpdcmd->_Value;
						curhttpdcmd->_Value = new char[valuesize + 1];
						scopy(argv[args], argv[args] + getlen(argv[args]), curhttpdcmd->_Value);
						curhttpdcmd->_Value[valuesize] = '\0';
					}
				}
			}
		}

		delete[] key;
	}
}

bool libhttppp::HTTPDCmdController::checkRequired() {
	for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) {
		if (curhttpdcmd->getRequired() && !curhttpdcmd->_Found) {
			return false;
		}
	}
	return true;
}

void libhttppp::HTTPDCmdController::printHelp() {
	for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) {
        Console con;
        con << "--" << curhttpdcmd->getKey()
            << " -" << curhttpdcmd->getShortkey()
            << " "  << curhttpdcmd->getHelp() << Console::endl;
	}
}

libhttppp::HTTPDCmd *libhttppp::HTTPDCmdController::getHTTPDCmdbyKey(const char *key) {
	for (HTTPDCmd *curhttpdcmd = _firstHTTPDCmd; curhttpdcmd; curhttpdcmd = curhttpdcmd->nextHTTPDCmd()) {
		if (strncmp(curhttpdcmd->getKey(), key, getlen(curhttpdcmd->getKey())) == 0) {
			return curhttpdcmd;
		}
	}
	return NULL;
}

libhttppp::HTTPDCmdController::~HTTPDCmdController() {
	delete _firstHTTPDCmd;
	_lastHTTPDCmd = NULL;
}

libhttppp::HttpD::HttpD(int argc, char** argv){
    CmdController= new HTTPDCmdController;
    /*Register Parameters*/
    CmdController->registerCmd("help", 'h', false, (const char*) NULL, "Helpmenu");
    CmdController->registerCmd("httpaddr",'a', true,(const char*) NULL,"Address to listen");
    CmdController->registerCmd("httpport", 'p', false, 8080, "Port to listen");
    CmdController->registerCmd("maxconnections", 'm',false, MAXDEFAULTCONN, "Max connections that can connect");
    CmdController->registerCmd("httpscert", 'c',false,(const char*) NULL, "HTTPS Certfile");
    CmdController->registerCmd("httpskey", 'k',false, (const char*) NULL, "HTTPS Keyfile");
    /*Parse Parameters*/
    CmdController->parseCmd(argc,argv);
    if (!CmdController->checkRequired()) {
        CmdController->printHelp();
        _httpexception[HTTPException::Critical] << "cmd parser not enough arguments given";
        throw _httpexception;
    }

    if (CmdController->getHTTPDCmdbyKey("help") && CmdController->getHTTPDCmdbyKey("help")->getFound()) {
        CmdController->printHelp();
        throw _httpexception[HTTPException::Note]<< "^-libhttppp default args-^";
    }

    /*get port from console paramter*/
    int port = 0;
    bool portset=false;
    if(CmdController->getHTTPDCmdbyKey("httpport")){
        port = CmdController->getHTTPDCmdbyKey("httpport")->getValueInt();
        portset = CmdController->getHTTPDCmdbyKey("httpport")->getFound();
    }

    /*get httpaddress from console paramter*/
    const char *httpaddr = NULL;
    if (CmdController->getHTTPDCmdbyKey("httpaddr"))
        httpaddr = CmdController->getHTTPDCmdbyKey("httpaddr")->getValue();

    /*get max connections from console paramter*/
    int maxconnections = 0;
    if (CmdController->getHTTPDCmdbyKey("maxconnections"))
        maxconnections = CmdController->getHTTPDCmdbyKey("maxconnections")->getValueInt();

    /*get httpaddress from console paramter*/
    const char *sslcertpath = NULL;
    if (CmdController->getHTTPDCmdbyKey("httpscert"))
        sslcertpath = CmdController->getHTTPDCmdbyKey("httpscert")->getValue();

    /*get httpaddress from console paramter*/
    const char *sslkeypath = NULL;
    if (CmdController->getHTTPDCmdbyKey("httpskey"))
        sslkeypath = CmdController->getHTTPDCmdbyKey("httpskey")->getValue();

    try {
        #ifndef Windows
        if (portset == true)
            _ServerSocket = new ServerSocket(httpaddr, port, maxconnections);
        else
            _ServerSocket = new ServerSocket(httpaddr, maxconnections);
        #else
        _ServerSocket = new ServerSocket(httpaddr, port, maxconnections);
        #endif

        if (sslcertpath && sslkeypath) {
            _ServerSocket->createContext();
            _ServerSocket->loadCertfile(sslcertpath);
            _ServerSocket->loadKeyfile(sslkeypath);
        }
    }catch (HTTPException &e) {
        throw e;
    }
}

libhttppp::ServerSocket *libhttppp::HttpD::getServerSocket(){
  return _ServerSocket;
}

libhttppp::HttpD::~HttpD(){
  delete _ServerSocket;
  delete CmdController;
}
<|endoftext|>


<commit_before>
#include <osgAnimation/RigTransformHardware>
#include <osgAnimation/RigTransformSoftware>
#include <osgAnimation/MorphTransformSoftware>
#include <osgDB/ObjectWrapper>
#include <osgDB/InputStream>
#include <osgDB/OutputStream>

namespace wrap_osgAnimationRigTransform{
  REGISTER_OBJECT_WRAPPER( osgAnimation_RigTransform,
                             NULL,
                             osgAnimation::RigTransform,
                             "osg::Object osgAnimation::RigTransform" ){}
}
namespace wrap_osgAnimationRigTransformSoftWare{
  REGISTER_OBJECT_WRAPPER( osgAnimation_RigTransformSoftware,
                             new osgAnimation::RigTransformSoftware,
                             osgAnimation::RigTransformSoftware,
                             "osg::Object osgAnimation::RigTransform  osgAnimation::RigTransformSoftware" ){}
}
namespace wrap_osgAnimationRigTransformHardWare{
  REGISTER_OBJECT_WRAPPER( osgAnimation_RigTransformHardware,
                             new osgAnimation::RigTransformHardware,
                             osgAnimation::RigTransformHardware,
                             "osg::Object osgAnimation::RigTransform osgAnimation::RigTransformHardware" ){}
}

namespace wrap_osgAnimationMorphTransform{
  REGISTER_OBJECT_WRAPPER( osgAnimation_MorphTransform,
                             NULL,
                             osgAnimation::MorphTransform,
                             "osg::Object osgAnimation::MorphTransform" ){}
}
namespace wrap_osgAnimationMorphTransformSoftWare{
  REGISTER_OBJECT_WRAPPER( osgAnimation_MorphTransformSoftware,
                             new osgAnimation::MorphTransformSoftware,
                             osgAnimation::MorphTransformSoftware,
                             "osg::Object osgAnimation::MorphTransform  osgAnimation::MorphTransformSoftware" ){}
}
<commit_msg>add MorphTransformHardware serializer<commit_after>
#include <osgAnimation/RigTransformHardware>
#include <osgAnimation/RigTransformSoftware>
#include <osgAnimation/MorphTransformSoftware>
#include <osgAnimation/MorphTransformHardware>
#include <osgDB/ObjectWrapper>
#include <osgDB/InputStream>
#include <osgDB/OutputStream>

namespace wrap_osgAnimationRigTransform{
  REGISTER_OBJECT_WRAPPER( osgAnimation_RigTransform,
                             NULL,
                             osgAnimation::RigTransform,
                             "osg::Object osgAnimation::RigTransform" ){}
}
namespace wrap_osgAnimationRigTransformSoftWare{
  REGISTER_OBJECT_WRAPPER( osgAnimation_RigTransformSoftware,
                             new osgAnimation::RigTransformSoftware,
                             osgAnimation::RigTransformSoftware,
                             "osg::Object osgAnimation::RigTransform  osgAnimation::RigTransformSoftware" ){}
}
namespace wrap_osgAnimationRigTransformHardWare{
  REGISTER_OBJECT_WRAPPER( osgAnimation_RigTransformHardware,
                             new osgAnimation::RigTransformHardware,
                             osgAnimation::RigTransformHardware,
                             "osg::Object osgAnimation::RigTransform osgAnimation::RigTransformHardware" ){}
}

namespace wrap_osgAnimationMorphTransform{
  REGISTER_OBJECT_WRAPPER( osgAnimation_MorphTransform,
                             NULL,
                             osgAnimation::MorphTransform,
                             "osg::Object osgAnimation::MorphTransform" ){}
}
namespace wrap_osgAnimationMorphTransformSoftWare{
  REGISTER_OBJECT_WRAPPER( osgAnimation_MorphTransformSoftware,
                             new osgAnimation::MorphTransformSoftware,
                             osgAnimation::MorphTransformSoftware,
                             "osg::Object osgAnimation::MorphTransform  osgAnimation::MorphTransformSoftware" ){}
}
namespace wrap_osgAnimationMorphTransformHardware{
  REGISTER_OBJECT_WRAPPER( osgAnimation_MorphTransformHardware,
                             new osgAnimation::MorphTransformHardware,
                             osgAnimation::MorphTransformHardware,
                             "osg::Object osgAnimation::MorphTransform  osgAnimation::MorphTransformHardware" ){}
}
<|endoftext|>


<commit_before>#include "editor/platform_interface.h"
#include "engine/hash_map.h"
#include "engine/mt/task.h"
#include "engine/profiler.h"
#include "engine/string.h"
#include "file_system_watcher.h"
#include <sys/inotify.h>
#include <unistd.h>

struct FileSystemWatcherImpl;

struct FileSystemWatcherTask : public Lumix::MT::Task
{
	FileSystemWatcherTask(const char* path,
        FileSystemWatcherImpl& _watcher,
		Lumix::IAllocator& _allocator)
		: Task(_allocator)
		, watcher(_watcher)
		, watched(_allocator)
		, allocator(_allocator)
	{
		Lumix::copyString(this->path, path);
		int len = Lumix::stringLength(path);
		if(len > 0 && path[len - 1] != '/') Lumix::catString(this->path, "/");
	}

	int task() override;

    Lumix::IAllocator& allocator;
    FileSystemWatcherImpl& watcher;
	volatile bool finished;
	char path[Lumix::MAX_PATH_LENGTH];
	Lumix::HashMap<int, Lumix::StaticString<Lumix::MAX_PATH_LENGTH> > watched;
	int fd;
};

struct FileSystemWatcherImpl : public FileSystemWatcher
{
	explicit FileSystemWatcherImpl(Lumix::IAllocator& _allocator)
		: allocator(_allocator)
		, task(nullptr)
	{
	}

    ~FileSystemWatcherImpl()
    {
        if (task)
        {
            task->destroy();
            LUMIX_DELETE(allocator, task);
        }
    }

    bool start(const char* path)
    {
        task = LUMIX_NEW(allocator, FileSystemWatcherTask)(path, *this, allocator);
        if (!task->create("FileSystemWatcherTask"))
        {
            LUMIX_DELETE(allocator, task);
            task = nullptr;
            return false;
        }
        return true;
    }

	virtual Lumix::Delegate<void(const char*)>& getCallback() { return callback; }

    FileSystemWatcherTask* task;
	Lumix::Delegate<void(const char*)> callback;
	Lumix::IAllocator& allocator;
};

FileSystemWatcher* FileSystemWatcher::create(const char* path, Lumix::IAllocator& allocator)
{
	auto* watcher = LUMIX_NEW(allocator, FileSystemWatcherImpl)(allocator);
	if(!watcher->start(path))
    {
        LUMIX_DELETE(allocator, watcher);
        return nullptr;
    }
	return watcher;
}

void FileSystemWatcher::destroy(FileSystemWatcher* watcher)
{
	if (!watcher) return;
	auto* impl_watcher = (FileSystemWatcherImpl*)watcher;
	LUMIX_DELETE(impl_watcher->allocator, impl_watcher);
}

static void addWatch(FileSystemWatcherTask& task, const char* path, int root_length)
{
	if (!PlatformInterface::dirExists(path)) return;

    int wd = inotify_add_watch(task.fd, path, IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO | IN_CLOSE_WRITE);
    task.watched.insert(wd, path + root_length);

    auto iter = PlatformInterface::createFileIterator(path, task.allocator);
    PlatformInterface::FileInfo info;
    while (PlatformInterface::getNextFile(iter, &info))
    {
        if (!info.is_directory) continue;
		if (Lumix::equalStrings(info.filename, ".")) continue;
		if (Lumix::equalStrings(info.filename, "..")) continue;

        Lumix::StaticString<Lumix::MAX_PATH_LENGTH> tmp(path, info.filename, "/");
        addWatch(task, tmp, root_length);
    }
    PlatformInterface::destroyFileIterator(iter);
}

static void getName(FileSystemWatcherTask& task, inotify_event* event, char* out, int max_size)
{
    auto iter = task.watched.find(event->wd);

    if (iter == task.watched.end())
    {
        Lumix::copyString(out, max_size, event->name);
        return;
    }

    Lumix::copyString(out, max_size, iter.value());
    Lumix::catString(out, max_size, event->name);
}

int FileSystemWatcherTask::task()
{
    fd = inotify_init();
    if (fd == -1) return false;

	int root_length = Lumix::stringLength(path);
    addWatch(*this, path, root_length);

    char buf[4096];
    while (!finished)
    {
        int r = read(fd, buf, sizeof(buf));
        if(r == -1) return 1;
        auto* event = (inotify_event*)buf;

        while ((char*)event < buf + r)
        {
            char tmp[Lumix::MAX_PATH_LENGTH];
            getName(*this, event, tmp, Lumix::lengthOf(tmp));
            if (event->mask & IN_CREATE) addWatch(*this, tmp, root_length);
            watcher.callback.invoke(tmp);

            event = (inotify_event*)((char*)event + sizeof(*event) + event->len);
        }
    }

    return close(fd) != -1;
}

<commit_msg>missing namespace<commit_after>#include "editor/platform_interface.h"
#include "engine/hash_map.h"
#include "engine/mt/task.h"
#include "engine/profiler.h"
#include "engine/string.h"
#include "file_system_watcher.h"
#include <sys/inotify.h>
#include <unistd.h>

namespace Lumix
{

struct FileSystemWatcherImpl;

struct FileSystemWatcherTask : public Lumix::MT::Task
{
	FileSystemWatcherTask(const char* path,
        FileSystemWatcherImpl& _watcher,
		Lumix::IAllocator& _allocator)
		: Task(_allocator)
		, watcher(_watcher)
		, watched(_allocator)
		, allocator(_allocator)
	{
		Lumix::copyString(this->path, path);
		int len = Lumix::stringLength(path);
		if(len > 0 && path[len - 1] != '/') Lumix::catString(this->path, "/");
	}

	int task() override;

    Lumix::IAllocator& allocator;
    FileSystemWatcherImpl& watcher;
	volatile bool finished;
	char path[Lumix::MAX_PATH_LENGTH];
	Lumix::HashMap<int, Lumix::StaticString<Lumix::MAX_PATH_LENGTH> > watched;
	int fd;
};

struct FileSystemWatcherImpl : public FileSystemWatcher
{
	explicit FileSystemWatcherImpl(Lumix::IAllocator& _allocator)
		: allocator(_allocator)
		, task(nullptr)
	{
	}

    ~FileSystemWatcherImpl()
    {
        if (task)
        {
            task->destroy();
            LUMIX_DELETE(allocator, task);
        }
    }

    bool start(const char* path)
    {
        task = LUMIX_NEW(allocator, FileSystemWatcherTask)(path, *this, allocator);
        if (!task->create("FileSystemWatcherTask"))
        {
            LUMIX_DELETE(allocator, task);
            task = nullptr;
            return false;
        }
        return true;
    }

	virtual Lumix::Delegate<void(const char*)>& getCallback() { return callback; }

    FileSystemWatcherTask* task;
	Lumix::Delegate<void(const char*)> callback;
	Lumix::IAllocator& allocator;
};

FileSystemWatcher* FileSystemWatcher::create(const char* path, Lumix::IAllocator& allocator)
{
	auto* watcher = LUMIX_NEW(allocator, FileSystemWatcherImpl)(allocator);
	if(!watcher->start(path))
    {
        LUMIX_DELETE(allocator, watcher);
        return nullptr;
    }
	return watcher;
}

void FileSystemWatcher::destroy(FileSystemWatcher* watcher)
{
	if (!watcher) return;
	auto* impl_watcher = (FileSystemWatcherImpl*)watcher;
	LUMIX_DELETE(impl_watcher->allocator, impl_watcher);
}

static void addWatch(FileSystemWatcherTask& task, const char* path, int root_length)
{
	if (!PlatformInterface::dirExists(path)) return;

    int wd = inotify_add_watch(task.fd, path, IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO | IN_CLOSE_WRITE);
    task.watched.insert(wd, path + root_length);

    auto iter = PlatformInterface::createFileIterator(path, task.allocator);
    PlatformInterface::FileInfo info;
    while (PlatformInterface::getNextFile(iter, &info))
    {
        if (!info.is_directory) continue;
		if (Lumix::equalStrings(info.filename, ".")) continue;
		if (Lumix::equalStrings(info.filename, "..")) continue;

        Lumix::StaticString<Lumix::MAX_PATH_LENGTH> tmp(path, info.filename, "/");
        addWatch(task, tmp, root_length);
    }
    PlatformInterface::destroyFileIterator(iter);
}

static void getName(FileSystemWatcherTask& task, inotify_event* event, char* out, int max_size)
{
    auto iter = task.watched.find(event->wd);

    if (iter == task.watched.end())
    {
        Lumix::copyString(out, max_size, event->name);
        return;
    }

    Lumix::copyString(out, max_size, iter.value());
    Lumix::catString(out, max_size, event->name);
}

int FileSystemWatcherTask::task()
{
    fd = inotify_init();
    if (fd == -1) return false;

	int root_length = Lumix::stringLength(path);
    addWatch(*this, path, root_length);

    char buf[4096];
    while (!finished)
    {
        int r = read(fd, buf, sizeof(buf));
        if(r == -1) return 1;
        auto* event = (inotify_event*)buf;

        while ((char*)event < buf + r)
        {
            char tmp[Lumix::MAX_PATH_LENGTH];
            getName(*this, event, tmp, Lumix::lengthOf(tmp));
            if (event->mask & IN_CREATE) addWatch(*this, tmp, root_length);
            watcher.callback.invoke(tmp);

            event = (inotify_event*)((char*)event + sizeof(*event) + event->len);
        }
    }

    return close(fd) != -1;
}

} // namespace Lumix<|endoftext|>


<commit_before>// Copyright 2019 Google LLC
//
// 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 "google/cloud/spanner/client.h"
#include "google/cloud/spanner/database_admin_client.h"
#include "google/cloud/internal/getenv.h"
#include "google/cloud/internal/random.h"
#include <sstream>
#include <tuple>
#include <utility>

namespace {

std::string RandomDatabaseName(
    google::cloud::internal::DefaultPRNG& generator) {
  // A database ID must be between 2 and 30 characters, fitting the regular
  // expression `[a-z][a-z0-9_\-]*[a-z0-9]`
  int max_size = 30;
  std::string const prefix = "db-";
  auto size = static_cast<int>(max_size - 1 - prefix.size());
  return prefix +
         google::cloud::internal::Sample(
             generator, size, "abcdefghijlkmnopqrstuvwxyz012345689_-") +
         google::cloud::internal::Sample(generator, 1,
                                         "abcdefghijlkmnopqrstuvwxyz");
}

void CreateDatabase(std::vector<std::string> const& argv) {
  if (argv.size() != 3) {
    throw std::runtime_error(
        "create-database <project-id> <instance-id> <database-id>");
  }

  //! [create-database] [START spanner_create_database]
  using google::cloud::future;
  using google::cloud::StatusOr;
  [](std::string const& project_id, std::string const& instance_id,
     std::string const& database_id) {
    google::cloud::spanner::DatabaseAdminClient client;
    future<StatusOr<google::spanner::admin::database::v1::Database>> future =
        client.CreateDatabase(project_id, instance_id, database_id,
                              {R"""(
                        CREATE TABLE Singers (
                                SingerId   INT64 NOT NULL,
                                FirstName  STRING(1024),
                                LastName   STRING(1024),
                                SingerInfo BYTES(MAX)
                        ) PRIMARY KEY (SingerId))""",
                               R"""(CREATE TABLE Albums (
                                SingerId     INT64 NOT NULL,
                                AlbumId      INT64 NOT NULL,
                                AlbumTitle   STRING(MAX)
                        ) PRIMARY KEY (SingerId, AlbumId),
                        INTERLEAVE IN PARENT Singers ON DELETE CASCADE)"""});
    StatusOr<google::spanner::admin::database::v1::Database> db = future.get();
    if (!db) {
      throw std::runtime_error(db.status().message());
    }
    std::cout << "Created database [" << database_id << "]\n";
  }
  //! [create-database] [END spanner_create_database]
  (argv[0], argv[1], argv[2]);
}

void AddColumn(std::vector<std::string> const& argv) {
  if (argv.size() != 3) {
    throw std::runtime_error(
        "add-column <project-id> <instance-id> <database-id>");
  }

  //! [update-database] [START spanner_add_column]
  using google::cloud::future;
  using google::cloud::StatusOr;
  [](std::string const& project_id, std::string const& instance_id,
     std::string const& database_id) {
    google::cloud::spanner::DatabaseAdminClient client;
    future<StatusOr<
        google::spanner::admin::database::v1::UpdateDatabaseDdlMetadata>>
        future = client.UpdateDatabase(
            project_id, instance_id, database_id,
            {"ALTER TABLE Albums ADD COLUMN MarketingBudget INT64"});
    StatusOr<google::spanner::admin::database::v1::UpdateDatabaseDdlMetadata>
        metadata = future.get();
    if (!metadata) {
      throw std::runtime_error(metadata.status().message());
    }
    std::cout << "Added MarketingBudget column\n";
  }
  //! [update-database] [END spanner_add_column]
  (argv[0], argv[1], argv[2]);
}

void QueryWithStruct(std::vector<std::string> const& argv) {
  if (argv.size() != 3) {
    throw std::runtime_error(
        "query-with-struct <project-id> <instance-id> <database-id>");
  }
  // TODO(#188): Add querying part once data client is ready.
  // [START spanner_create_struct_with_data]
  auto singer_info = std::make_tuple(std::make_pair("FirstName", "Elena"),
                                     std::make_pair("LastName", "Campbell"));
  // [END spanner_create_struct_with_data]
  std::cout << "Struct created with the following data:\n"
            << std::get<0>(singer_info).first << ":"
            << std::get<0>(singer_info).second << "\n"
            << std::get<1>(singer_info).first << ":"
            << std::get<1>(singer_info).second << "\n";
}

void DropDatabase(std::vector<std::string> const& argv) {
  if (argv.size() != 3) {
    throw std::runtime_error(
        "drop-database <project-id> <instance-id> <database-id>");
  }

  //! [drop-database] [START spanner_drop_database]
  [](std::string const& project_id, std::string const& instance_id,
     std::string const& database_id) {
    google::cloud::spanner::DatabaseAdminClient client;
    google::cloud::Status status =
        client.DropDatabase(project_id, instance_id, database_id);
    if (!status.ok()) {
      throw std::runtime_error(status.message());
    }
    std::cout << "Database " << database_id << " successfully dropped\n";
  }
  //! [drop-database] [END spanner_drop_database]
  (argv[0], argv[1], argv[2]);
}

void DmlStandardInsert(std::vector<std::string> const& argv) {
  if (argv.size() != 3) {
    throw std::runtime_error(
        "dml-standard-insert <project-id> <instance-id> <database-id>");
  }

  // TODO(#377) - cache the client across sample functions.
  namespace gcs = google::cloud::spanner;
  gcs::Client client(
      gcs::MakeConnection(gcs::MakeDatabaseName(argv[0], argv[1], argv[2])));

  //! [START spanner_dml_standard_insert]
  namespace gcs = google::cloud::spanner;
  [](gcs::Client client) {
    auto commit_result = gcs::RunTransaction(
        std::move(client), gcs::Transaction::ReadWriteOptions{},
        [](gcs::Client client, gcs::Transaction txn) {
          client.ExecuteSql(
              std::move(txn),
              gcs::SqlStatement(
                  "INSERT INTO Singers (SingerId, FirstName, LastName)"
                  "  VALUES (10, 'Virginia', 'Watson')",
                  {}));
          return gcs::TransactionAction{gcs::TransactionAction::kCommit, {}};
        });
    if (!commit_result) {
      throw std::runtime_error(commit_result.status().message());
    }
    std::cout << "Insert was successful\n";
  }
  //! [END spanner_dml_standard_insert]
  (std::move(client));
}

int RunOneCommand(std::vector<std::string> argv) {
  using CommandType = std::function<void(std::vector<std::string> const&)>;

  std::map<std::string, CommandType> commands = {
      {"create-database", &CreateDatabase},
      {"add-column", &AddColumn},
      {"query-with-struct", &QueryWithStruct},
      {"drop-database", &DropDatabase},
      {"dml-standard-insert", &DmlStandardInsert},
  };

  static std::string usage_msg = [&argv, &commands] {
    auto last_slash = std::string(argv[0]).find_last_of("/\\");
    auto program = argv[0].substr(last_slash + 1);
    std::string usage;
    usage += "Usage: ";
    usage += program;
    usage += " <command> [arguments]\n\n";
    usage += "Commands:\n";
    for (auto&& kv : commands) {
      try {
        kv.second({});
      } catch (std::exception const& ex) {
        usage += "    ";
        usage += ex.what();
        usage += "\n";
      }
    }
    return usage;
  }();

  if (argv.size() < 2) {
    std::cerr << "Missing command argument\n" << usage_msg << "\n";
    return 1;
  }
  std::string command_name = argv[1];
  argv.erase(argv.begin());  // remove the program name from the list.
  argv.erase(argv.begin());  // remove the command name from the list.

  auto command = commands.find(command_name);
  if (commands.end() == command) {
    std::cerr << "Unknown command " << command_name << "\n"
              << usage_msg << "\n";
    return 1;
  }

  // Run the command.
  command->second(argv);
  return 0;
}

void RunAll() {
  auto project_id =
      google::cloud::internal::GetEnv("GOOGLE_CLOUD_PROJECT").value_or("");
  auto instance_id =
      google::cloud::internal::GetEnv("GOOGLE_CLOUD_CPP_SPANNER_INSTANCE")
          .value_or("");

  if (project_id.empty()) {
    throw std::runtime_error("GOOGLE_CLOUD_PROJECT is not set or is empty");
  }
  if (instance_id.empty()) {
    throw std::runtime_error(
        "GOOGLE_CLOUD_CPP_SPANNER_INSTANCE is not set or is empty");
  }
  auto generator = google::cloud::internal::MakeDefaultPRNG();
  std::string database_id = RandomDatabaseName(generator);

  RunOneCommand({"", "create-database", project_id, instance_id, database_id});
  RunOneCommand({"", "add-column", project_id, instance_id, database_id});
  RunOneCommand(
      {"", "query-with-struct", project_id, instance_id, database_id});

  RunOneCommand(
      {"", "dml-standard-insert", project_id, instance_id, database_id});

  RunOneCommand({"", "drop-database", project_id, instance_id, database_id});
}

bool AutoRun() {
  return google::cloud::internal::GetEnv("GOOGLE_CLOUD_CPP_AUTO_RUN_EXAMPLES")
             .value_or("") == "yes";
}

}  // namespace

int main(int ac, char* av[]) try {
  if (AutoRun()) {
    RunAll();
    return 0;
  }

  return RunOneCommand({av, av + ac});
} catch (std::exception const& ex) {
  std::cerr << ex.what() << "\n";
  return 1;
}
<commit_msg>feat: Implement spanner_insert_data sample. (#381)<commit_after>// Copyright 2019 Google LLC
//
// 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 "google/cloud/spanner/client.h"
#include "google/cloud/spanner/database_admin_client.h"
#include "google/cloud/internal/getenv.h"
#include "google/cloud/internal/random.h"
#include <sstream>
#include <tuple>
#include <utility>

namespace {

std::string RandomDatabaseName(
    google::cloud::internal::DefaultPRNG& generator) {
  // A database ID must be between 2 and 30 characters, fitting the regular
  // expression `[a-z][a-z0-9_\-]*[a-z0-9]`
  int max_size = 30;
  std::string const prefix = "db-";
  auto size = static_cast<int>(max_size - 1 - prefix.size());
  return prefix +
         google::cloud::internal::Sample(
             generator, size, "abcdefghijlkmnopqrstuvwxyz012345689_-") +
         google::cloud::internal::Sample(generator, 1,
                                         "abcdefghijlkmnopqrstuvwxyz");
}

void CreateDatabase(std::vector<std::string> const& argv) {
  if (argv.size() != 3) {
    throw std::runtime_error(
        "create-database <project-id> <instance-id> <database-id>");
  }

  //! [create-database] [START spanner_create_database]
  using google::cloud::future;
  using google::cloud::StatusOr;
  [](std::string const& project_id, std::string const& instance_id,
     std::string const& database_id) {
    google::cloud::spanner::DatabaseAdminClient client;
    future<StatusOr<google::spanner::admin::database::v1::Database>> future =
        client.CreateDatabase(project_id, instance_id, database_id,
                              {R"""(
                        CREATE TABLE Singers (
                                SingerId   INT64 NOT NULL,
                                FirstName  STRING(1024),
                                LastName   STRING(1024),
                                SingerInfo BYTES(MAX)
                        ) PRIMARY KEY (SingerId))""",
                               R"""(CREATE TABLE Albums (
                                SingerId     INT64 NOT NULL,
                                AlbumId      INT64 NOT NULL,
                                AlbumTitle   STRING(MAX)
                        ) PRIMARY KEY (SingerId, AlbumId),
                        INTERLEAVE IN PARENT Singers ON DELETE CASCADE)"""});
    StatusOr<google::spanner::admin::database::v1::Database> db = future.get();
    if (!db) {
      throw std::runtime_error(db.status().message());
    }
    std::cout << "Created database [" << database_id << "]\n";
  }
  //! [create-database] [END spanner_create_database]
  (argv[0], argv[1], argv[2]);
}

void AddColumn(std::vector<std::string> const& argv) {
  if (argv.size() != 3) {
    throw std::runtime_error(
        "add-column <project-id> <instance-id> <database-id>");
  }

  //! [update-database] [START spanner_add_column]
  using google::cloud::future;
  using google::cloud::StatusOr;
  [](std::string const& project_id, std::string const& instance_id,
     std::string const& database_id) {
    google::cloud::spanner::DatabaseAdminClient client;
    future<StatusOr<
        google::spanner::admin::database::v1::UpdateDatabaseDdlMetadata>>
        future = client.UpdateDatabase(
            project_id, instance_id, database_id,
            {"ALTER TABLE Albums ADD COLUMN MarketingBudget INT64"});
    StatusOr<google::spanner::admin::database::v1::UpdateDatabaseDdlMetadata>
        metadata = future.get();
    if (!metadata) {
      throw std::runtime_error(metadata.status().message());
    }
    std::cout << "Added MarketingBudget column\n";
  }
  //! [update-database] [END spanner_add_column]
  (argv[0], argv[1], argv[2]);
}

void QueryWithStruct(std::vector<std::string> const& argv) {
  if (argv.size() != 3) {
    throw std::runtime_error(
        "query-with-struct <project-id> <instance-id> <database-id>");
  }
  // TODO(#188): Add querying part once data client is ready.
  // [START spanner_create_struct_with_data]
  auto singer_info = std::make_tuple(std::make_pair("FirstName", "Elena"),
                                     std::make_pair("LastName", "Campbell"));
  // [END spanner_create_struct_with_data]
  std::cout << "Struct created with the following data:\n"
            << std::get<0>(singer_info).first << ":"
            << std::get<0>(singer_info).second << "\n"
            << std::get<1>(singer_info).first << ":"
            << std::get<1>(singer_info).second << "\n";
}

void DropDatabase(std::vector<std::string> const& argv) {
  if (argv.size() != 3) {
    throw std::runtime_error(
        "drop-database <project-id> <instance-id> <database-id>");
  }

  //! [drop-database] [START spanner_drop_database]
  [](std::string const& project_id, std::string const& instance_id,
     std::string const& database_id) {
    google::cloud::spanner::DatabaseAdminClient client;
    google::cloud::Status status =
        client.DropDatabase(project_id, instance_id, database_id);
    if (!status.ok()) {
      throw std::runtime_error(status.message());
    }
    std::cout << "Database " << database_id << " successfully dropped\n";
  }
  //! [drop-database] [END spanner_drop_database]
  (argv[0], argv[1], argv[2]);
}

void InsertData(std::vector<std::string> const& argv) {
  if (argv.size() != 3) {
    throw std::runtime_error(
        "insert-data <project-id> <instance-id> <database-id>");
  }

  // TODO(#377) - cache the client across sample functions.
  namespace spanner = google::cloud::spanner;
  spanner::Client client(spanner::MakeConnection(
      spanner::MakeDatabaseName(argv[0], argv[1], argv[2])));

  //! [START spanner_insert_data]
  namespace spanner = google::cloud::spanner;
  [](spanner::Client client) {
    auto insert_singers = spanner::InsertMutationBuilder(
                              "Singers", {"SingerId", "FirstName", "LastName"})
                              .EmplaceRow(1, "Marc", "Richards")
                              .EmplaceRow(2, "Catalina", "Smith")
                              .EmplaceRow(3, "Alice", "Trentor")
                              .EmplaceRow(4, "Lea", "Martin")
                              .EmplaceRow(5, "David", "Lomond")
                              .Build();

    auto insert_albums = spanner::InsertMutationBuilder(
                             "Albums", {"SingerId", "AlbumId", "AlbumTitle"})
                             .EmplaceRow(1, 1, "Total Junk")
                             .EmplaceRow(1, 2, "Go, Go, Go")
                             .EmplaceRow(2, 1, "Green")
                             .EmplaceRow(2, 2, "Forever Hold Your Peace")
                             .EmplaceRow(2, 3, "Terrified")
                             .Build();

    auto commit_result =
        client.Commit(spanner::MakeReadWriteTransaction(),
                      {std::move(insert_singers), std::move(insert_albums)});
    if (!commit_result) {
      throw std::runtime_error(commit_result.status().message());
    }
    std::cout << "Insert was successful\n";
  }
  //! [END spanner_insert_data]
  (std::move(client));
}

void DmlStandardInsert(std::vector<std::string> const& argv) {
  if (argv.size() != 3) {
    throw std::runtime_error(
        "dml-standard-insert <project-id> <instance-id> <database-id>");
  }

  // TODO(#377) - cache the client across sample functions.
  namespace spanner = google::cloud::spanner;
  spanner::Client client(spanner::MakeConnection(
      spanner::MakeDatabaseName(argv[0], argv[1], argv[2])));

  //! [START spanner_dml_standard_insert]
  namespace spanner = google::cloud::spanner;
  [](spanner::Client client) {
    auto commit_result = spanner::RunTransaction(
        std::move(client), spanner::Transaction::ReadWriteOptions{},
        [](spanner::Client client, spanner::Transaction txn) {
          client.ExecuteSql(
              std::move(txn),
              spanner::SqlStatement(
                  "INSERT INTO Singers (SingerId, FirstName, LastName)"
                  "  VALUES (10, 'Virginia', 'Watson')",
                  {}));
          return spanner::TransactionAction{spanner::TransactionAction::kCommit,
                                            {}};
        });
    if (!commit_result) {
      throw std::runtime_error(commit_result.status().message());
    }
    std::cout << "Insert was successful\n";
  }
  //! [END spanner_dml_standard_insert]
  (std::move(client));
}

int RunOneCommand(std::vector<std::string> argv) {
  using CommandType = std::function<void(std::vector<std::string> const&)>;

  std::map<std::string, CommandType> commands = {
      {"create-database", &CreateDatabase},
      {"add-column", &AddColumn},
      {"query-with-struct", &QueryWithStruct},
      {"drop-database", &DropDatabase},
      {"insert-data", &InsertData},
      {"dml-standard-insert", &DmlStandardInsert},
  };

  static std::string usage_msg = [&argv, &commands] {
    auto last_slash = std::string(argv[0]).find_last_of("/\\");
    auto program = argv[0].substr(last_slash + 1);
    std::string usage;
    usage += "Usage: ";
    usage += program;
    usage += " <command> [arguments]\n\n";
    usage += "Commands:\n";
    for (auto&& kv : commands) {
      try {
        kv.second({});
      } catch (std::exception const& ex) {
        usage += "    ";
        usage += ex.what();
        usage += "\n";
      }
    }
    return usage;
  }();

  if (argv.size() < 2) {
    std::cerr << "Missing command argument\n" << usage_msg << "\n";
    return 1;
  }
  std::string command_name = argv[1];
  argv.erase(argv.begin());  // remove the program name from the list.
  argv.erase(argv.begin());  // remove the command name from the list.

  auto command = commands.find(command_name);
  if (commands.end() == command) {
    std::cerr << "Unknown command " << command_name << "\n"
              << usage_msg << "\n";
    return 1;
  }

  // Run the command.
  command->second(argv);
  return 0;
}

void RunAll() {
  auto project_id =
      google::cloud::internal::GetEnv("GOOGLE_CLOUD_PROJECT").value_or("");
  auto instance_id =
      google::cloud::internal::GetEnv("GOOGLE_CLOUD_CPP_SPANNER_INSTANCE")
          .value_or("");

  if (project_id.empty()) {
    throw std::runtime_error("GOOGLE_CLOUD_PROJECT is not set or is empty");
  }
  if (instance_id.empty()) {
    throw std::runtime_error(
        "GOOGLE_CLOUD_CPP_SPANNER_INSTANCE is not set or is empty");
  }
  auto generator = google::cloud::internal::MakeDefaultPRNG();
  std::string database_id = RandomDatabaseName(generator);

  RunOneCommand({"", "create-database", project_id, instance_id, database_id});
  RunOneCommand({"", "add-column", project_id, instance_id, database_id});
  RunOneCommand({"", "insert-data", project_id, instance_id, database_id});
  RunOneCommand(
      {"", "query-with-struct", project_id, instance_id, database_id});

  RunOneCommand(
      {"", "dml-standard-insert", project_id, instance_id, database_id});

  RunOneCommand({"", "drop-database", project_id, instance_id, database_id});
}

bool AutoRun() {
  return google::cloud::internal::GetEnv("GOOGLE_CLOUD_CPP_AUTO_RUN_EXAMPLES")
             .value_or("") == "yes";
}

}  // namespace

int main(int ac, char* av[]) try {
  if (AutoRun()) {
    RunAll();
    return 0;
  }

  return RunOneCommand({av, av + ac});
} catch (std::exception const& ex) {
  std::cerr << ex.what() << "\n";
  return 1;
}
<|endoftext|>


<commit_before>#include <configure/bind.hpp>

#include <configure/Rule.hpp>
#include <configure/lua/State.hpp>
#include <configure/lua/Type.hpp>

#include <boost/filesystem/path.hpp>

namespace fs = boost::filesystem;

namespace configure {

	static int Rule_new(lua_State* state)
	{
		lua::Converter<Rule>::push(state);
		return 1;
	}
	static int Rule_tostring(lua_State* state)
	{
		std::string res = "<Rule ";
		Rule& rule = lua::Converter<Rule>::extract(state, 1);
		for (auto&& node: rule.sources())
		{
			lua::Converter<NodePtr>::push(state, node);
			res.push_back(' ');
			res.append(luaL_tolstring(state, -1, nullptr));
			lua_pop(state, 1);
		}
		if (rule.sources().empty())
			res.append(" ()");
		res.append(" ->");

		for (auto&& node: rule.targets())
		{
			lua::Converter<NodePtr>::push(state, node);
			res.push_back(' ');
			res.append(luaL_tolstring(state, -1, nullptr));
			lua_pop(state, 1);
		}
		if (rule.targets().empty())
			res.append(" ()");

		res.push_back(':');
		for (auto&& cmd: rule.shell_commands())
		{
			lua::Converter<ShellCommand>::push(state, cmd);
			res.push_back(' ');
			res.append(luaL_tolstring(state, -1, nullptr));
			lua_pop(state, 1);
		}
		res.push_back('>');
		lua_pushstring(state, res.c_str());
		return 1;
	}

	static int Rule_add_source(lua_State* state)
	{
		Rule& self = lua::Converter<Rule>::extract(state, 1);
		if (NodePtr* n = lua::Converter<NodePtr>::extract_ptr(state, 2))
			self.add_source(*n);
		else
			CONFIGURE_THROW(
				error::LuaError(
					"Expected source node, got '" + std::string(luaL_tolstring(state, 2, nullptr)) + "'"
				)
			);
		lua_pushvalue(state, 1);
		return 1;
	}

	static int Rule_add_sources(lua_State* state)
	{
		Rule& self = lua::Converter<Rule>::extract(state, 1);
		if (!lua_istable(state, 2))
			CONFIGURE_THROW(
				error::LuaError(
					"Expected a table, got '" + std::string(luaL_tolstring(state, 2, nullptr)) + "'"
				)
			);
		for (int i = 1, len = lua_rawlen(state, 2); i <= len; ++i)
		{
			lua_rawgeti(state, 2, i);
			if (NodePtr* n = lua::Converter<NodePtr>::extract_ptr(state, -1))
				self.add_source(*n);
			else
				CONFIGURE_THROW(
					error::LuaError(
						"Expected source node, got '" + std::string(luaL_tolstring(state, -1, nullptr))
						+ "' at index " + std::to_string(i)
					)
				);
			lua_remove(state, -1);
		}
		lua_pushvalue(state, 1);
		return 1;
	}

	static int Rule_add_target(lua_State* state)
	{
		Rule& self = lua::Converter<Rule>::extract(state, 1);
		if (NodePtr* n = lua::Converter<NodePtr>::extract_ptr(state, 2))
			self.add_target(*n);
		else
			throw std::runtime_error("Cannot extract a target node");
		lua_pushvalue(state, 1);
		return 1;
	}

	static int Rule_add_shell_command(lua_State* state)
	{
		Rule& self = lua::Converter<Rule>::extract(state, 1);
		if (ShellCommand* n = lua::Converter<ShellCommand>::extract_ptr(state, 2))
			self.add_shell_command(*n);
		else
			throw std::runtime_error("Cannot extract a shell command");
		lua_pushvalue(state, 1);
		return 1;
	}

	void bind_rule(lua::State& state)
	{
		/// @classmod Rule
		lua::Type<Rule>(state, "Rule")
			/// Create a new rule
			// @function Rule:new
			// @treturn New instance
			.def("new", &Rule_new)
			.def("__tostring", &Rule_tostring)

			/// Add a source @{Node}
			// @function Rule:add_source
			// @tparam Node source
			// @treturn Rule self instance
			.def("add_source", &Rule_add_source)

			/// Add source @{Node}s
			// @function Rule:add_sources
			// @tparam table sources List of source nodes
			// @treturn Rule self instance
			.def("add_sources", &Rule_add_sources)

			/// Add a target @{Node}
			// @function Rule:add_target
			// @tparam Node target
			// @treturn Rule self instance
			.def("add_target", &Rule_add_target)

			/// Add a @{ShellCommand}
			// @function Rule:add_shell_command
			// @tparam ShellCommand cmd the shell command
			// @treturn Rule self instance
			.def("add_shell_command", &Rule_add_shell_command)
		;
	}

}
<commit_msg>Move shell command instance in rule binding.<commit_after>#include <configure/bind.hpp>

#include <configure/Rule.hpp>
#include <configure/lua/State.hpp>
#include <configure/lua/Type.hpp>

#include <boost/filesystem/path.hpp>

namespace fs = boost::filesystem;

namespace configure {

	static int Rule_new(lua_State* state)
	{
		lua::Converter<Rule>::push(state);
		return 1;
	}
	static int Rule_tostring(lua_State* state)
	{
		std::string res = "<Rule ";
		Rule& rule = lua::Converter<Rule>::extract(state, 1);
		for (auto&& node: rule.sources())
		{
			lua::Converter<NodePtr>::push(state, node);
			res.push_back(' ');
			res.append(luaL_tolstring(state, -1, nullptr));
			lua_pop(state, 1);
		}
		if (rule.sources().empty())
			res.append(" ()");
		res.append(" ->");

		for (auto&& node: rule.targets())
		{
			lua::Converter<NodePtr>::push(state, node);
			res.push_back(' ');
			res.append(luaL_tolstring(state, -1, nullptr));
			lua_pop(state, 1);
		}
		if (rule.targets().empty())
			res.append(" ()");

		res.push_back(':');
		for (auto&& cmd: rule.shell_commands())
		{
			lua::Converter<ShellCommand>::push(state, cmd);
			res.push_back(' ');
			res.append(luaL_tolstring(state, -1, nullptr));
			lua_pop(state, 1);
		}
		res.push_back('>');
		lua_pushstring(state, res.c_str());
		return 1;
	}

	static int Rule_add_source(lua_State* state)
	{
		Rule& self = lua::Converter<Rule>::extract(state, 1);
		if (NodePtr* n = lua::Converter<NodePtr>::extract_ptr(state, 2))
			self.add_source(*n);
		else
			CONFIGURE_THROW(
				error::LuaError(
					"Expected source node, got '" + std::string(luaL_tolstring(state, 2, nullptr)) + "'"
				)
			);
		lua_pushvalue(state, 1);
		return 1;
	}

	static int Rule_add_sources(lua_State* state)
	{
		Rule& self = lua::Converter<Rule>::extract(state, 1);
		if (!lua_istable(state, 2))
			CONFIGURE_THROW(
				error::LuaError(
					"Expected a table, got '" + std::string(luaL_tolstring(state, 2, nullptr)) + "'"
				)
			);
		for (int i = 1, len = lua_rawlen(state, 2); i <= len; ++i)
		{
			lua_rawgeti(state, 2, i);
			if (NodePtr* n = lua::Converter<NodePtr>::extract_ptr(state, -1))
				self.add_source(*n);
			else
				CONFIGURE_THROW(
					error::LuaError(
						"Expected source node, got '" + std::string(luaL_tolstring(state, -1, nullptr))
						+ "' at index " + std::to_string(i)
					)
				);
			lua_remove(state, -1);
		}
		lua_pushvalue(state, 1);
		return 1;
	}

	static int Rule_add_target(lua_State* state)
	{
		Rule& self = lua::Converter<Rule>::extract(state, 1);
		if (NodePtr* n = lua::Converter<NodePtr>::extract_ptr(state, 2))
			self.add_target(*n);
		else
			throw std::runtime_error("Cannot extract a target node");
		lua_pushvalue(state, 1);
		return 1;
	}

	static int Rule_add_shell_command(lua_State* state)
	{
		Rule& self = lua::Converter<Rule>::extract(state, 1);
		if (ShellCommand* n = lua::Converter<ShellCommand>::extract_ptr(state, 2))
			self.add_shell_command(std::move(*n));
		else
			throw std::runtime_error("Cannot extract a shell command");
		lua_pushvalue(state, 1);
		return 1;
	}

	void bind_rule(lua::State& state)
	{
		/// @classmod Rule
		lua::Type<Rule>(state, "Rule")
			/// Create a new rule
			// @function Rule:new
			// @treturn New instance
			.def("new", &Rule_new)
			.def("__tostring", &Rule_tostring)

			/// Add a source @{Node}
			// @function Rule:add_source
			// @tparam Node source
			// @treturn Rule self instance
			.def("add_source", &Rule_add_source)

			/// Add source @{Node}s
			// @function Rule:add_sources
			// @tparam table sources List of source nodes
			// @treturn Rule self instance
			.def("add_sources", &Rule_add_sources)

			/// Add a target @{Node}
			// @function Rule:add_target
			// @tparam Node target
			// @treturn Rule self instance
			.def("add_target", &Rule_add_target)

			/// Add a @{ShellCommand}
			// @function Rule:add_shell_command
			// @tparam ShellCommand cmd the shell command
			// @treturn Rule self instance
			.def("add_shell_command", &Rule_add_shell_command)
		;
	}

}
<|endoftext|>


<commit_before>// graph500/grappa/
// XXX shouldn't have to include this first: common.h and oned_csr.h have cyclic dependency
#include "../graph500/grappa/common.h"
#include "../graph500/grappa/oned_csr.h"
#include "../graph500/grappa/graph.hpp"

#include <Grappa.hpp>

#include <iostream>

struct weighted_csr_graph {
  GlobalAddress<int64_t> xoff, xadj, xadjstore;
  GlobalAddress<double> adjweight;
  int64_t nv;
  int64_t nadj;

  weighted_csr_graph() {}
  weighted_csr_graph( csr_graph copied )
    : xoff( copied.xoff )
    , xadj( copied.xadj )
    , xadjstore( copied.xadjstore )
    , nv( copied.nv )
    , nadj( copied.nadj ) {}
};

typedef int vindex;
struct element_pair {
  double vp[2];
};
struct vector {
  GlobalAddress<element_pair> a;
  uint64_t length;
};

struct WeightedAdjVertex : public Vertex {
  double * weights;

  WeightedAdjVertex(): Vertex(), weights(nullptr) {}
};

void spmv_mult( weighted_csr_graph A, vector v, vindex x, vindex y );

void spmv_mult(GlobalAddress<Graph<WeightedAdjVertex>> g, vector v, vindex x, vindex y);

void matrix_out( weighted_csr_graph * g, std::ostream& o, bool dense );
void R_matrix_out( weighted_csr_graph * g, std::ostream& o);
void vector_out( vector * v, std::ostream& o );
void R_vector_out( vector * v, std::ostream& o );
<commit_msg>add missing alignment specification for pagerank<commit_after>// graph500/grappa/
// XXX shouldn't have to include this first: common.h and oned_csr.h have cyclic dependency
#include "../graph500/grappa/common.h"
#include "../graph500/grappa/oned_csr.h"
#include "../graph500/grappa/graph.hpp"

#include <Grappa.hpp>

#include <iostream>

struct weighted_csr_graph {
  GlobalAddress<int64_t> xoff, xadj, xadjstore;
  GlobalAddress<double> adjweight;
  int64_t nv;
  int64_t nadj;

  weighted_csr_graph() {}
  weighted_csr_graph( csr_graph copied )
    : xoff( copied.xoff )
    , xadj( copied.xadj )
    , xadjstore( copied.xadjstore )
    , nv( copied.nv )
    , nadj( copied.nadj ) {}
};

typedef int vindex;
struct element_pair {
  double vp[2];
};
struct vector {
  GlobalAddress<element_pair> a;
  uint64_t length;
};

struct WeightedAdjVertex : public Vertex {
  double * weights;

  WeightedAdjVertex(): Vertex(), weights(nullptr) {}
} GRAPPA_BLOCK_ALIGNED;

void spmv_mult( weighted_csr_graph A, vector v, vindex x, vindex y );

void spmv_mult(GlobalAddress<Graph<WeightedAdjVertex>> g, vector v, vindex x, vindex y);

void matrix_out( weighted_csr_graph * g, std::ostream& o, bool dense );
void R_matrix_out( weighted_csr_graph * g, std::ostream& o);
void vector_out( vector * v, std::ostream& o );
void R_vector_out( vector * v, std::ostream& o );
<|endoftext|>


<commit_before>#include "gtest.h"
#include "any_with_traits.h"

#include <array>
#include <map>
#include <memory>
#include <functional>
#include <unordered_set>

TEST(any, all)
{
  {
    any_t<any_trait::destructible> v(123);
    EXPECT_TRUE(v.type() == typeid (int));
    EXPECT_EQ(123, *any_cast<int> (&v));
    EXPECT_EQ(nullptr, any_cast<double> (&v));
    EXPECT_EQ(123, any_cast<int> (v));
    EXPECT_THROW(any_cast<double> (v), std::bad_cast);
  }
  {
    any_t < any_trait::destructible, any_trait::copiable, any_trait::movable> v(123);
    EXPECT_EQ(123, any_cast<int> (v));
    auto v2 = v;
    EXPECT_EQ(123, any_cast<int> (v2));
    auto v3 = std::move(v);
    EXPECT_EQ(123, any_cast<int> (v3));
    v3 = {};
    EXPECT_FALSE(v3.has_value ());
  }

  {
    using huge_type = std::array<int, 123>;
    huge_type initial_value;
    initial_value.fill(123);

    any_t < any_trait::destructible, any_trait::copiable, any_trait::movable> v(initial_value);
    EXPECT_EQ(initial_value, any_cast<huge_type> (v));
    auto v2 = v;
    EXPECT_EQ(initial_value, any_cast<huge_type> (v2));
    auto v3 = std::move(v);
    EXPECT_EQ(initial_value, any_cast<huge_type> (v3));
    v3.reset ();
    EXPECT_FALSE(v3.has_value());
    v2 = v3;
    EXPECT_FALSE(v2.has_value());
    v = std::move(v3);
    EXPECT_FALSE(v.has_value());
  }
  {
    using any = any_t <any_trait::destructible, any_trait::callable<int(int, int)>>;
    any v(std::plus<int> {});
    EXPECT_EQ (17, v (12, 5));
    v = std::minus<int> {};
    EXPECT_EQ(7, v(12, 5));
    any p;
    EXPECT_THROW(p(12, 5), std::bad_function_call);
  }
  {
    using any = any_t <any_trait::destructible, any_trait::comparable, any_trait::copiable>;
    any v(13);
    auto y = v;
    EXPECT_EQ(y, v);
    EXPECT_TRUE(13 == v);
    EXPECT_TRUE(v == 13);
    y = std::string ("Hello");
    EXPECT_EQ(std::string("Hello"), y);
    EXPECT_NE(13, y);
    EXPECT_TRUE(13 != y);
    EXPECT_TRUE(y != 13);
    any empty;
    EXPECT_NE (empty, y);
    y = empty;
    EXPECT_EQ(y ,empty);
  }
  {
    using any = any_t<any_trait::destructible, any_trait::orderable, any_trait::movable, any_trait::copiable> ;
    std::vector<any> v;
    v.emplace_back(25);
    v.emplace_back(-15);
    v.emplace_back(3);
    std::sort(v.begin(), v.end());
    EXPECT_EQ(25, any_cast<int> (v.back()));
    EXPECT_EQ(-15, any_cast<int> (v.front()));
    std::map<any, int> m;
    m[13] = 27;
    m[std::string ("acdcd")] = 34;
    m[std::vector<int> {1, 5, 3}] = 666;
    EXPECT_EQ(3u, m.size());
    EXPECT_EQ(666, m[std::vector<int> ({1, 5, 3})]);
    EXPECT_LT(any{}, m[13]);
    EXPECT_FALSE(any{} < any{});
    EXPECT_FALSE(any{} > any{});
  }
  {
    using any = any_t<any_trait::destructible, any_trait::movable, any_trait::copiable, any_trait::hashable, any_trait::comparable>;
    std::unordered_set<any> vv;
    vv.insert(17);
    vv.insert(13);
    vv.insert(19);
    vv.insert(std::string("13"));
    vv.insert({}); // empty any is fine for hashing
    EXPECT_EQ(1, vv.count (std::string ("13")));
    EXPECT_EQ(0, vv.count(std::string("27")));
    EXPECT_EQ(1, vv.count({}));
  }
}
<commit_msg>Fix broken test.<commit_after>#include "gtest.h"
#include "any_with_traits.h"

#include <array>
#include <map>
#include <memory>
#include <functional>
#include <unordered_set>

TEST(any, all)
{
  {
    any_t<any_trait::destructible> v(123);
    EXPECT_TRUE(v.type() == typeid (int));
    EXPECT_EQ(123, *any_cast<int> (&v));
    EXPECT_EQ(nullptr, any_cast<double> (&v));
    EXPECT_EQ(123, any_cast<int> (v));
    EXPECT_THROW(any_cast<double> (v), std::bad_cast);
  }
  {
    any_t < any_trait::destructible, any_trait::copiable, any_trait::movable> v(123);
    EXPECT_EQ(123, any_cast<int> (v));
    auto v2 = v;
    EXPECT_EQ(123, any_cast<int> (v2));
    auto v3 = std::move(v);
    EXPECT_EQ(123, any_cast<int> (v3));
    v3 = {};
    EXPECT_FALSE(v3.has_value ());
  }

  {
    using huge_type = std::array<int, 123>;
    huge_type initial_value;
    initial_value.fill(123);

    any_t < any_trait::destructible, any_trait::copiable, any_trait::movable> v(initial_value);
    EXPECT_EQ(initial_value, any_cast<huge_type> (v));
    auto v2 = v;
    EXPECT_EQ(initial_value, any_cast<huge_type> (v2));
    auto v3 = std::move(v);
    EXPECT_EQ(initial_value, any_cast<huge_type> (v3));
    v3.reset ();
    EXPECT_FALSE(v3.has_value());
    v2 = v3;
    EXPECT_FALSE(v2.has_value());
    v = std::move(v3);
    EXPECT_FALSE(v.has_value());
  }
  {
    using any = any_t <any_trait::destructible, any_trait::callable<int(int, int)>>;
    any v(std::plus<int> {});
    EXPECT_EQ (17, v (12, 5));
    v = std::minus<int> {};
    EXPECT_EQ(7, v(12, 5));
    any p;
    EXPECT_THROW(p(12, 5), std::bad_function_call);
  }
  {
    using any = any_t <any_trait::destructible, any_trait::comparable, any_trait::copiable>;
    any v(13);
    auto y = v;
    EXPECT_EQ(y, v);
    EXPECT_TRUE(13 == v);
    EXPECT_TRUE(v == 13);
    y = std::string ("Hello");
    EXPECT_EQ(std::string("Hello"), y);
    EXPECT_NE(13, y);
    EXPECT_TRUE(13 != y);
    EXPECT_TRUE(y != 13);
    any empty;
    EXPECT_NE (empty, y);
    y = empty;
    EXPECT_EQ(y ,empty);
  }
  {
    using any = any_t<any_trait::destructible, any_trait::orderable, any_trait::movable, any_trait::copiable> ;
    std::vector<any> v;
    v.emplace_back(25);
    v.emplace_back(-15);
    v.emplace_back(3);
    std::sort(v.begin(), v.end());
    EXPECT_EQ(25, any_cast<int> (v.back()));
    EXPECT_EQ(-15, any_cast<int> (v.front()));
    std::map<any, int> m;
    m[13] = 27;
    m[std::string ("acdcd")] = 34;
    m[std::vector<int> {1, 5, 3}] = 666;
    EXPECT_EQ(3u, m.size());
    EXPECT_EQ(666, m[std::vector<int> ({1, 5, 3})]);
    EXPECT_LT(any{}, m[13]);
    EXPECT_FALSE(any{} < any{});
    EXPECT_FALSE(any{} > any{});
  }
  {
    using any = any_t<any_trait::destructible, any_trait::movable, any_trait::copiable, any_trait::hashable, any_trait::comparable>;
    std::unordered_set<any> vv;
    vv.insert(17);
    vv.insert(13);
    vv.insert(19);
    vv.insert(std::string("13"));
    vv.insert(any{}); // empty any is fine for hashing
    EXPECT_EQ(1, vv.count (std::string ("13")));
    EXPECT_EQ(0, vv.count(std::string("27")));
    EXPECT_EQ(1, vv.count({}));
  }
}
<|endoftext|>


<commit_before>#include "easypr/chars_identify.h"
#include "easypr/core_func.h"

/*! \namespace easypr
        Namespace where all the C++ EasyPR functionality resides
        */
namespace easypr {

#define NDEBUG

//й
const char strCharacters[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                              'A', 'B', 'C', 'D', 'E', 'F', 'G',
                              'H', /* ûI */
                              'J', 'K', 'L', 'M', 'N', /* ûO */ 'P', 'Q',
                              'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
const int numCharacter = 34; /* ûI0,1024Ӣַ֮ */

//¶ѵʱõַݣȫ棬Щʡûѵûַ
//Щ2ıʾѵʱַһֱΣҲΪѵݴ洢
const string strChinese[] = {
    "zh_cuan" /*  */,  "zh_e" /*  */,    "zh_gan" /* */,
    "zh_gan1" /**/,    "zh_gui" /*  */,  "zh_gui1" /*  */,
    "zh_hei" /*  */,   "zh_hu" /*  */,   "zh_ji" /*  */,
    "zh_jin" /*  */,   "zh_jing" /*  */, "zh_jl" /*  */,
    "zh_liao" /*  */,  "zh_lu" /* ³ */,   "zh_meng" /*  */,
    "zh_min" /*  */,   "zh_ning" /*  */, "zh_qing" /*  */,
    "zh_qiong" /*  */, "zh_shan" /*  */, "zh_su" /*  */,
    "zh_sx" /*  */,    "zh_wan" /*  */,  "zh_xiang" /*  */,
    "zh_xin" /*  */,   "zh_yu" /* ԥ */,   "zh_yu1" /*  */,
    "zh_yue" /*  */,   "zh_yun" /*  */,  "zh_zang" /*  */,
    "zh_zhe" /*  */};

const int numChinese = 31;
const int numAll = 65; /* 34+20=54 */

CCharsIdentify::CCharsIdentify() {
  // cout << "CCharsIdentify" << endl;
  m_predictSize = 10;
  m_path = "resources/model/ann.xml";
  LoadModel();

  typedef pair<string, string> CodeProvince;

  if (m_map.empty()) {
    m_map.insert(CodeProvince("zh_cuan", ""));
    m_map.insert(CodeProvince("zh_e", ""));
    m_map.insert(CodeProvince("zh_gan", ""));
    m_map.insert(CodeProvince("zh_gan1", ""));
    m_map.insert(CodeProvince("zh_gui", ""));
    m_map.insert(CodeProvince("zh_gui1", ""));
    m_map.insert(CodeProvince("zh_hei", ""));
    m_map.insert(CodeProvince("zh_hu", ""));
    m_map.insert(CodeProvince("zh_ji", ""));
    m_map.insert(CodeProvince("zh_jin", ""));
    m_map.insert(CodeProvince("zh_jing", ""));
    m_map.insert(CodeProvince("zh_jl", ""));
    m_map.insert(CodeProvince("zh_liao", ""));
    m_map.insert(CodeProvince("zh_lu", "³"));
    m_map.insert(CodeProvince("zh_meng", ""));
    m_map.insert(CodeProvince("zh_min", ""));
    m_map.insert(CodeProvince("zh_ning", ""));
    m_map.insert(CodeProvince("zh_qing", ""));
    m_map.insert(CodeProvince("zh_qiong", ""));
    m_map.insert(CodeProvince("zh_shan", ""));
    m_map.insert(CodeProvince("zh_su", ""));
    m_map.insert(CodeProvince("zh_sx", ""));
    m_map.insert(CodeProvince("zh_wan", ""));
    m_map.insert(CodeProvince("zh_xiang", ""));
    m_map.insert(CodeProvince("zh_xin", ""));
    m_map.insert(CodeProvince("zh_yu", "ԥ"));
    m_map.insert(CodeProvince("zh_yu1", ""));
    m_map.insert(CodeProvince("zh_yue", ""));
    m_map.insert(CodeProvince("zh_yun", ""));
    m_map.insert(CodeProvince("zh_zang", ""));
    m_map.insert(CodeProvince("zh_zhe", ""));
  }
}

void CCharsIdentify::LoadModel() {
  ann.clear();
  ann.load(m_path.c_str(), "ann");
}

void CCharsIdentify::LoadModel(string s) {
  ann.clear();
  ann.load(s.c_str(), "ann");
}

int CCharsIdentify::classify(Mat f, bool isChinses, bool isSpeci) {
  int result = -1;
  Mat output(1, numAll, CV_32FC1);
  ann.predict(f, output);  //ʹannַж

  if (!isChinses)  //ַж
  {
    if (isSpeci) {
      result = 0;
      float maxVal = -2;
      for (int j = 10; j < numCharacter; j++) {
        float val = output.at<float>(j);
        // cout << "j:" << j << "val:"<< val << endl;
        if (val > maxVal) {
          maxVal = val;
          result = j;
        }
      }

    } else {
      result = 0;
      float maxVal = -2;
      for (int j = 0; j < numCharacter; j++) {
        float val = output.at<float>(j);
        // cout << "j:" << j << "val:"<< val << endl;
        if (val >
            maxVal)  //ַȨǸҲͨannΪַܵ
        {
          maxVal = val;
          result = j;
        }
      }
    }
  } else  //ֺӢĸж
  {
    result = numCharacter;
    float maxVal = -2;
    for (int j = numCharacter; j < numAll; j++) {
      float val = output.at<float>(j);
      // cout << "j:" << j << "val:"<< val << endl;
      if (val > maxVal) {
        maxVal = val;
        result = j;
      }
    }
  }
  return result;
}

int CCharsIdentify::classify(Mat f) {
  int result = -1;
  Mat output(1, numAll, CV_32FC1);
  ann.predict(f, output);  //ʹannַж

  float maxVal = -2;
  for (int j = 0; j < numCharacter; j++) {
    float val = output.at<float>(j);
    // cout << "j:" << j << "val:"<< val << endl;
    if (val > maxVal)
    //ַȨǸҲͨannΪַܵ
    {
      maxVal = val;
      result = j;
    }
  }

  for (int j = numCharacter; j < numAll; j++) {
    float val = output.at<float>(j);
    // cout << "j:" << j << "val:"<< val << endl;
    if (val > maxVal) {
      maxVal = val;
      result = j;
    }
  }

  return result;
}

string CCharsIdentify::charsIdentify(Mat input) {
  Mat f = features(input, m_predictSize);
  string result = "";
  int index = classify(f);  //ʹannбǸַ

  if (index >= numCharacter) {
    string s = strChinese[index - numCharacter];
    string province = m_map[s];
    return s;
  } else {
    char s = strCharacters[index];
    char szBuf[216];
    sprintf(szBuf, "%c", s);
    return szBuf;
  }
}

//뵱ַMat,ַstring
string CCharsIdentify::charsIdentify(Mat input, bool isChinese, bool isSpeci) {
  Mat f = features(input, m_predictSize);

  string result = "";
  int index = classify(f, isChinese, isSpeci);  //ʹannбǸַ

  if (!isChinese) {
    result = result + strCharacters[index];
  } else {
    string s = strChinese[index - numCharacter];
    string province = m_map[s];
    result = province + result;
  }

  return result;
}

} /*! \namespace easypr*/
<commit_msg>Remove redefined macro NDEBUG.<commit_after>#include "easypr/chars_identify.h"
#include "easypr/core_func.h"

/*! \namespace easypr
        Namespace where all the C++ EasyPR functionality resides
        */
namespace easypr {

//й
const char strCharacters[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                              'A', 'B', 'C', 'D', 'E', 'F', 'G',
                              'H', /* ûI */
                              'J', 'K', 'L', 'M', 'N', /* ûO */ 'P', 'Q',
                              'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
const int numCharacter = 34; /* ûI0,1024Ӣַ֮ */

//¶ѵʱõַݣȫ棬Щʡûѵûַ
//Щ2ıʾѵʱַһֱΣҲΪѵݴ洢
const string strChinese[] = {
    "zh_cuan" /*  */,  "zh_e" /*  */,    "zh_gan" /* */,
    "zh_gan1" /**/,    "zh_gui" /*  */,  "zh_gui1" /*  */,
    "zh_hei" /*  */,   "zh_hu" /*  */,   "zh_ji" /*  */,
    "zh_jin" /*  */,   "zh_jing" /*  */, "zh_jl" /*  */,
    "zh_liao" /*  */,  "zh_lu" /* ³ */,   "zh_meng" /*  */,
    "zh_min" /*  */,   "zh_ning" /*  */, "zh_qing" /*  */,
    "zh_qiong" /*  */, "zh_shan" /*  */, "zh_su" /*  */,
    "zh_sx" /*  */,    "zh_wan" /*  */,  "zh_xiang" /*  */,
    "zh_xin" /*  */,   "zh_yu" /* ԥ */,   "zh_yu1" /*  */,
    "zh_yue" /*  */,   "zh_yun" /*  */,  "zh_zang" /*  */,
    "zh_zhe" /*  */};

const int numChinese = 31;
const int numAll = 65; /* 34+20=54 */

CCharsIdentify::CCharsIdentify() {
  // cout << "CCharsIdentify" << endl;
  m_predictSize = 10;
  m_path = "resources/model/ann.xml";
  LoadModel();

  typedef pair<string, string> CodeProvince;

  if (m_map.empty()) {
    m_map.insert(CodeProvince("zh_cuan", ""));
    m_map.insert(CodeProvince("zh_e", ""));
    m_map.insert(CodeProvince("zh_gan", ""));
    m_map.insert(CodeProvince("zh_gan1", ""));
    m_map.insert(CodeProvince("zh_gui", ""));
    m_map.insert(CodeProvince("zh_gui1", ""));
    m_map.insert(CodeProvince("zh_hei", ""));
    m_map.insert(CodeProvince("zh_hu", ""));
    m_map.insert(CodeProvince("zh_ji", ""));
    m_map.insert(CodeProvince("zh_jin", ""));
    m_map.insert(CodeProvince("zh_jing", ""));
    m_map.insert(CodeProvince("zh_jl", ""));
    m_map.insert(CodeProvince("zh_liao", ""));
    m_map.insert(CodeProvince("zh_lu", "³"));
    m_map.insert(CodeProvince("zh_meng", ""));
    m_map.insert(CodeProvince("zh_min", ""));
    m_map.insert(CodeProvince("zh_ning", ""));
    m_map.insert(CodeProvince("zh_qing", ""));
    m_map.insert(CodeProvince("zh_qiong", ""));
    m_map.insert(CodeProvince("zh_shan", ""));
    m_map.insert(CodeProvince("zh_su", ""));
    m_map.insert(CodeProvince("zh_sx", ""));
    m_map.insert(CodeProvince("zh_wan", ""));
    m_map.insert(CodeProvince("zh_xiang", ""));
    m_map.insert(CodeProvince("zh_xin", ""));
    m_map.insert(CodeProvince("zh_yu", "ԥ"));
    m_map.insert(CodeProvince("zh_yu1", ""));
    m_map.insert(CodeProvince("zh_yue", ""));
    m_map.insert(CodeProvince("zh_yun", ""));
    m_map.insert(CodeProvince("zh_zang", ""));
    m_map.insert(CodeProvince("zh_zhe", ""));
  }
}

void CCharsIdentify::LoadModel() {
  ann.clear();
  ann.load(m_path.c_str(), "ann");
}

void CCharsIdentify::LoadModel(string s) {
  ann.clear();
  ann.load(s.c_str(), "ann");
}

int CCharsIdentify::classify(Mat f, bool isChinses, bool isSpeci) {
  int result = -1;
  Mat output(1, numAll, CV_32FC1);
  ann.predict(f, output);  //ʹannַж

  if (!isChinses)  //ַж
  {
    if (isSpeci) {
      result = 0;
      float maxVal = -2;
      for (int j = 10; j < numCharacter; j++) {
        float val = output.at<float>(j);
        // cout << "j:" << j << "val:"<< val << endl;
        if (val > maxVal) {
          maxVal = val;
          result = j;
        }
      }

    } else {
      result = 0;
      float maxVal = -2;
      for (int j = 0; j < numCharacter; j++) {
        float val = output.at<float>(j);
        // cout << "j:" << j << "val:"<< val << endl;
        if (val >
            maxVal)  //ַȨǸҲͨannΪַܵ
        {
          maxVal = val;
          result = j;
        }
      }
    }
  } else  //ֺӢĸж
  {
    result = numCharacter;
    float maxVal = -2;
    for (int j = numCharacter; j < numAll; j++) {
      float val = output.at<float>(j);
      // cout << "j:" << j << "val:"<< val << endl;
      if (val > maxVal) {
        maxVal = val;
        result = j;
      }
    }
  }
  return result;
}

int CCharsIdentify::classify(Mat f) {
  int result = -1;
  Mat output(1, numAll, CV_32FC1);
  ann.predict(f, output);  //ʹannַж

  float maxVal = -2;
  for (int j = 0; j < numCharacter; j++) {
    float val = output.at<float>(j);
    // cout << "j:" << j << "val:"<< val << endl;
    if (val > maxVal)
    //ַȨǸҲͨannΪַܵ
    {
      maxVal = val;
      result = j;
    }
  }

  for (int j = numCharacter; j < numAll; j++) {
    float val = output.at<float>(j);
    // cout << "j:" << j << "val:"<< val << endl;
    if (val > maxVal) {
      maxVal = val;
      result = j;
    }
  }

  return result;
}

string CCharsIdentify::charsIdentify(Mat input) {
  Mat f = features(input, m_predictSize);
  string result = "";
  int index = classify(f);  //ʹannбǸַ

  if (index >= numCharacter) {
    string s = strChinese[index - numCharacter];
    string province = m_map[s];
    return s;
  } else {
    char s = strCharacters[index];
    char szBuf[216];
    sprintf(szBuf, "%c", s);
    return szBuf;
  }
}

//뵱ַMat,ַstring
string CCharsIdentify::charsIdentify(Mat input, bool isChinese, bool isSpeci) {
  Mat f = features(input, m_predictSize);

  string result = "";
  int index = classify(f, isChinese, isSpeci);  //ʹannбǸַ

  if (!isChinese) {
    result = result + strCharacters[index];
  } else {
    string s = strChinese[index - numCharacter];
    string province = m_map[s];
    result = province + result;
  }

  return result;
}

} /*! \namespace easypr*/
<|endoftext|>