<commit_before>/***********************************************************************
 type_info.cpp - Implements the mysql_type_info class.

 Copyright (c) 1998 by Kevin Atkinson, (c) 1999-2001 by MySQL AB, and
 (c) 2004-2007 by Educational Technology Resources, Inc.  Others may
 also hold copyrights on code in this file.  See the CREDITS file in
 the top directory of the distribution for details.

 This file is part of MySQL++.

 MySQL++ 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.

 MySQL++ 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 MySQL++; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
 USA
***********************************************************************/

#include "common.h"
#include "type_info.h"

#include "datetime.h"
#include "myset.h"
#include "sql_types.h"

#include <mysql.h>

#include <string>

using namespace std;

namespace mysqlpp {

// This table maps C++ type information to SQL type information.  As you
// can see, it's intimately tied in with MySQL's type constants, thus the
// name.  Unlike in earlier versions of MySQL++, this table is the only
// place with such a dependency.  Everything else abstracts MySQL's
// type system away by bouncing things through this table.
//
// The second half of the table parallels the first, to handle null-able
// versions of the types in the first half.  This is required because
// SQL's 'null' concept does not map neatly into the C++ type system, so
// null-able versions of these types have to have a different C++ type,
// implemented using the Null template.  See null.h for further details.
//
// Types with tf_default set are added to a lookup map in the
// mysql_type_info_lookup class in order to provide reverse lookup
// of C++ types to SQL types.  If you take the subset of all items
// marked as default, the typeid() of each item must be unique.
const mysql_type_info::sql_type_info mysql_type_info::types[] = {
	sql_type_info("DECIMAL NOT NULL", typeid(sql_decimal),
#if MYSQL_VERSION_ID >= 50001
			MYSQL_TYPE_NEWDECIMAL
#else
			MYSQL_TYPE_DECIMAL
#endif
			),
	sql_type_info("TINYINT NOT NULL", typeid(sql_tinyint),
			MYSQL_TYPE_TINY, mysql_ti_sql_type_info::tf_default),
	sql_type_info("TINYINT UNSIGNED NOT NULL", typeid(sql_tinyint_unsigned),
			MYSQL_TYPE_TINY, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_unsigned),
	sql_type_info("SMALLINT NOT NULL", typeid(sql_smallint),
			MYSQL_TYPE_SHORT, mysql_ti_sql_type_info::tf_default),
	sql_type_info("SMALLINT UNSIGNED NOT NULL", typeid(sql_smallint_unsigned),
			MYSQL_TYPE_SHORT, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_unsigned),
	sql_type_info("INT NOT NULL", typeid(sql_int),
			MYSQL_TYPE_LONG, mysql_ti_sql_type_info::tf_default),
	sql_type_info("INT UNSIGNED NOT NULL", typeid(sql_int_unsigned),
			MYSQL_TYPE_LONG, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_unsigned),
	sql_type_info("FLOAT NOT NULL", typeid(sql_float),
			MYSQL_TYPE_FLOAT, mysql_ti_sql_type_info::tf_default),
	sql_type_info("DOUBLE NOT NULL", typeid(sql_double),
			MYSQL_TYPE_DOUBLE, mysql_ti_sql_type_info::tf_default),
	sql_type_info("NULL NOT NULL", typeid(void),
			MYSQL_TYPE_NULL, mysql_ti_sql_type_info::tf_default),
	sql_type_info("TIMESTAMP NOT NULL", typeid(sql_timestamp),
			MYSQL_TYPE_TIMESTAMP),
	sql_type_info("BIGINT NOT NULL", typeid(sql_bigint),
			MYSQL_TYPE_LONGLONG, mysql_ti_sql_type_info::tf_default),
	sql_type_info("BIGINT UNSIGNED NOT NULL", typeid(sql_bigint_unsigned),
			MYSQL_TYPE_LONGLONG, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_unsigned),
	sql_type_info("MEDIUMINT NOT NULL", typeid(sql_mediumint),
			MYSQL_TYPE_INT24, mysql_ti_sql_type_info::tf_unsigned),
	sql_type_info("MEDIUMINT UNSIGNED NOT NULL", typeid(sql_mediumint_unsigned),
			MYSQL_TYPE_INT24, mysql_ti_sql_type_info::tf_unsigned),
	sql_type_info("DATE NOT NULL", typeid(sql_date),
			MYSQL_TYPE_DATE, mysql_ti_sql_type_info::tf_default),
	sql_type_info("TIME NOT NULL", typeid(sql_time),
			MYSQL_TYPE_TIME, mysql_ti_sql_type_info::tf_default),
	sql_type_info("DATETIME NOT NULL", typeid(sql_datetime),
			MYSQL_TYPE_DATETIME, mysql_ti_sql_type_info::tf_default),
	sql_type_info("ENUM NOT NULL", typeid(sql_enum),
			MYSQL_TYPE_ENUM, mysql_ti_sql_type_info::tf_default),
	sql_type_info("SET NOT NULL", typeid(sql_set),
			MYSQL_TYPE_SET, mysql_ti_sql_type_info::tf_default),
	sql_type_info("TINYBLOB NOT NULL", typeid(sql_tinyblob),
			MYSQL_TYPE_TINY_BLOB),
	sql_type_info("MEDIUMBLOB NOT NULL", typeid(sql_mediumblob),
			MYSQL_TYPE_MEDIUM_BLOB),
	sql_type_info("LONGBLOB NOT NULL", typeid(sql_longblob),
			MYSQL_TYPE_LONG_BLOB),
	sql_type_info("BLOB NOT NULL", typeid(sql_blob),
			MYSQL_TYPE_BLOB),
	sql_type_info("VARCHAR NOT NULL", typeid(sql_varchar),
			MYSQL_TYPE_VAR_STRING, mysql_ti_sql_type_info::tf_default),
	sql_type_info("CHAR NOT NULL", typeid(sql_char),
			MYSQL_TYPE_STRING),

	sql_type_info("DECIMAL NULL", typeid(Null<sql_decimal>),
#if MYSQL_VERSION_ID >= 50001
			MYSQL_TYPE_NEWDECIMAL
#else
			MYSQL_TYPE_DECIMAL
#endif
			, mysql_ti_sql_type_info::tf_null),
	sql_type_info("TINYINT NULL", typeid(Null<sql_tinyint>),
			MYSQL_TYPE_TINY, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null),
	sql_type_info("TINYINT UNSIGNED NULL", typeid(Null<sql_tinyint_unsigned>),
			MYSQL_TYPE_TINY, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null |
			mysql_ti_sql_type_info::tf_unsigned),
	sql_type_info("SMALLINT NULL", typeid(Null<sql_smallint>),
			MYSQL_TYPE_SHORT, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null),
	sql_type_info("SMALLINT UNSIGNED NULL", typeid(Null<sql_smallint_unsigned>),
			MYSQL_TYPE_SHORT, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null |
			mysql_ti_sql_type_info::tf_unsigned),
	sql_type_info("INT NULL", typeid(Null<sql_int>),
			MYSQL_TYPE_LONG, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null),
	sql_type_info("INT UNSIGNED NULL", typeid(Null<sql_int_unsigned>),
			MYSQL_TYPE_LONG, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null |
			mysql_ti_sql_type_info::tf_unsigned),
	sql_type_info("FLOAT NULL", typeid(Null<sql_float>),
			MYSQL_TYPE_FLOAT, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null),
	sql_type_info("DOUBLE NULL", typeid(Null<sql_double>),
			MYSQL_TYPE_DOUBLE, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null),
	sql_type_info("NULL NULL", typeid(Null<void>),
			MYSQL_TYPE_NULL, mysql_ti_sql_type_info::tf_null),
	sql_type_info("TIMESTAMP NULL", typeid(Null<sql_timestamp>),
			MYSQL_TYPE_TIMESTAMP),
	sql_type_info("BIGINT NULL", typeid(Null<sql_bigint>),
			MYSQL_TYPE_LONGLONG, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null),
	sql_type_info("BIGINT UNSIGNED NULL", typeid(Null<sql_bigint_unsigned>),
			MYSQL_TYPE_LONGLONG, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null |
			mysql_ti_sql_type_info::tf_unsigned),
	sql_type_info("MEDIUMINT NULL", typeid(Null<sql_mediumint>),
			MYSQL_TYPE_INT24, mysql_ti_sql_type_info::tf_null),
	sql_type_info("MEDIUMINT UNSIGNED NULL", typeid(Null<sql_mediumint_unsigned>),
			MYSQL_TYPE_INT24, mysql_ti_sql_type_info::tf_null |
			mysql_ti_sql_type_info::tf_unsigned),
	sql_type_info("DATE NULL", typeid(Null<sql_date>),
			MYSQL_TYPE_DATE, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null),
	sql_type_info("TIME NULL", typeid(Null<sql_time>),
			MYSQL_TYPE_TIME, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null),
	sql_type_info("DATETIME NULL", typeid(Null<sql_datetime>),
			MYSQL_TYPE_DATETIME, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null),
	sql_type_info("ENUM NULL", typeid(Null<sql_enum>),
			MYSQL_TYPE_ENUM, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null),
	sql_type_info("SET NULL", typeid(Null<sql_set>),
			MYSQL_TYPE_SET, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null),
	sql_type_info("TINYBLOB NULL", typeid(Null<sql_tinyblob>),
			MYSQL_TYPE_TINY_BLOB, mysql_ti_sql_type_info::tf_null),
	sql_type_info("MEDIUMBLOB NULL", typeid(Null<sql_mediumblob>),
			MYSQL_TYPE_MEDIUM_BLOB, mysql_ti_sql_type_info::tf_null),
	sql_type_info("LONGBLOB NULL", typeid(Null<sql_longblob>),
			MYSQL_TYPE_LONG_BLOB, mysql_ti_sql_type_info::tf_null),
	sql_type_info("BLOB NULL", typeid(Null<sql_blob>),
			MYSQL_TYPE_BLOB, mysql_ti_sql_type_info::tf_null),
	sql_type_info("VARCHAR NULL", typeid(Null<sql_varchar>),
			MYSQL_TYPE_VAR_STRING, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null),
	sql_type_info("CHAR NULL", typeid(Null<sql_char>),
			MYSQL_TYPE_STRING, mysql_ti_sql_type_info::tf_null)
};

const int mysql_type_info::num_types =
		sizeof(mysql_type_info::types) / sizeof(mysql_type_info::types[0]);

const mysql_type_info::sql_type_info_lookup
		mysql_type_info::lookups(mysql_type_info::types,
		mysql_type_info::num_types);

#if !defined(DOXYGEN_IGNORE)
// Doxygen will not generate documentation for this section.

mysql_ti_sql_type_info_lookup::mysql_ti_sql_type_info_lookup(
		const sql_type_info types[], const int size)
{
	for (int i = 0; i < size; ++i) {
		if (types[i].is_default()) {
			map_[types[i].c_type_] = i;
		}
	}
}

#endif // !defined(DOXYGEN_IGNORE)

unsigned char mysql_type_info::type(enum_field_types t,
		bool _unsigned, bool _null)
{
	for (unsigned char i = 0; i < num_types; ++i) {
		if ((types[i].base_type_ == t) &&
				(!_unsigned || types[i].is_unsigned()) &&
				(!_null || types[i].is_null())) {
			return i;
		}
	}

	return type(MYSQL_TYPE_STRING, false, _null);	// punt!
}

bool mysql_type_info::quote_q() const
{
	const type_info& ti = base_type().c_type();
	return ti == typeid(string) ||
			ti == typeid(sql_date) ||
			ti == typeid(sql_time) ||
			ti == typeid(sql_datetime) ||
			ti == typeid(sql_set);
}

bool mysql_type_info::escape_q() const
{
	const type_info& ti = c_type();
	return ti == typeid(string) ||
			ti == typeid(sql_enum) ||
			ti == typeid(sql_blob) ||
			ti == typeid(sql_tinyblob) ||
			ti == typeid(sql_mediumblob) ||
			ti == typeid(sql_longblob) ||
			ti == typeid(sql_char) ||
			ti == typeid(sql_varchar);
}

} // end namespace mysqlpp

<commit_msg>Fixes to type_info module to allow passing a SSQLS with a nullable BLOB column to Query::insert().  (Recent attempts at this only worked if the column was null, not if it contained actual data.)  Patch by Russell Robinson <russellr@openconcepts.com.au><commit_after>/***********************************************************************
 type_info.cpp - Implements the mysql_type_info class.

 Copyright (c) 1998 by Kevin Atkinson, (c) 1999-2001 by MySQL AB, and
 (c) 2004-2007 by Educational Technology Resources, Inc.  Others may
 also hold copyrights on code in this file.  See the CREDITS file in
 the top directory of the distribution for details.

 This file is part of MySQL++.

 MySQL++ 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.

 MySQL++ 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 MySQL++; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
 USA
***********************************************************************/

#include "common.h"
#include "type_info.h"

#include "datetime.h"
#include "myset.h"
#include "sql_types.h"

#include <mysql.h>

#include <string>

using namespace std;

namespace mysqlpp {

// This table maps C++ type information to SQL type information.  As you
// can see, it's intimately tied in with MySQL's type constants, thus the
// name.  Unlike in earlier versions of MySQL++, this table is the only
// place with such a dependency.  Everything else abstracts MySQL's
// type system away by bouncing things through this table.
//
// The second half of the table parallels the first, to handle null-able
// versions of the types in the first half.  This is required because
// SQL's 'null' concept does not map neatly into the C++ type system, so
// null-able versions of these types have to have a different C++ type,
// implemented using the Null template.  See null.h for further details.
//
// Types with tf_default set are added to a lookup map in the
// mysql_type_info_lookup class in order to provide reverse lookup
// of C++ types to SQL types.  If you take the subset of all items
// marked as default, the typeid() of each item must be unique.
const mysql_type_info::sql_type_info mysql_type_info::types[] = {
	sql_type_info("DECIMAL NOT NULL", typeid(sql_decimal),
#if MYSQL_VERSION_ID >= 50001
			MYSQL_TYPE_NEWDECIMAL
#else
			MYSQL_TYPE_DECIMAL
#endif
			),
	sql_type_info("TINYINT NOT NULL", typeid(sql_tinyint),
			MYSQL_TYPE_TINY, mysql_ti_sql_type_info::tf_default),
	sql_type_info("TINYINT UNSIGNED NOT NULL", typeid(sql_tinyint_unsigned),
			MYSQL_TYPE_TINY, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_unsigned),
	sql_type_info("SMALLINT NOT NULL", typeid(sql_smallint),
			MYSQL_TYPE_SHORT, mysql_ti_sql_type_info::tf_default),
	sql_type_info("SMALLINT UNSIGNED NOT NULL", typeid(sql_smallint_unsigned),
			MYSQL_TYPE_SHORT, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_unsigned),
	sql_type_info("INT NOT NULL", typeid(sql_int),
			MYSQL_TYPE_LONG, mysql_ti_sql_type_info::tf_default),
	sql_type_info("INT UNSIGNED NOT NULL", typeid(sql_int_unsigned),
			MYSQL_TYPE_LONG, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_unsigned),
	sql_type_info("FLOAT NOT NULL", typeid(sql_float),
			MYSQL_TYPE_FLOAT, mysql_ti_sql_type_info::tf_default),
	sql_type_info("DOUBLE NOT NULL", typeid(sql_double),
			MYSQL_TYPE_DOUBLE, mysql_ti_sql_type_info::tf_default),
	sql_type_info("NULL NOT NULL", typeid(void),
			MYSQL_TYPE_NULL, mysql_ti_sql_type_info::tf_default),
	sql_type_info("TIMESTAMP NOT NULL", typeid(sql_timestamp),
			MYSQL_TYPE_TIMESTAMP),
	sql_type_info("BIGINT NOT NULL", typeid(sql_bigint),
			MYSQL_TYPE_LONGLONG, mysql_ti_sql_type_info::tf_default),
	sql_type_info("BIGINT UNSIGNED NOT NULL", typeid(sql_bigint_unsigned),
			MYSQL_TYPE_LONGLONG, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_unsigned),
	sql_type_info("MEDIUMINT NOT NULL", typeid(sql_mediumint),
			MYSQL_TYPE_INT24, mysql_ti_sql_type_info::tf_unsigned),
	sql_type_info("MEDIUMINT UNSIGNED NOT NULL", typeid(sql_mediumint_unsigned),
			MYSQL_TYPE_INT24, mysql_ti_sql_type_info::tf_unsigned),
	sql_type_info("DATE NOT NULL", typeid(sql_date),
			MYSQL_TYPE_DATE, mysql_ti_sql_type_info::tf_default),
	sql_type_info("TIME NOT NULL", typeid(sql_time),
			MYSQL_TYPE_TIME, mysql_ti_sql_type_info::tf_default),
	sql_type_info("DATETIME NOT NULL", typeid(sql_datetime),
			MYSQL_TYPE_DATETIME, mysql_ti_sql_type_info::tf_default),
	sql_type_info("ENUM NOT NULL", typeid(sql_enum),
			MYSQL_TYPE_ENUM, mysql_ti_sql_type_info::tf_default),
	sql_type_info("SET NOT NULL", typeid(sql_set),
			MYSQL_TYPE_SET, mysql_ti_sql_type_info::tf_default),
	sql_type_info("TINYBLOB NOT NULL", typeid(sql_tinyblob),
			MYSQL_TYPE_TINY_BLOB),
	sql_type_info("MEDIUMBLOB NOT NULL", typeid(sql_mediumblob),
			MYSQL_TYPE_MEDIUM_BLOB),
	sql_type_info("LONGBLOB NOT NULL", typeid(sql_longblob),
			MYSQL_TYPE_LONG_BLOB),
	sql_type_info("BLOB NOT NULL", typeid(sql_blob),
			MYSQL_TYPE_BLOB, mysql_ti_sql_type_info::tf_default),
	sql_type_info("VARCHAR NOT NULL", typeid(sql_varchar),
			MYSQL_TYPE_VAR_STRING, mysql_ti_sql_type_info::tf_default),
	sql_type_info("CHAR NOT NULL", typeid(sql_char),
			MYSQL_TYPE_STRING),

	sql_type_info("DECIMAL NULL", typeid(Null<sql_decimal>),
#if MYSQL_VERSION_ID >= 50001
			MYSQL_TYPE_NEWDECIMAL
#else
			MYSQL_TYPE_DECIMAL
#endif
			, mysql_ti_sql_type_info::tf_null),
	sql_type_info("TINYINT NULL", typeid(Null<sql_tinyint>),
			MYSQL_TYPE_TINY, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null),
	sql_type_info("TINYINT UNSIGNED NULL", typeid(Null<sql_tinyint_unsigned>),
			MYSQL_TYPE_TINY, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null |
			mysql_ti_sql_type_info::tf_unsigned),
	sql_type_info("SMALLINT NULL", typeid(Null<sql_smallint>),
			MYSQL_TYPE_SHORT, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null),
	sql_type_info("SMALLINT UNSIGNED NULL", typeid(Null<sql_smallint_unsigned>),
			MYSQL_TYPE_SHORT, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null |
			mysql_ti_sql_type_info::tf_unsigned),
	sql_type_info("INT NULL", typeid(Null<sql_int>),
			MYSQL_TYPE_LONG, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null),
	sql_type_info("INT UNSIGNED NULL", typeid(Null<sql_int_unsigned>),
			MYSQL_TYPE_LONG, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null |
			mysql_ti_sql_type_info::tf_unsigned),
	sql_type_info("FLOAT NULL", typeid(Null<sql_float>),
			MYSQL_TYPE_FLOAT, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null),
	sql_type_info("DOUBLE NULL", typeid(Null<sql_double>),
			MYSQL_TYPE_DOUBLE, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null),
	sql_type_info("NULL NULL", typeid(Null<void>),
			MYSQL_TYPE_NULL, mysql_ti_sql_type_info::tf_null),
	sql_type_info("TIMESTAMP NULL", typeid(Null<sql_timestamp>),
			MYSQL_TYPE_TIMESTAMP),
	sql_type_info("BIGINT NULL", typeid(Null<sql_bigint>),
			MYSQL_TYPE_LONGLONG, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null),
	sql_type_info("BIGINT UNSIGNED NULL", typeid(Null<sql_bigint_unsigned>),
			MYSQL_TYPE_LONGLONG, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null |
			mysql_ti_sql_type_info::tf_unsigned),
	sql_type_info("MEDIUMINT NULL", typeid(Null<sql_mediumint>),
			MYSQL_TYPE_INT24, mysql_ti_sql_type_info::tf_null),
	sql_type_info("MEDIUMINT UNSIGNED NULL", typeid(Null<sql_mediumint_unsigned>),
			MYSQL_TYPE_INT24, mysql_ti_sql_type_info::tf_null |
			mysql_ti_sql_type_info::tf_unsigned),
	sql_type_info("DATE NULL", typeid(Null<sql_date>),
			MYSQL_TYPE_DATE, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null),
	sql_type_info("TIME NULL", typeid(Null<sql_time>),
			MYSQL_TYPE_TIME, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null),
	sql_type_info("DATETIME NULL", typeid(Null<sql_datetime>),
			MYSQL_TYPE_DATETIME, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null),
	sql_type_info("ENUM NULL", typeid(Null<sql_enum>),
			MYSQL_TYPE_ENUM, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null),
	sql_type_info("SET NULL", typeid(Null<sql_set>),
			MYSQL_TYPE_SET, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null),
	sql_type_info("TINYBLOB NULL", typeid(Null<sql_tinyblob>),
			MYSQL_TYPE_TINY_BLOB, mysql_ti_sql_type_info::tf_null),
	sql_type_info("MEDIUMBLOB NULL", typeid(Null<sql_mediumblob>),
			MYSQL_TYPE_MEDIUM_BLOB, mysql_ti_sql_type_info::tf_null),
	sql_type_info("LONGBLOB NULL", typeid(Null<sql_longblob>),
			MYSQL_TYPE_LONG_BLOB, mysql_ti_sql_type_info::tf_null),
	sql_type_info("BLOB NULL", typeid(Null<sql_blob>),
			MYSQL_TYPE_BLOB, mysql_ti_sql_type_info::tf_default |
            mysql_ti_sql_type_info::tf_null),
	sql_type_info("VARCHAR NULL", typeid(Null<sql_varchar>),
			MYSQL_TYPE_VAR_STRING, mysql_ti_sql_type_info::tf_default |
			mysql_ti_sql_type_info::tf_null),
	sql_type_info("CHAR NULL", typeid(Null<sql_char>),
			MYSQL_TYPE_STRING, mysql_ti_sql_type_info::tf_null)
};

const int mysql_type_info::num_types =
		sizeof(mysql_type_info::types) / sizeof(mysql_type_info::types[0]);

const mysql_type_info::sql_type_info_lookup
		mysql_type_info::lookups(mysql_type_info::types,
		mysql_type_info::num_types);

#if !defined(DOXYGEN_IGNORE)
// Doxygen will not generate documentation for this section.

mysql_ti_sql_type_info_lookup::mysql_ti_sql_type_info_lookup(
		const sql_type_info types[], const int size)
{
	for (int i = 0; i < size; ++i) {
		if (types[i].is_default()) {
			map_[types[i].c_type_] = i;
		}
	}
}

#endif // !defined(DOXYGEN_IGNORE)

unsigned char mysql_type_info::type(enum_field_types t,
		bool _unsigned, bool _null)
{
	for (unsigned char i = 0; i < num_types; ++i) {
		if ((types[i].base_type_ == t) &&
				(!_unsigned || types[i].is_unsigned()) &&
				(!_null || types[i].is_null())) {
			return i;
		}
	}

	return type(MYSQL_TYPE_STRING, false, _null);	// punt!
}

bool mysql_type_info::quote_q() const
{
	const type_info& ti = base_type().c_type();
	return ti == typeid(string) ||
			ti == typeid(sql_date) ||
			ti == typeid(sql_time) ||
			ti == typeid(sql_datetime) ||
			ti == typeid(sql_blob) ||
			ti == typeid(sql_tinyblob) ||
			ti == typeid(sql_mediumblob) ||
			ti == typeid(sql_longblob) ||
			ti == typeid(sql_char) ||
			ti == typeid(sql_set);
}

bool mysql_type_info::escape_q() const
{
	const type_info& ti = c_type();
	return ti == typeid(string) ||
			ti == typeid(sql_enum) ||
			ti == typeid(sql_blob) ||
			ti == typeid(sql_tinyblob) ||
			ti == typeid(sql_mediumblob) ||
			ti == typeid(sql_longblob) ||
			ti == typeid(sql_char) ||
			ti == typeid(sql_varchar);
}

} // end namespace mysqlpp

<|endoftext|>


<commit_before>/*
 * http_server.cpp
 *
 *  Created on: Oct 26, 2014
 *      Author: liao
 */

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/epoll.h>
#include <sys/fcntl.h>
#include <unistd.h>
#include <sstream>
#include "simple_log.h"
#include "http_parser.h"
#include "http_server.h"

int HttpServer::listen_on(int port, int backlog) {
	int sockfd; /* listen on sock_fd, new connection on new_fd */

	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
		perror("socket");
		exit(1);
	}

	struct sockaddr_in my_addr; /* my address information */
	memset (&my_addr, 0, sizeof(my_addr));
	my_addr.sin_family = AF_INET; /* host byte order */
	my_addr.sin_port = htons(port); /* short, network byte order */
	my_addr.sin_addr.s_addr = INADDR_ANY; /* auto-fill with my IP */

	int opt = 1;
	setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

	if (bind(sockfd, (struct sockaddr *) &my_addr, sizeof(struct sockaddr)) == -1) {
		perror("bind");
		exit(1);
	}

	if (listen(sockfd, backlog) == -1) {
		perror("listen");
		exit(1);
	}

	LOG_INFO("start HttpServer on port : %d", port);
	return sockfd;
}

int HttpServer::accept_socket(int sockfd) {
	int new_fd;
	struct sockaddr_in their_addr; /* connector's address information */
	socklen_t sin_size = sizeof(struct sockaddr_in);

	if ((new_fd = accept(sockfd, (struct sockaddr *) &their_addr, &sin_size)) == -1) {
		perror("accept");
		return -1;
	}

	LOG_DEBUG("server: got connection from %s\n", inet_ntoa(their_addr.sin_addr));
	return new_fd;
}

int HttpServer::setNonblocking(int fd) {
	int flags;

	if (-1 == (flags = fcntl(fd, F_GETFL, 0)))
		flags = 0;
	return fcntl(fd, F_SETFL, flags | O_NONBLOCK);

}

int HttpServer::start(int port, int backlog) {

	int sockfd = this->listen_on(port, backlog);

	struct epoll_event ev;
	int epollfd = epoll_create(10);
	if (epollfd == -1) {
		perror("epoll_create");
		exit(EXIT_FAILURE);
	}

	ev.events = EPOLLIN;
	ev.data.fd = sockfd;
	if(epoll_ctl(epollfd, EPOLL_CTL_ADD, sockfd, &ev) == -1) {
		perror("epoll_ctl: listen_sock");
		exit(EXIT_FAILURE);
	}

	epoll_event events[10];

	while(1) {
		int fds_num = epoll_wait(epollfd, events, 10, -1);
		if(fds_num == -1) {
			perror("epoll_pwait");
			exit(EXIT_FAILURE);
		}

		for (int i = 0; i < fds_num; i++) {
			if(events[i].data.fd == sockfd) {
				int conn_sock = accept_socket(sockfd);
				setNonblocking(conn_sock);
				LOG_DEBUG("get accept socket which listen fd:%d, conn_sock_fd:%d", sockfd, conn_sock);

				epoll_event conn_sock_ev;
				conn_sock_ev.events = EPOLLIN | EPOLLET;
				conn_sock_ev.data.ptr = new HttpContext(new Request(), new Response(STATUS_OK), conn_sock);

				if (epoll_ctl(epollfd, EPOLL_CTL_ADD, conn_sock, &conn_sock_ev) == -1) {
				   perror("epoll_ctl: conn_sock");
				   exit(EXIT_FAILURE);
				}

			} else if(events[i].events & EPOLLIN ){ // readable
				HttpContext *hc = (HttpContext *) events[i].data.ptr;
				int fd = hc->fd;
				int buffer_size = 1024;
				char read_buffer[buffer_size];
				memset(read_buffer, 0, buffer_size);
				int read_size = 0;

				if((read_size = recv(fd, read_buffer, buffer_size, 0)) > 0) {
					LOG_DEBUG("read success which read content:%s", read_buffer);

					int parse_part = PARSE_REQ_LINE;
					HttpContext *http_context = (HttpContext *) events[i].data.ptr;
					http_context->record_start_time();

					int ret = parse_request(read_buffer, buffer_size, read_size, parse_part, *(http_context->req));
					if(ret != 0) {
						LOG_WARN("parse_request error which ret:%d", ret);

						close_and_remove_epoll_events(epollfd, events[i]);
						continue;
					}
					this->handle_request(*(http_context->req), *(http_context->res));

					events[i].events = EPOLLOUT | EPOLLET;
					epoll_ctl(epollfd, EPOLL_CTL_MOD, fd, &events[i]);

				} else {
					LOG_DEBUG("read_size not normal which size:%d", read_size);
					close_and_remove_epoll_events(epollfd, events[i]);
				}
			} else if(events[i].events & EPOLLOUT) { // writeable
				HttpContext *hc = (HttpContext *) events[i].data.ptr;
				int fd = hc->fd;
				LOG_DEBUG("start write data");

				bool is_keepalive = (strcasecmp(hc->req->get_header("Connection").c_str(), "keep-alive") == 0);
				std::string content = hc->res->gen_response(hc->req->line.http_version, is_keepalive);

				// write until body response
				int body_size = content.size();
				int write_num = 0;
				const char *p = content.c_str();
				while(body_size > write_num) {
					int buf_size = 65536;
					if(body_size - write_num < buf_size) {
						buf_size = body_size - write_num;
					}
					int one_write = send(fd, p + write_num, buf_size, 0);
					if(write_num < 0) {
						perror("send");
						break;
					}
					write_num += one_write;
				}

				LOG_DEBUG("send complete which write_num:%d, content_size:%d", write_num, content.size());

				hc->print_access_log();

				if(is_keepalive) {
					events[i].events = EPOLLIN | EPOLLET;
					epoll_ctl(epollfd, EPOLL_CTL_MOD, fd, &events[i]);
				} else {
					close_and_remove_epoll_events(epollfd, events[i]);
				}
			} else {
				LOG_INFO("unkonw events :%d", events[i].events);
				continue;
			}
		}
	}

}

int HttpServer::close_and_remove_epoll_events(int &epollfd, epoll_event &epoll_event) {
	LOG_INFO("connect close");
	HttpContext *hc = (HttpContext *) epoll_event.data.ptr;
	int fd = hc->fd;
	epoll_event.events = EPOLLIN | EPOLLOUT | EPOLLET;
	epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, &epoll_event);

	if(epoll_event.data.ptr != NULL) {
		delete (HttpContext *)epoll_event.data.ptr;
		epoll_event.data.ptr = NULL;
	}

	int ret = close(fd);
	LOG_DEBUG("connect close complete which fd:%d, ret:%d", fd, ret);
	return 0;
}

void HttpServer::add_mapping(std::string path, method_handler_ptr handler, HttpMethod method) {
	Resource resource = {method, handler};
	resource_map[path] = resource;
}

int HttpServer::handle_request(Request &req, Response &res) {
	std::string uri = req.get_request_uri();
	if(this->resource_map.find(uri) == this->resource_map.end()) { // not found
		res.code_msg = STATUS_NOT_FOUND;
		res.body = STATUS_NOT_FOUND.msg;
		LOG_INFO("page not found which uri:%s", uri.c_str());
		return 0;
	}

	Resource resource = this->resource_map[req.get_request_uri()];
	// check method
	HttpMethod method = resource.method;
	if(method.code != ALL_METHOD.code && method.name != req.line.method) {
		res.code_msg = STATUS_METHOD_NOT_ALLOWED;
		res.set_head("Allow", method.name);
		res.body.clear();
		LOG_INFO("not allow method, allowed:%s, request method:%s", method.name.c_str(), req.line.method.c_str());
		return 0;
	}
	method_handler_ptr handle = resource.handler_ptr;
	if(handle != NULL) {
		res = handle(req);
	}
	LOG_DEBUG("handle response success which code:%d, msg:%s", res.code_msg.status_code, res.code_msg.msg.c_str());
	return 0;
}
<commit_msg>bug fix<commit_after>/*
 * http_server.cpp
 *
 *  Created on: Oct 26, 2014
 *      Author: liao
 */

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/epoll.h>
#include <sys/fcntl.h>
#include <unistd.h>
#include <sstream>
#include "simple_log.h"
#include "http_parser.h"
#include "http_server.h"

int HttpServer::listen_on(int port, int backlog) {
	int sockfd; /* listen on sock_fd, new connection on new_fd */

	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
		perror("socket");
		exit(1);
	}

	struct sockaddr_in my_addr; /* my address information */
	memset (&my_addr, 0, sizeof(my_addr));
	my_addr.sin_family = AF_INET; /* host byte order */
	my_addr.sin_port = htons(port); /* short, network byte order */
	my_addr.sin_addr.s_addr = INADDR_ANY; /* auto-fill with my IP */

	int opt = 1;
	setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

	if (bind(sockfd, (struct sockaddr *) &my_addr, sizeof(struct sockaddr)) == -1) {
		perror("bind");
		exit(1);
	}

	if (listen(sockfd, backlog) == -1) {
		perror("listen");
		exit(1);
	}

	LOG_INFO("start HttpServer on port : %d", port);
	return sockfd;
}

int HttpServer::accept_socket(int sockfd) {
	int new_fd;
	struct sockaddr_in their_addr; /* connector's address information */
	socklen_t sin_size = sizeof(struct sockaddr_in);

	if ((new_fd = accept(sockfd, (struct sockaddr *) &their_addr, &sin_size)) == -1) {
		perror("accept");
		return -1;
	}

	LOG_DEBUG("server: got connection from %s\n", inet_ntoa(their_addr.sin_addr));
	return new_fd;
}

int HttpServer::setNonblocking(int fd) {
	int flags;

	if (-1 == (flags = fcntl(fd, F_GETFL, 0)))
		flags = 0;
	return fcntl(fd, F_SETFL, flags | O_NONBLOCK);

}

int HttpServer::start(int port, int backlog) {

	int sockfd = this->listen_on(port, backlog);

	struct epoll_event ev;
	int epollfd = epoll_create(10);
	if (epollfd == -1) {
		perror("epoll_create");
		exit(EXIT_FAILURE);
	}

	ev.events = EPOLLIN;
	ev.data.fd = sockfd;
	if(epoll_ctl(epollfd, EPOLL_CTL_ADD, sockfd, &ev) == -1) {
		perror("epoll_ctl: listen_sock");
		exit(EXIT_FAILURE);
	}

	epoll_event events[10];

	while(1) {
		int fds_num = epoll_wait(epollfd, events, 10, -1);
		if(fds_num == -1) {
			perror("epoll_pwait");
			exit(EXIT_FAILURE);
		}

		for (int i = 0; i < fds_num; i++) {
			if(events[i].data.fd == sockfd) {
				int conn_sock = accept_socket(sockfd);
				setNonblocking(conn_sock);
				LOG_DEBUG("get accept socket which listen fd:%d, conn_sock_fd:%d", sockfd, conn_sock);

				epoll_event conn_sock_ev;
				conn_sock_ev.events = EPOLLIN | EPOLLET;
				conn_sock_ev.data.ptr = new HttpContext(new Request(), new Response(STATUS_OK), conn_sock);

				if (epoll_ctl(epollfd, EPOLL_CTL_ADD, conn_sock, &conn_sock_ev) == -1) {
				   perror("epoll_ctl: conn_sock");
				   exit(EXIT_FAILURE);
				}

			} else if(events[i].events & EPOLLIN ){ // readable
				HttpContext *hc = (HttpContext *) events[i].data.ptr;
				int fd = hc->fd;
				int buffer_size = 1024;
				char read_buffer[buffer_size];
				memset(read_buffer, 0, buffer_size);
				int read_size = 0;

				if((read_size = recv(fd, read_buffer, buffer_size, 0)) > 0) {
					LOG_DEBUG("read success which read content:%s", read_buffer);

					int parse_part = PARSE_REQ_LINE;
					HttpContext *http_context = (HttpContext *) events[i].data.ptr;
					http_context->record_start_time();

					int ret = parse_request(read_buffer, buffer_size, read_size, parse_part, *(http_context->req));
					if(ret != 0) {
						LOG_WARN("parse_request error which ret:%d", ret);

						close_and_remove_epoll_events(epollfd, events[i]);
						continue;
					}
					this->handle_request(*(http_context->req), *(http_context->res));

					events[i].events = EPOLLOUT | EPOLLET;
					epoll_ctl(epollfd, EPOLL_CTL_MOD, fd, &events[i]);

				} else {
					LOG_DEBUG("read_size not normal which size:%d", read_size);
					close_and_remove_epoll_events(epollfd, events[i]);
				}
			} else if(events[i].events & EPOLLOUT) { // writeable
				HttpContext *hc = (HttpContext *) events[i].data.ptr;
				int fd = hc->fd;
				LOG_DEBUG("start write data");

				bool is_keepalive = (strcasecmp(hc->req->get_header("Connection").c_str(), "keep-alive") == 0);
				std::string content = hc->res->gen_response(hc->req->line.http_version, is_keepalive);

				// write until body response
				int body_size = content.size();
				int write_num = 0;
				const char *p = content.c_str();
				while(body_size > write_num) {
					int buf_size = 65536;
					if(body_size - write_num < buf_size) {
						buf_size = body_size - write_num;
					}
					int one_write = send(fd, p + write_num, buf_size, 0);
					if(one_write < 0) {
						perror("send");
						break;
					}
					write_num += one_write;
				}

				LOG_DEBUG("send complete which write_num:%d, content_size:%d", write_num, content.size());

				hc->print_access_log();

				if(is_keepalive) {
					events[i].events = EPOLLIN | EPOLLET;
					epoll_ctl(epollfd, EPOLL_CTL_MOD, fd, &events[i]);
				} else {
					close_and_remove_epoll_events(epollfd, events[i]);
				}
			} else {
				LOG_INFO("unkonw events :%d", events[i].events);
				continue;
			}
		}
	}

}

int HttpServer::close_and_remove_epoll_events(int &epollfd, epoll_event &epoll_event) {
	LOG_INFO("connect close");
	HttpContext *hc = (HttpContext *) epoll_event.data.ptr;
	int fd = hc->fd;
	epoll_event.events = EPOLLIN | EPOLLOUT | EPOLLET;
	epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, &epoll_event);

	if(epoll_event.data.ptr != NULL) {
		delete (HttpContext *)epoll_event.data.ptr;
		epoll_event.data.ptr = NULL;
	}

	int ret = close(fd);
	LOG_DEBUG("connect close complete which fd:%d, ret:%d", fd, ret);
	return 0;
}

void HttpServer::add_mapping(std::string path, method_handler_ptr handler, HttpMethod method) {
	Resource resource = {method, handler};
	resource_map[path] = resource;
}

int HttpServer::handle_request(Request &req, Response &res) {
	std::string uri = req.get_request_uri();
	if(this->resource_map.find(uri) == this->resource_map.end()) { // not found
		res.code_msg = STATUS_NOT_FOUND;
		res.body = STATUS_NOT_FOUND.msg;
		LOG_INFO("page not found which uri:%s", uri.c_str());
		return 0;
	}

	Resource resource = this->resource_map[req.get_request_uri()];
	// check method
	HttpMethod method = resource.method;
	if(method.code != ALL_METHOD.code && method.name != req.line.method) {
		res.code_msg = STATUS_METHOD_NOT_ALLOWED;
		res.set_head("Allow", method.name);
		res.body.clear();
		LOG_INFO("not allow method, allowed:%s, request method:%s", method.name.c_str(), req.line.method.c_str());
		return 0;
	}
	method_handler_ptr handle = resource.handler_ptr;
	if(handle != NULL) {
		res = handle(req);
	}
	LOG_DEBUG("handle response success which code:%d, msg:%s", res.code_msg.status_code, res.code_msg.msg.c_str());
	return 0;
}
<|endoftext|>


<commit_before>// Copyright 2014 Toggl Desktop developers.

#include "./https_client.h"

#include <string>
#include <sstream>

#include "Poco/Exception.h"
#include "Poco/InflatingStream.h"
#include "Poco/DeflatingStream.h"
#include "Poco/Logger.h"
#include "Poco/URI.h"
#include "Poco/NumberParser.h"
#include "Poco/Net/Context.h"
#include "Poco/Net/NameValueCollection.h"
#include "Poco/Net/HTTPMessage.h"
#include "Poco/Net/HTTPBasicCredentials.h"
#include "Poco/Net/InvalidCertificateHandler.h"
#include "Poco/Net/AcceptCertificateHandler.h"
#include "Poco/Net/SSLManager.h"
#include "Poco/Net/PrivateKeyPassphraseHandler.h"
#include "Poco/Net/SecureStreamSocket.h"

#include "./libjson.h"
#include "./const.h"

namespace kopsik {

std::string HTTPSClient::AppName = std::string("");
std::string HTTPSClient::AppVersion = std::string("");
std::string HTTPSClient::APIURL = std::string(kAPIURL);
bool HTTPSClient::UseProxy = false;
bool HTTPSClient::IgnoreCert = false;
kopsik::Proxy HTTPSClient::ProxySettings = Proxy();

error HTTPSClient::PostJSON(
    const std::string relative_url,
    const std::string json,
    const std::string basic_auth_username,
    const std::string basic_auth_password,
    std::string *response_body) {
    return requestJSON(Poco::Net::HTTPRequest::HTTP_POST,
                       relative_url,
                       json,
                       basic_auth_username,
                       basic_auth_password,
                       response_body);
}

error HTTPSClient::GetJSON(
    const std::string relative_url,
    const std::string basic_auth_username,
    const std::string basic_auth_password,
    std::string *response_body) {
    return requestJSON(Poco::Net::HTTPRequest::HTTP_GET,
                       relative_url,
                       "",
                       basic_auth_username,
                       basic_auth_password,
                       response_body);
}

error HTTPSClient::requestJSON(
    const std::string method,
    const std::string relative_url,
    const std::string json,
    const std::string basic_auth_username,
    const std::string basic_auth_password,
    std::string *response_body) {
    return request(
        method,
        relative_url,
        json,
        basic_auth_username,
        basic_auth_password,
        response_body);
}

error HTTPSClient::request(
    const std::string method,
    const std::string relative_url,
    const std::string payload,
    const std::string basic_auth_username,
    const std::string basic_auth_password,
    std::string *response_body) {

    poco_assert(!method.empty());
    poco_assert(!relative_url.empty());

    poco_check_ptr(response_body);

    *response_body = "";

    try {
        Poco::URI uri(APIURL);

        Poco::SharedPtr<Poco::Net::InvalidCertificateHandler>
        acceptCertHandler =
            new Poco::Net::AcceptCertificateHandler(true);

        Poco::Net::Context::VerificationMode verification_mode =
            Poco::Net::Context::VERIFY_RELAXED;
        if (IgnoreCert) {
            verification_mode = Poco::Net::Context::VERIFY_NONE;
        }
        Poco::Net::Context::Ptr context = new Poco::Net::Context(
            Poco::Net::Context::CLIENT_USE, "",
            verification_mode, 9, true, "ALL");

        Poco::Net::SSLManager::instance().initializeClient(
            0, acceptCertHandler, context);

        Poco::Net::HTTPSClientSession session(uri.getHost(), uri.getPort(),
                                              context);
        if (ProxySettings.IsConfigured()) {
            session.setProxy(ProxySettings.host, ProxySettings.port);
            if (ProxySettings.HasCredentials()) {
                session.setProxyCredentials(ProxySettings.username,
                                            ProxySettings.password);
            }
        }
        session.setKeepAlive(false);
        session.setTimeout(Poco::Timespan(10 * Poco::Timespan::SECONDS));

        Poco::Logger &logger = Poco::Logger::get("https_client");
        {
            std::stringstream ss;
            ss << "Sending request to " << relative_url << " ..";
            logger.debug(ss.str());
        }

        Poco::Net::HTTPRequest req(method,
                                   relative_url,
                                   Poco::Net::HTTPMessage::HTTP_1_1);
        req.setKeepAlive(false);
        req.setContentType("application/json");
        req.set("User-Agent", UserAgent());
        req.setChunkedTransferEncoding(true);

        Poco::Net::HTTPBasicCredentials cred(
            basic_auth_username, basic_auth_password);
        if (!basic_auth_username.empty() && !basic_auth_password.empty()) {
            cred.authenticate(req);
        }

        std::istringstream requestStream(payload);
        Poco::DeflatingInputStream gzipRequest(
            requestStream,
            Poco::DeflatingStreamBuf::STREAM_GZIP);
        Poco::DeflatingStreamBuf *pBuff = gzipRequest.rdbuf();

        Poco::Int64 size = pBuff->pubseekoff(0, std::ios::end, std::ios::in);
        pBuff->pubseekpos(0, std::ios::in);

        req.setContentLength(size);
        req.set("Content-Encoding", "gzip");
        req.set("Accept-Encoding", "gzip");

        session.sendRequest(req) << pBuff << std::flush;

        // Log out request contents
        std::stringstream request_string;
        req.write(request_string);
        logger.debug(request_string.str());

        logger.debug("Request sent. Receiving response..");

        // Receive response
        Poco::Net::HTTPResponse response;
        std::istream& is = session.receiveResponse(response);

        {
            std::stringstream ss;
            ss << "Response status code " << response.getStatus()
               << ", content length " << response.getContentLength()
               << ", content type " << response.getContentType();
            if (response.has("Content-Encoding")) {
                ss << ", content encoding " << response.get("Content-Encoding");
            } else {
                ss << ", unknown content encoding";
            }
            logger.debug(ss.str());
        }

        // Inflate, if gzip was sent
        if (response.has("Content-Encoding") &&
                "gzip" == response.get("Content-Encoding")) {
            Poco::InflatingInputStream inflater(
                is,
                Poco::InflatingStreamBuf::STREAM_GZIP);
            {
                std::stringstream ss;
                ss << inflater.rdbuf();
                *response_body = ss.str();
            }
        } else {
            std::istreambuf_iterator<char> eos;
            *response_body =
                std::string(std::istreambuf_iterator<char>(is), eos);
        }

        logger.trace(*response_body);

        if (response.getStatus() < 200 || response.getStatus() >= 300) {
            if (response_body->empty()) {
                std::stringstream description;
                description << "Request to server failed with status code: "
                            << response.getStatus();
                return description.str();
            }
            return "Request failed with error: " + *response_body;
        }
    } catch(const Poco::Exception& exc) {
        return exc.displayText();
    } catch(const std::exception& ex) {
        return ex.what();
    } catch(const std::string& ex) {
        return ex;
    }
    return noError;
}

}   // namespace kopsik
<commit_msg>Encode http request URIs<commit_after>// Copyright 2014 Toggl Desktop developers.

#include "./https_client.h"

#include <string>
#include <sstream>

#include "Poco/Exception.h"
#include "Poco/InflatingStream.h"
#include "Poco/DeflatingStream.h"
#include "Poco/Logger.h"
#include "Poco/URI.h"
#include "Poco/NumberParser.h"
#include "Poco/Net/Context.h"
#include "Poco/Net/NameValueCollection.h"
#include "Poco/Net/HTTPMessage.h"
#include "Poco/Net/HTTPBasicCredentials.h"
#include "Poco/Net/InvalidCertificateHandler.h"
#include "Poco/Net/AcceptCertificateHandler.h"
#include "Poco/Net/SSLManager.h"
#include "Poco/Net/PrivateKeyPassphraseHandler.h"
#include "Poco/Net/SecureStreamSocket.h"

#include "./libjson.h"
#include "./const.h"

namespace kopsik {

std::string HTTPSClient::AppName = std::string("");
std::string HTTPSClient::AppVersion = std::string("");
std::string HTTPSClient::APIURL = std::string(kAPIURL);
bool HTTPSClient::UseProxy = false;
bool HTTPSClient::IgnoreCert = false;
kopsik::Proxy HTTPSClient::ProxySettings = Proxy();

error HTTPSClient::PostJSON(
    const std::string relative_url,
    const std::string json,
    const std::string basic_auth_username,
    const std::string basic_auth_password,
    std::string *response_body) {
    return requestJSON(Poco::Net::HTTPRequest::HTTP_POST,
                       relative_url,
                       json,
                       basic_auth_username,
                       basic_auth_password,
                       response_body);
}

error HTTPSClient::GetJSON(
    const std::string relative_url,
    const std::string basic_auth_username,
    const std::string basic_auth_password,
    std::string *response_body) {
    return requestJSON(Poco::Net::HTTPRequest::HTTP_GET,
                       relative_url,
                       "",
                       basic_auth_username,
                       basic_auth_password,
                       response_body);
}

error HTTPSClient::requestJSON(
    const std::string method,
    const std::string relative_url,
    const std::string json,
    const std::string basic_auth_username,
    const std::string basic_auth_password,
    std::string *response_body) {
    return request(
        method,
        relative_url,
        json,
        basic_auth_username,
        basic_auth_password,
        response_body);
}

error HTTPSClient::request(
    const std::string method,
    const std::string relative_url,
    const std::string payload,
    const std::string basic_auth_username,
    const std::string basic_auth_password,
    std::string *response_body) {

    poco_assert(!method.empty());
    poco_assert(!relative_url.empty());

    poco_check_ptr(response_body);

    *response_body = "";

    try {
        Poco::URI uri(APIURL);

        Poco::SharedPtr<Poco::Net::InvalidCertificateHandler>
        acceptCertHandler =
            new Poco::Net::AcceptCertificateHandler(true);

        Poco::Net::Context::VerificationMode verification_mode =
            Poco::Net::Context::VERIFY_RELAXED;
        if (IgnoreCert) {
            verification_mode = Poco::Net::Context::VERIFY_NONE;
        }
        Poco::Net::Context::Ptr context = new Poco::Net::Context(
            Poco::Net::Context::CLIENT_USE, "",
            verification_mode, 9, true, "ALL");

        Poco::Net::SSLManager::instance().initializeClient(
            0, acceptCertHandler, context);

        Poco::Net::HTTPSClientSession session(uri.getHost(), uri.getPort(),
                                              context);
        if (ProxySettings.IsConfigured()) {
            session.setProxy(ProxySettings.host, ProxySettings.port);
            if (ProxySettings.HasCredentials()) {
                session.setProxyCredentials(ProxySettings.username,
                                            ProxySettings.password);
            }
        }
        session.setKeepAlive(false);
        session.setTimeout(Poco::Timespan(10 * Poco::Timespan::SECONDS));

        Poco::Logger &logger = Poco::Logger::get("https_client");
        {
            std::stringstream ss;
            ss << "Sending request to " << relative_url << " ..";
            logger.debug(ss.str());
        }

        std::string encoded_url("");
        Poco::URI::encode(relative_url, "", encoded_url);
        Poco::Net::HTTPRequest req(method,
                                   encoded_url,
                                   Poco::Net::HTTPMessage::HTTP_1_1);
        req.setKeepAlive(false);
        req.setContentType("application/json");
        req.set("User-Agent", UserAgent());
        req.setChunkedTransferEncoding(true);

        Poco::Net::HTTPBasicCredentials cred(
            basic_auth_username, basic_auth_password);
        if (!basic_auth_username.empty() && !basic_auth_password.empty()) {
            cred.authenticate(req);
        }

        std::istringstream requestStream(payload);
        Poco::DeflatingInputStream gzipRequest(
            requestStream,
            Poco::DeflatingStreamBuf::STREAM_GZIP);
        Poco::DeflatingStreamBuf *pBuff = gzipRequest.rdbuf();

        Poco::Int64 size = pBuff->pubseekoff(0, std::ios::end, std::ios::in);
        pBuff->pubseekpos(0, std::ios::in);

        req.setContentLength(size);
        req.set("Content-Encoding", "gzip");
        req.set("Accept-Encoding", "gzip");

        session.sendRequest(req) << pBuff << std::flush;

        // Log out request contents
        std::stringstream request_string;
        req.write(request_string);
        logger.debug(request_string.str());

        logger.debug("Request sent. Receiving response..");

        // Receive response
        Poco::Net::HTTPResponse response;
        std::istream& is = session.receiveResponse(response);

        {
            std::stringstream ss;
            ss << "Response status code " << response.getStatus()
               << ", content length " << response.getContentLength()
               << ", content type " << response.getContentType();
            if (response.has("Content-Encoding")) {
                ss << ", content encoding " << response.get("Content-Encoding");
            } else {
                ss << ", unknown content encoding";
            }
            logger.debug(ss.str());
        }

        // Inflate, if gzip was sent
        if (response.has("Content-Encoding") &&
                "gzip" == response.get("Content-Encoding")) {
            Poco::InflatingInputStream inflater(
                is,
                Poco::InflatingStreamBuf::STREAM_GZIP);
            {
                std::stringstream ss;
                ss << inflater.rdbuf();
                *response_body = ss.str();
            }
        } else {
            std::istreambuf_iterator<char> eos;
            *response_body =
                std::string(std::istreambuf_iterator<char>(is), eos);
        }

        logger.trace(*response_body);

        if (response.getStatus() < 200 || response.getStatus() >= 300) {
            if (response_body->empty()) {
                std::stringstream description;
                description << "Request to server failed with status code: "
                            << response.getStatus();
                return description.str();
            }
            return "Request failed with error: " + *response_body;
        }
    } catch(const Poco::Exception& exc) {
        return exc.displayText();
    } catch(const std::exception& ex) {
        return ex.what();
    } catch(const std::string& ex) {
        return ex;
    }
    return noError;
}

}   // namespace kopsik
<|endoftext|>


<commit_before>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <vector>
#include <string>
#define MemoryPool 0x100000 * 1

#ifndef as_header
#define as_header
#include "vm.h"
#include "instruction.h"
#undef as_header
#endif

std::vector<long long> text;
std::vector<long long> text_line;
std::vector<char*> line_front;

enum Tool {submit = 1, interpret, debug} Todo;
char* code;
char* p_code;
FILE* inputFile;

void printHelp() {
  printf("exit code:\n"
        "  0  successfully\n"
        "  -1 file error\n"
        "  -2 compile error\n"
        "\n"
        "usage:\n"
        "  s    generate a code for submission online\n"
        "  i    interpret\n"
        "  d    debug\n"
        "\n"
        "example:\n"
        "  ./vm s code.vm input.txt\n");
}

#define report(...) fprintf(stderr, __VA_ARGS__), exit(-1)

void argument(int argc, char* argv[]) {
  if (argc != 3 && argc != 4) {printHelp(); report("no input.\n");}

  if (argv[1][0] == 's') Todo = submit;
  else if (argv[1][0] == 'i') Todo = interpret;
  else if (argv[1][0] == 'd') {
    Todo = debug;
    if (argc != 4) report("debug mode need an input file.\n");
  }

  if (! Todo) report("nothing to be done.\n");
  char* fileName = argv[2];
#define report_close(...) fclose(input), report(__VA_ARGS__)
  if (FILE* input = fopen(fileName, "r")) {
    if (fseek(input, 0, SEEK_END)) report_close("seek_end error.\n");
    int lenCode = ftell(input);
    code = new char[lenCode + 1];
    if (fseek(input, 0, SEEK_SET)) report_close("seek_set error.\n");
    if (lenCode != (int) fread(code, 1, lenCode, input)) report_close("couldn't read the code!\n");
    code[lenCode] = 0; // append '\0'
    if (fclose(input)) report("couldn't close '%s'\n", fileName);
  }
  else report("couldn't open '%s'\n", fileName);
#undef report_close

  if (argc == 4) {
   if (! (inputFile = fopen(argv[3], "r"))) report("couldn't open '%s'\n", argv[3]);
  }
}

int line, column;

void print_code_line(int line) {
  fprintf(stderr, "%4d: ", line);
  char* front = line_front[line];
  while (*front!= '\n' && *front)
    fprintf(stderr, "%c", *front++);
  fprintf(stderr, "\n");
}

void report_compile_error(const char* const msg) {
  print_code_line(line);
  for (int i = 1; i < column + 5; i++) fprintf(stderr, " ");
  fprintf(stderr, "^\nerror: %s\n", msg);
  exit(-2);
}

int nextChar() {
  if (*p_code == '\0') return EOF;
  if (p_code == code || *(p_code - 1) == '\n') {
    line++;
    column = 1;
    line_front.push_back(p_code);
  }
  else column++;
  return *p_code++;
}

enum token {
  tok_num = -100,
  tok_label,
  tok_eof,
};

int CurToken;
long long Number;
std::string StrToken;

int counter;
std::map<std::string, long long> label; // used for 'jump' instruction

bool isidentifier(int c) {
  return isalpha(c) || isdigit(c) || c == '_' || c == '-';
}

void nextToken(int take_place = 1) {
#define MAXBUFFER 256
  static char s[MAXBUFFER];
  static int c;
  if (p_code == code) c = ' ';
  while (1) {
    while (isspace(c) && c != EOF) c = nextChar();
    if (c == ';') while (c != '\n' && c != EOF) c = nextChar();
    else break;
  }
  if (c == EOF) {
    CurToken = tok_eof;
    return;
  }
  if (! isidentifier(c)) {
    CurToken = c;
    c = nextChar();
    return;
  }

  int len = 0;
  while (isidentifier(c)) {
    s[len++] = c;
    if (len + 2 >= MAXBUFFER) report_compile_error("identifier too long.");
    c = nextChar();
  }
  s[len] = 0;
#undef MAXBUFFER

  //fprintf(stderr, "%s at %d\n", s, counter);
  if (take_place) counter++; // !

  int isNum = 1;
  for (int i = 0; i < len; i++)
    if (! isdigit(s[i]) && s[i] != '-') {isNum = 0; break;}
  if (isNum) {
    if (1 != sscanf(s, "%lld", &Number)) report_compile_error("unknown number.");
    CurToken = tok_num;
    return;
  }

  CurToken = tok_eof;
  if      (! strcmp(s, "LOD")) Number = LOD, CurToken = tok_num;
  else if (! strcmp(s, "IMM")) Number = IMM, CurToken = tok_num;
  else if (! strcmp(s, "LEA")) Number = LEA, CurToken = tok_num;
  else if (! strcmp(s, "JMP")) Number = JMP, CurToken = tok_num;
  else if (! strcmp(s, "JZ" )) Number = JZ , CurToken = tok_num;

  else if (! strcmp(s, "JNZ")) Number = JNZ, CurToken = tok_num;
  else if (! strcmp(s, "STO")) Number = STO, CurToken = tok_num;
  else if (! strcmp(s, "PSH")) Number = PSH, CurToken = tok_num;
  else if (! strcmp(s, "ENT")) Number = ENT, CurToken = tok_num;
  else if (! strcmp(s, "LEV")) Number = LEV, CurToken = tok_num;

  else if (! strcmp(s, "CALL")) Number = CALL, CurToken = tok_num;
  else if (! strcmp(s, "EXIT")) Number = EXIT, CurToken = tok_num;
  else if (! strcmp(s, "ADJ"))  Number = ADJ,  CurToken = tok_num;

  /* ------------------------------ */
  else if (! strcmp(s, "ADD")) Number = ADD, CurToken = tok_num;
  else if (! strcmp(s, "SUB")) Number = SUB, CurToken = tok_num;
  else if (! strcmp(s, "MUL")) Number = MUL, CurToken = tok_num;
  else if (! strcmp(s, "DIV")) Number = DIV, CurToken = tok_num;
  else if (! strcmp(s, "MOD")) Number = MOD, CurToken = tok_num;

  else if (! strcmp(s, "EQ")) Number = EQ, CurToken = tok_num;
  else if (! strcmp(s, "NE")) Number = NE, CurToken = tok_num;
  else if (! strcmp(s, "XOR"))Number = XOR,CurToken = tok_num;
  else if (! strcmp(s, "LT")) Number = LT, CurToken = tok_num;
  else if (! strcmp(s, "GT")) Number = GT, CurToken = tok_num;

  else if (! strcmp(s, "LE")) Number = LE, CurToken = tok_num;
  else if (! strcmp(s, "GE" )) Number = GE , CurToken = tok_num;
  else if (! strcmp(s, "SHL")) Number = SHL, CurToken = tok_num;
  else if (! strcmp(s, "SHR")) Number = SHR, CurToken = tok_num;
  else if (! strcmp(s, "INC")) Number = INC, CurToken = tok_num;

  else if (! strcmp(s, "DEC")) Number = DEC, CurToken = tok_num;

  /* ------------------------------ */
  else if (! strcmp(s, "RINT")) Number = RINT, CurToken = tok_num;
  else if (! strcmp(s, "WINT")) Number = WINT, CurToken = tok_num;
  else if (! strcmp(s, "GETC")) Number = GETC, CurToken = tok_num;
  else if (! strcmp(s, "PUTC")) Number = PUTC, CurToken = tok_num;
  if (CurToken != tok_eof) return;

  StrToken.assign(s);
  if (label.count(StrToken)) {
    Number = label[StrToken];
    CurToken = tok_num;
  }
  else CurToken = tok_label;
}

void init() {
  p_code = code;
  line = column = 0;
  line_front.clear();
  line_front.push_back(0); // start from 1
  nextToken();
}

void clean() {
  delete []code;
  if (inputFile) fclose(inputFile);
}

void cat(const char* const s) {
  if (FILE* f = fopen(s, "rb")) {
    int t;
    while (EOF != (t = fgetc(f))) putchar(t);
    if (fclose(f)) report("couldn't close file '%s'", s);
    putchar(10);
  }
  else report("couldn't find '%s'", s);
}

void debug_scanf(long long &x) {
  if (inputFile) fscanf(inputFile, "%lld", &x);
  else scanf("%lld", &x);
}

void debug_getchar(long long &x) {
  if (inputFile) x = fgetc(inputFile);
  else x = getchar();
}

void debug_handle(int cur, long long reg, int sp) {
  if (Todo != debug) return;
  if (cur < 0 || cur >= (int) text.size()) {
    // the bottom of the stack is PSH EXIT
    if (cur != MemoryPool - 1 &&
        cur != MemoryPool - 2)
      fprintf(stderr, "debug error: the %%cur beyond the text.\n");
    return;
  }
  int curLine = text_line[cur];
  static int lastLine = -1;
  if (curLine == lastLine) return;
  static int hook = -1; // use for setting a breakpoint
  if (hook != -1) {
    if (curLine != hook) return;
    else hook = -1;
  }

  print_code_line(curLine);

  int command, adr;
  while (1) {
    fprintf(stderr, "debug> ");
    command = getchar();
    std::string s("");

    if (command != '\n') {
      adr = 0;
      do {
        if (adr != -1) {
          if (! isdigit(command)) adr = -1;
          else adr = adr * 10 + (15 & command);
        }
        s += command;
        command = getchar();
      }while (command != '\n');
    }
    else {
      adr = -1;
      s = "n";
    }

    // next
    if      (s == "n") {
      break;
    }
    // quit
    else if (s == "q") {
      fprintf(stderr, "quit now.\n");
      exit(0);
    }
    // show reg ans stk
    else if (s == "p") {
      fprintf(stderr, "      reg: %6lld stk:", reg);
      for (int i = MemoryPool - 1; i >= sp; i--)
        fprintf(stderr, " %lld", m[i]);
      fprintf(stderr, "\n");
    }
    // show code
    else if (s == "l") {
      for (int i = std::max(1, curLine - 10),
          _i = std::min(curLine + 10, (int) line_front.size() - 1);
          i < _i; i++)
        print_code_line(i);
    }
    // show m[address] or set a breakpoint
    else if (adr != -1) {
      if (adr < 0 || adr >= MemoryPool)
        fprintf(stderr, "debug error: address beyond the memory.\n");
      else if (adr >= (int) text.size())
        fprintf(stderr, "     memory[%d] = %lld\n", adr, m[adr]);
      else if (adr != curLine) {
        hook = adr;
        break;
      }
      else
        fprintf(stderr, "nothing to do.\n");
    }
    // show varible or label
    else if (label.count(s)) {
      fprintf(stderr, "     %s = %lld\n", s.c_str(), label[s]);
    }
    else {
      //fprintf(stderr, "nothing to do.\n");
    }
  }
  while (command != '\n') command = getchar();

  lastLine = curLine;
}

int main(int argc, char* argv[]) {
  argument(argc, argv);
  for (int i = 0; i < 2; i++) {
    init();
    while (1) {
      if      (CurToken == tok_num) {
        if (i) {
          text.push_back(Number);
          if (Todo == debug) text_line.push_back(line);
        }
        nextToken();
      }
      else if (CurToken == '@') {
        nextToken(0);
        int location = counter; // jump to location
        if (CurToken != tok_label && i == 0) report_compile_error("expected label");
        std::string s = StrToken;
        nextToken();
        if (CurToken == '=') {
          nextToken(0);
          if (i == 0) {
            if (CurToken != tok_num) report_compile_error("expected number");
            label[s] = Number;
          }
          nextToken();
        }
        else if (i == 0) {
          //fprintf(stderr, "%s -> %d\n", s.c_str(), counter);
          label[s] = location;
        }
      }
      else if (CurToken == tok_eof) break;
      else if (i == 0) nextToken();
      else report_compile_error("unknown token");
    }
  }

  if (Todo == submit) {
    printf("#include <stdio.h>\n"
           "#include <stdlib.h>\n");
    printf("#define MemoryPool %d\n", (int) 1e6);
    cat("vm.h");
    printf("const long long text[] = {");
    for (int i = 0, _i = text.size(); i < _i; i++) {
      printf("%lld", text[i]);
      if (text[i] >= (1LL << 31) || text[i] < -(1LL << 31)) printf("ll");
      if (i + 1 < _i) printf(",");
    }
    printf("};\n");
    printf("int main() {\n"
        "int i; for (i = 0; i < %d; i++) m[i] = text[i];\n", (int) text.size());
    printf("VMRun();\n"
        "return 0;}\n");
  }
  else if (Todo == interpret || Todo == debug) {
    for (int i = 0, _i = (int) text.size(); i < _i; i++) m[i] = text[i];
    VMRun();
  }
  else report("nothing to be done.\n");

  clean();
  return 0;
}
<commit_msg>update debug mode<commit_after>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <vector>
#include <string>
#define MemoryPool 0x100000 * 1

#ifndef as_header
#define as_header
#include "vm.h"
#include "instruction.h"
#undef as_header
#endif

std::vector<long long> text;
std::vector<long long> text_line;
std::vector<char*> line_front;

enum Tool {submit = 1, interpret, debug} Todo;
char* code;
char* p_code;
FILE* inputFile;

void printHelp() {
  printf("exit code:\n"
        "  0  successfully\n"
        "  -1 file error\n"
        "  -2 compile error\n"
        "\n"
        "usage:\n"
        "  s    generate a code for submission online\n"
        "  i    interpret\n"
        "  d    debug\n"
        "\n"
        "example:\n"
        "  ./vm s code.vm input.txt\n");
}

#define report(...) fprintf(stderr, __VA_ARGS__), exit(-1)

void argument(int argc, char* argv[]) {
  if (argc != 3 && argc != 4) {printHelp(); report("no input.\n");}

  if (argv[1][0] == 's') Todo = submit;
  else if (argv[1][0] == 'i') Todo = interpret;
  else if (argv[1][0] == 'd') {
    Todo = debug;
    if (argc != 4) report("debug mode need an input file.\n");
  }

  if (! Todo) report("nothing to be done.\n");
  char* fileName = argv[2];
#define report_close(...) fclose(input), report(__VA_ARGS__)
  if (FILE* input = fopen(fileName, "r")) {
    if (fseek(input, 0, SEEK_END)) report_close("seek_end error.\n");
    int lenCode = ftell(input);
    code = new char[lenCode + 1];
    if (fseek(input, 0, SEEK_SET)) report_close("seek_set error.\n");
    if (lenCode != (int) fread(code, 1, lenCode, input)) report_close("couldn't read the code!\n");
    code[lenCode] = 0; // append '\0'
    if (fclose(input)) report("couldn't close '%s'\n", fileName);
  }
  else report("couldn't open '%s'\n", fileName);
#undef report_close

  if (argc == 4) {
   if (! (inputFile = fopen(argv[3], "r"))) report("couldn't open '%s'\n", argv[3]);
  }
}

int line, column;

void print_code_line(int line) {
  fprintf(stderr, "%4d: ", line);
  char* front = line_front[line];
  while (*front!= '\n' && *front)
    fprintf(stderr, "%c", *front++);
  fprintf(stderr, "\n");
}

bool empty_line(int line) {
  if (line == (int) line_front.size()) return false;
  char* front = line_front[line];
  while (*front!= '\n' && *front) {
    if (*front == ';') break;
    if (! isspace(*front)) return false;
    front++;
  }
  return true;
}

void report_compile_error(const char* const msg) {
  print_code_line(line);
  for (int i = 1; i < column + 5; i++) fprintf(stderr, " ");
  fprintf(stderr, "^\nerror: %s\n", msg);
  exit(-2);
}

int nextChar() {
  if (*p_code == '\0') return EOF;
  if (p_code == code || *(p_code - 1) == '\n') {
    line++;
    column = 1;
    line_front.push_back(p_code);
  }
  else column++;
  return *p_code++;
}

enum token {
  tok_num = -100,
  tok_label,
  tok_eof,
};

int CurToken;
long long Number;
std::string StrToken;

int counter;
std::map<std::string, long long> label; // used for 'jump' instruction

bool isidentifier(int c) {
  return isalpha(c) || isdigit(c) || c == '_' || c == '-';
}

void nextToken(int take_place = 1) {
#define MAXBUFFER 256
  static char s[MAXBUFFER];
  static int c;
  if (p_code == code) c = ' ';
  while (1) {
    while (isspace(c) && c != EOF) c = nextChar();
    if (c == ';') while (c != '\n' && c != EOF) c = nextChar();
    else break;
  }
  if (c == EOF) {
    CurToken = tok_eof;
    return;
  }
  if (! isidentifier(c)) {
    CurToken = c;
    c = nextChar();
    return;
  }

  int len = 0;
  while (isidentifier(c)) {
    s[len++] = c;
    if (len + 2 >= MAXBUFFER) report_compile_error("identifier too long.");
    c = nextChar();
  }
  s[len] = 0;
#undef MAXBUFFER

  //fprintf(stderr, "%s at %d\n", s, counter);
  if (take_place) counter++; // !

  int isNum = 1;
  for (int i = 0; i < len; i++)
    if (! isdigit(s[i]) && s[i] != '-') {isNum = 0; break;}
  if (isNum) {
    if (1 != sscanf(s, "%lld", &Number)) report_compile_error("unknown number.");
    CurToken = tok_num;
    return;
  }

  CurToken = tok_eof;
  if      (! strcmp(s, "LOD")) Number = LOD, CurToken = tok_num;
  else if (! strcmp(s, "IMM")) Number = IMM, CurToken = tok_num;
  else if (! strcmp(s, "LEA")) Number = LEA, CurToken = tok_num;
  else if (! strcmp(s, "JMP")) Number = JMP, CurToken = tok_num;
  else if (! strcmp(s, "JZ" )) Number = JZ , CurToken = tok_num;

  else if (! strcmp(s, "JNZ")) Number = JNZ, CurToken = tok_num;
  else if (! strcmp(s, "STO")) Number = STO, CurToken = tok_num;
  else if (! strcmp(s, "PSH")) Number = PSH, CurToken = tok_num;
  else if (! strcmp(s, "ENT")) Number = ENT, CurToken = tok_num;
  else if (! strcmp(s, "LEV")) Number = LEV, CurToken = tok_num;

  else if (! strcmp(s, "CALL")) Number = CALL, CurToken = tok_num;
  else if (! strcmp(s, "EXIT")) Number = EXIT, CurToken = tok_num;
  else if (! strcmp(s, "ADJ"))  Number = ADJ,  CurToken = tok_num;

  /* ------------------------------ */
  else if (! strcmp(s, "ADD")) Number = ADD, CurToken = tok_num;
  else if (! strcmp(s, "SUB")) Number = SUB, CurToken = tok_num;
  else if (! strcmp(s, "MUL")) Number = MUL, CurToken = tok_num;
  else if (! strcmp(s, "DIV")) Number = DIV, CurToken = tok_num;
  else if (! strcmp(s, "MOD")) Number = MOD, CurToken = tok_num;

  else if (! strcmp(s, "EQ")) Number = EQ, CurToken = tok_num;
  else if (! strcmp(s, "NE")) Number = NE, CurToken = tok_num;
  else if (! strcmp(s, "XOR"))Number = XOR,CurToken = tok_num;
  else if (! strcmp(s, "LT")) Number = LT, CurToken = tok_num;
  else if (! strcmp(s, "GT")) Number = GT, CurToken = tok_num;

  else if (! strcmp(s, "LE")) Number = LE, CurToken = tok_num;
  else if (! strcmp(s, "GE" )) Number = GE , CurToken = tok_num;
  else if (! strcmp(s, "SHL")) Number = SHL, CurToken = tok_num;
  else if (! strcmp(s, "SHR")) Number = SHR, CurToken = tok_num;
  else if (! strcmp(s, "INC")) Number = INC, CurToken = tok_num;

  else if (! strcmp(s, "DEC")) Number = DEC, CurToken = tok_num;

  /* ------------------------------ */
  else if (! strcmp(s, "RINT")) Number = RINT, CurToken = tok_num;
  else if (! strcmp(s, "WINT")) Number = WINT, CurToken = tok_num;
  else if (! strcmp(s, "GETC")) Number = GETC, CurToken = tok_num;
  else if (! strcmp(s, "PUTC")) Number = PUTC, CurToken = tok_num;
  if (CurToken != tok_eof) return;

  StrToken.assign(s);
  if (label.count(StrToken)) {
    Number = label[StrToken];
    CurToken = tok_num;
  }
  else CurToken = tok_label;
}

void init() {
  p_code = code;
  line = column = 0;
  line_front.clear();
  line_front.push_back(0); // start from 1
  nextToken();
}

void clean() {
  delete []code;
  if (inputFile) fclose(inputFile);
}

void cat(const char* const s) {
  if (FILE* f = fopen(s, "rb")) {
    int t;
    while (EOF != (t = fgetc(f))) putchar(t);
    if (fclose(f)) report("couldn't close file '%s'", s);
    putchar(10);
  }
  else report("couldn't find '%s'", s);
}

void debug_scanf(long long &x) {
  if (inputFile) fscanf(inputFile, "%lld", &x);
  else scanf("%lld", &x);
}

void debug_getchar(long long &x) {
  if (inputFile) x = fgetc(inputFile);
  else x = getchar();
}

void debug_handle(int cur, long long reg, int sp) {
  if (Todo != debug) return;
  if (cur < 0 || cur >= (int) text.size()) {
    // the bottom of the stack is PSH EXIT
    if (cur != MemoryPool - 1 &&
        cur != MemoryPool - 2)
      fprintf(stderr, "debug error: the %%cur beyond the text.\n");
    return;
  }
  int curLine = text_line[cur];
  static int lastLine = -1;
  if (curLine == lastLine) return;
  static int hook = -1; // use for setting a breakpoint
  if (hook != -1) {
    if (curLine != hook) return;
    else hook = -1;
  }

  print_code_line(curLine);

  int command, adr;
  while (1) {
    fprintf(stderr, "debug> ");
    command = getchar();
    std::string s("");

    if (command != '\n') {
      adr = 0;
      do {
        if (adr != -1) {
          if (! isdigit(command)) adr = -1;
          else adr = adr * 10 + (15 & command);
        }
        s += command;
        command = getchar();
      }while (command != '\n');
    }
    else {
      adr = -1;
      s = "n";
    }

    // next
    if      (s == "n") {
      break;
    }
    // quit
    else if (s == "q") {
      fprintf(stderr, "quit now.\n");
      exit(0);
    }
    // show reg ans stk
    else if (s == "p") {
      fprintf(stderr, "      reg: %6lld stk:", reg);
      for (int i = MemoryPool - 1; i >= sp; i--)
        fprintf(stderr, " %lld", m[i]);
      fprintf(stderr, "\n");
    }
    // show code
    else if (s == "l") {
      for (int i = std::max(1, curLine - 10),
          _i = std::min(curLine + 10, (int) line_front.size() - 1);
          i < _i; i++)
        print_code_line(i);
    }
    // show m[address] or set a breakpoint
    else if (adr != -1) {
      if (adr < 0 || adr >= MemoryPool)
        fprintf(stderr, "debug error: address beyond the memory.\n");
      else if (adr >= (int) text.size())
        fprintf(stderr, "     memory[%d] = %lld\n", adr, m[adr]);
      else if (adr != curLine) {
        hook = adr;
        while (empty_line(hook)) hook++;
        break;
      }
      else
        fprintf(stderr, "nothing to do.\n");
    }
    // show varible or label
    else if (label.count(s)) {
      fprintf(stderr, "     %s = %lld\n", s.c_str(), label[s]);
    }
    else {
      //fprintf(stderr, "nothing to do.\n");
    }
  }
  while (command != '\n') command = getchar();

  lastLine = curLine;
}

int main(int argc, char* argv[]) {
  argument(argc, argv);
  for (int i = 0; i < 2; i++) {
    init();
    while (1) {
      if      (CurToken == tok_num) {
        if (i) {
          text.push_back(Number);
          if (Todo == debug) text_line.push_back(line);
        }
        nextToken();
      }
      else if (CurToken == '@') {
        nextToken(0);
        int location = counter; // jump to location
        if (CurToken != tok_label && i == 0) report_compile_error("expected label");
        std::string s = StrToken;
        nextToken();
        if (CurToken == '=') {
          nextToken(0);
          if (i == 0) {
            if (CurToken != tok_num) report_compile_error("expected number");
            label[s] = Number;
          }
          nextToken();
        }
        else if (i == 0) {
          //fprintf(stderr, "%s -> %d\n", s.c_str(), counter);
          label[s] = location;
        }
      }
      else if (CurToken == tok_eof) break;
      else if (i == 0) nextToken();
      else report_compile_error("unknown token");
    }
  }

  if (Todo == submit) {
    printf("#include <stdio.h>\n"
           "#include <stdlib.h>\n");
    printf("#define MemoryPool %d\n", (int) 1e6);
    cat("vm.h");
    printf("const long long text[] = {");
    for (int i = 0, _i = text.size(); i < _i; i++) {
      printf("%lld", text[i]);
      if (text[i] >= (1LL << 31) || text[i] < -(1LL << 31)) printf("ll");
      if (i + 1 < _i) printf(",");
    }
    printf("};\n");
    printf("int main() {\n"
        "int i; for (i = 0; i < %d; i++) m[i] = text[i];\n", (int) text.size());
    printf("VMRun();\n"
        "return 0;}\n");
  }
  else if (Todo == interpret || Todo == debug) {
    for (int i = 0, _i = (int) text.size(); i < _i; i++) m[i] = text[i];
    VMRun();
  }
  else report("nothing to be done.\n");

  clean();
  return 0;
}
<|endoftext|>


<commit_before>//=======================================================================================================
// Copyright 2015 Asgeir Bjorgan, Lise Lyngsnes Randeberg, Norwegian University of Science and Technology
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================================================

#include "imageViewer.h"
#include <cmath>
#include <QGridLayout>
#include <QLabel>
#include <QScrollBar>
#include <QScrollArea>
#include <QEvent>
#include <QPainter>
#include <QMouseEvent>
#include <iostream>
using namespace std;

bool isValidValue(float val){
	return (0*val == 0*val); //should check for both Inf and NaN. Not sure if platform independent.
}

/////////////////
// ImageViewer //
/////////////////

ImageViewer::ImageViewer(float *data, int lines, int samples, int bands, vector<float> wlens, QWidget *parent) : data(data), lines(lines), samples(samples), bands(bands), wlens(wlens), QWidget(parent){
	currImgData = new uchar[samples*lines*3];
	imageLabel = new QLabel;

	//scrollbar for choosing band
	QScrollBar *bandChooser = new QScrollBar;
	bandChooser->setMaximum(bands-1);
	connect(bandChooser, SIGNAL(valueChanged(int)), SLOT(updateImage(int)));

	//layout
	QGridLayout *layout = new QGridLayout(this);
	layout->addWidget(bandChooser, 0, 1);
	updateImage(0);
	QScrollArea *area = new QScrollArea;
	layout->addWidget(area, 0, 0);

	imageLabel->setBackgroundRole(QPalette::Base);
	imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
	area->setWidget(imageLabel);

	imageLabel->setScaledContents(true);
	imageLabel->setMouseTracking(true);
	imageLabel->installEventFilter(this);

	bandChooser->setValue(0);

	//plot displayer, if compiled with support for this
	#ifdef WITH_QWT
	SpectrumDisplayer *spectrumDisplayer = new SpectrumDisplayer;
	connect(this, SIGNAL(clickedPixel(int, int, QVector<double>, QVector<double>, KeepMode)), spectrumDisplayer, SLOT(displaySpectrum(int, int, QVector<double>, QVector<double>, KeepMode)));
	connect(this, SIGNAL(newBand(float)), spectrumDisplayer, SLOT(setVerticalLine(float)));
	spectrumDisplayer->show();
	#endif
}

void ImageViewer::paintEvent(QPaintEvent *evt){
	Q_UNUSED(evt);

	//scale QImage to current widget size
	QImage resImage;
	int imHeight = currImage.height();
	int imWidth = currImage.width();
	resImage = currImage.scaledToWidth(size().width()-30);

	//update scaling factors
	int newHeight = resImage.height();
	int newWidth = resImage.width();
	widthScale = imWidth*1.0f/(newWidth*1.0f);
	heightScale = imHeight*1.0f/(newHeight*1.0f);

	//update label with current pixmap
	this->imageLabel->setPixmap(QPixmap::fromImage(resImage));
	this->imageLabel->adjustSize();

}

void ImageViewer::getSpectrum(int x, int y, float *spec){
	for (int i=0; i < bands; i++){
		spec[i] = data[y*samples*bands + i*samples + x];
	}
}

void ImageViewer::updateImage(int band){
	int c = 0;
	float *imgDataTmp = new float[lines*samples*3]();
	double std = 0, mean = 0;
	long n = 0;

	float max = -1000;
	float min = +1000;

	//convert to greyscale array
	for (int i=0; i < lines; i++){
		for (int j=0; j < samples; j++){
			float val = data[i*samples*bands + band*samples + j];
			if (isValidValue(val)){ //check for NaN and Inf, in case the input image is sketchy
				n++;
				double delta = val - mean;
				mean = mean + delta/(1.0f*n);
				std = std + delta*(val - mean);
			} else {
				val = 0;
			}
			imgDataTmp[c++] = val;
			imgDataTmp[c++] = val;
			imgDataTmp[c++] = val;
			if (val > max){
				max = val;
			}
			if (val < min){
				min = val;
			}
		}
	}
	std = sqrt(std/(n-1));

	if (isValidValue(mean)){
		//mean is well-defined, define new min and max from dynamic ranges
		max = mean + 2*std;
		min = mean - 2*std;
	}

	//convert to positive values, divide by largest value
	for (int i=0; i < lines*samples*3; i++){
		if (imgDataTmp[i] > (mean + 2*std)){
			imgDataTmp[i] = max;
		}
		if (imgDataTmp[i] < (mean - 2*std)){
			imgDataTmp[i] = min;
		}
		currImgData[i] = (uchar)((imgDataTmp[i] - min)/(max - min)*255);
	}

	currImage = QImage(currImgData, samples, lines, 3*samples, QImage::Format_RGB888);
	update();

	delete [] imgDataTmp;

	//signal that the wavelength has changed
	if (band < wlens.size()){
		emit newBand(wlens[band]);
	}
}

void ImageViewer::saveImage(int band, string bandimagename){
	updateImage(band);
	currImage.save(QString::fromStdString(bandimagename));
}

bool ImageViewer::eventFilter(QObject *object, QEvent *event){
	Q_UNUSED(object);

	//update displayed spectrum on mouse button press
	if ((event->type() == QEvent::MouseButtonPress)){
		QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
		KeepMode keepMode = DELETE_PREVIOUS_SPECTRA;

		if (mouseEvent->modifiers() == Qt::ControlModifier){
			//ctrl was pressed. Keep previous spectra
			keepMode = KEEP_PREVIOUS_SPECTRA;
		}

		//get spectrum in current position
		int pixel = widthScale*mouseEvent->x();
		int line = heightScale*mouseEvent->y();
		float *spectrum = new float[bands];
		this->getSpectrum(pixel, line, spectrum);

		//convert data to QVector and emit signal (to plot displayer, if compiled with support for this...)
		QVector<double> wlens_vec;
		QVector<double> spectrum_vec;
		for (int i=0; i < bands; i++){
			if (isValidValue(spectrum[i])){
				wlens_vec.push_back(wlens[i]);
				spectrum_vec.push_back(spectrum[i]);
			}
		}

		emit clickedPixel(line, pixel, wlens_vec, spectrum_vec, keepMode);
		delete [] spectrum;
	}
	return false;
}

////////////////////////
// Spectrum displayer //
////////////////////////

#ifdef WITH_QWT
#include <qwt_plot.h>
#include <qwt_plot_curve.h>
#include <qwt_legend.h>
#include <qwt_symbol.h>
#include <qwt_plot_marker.h>

SpectrumDisplayer::SpectrumDisplayer(QWidget *parent) : QWidget(parent){
	this->setWindowTitle("Spectra");

	plot = new QwtPlot(this);
	plot->setAxisTitle(QwtPlot::yLeft, "Pixel intensity");
	plot->setAxisTitle(QwtPlot::xBottom, "Wavelength (nm)");
	QwtLegend *legend = new QwtLegend;
	plot->insertLegend(legend, QwtPlot::RightLegend);

	QGridLayout *layout = new QGridLayout(this);
	layout->addWidget(plot, 0, 0);
	colorCtr = 0;

	//vertical line indicating current wavelength
	vertLine = new QwtPlotMarker;
	vertLine->setLineStyle(QwtPlotMarker::VLine);
	vertLine->attach(plot);
}

void SpectrumDisplayer::displaySpectrum(int y, int x, QVector<double> wlens, QVector<double> intensity, KeepMode keepBehavior){
	QwtPlotCurve *curve = new QwtPlotCurve("Line " + QString::number(y) + ", sample " + QString::number(x));
	curve->setRawSamples(wlens.data(), intensity.data(), wlens.size());
	curve->setPen(QColor::fromHsv(colorCtr, 255, 150));
	curve->attach(plot);
	colorCtr += 30;
	if (colorCtr > 255){
		colorCtr = 0;
	}

	//remove previous spectra
	if (keepBehavior == DELETE_PREVIOUS_SPECTRA){
		for (int i=0; i < curves.size(); i++){
			curves[i]->detach();
		}
		curves.clear();
		colorCtr = 0;
	}
	curves.push_back(curve);
	plot->replot();

}

void SpectrumDisplayer::setVerticalLine(float wavelength){
	vertLine->setXValue(wavelength);
	plot->replot();
}
#endif

<commit_msg>Remove superfluous space.<commit_after>//=======================================================================================================
// Copyright 2015 Asgeir Bjorgan, Lise Lyngsnes Randeberg, Norwegian University of Science and Technology
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================================================

#include "imageViewer.h"
#include <cmath>
#include <QGridLayout>
#include <QLabel>
#include <QScrollBar>
#include <QScrollArea>
#include <QEvent>
#include <QPainter>
#include <QMouseEvent>
#include <iostream>
using namespace std;

bool isValidValue(float val){
	return (0*val == 0*val); //should check for both Inf and NaN. Not sure if platform independent.
}

/////////////////
// ImageViewer //
/////////////////

ImageViewer::ImageViewer(float *data, int lines, int samples, int bands, vector<float> wlens, QWidget *parent) : data(data), lines(lines), samples(samples), bands(bands), wlens(wlens), QWidget(parent){
	currImgData = new uchar[samples*lines*3];
	imageLabel = new QLabel;

	//scrollbar for choosing band
	QScrollBar *bandChooser = new QScrollBar;
	bandChooser->setMaximum(bands-1);
	connect(bandChooser, SIGNAL(valueChanged(int)), SLOT(updateImage(int)));

	//layout
	QGridLayout *layout = new QGridLayout(this);
	layout->addWidget(bandChooser, 0, 1);
	updateImage(0);
	QScrollArea *area = new QScrollArea;
	layout->addWidget(area, 0, 0);

	imageLabel->setBackgroundRole(QPalette::Base);
	imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
	area->setWidget(imageLabel);

	imageLabel->setScaledContents(true);
	imageLabel->setMouseTracking(true);
	imageLabel->installEventFilter(this);

	bandChooser->setValue(0);

	//plot displayer, if compiled with support for this
	#ifdef WITH_QWT
	SpectrumDisplayer *spectrumDisplayer = new SpectrumDisplayer;
	connect(this, SIGNAL(clickedPixel(int, int, QVector<double>, QVector<double>, KeepMode)), spectrumDisplayer, SLOT(displaySpectrum(int, int, QVector<double>, QVector<double>, KeepMode)));
	connect(this, SIGNAL(newBand(float)), spectrumDisplayer, SLOT(setVerticalLine(float)));
	spectrumDisplayer->show();
	#endif
}

void ImageViewer::paintEvent(QPaintEvent *evt){
	Q_UNUSED(evt);

	//scale QImage to current widget size
	QImage resImage;
	int imHeight = currImage.height();
	int imWidth = currImage.width();
	resImage = currImage.scaledToWidth(size().width()-30);

	//update scaling factors
	int newHeight = resImage.height();
	int newWidth = resImage.width();
	widthScale = imWidth*1.0f/(newWidth*1.0f);
	heightScale = imHeight*1.0f/(newHeight*1.0f);

	//update label with current pixmap
	this->imageLabel->setPixmap(QPixmap::fromImage(resImage));
	this->imageLabel->adjustSize();

}

void ImageViewer::getSpectrum(int x, int y, float *spec){
	for (int i=0; i < bands; i++){
		spec[i] = data[y*samples*bands + i*samples + x];
	}
}

void ImageViewer::updateImage(int band){
	int c = 0;
	float *imgDataTmp = new float[lines*samples*3]();
	double std = 0, mean = 0;
	long n = 0;

	float max = -1000;
	float min = +1000;

	//convert to greyscale array
	for (int i=0; i < lines; i++){
		for (int j=0; j < samples; j++){
			float val = data[i*samples*bands + band*samples + j];
			if (isValidValue(val)){ //check for NaN and Inf, in case the input image is sketchy
				n++;
				double delta = val - mean;
				mean = mean + delta/(1.0f*n);
				std = std + delta*(val - mean);
			} else {
				val = 0;
			}
			imgDataTmp[c++] = val;
			imgDataTmp[c++] = val;
			imgDataTmp[c++] = val;
			if (val > max){
				max = val;
			}
			if (val < min){
				min = val;
			}
		}
	}
	std = sqrt(std/(n-1));

	if (isValidValue(mean)){
		//mean is well-defined, define new min and max from dynamic ranges
		max = mean + 2*std;
		min = mean - 2*std;
	}

	//convert to positive values, divide by largest value
	for (int i=0; i < lines*samples*3; i++){
		if (imgDataTmp[i] > (mean + 2*std)){
			imgDataTmp[i] = max;
		}
		if (imgDataTmp[i] < (mean - 2*std)){
			imgDataTmp[i] = min;
		}
		currImgData[i] = (uchar)((imgDataTmp[i] - min)/(max - min)*255);
	}

	currImage = QImage(currImgData, samples, lines, 3*samples, QImage::Format_RGB888);
	update();

	delete [] imgDataTmp;

	//signal that the wavelength has changed
	if (band < wlens.size()){
		emit newBand(wlens[band]);
	}
}

void ImageViewer::saveImage(int band, string bandimagename){
	updateImage(band);
	currImage.save(QString::fromStdString(bandimagename));
}

bool ImageViewer::eventFilter(QObject *object, QEvent *event){
	Q_UNUSED(object);

	//update displayed spectrum on mouse button press
	if ((event->type() == QEvent::MouseButtonPress)){
		QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
		KeepMode keepMode = DELETE_PREVIOUS_SPECTRA;

		if (mouseEvent->modifiers() == Qt::ControlModifier){
			//ctrl was pressed. Keep previous spectra
			keepMode = KEEP_PREVIOUS_SPECTRA;
		}

		//get spectrum in current position
		int pixel = widthScale*mouseEvent->x();
		int line = heightScale*mouseEvent->y();
		float *spectrum = new float[bands];
		this->getSpectrum(pixel, line, spectrum);

		//convert data to QVector and emit signal (to plot displayer, if compiled with support for this...)
		QVector<double> wlens_vec;
		QVector<double> spectrum_vec;
		for (int i=0; i < bands; i++){
			if (isValidValue(spectrum[i])){
				wlens_vec.push_back(wlens[i]);
				spectrum_vec.push_back(spectrum[i]);
			}
		}

		emit clickedPixel(line, pixel, wlens_vec, spectrum_vec, keepMode);
		delete [] spectrum;
	}
	return false;
}

////////////////////////
// Spectrum displayer //
////////////////////////

#ifdef WITH_QWT
#include <qwt_plot.h>
#include <qwt_plot_curve.h>
#include <qwt_legend.h>
#include <qwt_symbol.h>
#include <qwt_plot_marker.h>

SpectrumDisplayer::SpectrumDisplayer(QWidget *parent) : QWidget(parent){
	this->setWindowTitle("Spectra");

	plot = new QwtPlot(this);
	plot->setAxisTitle(QwtPlot::yLeft, "Pixel intensity");
	plot->setAxisTitle(QwtPlot::xBottom, "Wavelength (nm)");
	QwtLegend *legend = new QwtLegend;
	plot->insertLegend(legend, QwtPlot::RightLegend);

	QGridLayout *layout = new QGridLayout(this);
	layout->addWidget(plot, 0, 0);
	colorCtr = 0;

	//vertical line indicating current wavelength
	vertLine = new QwtPlotMarker;
	vertLine->setLineStyle(QwtPlotMarker::VLine);
	vertLine->attach(plot);
}

void SpectrumDisplayer::displaySpectrum(int y, int x, QVector<double> wlens, QVector<double> intensity, KeepMode keepBehavior){
	QwtPlotCurve *curve = new QwtPlotCurve("Line " + QString::number(y) + ", sample " + QString::number(x));
	curve->setRawSamples(wlens.data(), intensity.data(), wlens.size());
	curve->setPen(QColor::fromHsv(colorCtr, 255, 150));
	curve->attach(plot);
	colorCtr += 30;
	if (colorCtr > 255){
		colorCtr = 0;
	}

	//remove previous spectra
	if (keepBehavior == DELETE_PREVIOUS_SPECTRA){
		for (int i=0; i < curves.size(); i++){
			curves[i]->detach();
		}
		curves.clear();
		colorCtr = 0;
	}
	curves.push_back(curve);
	plot->replot();

}

void SpectrumDisplayer::setVerticalLine(float wavelength){
	vertLine->setXValue(wavelength);
	plot->replot();
}
#endif

<|endoftext|>


<commit_before>#include "Lattice.h"
#include <cstdlib>
#include <iostream> //<-- used for debugging

Lattice::Lattice(const int Nx, const int Ny, const int Nz):
Nx(Nx), Ny(Ny), Nz(Nz), numSpd(0),

ex(NULL), ey(NULL), ez(NULL),w(NULL), bbSpd(NULL), Qflat(NULL)
{

}

Lattice::~Lattice()
{

}

void Lattice::bounceBack(LBM_DataHandler& f)
{
	float fTmp[numSpd];
	for(int spd=0;spd<numSpd;spd++)
	{
		fTmp[spd]=f.f[bbSpd[spd]];
	}
	for(int spd=0;spd<numSpd;spd++)
	{
		f.f[spd]=fTmp[spd];
	}

}
void Lattice::computeMacroscopicData(float& rho, float& ux, float& uy, float& uz, const float* f)
{
	rho = 0.; ux = 0.; uy = 0.; uz = 0.;
	for(int spd = 0; spd<numSpd; spd++)
	{
		rho+=f[spd];
		ux+=ex[spd]*f[spd];
		uy+=ey[spd]*f[spd];
		uz+=ez[spd]*f[spd];
	}
	ux/=rho; uy/=rho; uz/=rho;

}
void Lattice::computeMacroscopicData(LBM_DataHandler& f)
{
	float rho, ux, uy, uz;
	rho = 0.; ux = 0.; uy = 0.; uz = 0.;
	for(int spd = 0; spd<numSpd; spd++)
	{

		rho+=f.f[spd];
		ux+=ex[spd]*f.f[spd];
		uy+=ey[spd]*f.f[spd];
		uz+=ez[spd]*f.f[spd];
	}
	ux/=rho; uy/=rho; uz/=rho;
	f.rho = rho; f.ux = ux; f.uy = uy; f.uz = uz;

}

void Lattice::computeEquilibrium(float * fEq,const float ux, const float uy, const float uz, const float rho)
{
	//this will assume that up-to-date data exists in rho, ux, uy, and uz class variables
	//and that ex,ey,ez,and w have been updated with the lattice-specific info
	float cu;

	for(int spd = 0; spd<numSpd;spd++)
	{
		fEq[spd] = 0;
		cu = 3.f*(ex[spd]*ux+ey[spd]*uy+ez[spd]*uz);
		fEq[spd]=w[spd]*rho*(1.f+cu+0.5f*(cu*cu)-3.f/2.f*(ux*ux+uy*uy+uz*uz));

	}
}

void Lattice::computeEquilibrium(LBM_DataHandler& f)
{

	computeEquilibrium(f.fEq,f.ux,f.uy,f.uz,f.rho);
}

void Lattice::compute_piFlat(LBM_DataHandler& f)
{

	//f.piFlat = {0,0,0,0,0,0,0,0,0}; // initialized in constructor
	for(int k=0; k<9;k++)
	{
		f.piFlat[k]=0.;
	}
	float fNeq;
	for(int spd = 0; spd<numSpd; spd++)
	{
		fNeq = f.f[spd] - f.fEq[spd];
		f.piFlat[0]+=ex[spd]*ex[spd]*fNeq;
		f.piFlat[1]+=ey[spd]*ex[spd]*fNeq;
		f.piFlat[2]+=ez[spd]*ex[spd]*fNeq;
		f.piFlat[3]+=ex[spd]*ey[spd]*fNeq;
		f.piFlat[4]+=ey[spd]*ey[spd]*fNeq;
		f.piFlat[5]+=ez[spd]*ey[spd]*fNeq;
		f.piFlat[6]+=ex[spd]*ez[spd]*fNeq;
		f.piFlat[7]+=ey[spd]*ez[spd]*fNeq;
		f.piFlat[8]+=ez[spd]*ez[spd]*fNeq;

	}
}

void Lattice::regularize(LBM_DataHandler& f)
{

	float wa;

	for(int spd = 0; spd<numSpd; spd++)
	{
		// get leading constant
		wa = (9.f/2.f)*w[spd];
		f.f[spd]=f.fEq[spd];
		// load chunk of Qflat:
		for(int k=0;k<9;k++)
		{
			f.f[spd]+= wa*Qflat[spd*9+k]*f.piFlat[k];
		}
	}
}

void Lattice::relax(LBM_DataHandler& f)
{

	for(int spd=0;spd<numSpd;spd++)
	{
		f.fOut[spd]=f.f[spd]-f.omega*(f.f[spd] - f.fEq[spd]);
	}

}

void Lattice::set_Vz_micro(LBM_DataHandler & f)
{
	for(int spd = 0; spd<numSpd; spd++)
	{
		// push microscopic BCs towards desired value
		f.f[spd]+=3.*f.rho*w[spd]*(ez[spd]*(f.u_bc - f.uz) +
				ex[spd]*(0. - f.ux) + ey[spd]*(0.-f.uy));
	}
	// update macro BCs so Equilibrium will be calculated as desired.
	f.ux = 0.; f.uy = 0.; f.uz = f.u_bc;
}

void Lattice::computeFout(LBM_DataHandler& f)
{
	// node type 1: just bounce back
	// node type 0, 2, and 3 continue with the following steps:

	// compute macroscopic velocity and pressure
	computeMacroscopicData(f);
	if(f.nodeType==1)
	{
		f.ux = 0.; f.uy = 0.; f.uz = 0; // solid nodes, zero velocity
	}

	// node type 2 and 3 apply macroscopic boundary conditions
	if(f.nodeType==2) //inlet node
	{
		set_inlet_bc_macro(f);
	}
	if(f.nodeType==3) // outlet node
	{
		set_outlet_bc_macro(f);
	}
	if(f.nodeType==5)
	{
		set_Vz_micro(f); // this type of BC should be set prior to computing equilibrium
	}

	// compute equilibrium
	computeEquilibrium(f);

	// node type 2 and 3 apply microscopic boundary conditions and regularization
	if(f.nodeType==2)
	{
		set_inlet_bc_micro(f);
	}
	if(f.nodeType==3)
	{
		set_outlet_bc_micro(f);
	}

	// get (flattened) second-order moment of particle density distribution
	compute_piFlat(f);
	regularize(f);
	relax(f);

}
<commit_msg>changed multiple if-statements into a switch-case structure in Lattice.cpp<commit_after>#include "Lattice.h"
#include <cstdlib>
#include <iostream> //<-- used for debugging

Lattice::Lattice(const int Nx, const int Ny, const int Nz):
Nx(Nx), Ny(Ny), Nz(Nz), numSpd(0),

ex(NULL), ey(NULL), ez(NULL),w(NULL), bbSpd(NULL), Qflat(NULL)
{

}

Lattice::~Lattice()
{

}

void Lattice::bounceBack(LBM_DataHandler& f)
{
	float fTmp[numSpd];
	for(int spd=0;spd<numSpd;spd++)
	{
		fTmp[spd]=f.f[bbSpd[spd]];
	}
	for(int spd=0;spd<numSpd;spd++)
	{
		f.f[spd]=fTmp[spd];
	}

}
void Lattice::computeMacroscopicData(float& rho, float& ux, float& uy, float& uz, const float* f)
{
	rho = 0.; ux = 0.; uy = 0.; uz = 0.;
	for(int spd = 0; spd<numSpd; spd++)
	{
		rho+=f[spd];
		ux+=ex[spd]*f[spd];
		uy+=ey[spd]*f[spd];
		uz+=ez[spd]*f[spd];
	}
	ux/=rho; uy/=rho; uz/=rho;

}
void Lattice::computeMacroscopicData(LBM_DataHandler& f)
{
	float rho, ux, uy, uz;
	rho = 0.; ux = 0.; uy = 0.; uz = 0.;
	for(int spd = 0; spd<numSpd; spd++)
	{

		rho+=f.f[spd];
		ux+=ex[spd]*f.f[spd];
		uy+=ey[spd]*f.f[spd];
		uz+=ez[spd]*f.f[spd];
	}
	ux/=rho; uy/=rho; uz/=rho;
	f.rho = rho; f.ux = ux; f.uy = uy; f.uz = uz;

}

void Lattice::computeEquilibrium(float * fEq,const float ux, const float uy, const float uz, const float rho)
{
	//this will assume that up-to-date data exists in rho, ux, uy, and uz class variables
	//and that ex,ey,ez,and w have been updated with the lattice-specific info
	float cu;

	for(int spd = 0; spd<numSpd;spd++)
	{
		fEq[spd] = 0;
		cu = 3.f*(ex[spd]*ux+ey[spd]*uy+ez[spd]*uz);
		fEq[spd]=w[spd]*rho*(1.f+cu+0.5f*(cu*cu)-3.f/2.f*(ux*ux+uy*uy+uz*uz));

	}
}

void Lattice::computeEquilibrium(LBM_DataHandler& f)
{

	computeEquilibrium(f.fEq,f.ux,f.uy,f.uz,f.rho);
}

void Lattice::compute_piFlat(LBM_DataHandler& f)
{

	//f.piFlat = {0,0,0,0,0,0,0,0,0}; // initialized in constructor
	for(int k=0; k<9;k++)
	{
		f.piFlat[k]=0.;
	}
	float fNeq;
	for(int spd = 0; spd<numSpd; spd++)
	{
		fNeq = f.f[spd] - f.fEq[spd];
		f.piFlat[0]+=ex[spd]*ex[spd]*fNeq;
		f.piFlat[1]+=ey[spd]*ex[spd]*fNeq;
		f.piFlat[2]+=ez[spd]*ex[spd]*fNeq;
		f.piFlat[3]+=ex[spd]*ey[spd]*fNeq;
		f.piFlat[4]+=ey[spd]*ey[spd]*fNeq;
		f.piFlat[5]+=ez[spd]*ey[spd]*fNeq;
		f.piFlat[6]+=ex[spd]*ez[spd]*fNeq;
		f.piFlat[7]+=ey[spd]*ez[spd]*fNeq;
		f.piFlat[8]+=ez[spd]*ez[spd]*fNeq;

	}
}

void Lattice::regularize(LBM_DataHandler& f)
{

	float wa;

	for(int spd = 0; spd<numSpd; spd++)
	{
		// get leading constant
		wa = (9.f/2.f)*w[spd];
		f.f[spd]=f.fEq[spd];
		// load chunk of Qflat:
		for(int k=0;k<9;k++)
		{
			f.f[spd]+= wa*Qflat[spd*9+k]*f.piFlat[k];
		}
	}
}

void Lattice::relax(LBM_DataHandler& f)
{

	for(int spd=0;spd<numSpd;spd++)
	{
		f.fOut[spd]=f.f[spd]-f.omega*(f.f[spd] - f.fEq[spd]);
	}

}

void Lattice::set_Vz_micro(LBM_DataHandler & f)
{
	for(int spd = 0; spd<numSpd; spd++)
	{
		// push microscopic BCs towards desired value
		f.f[spd]+=3.*f.rho*w[spd]*(ez[spd]*(f.u_bc - f.uz) +
				ex[spd]*(0. - f.ux) + ey[spd]*(0.-f.uy));
	}
	// update macro BCs so Equilibrium will be calculated as desired.
	f.ux = 0.; f.uy = 0.; f.uz = f.u_bc;
}

void Lattice::computeFout(LBM_DataHandler& f)
{
	// compute macroscopic velocity and pressure
	computeMacroscopicData(f);
	if(f.nodeType==1)
	{
		f.ux = 0.; f.uy = 0.; f.uz = 0; // solid nodes, zero velocity
	}

	// node type 2 and 3 apply macroscopic boundary conditions
	switch (f.nodeType)
	{
	case 2:
		set_inlet_bc_macro(f);
		break;
	case 3:
		set_outlet_bc_macro(f);
		break;
	case 5:
		set_Vz_micro(f);
		break;
	}

	// compute equilibrium
	computeEquilibrium(f);

	switch(f.nodeType)
	{
	case 2:
		set_inlet_bc_micro(f);
		break;
	case 3:
		set_outlet_bc_micro(f);
		break;
	}

	// get (flattened) second-order moment of particle density distribution
	compute_piFlat(f);
	regularize(f);
	relax(f);

}
<|endoftext|>