<commit_before>#ifndef __CRYPTO_COMMON_HH
#define __CRYPTO_COMMON_HH

#include <cstdint>
#include <cstring>
#include <memory>
#include <string>

namespace crypto {

/**
 * A generic structure to represent a pointer to a bounded segment in the
 * memory without any assertions on the ownership of that segment.
 *
 * The class has two accessors: ptr() and cptr().  First returns a read-write
 * pointer, second returns read-only pointer, and it's the only one you can use
 * if you have a const memslice.  To create a const memslice, use cmem()
 * function.
 *
 * By convention, a null memory slice is represented as {nullptr, 0},
 * which is normally referred to as nullmem.
 */
struct memslice {
  private:
    uint8_t *ptr_;
    size_t size_;

  public:
    inline memslice(uint8_t *ptr, size_t size)
        : ptr_(ptr), size_(size) {}
    operator bool() { return ptr_ != nullptr; }

    inline uint8_t *ptr() { return ptr_; }
    inline char *charptr() { return reinterpret_cast<char*>(ptr_); }
    inline const uint8_t *cptr() const { return ptr_; }
    inline const char *ccharptr() const { return reinterpret_cast<const char*>(ptr_); }
    inline const size_t size() const { return size_; }

    inline bool eq(const memslice other) const {
        return !(size() != other.size() || memcmp(cptr(), other.cptr(), size()));
    }
    inline int cmp(const memslice other) const {
        int cmp_shortest = memcmp(cptr(), other.cptr(), std::min(size(), other.size()));
        if (cmp_shortest == 0 && size() != other.size()) {
            return size() > other.size() ? 1 : -1;
        } else {
            return cmp_shortest;
        }
    }
};

const memslice nullmem = { nullptr, 0 };

// Convenience functions
inline memslice mem(uint8_t *ptr, size_t size) {
    return memslice(ptr, size);
}

inline const memslice cmem(const uint8_t *ptr, size_t size) {
    return memslice(const_cast<uint8_t*>(ptr), size);
}

/**
 * A generic class representing a buffer containing bytes.
 */
class bytestring : public std::basic_string<uint8_t> {
  public:
    /**
     * Returns a pointer to the contents of the buffer.
     */
    inline uint8_t *ptr() { return empty() ? nullptr : &*begin(); }

    /**
     * Returns a constant pointer to the contents of the buffer.
     */
    inline const uint8_t *cptr() const {
        return empty() ? nullptr : &*cbegin();
    }

    /**
     * Wrapper for functions which accept char* pointers.
     */
    inline char *charptr() {
        return reinterpret_cast<char*>(ptr());
    }

    /**
     * Wrapper for functions which accept const char* pointers.
     */
    inline const char *ccharptr() const {
        return reinterpret_cast<const char*>(cptr());
    }

    /**
     * Returns the pointer and the length of the buffer.
     */
    inline memslice mem() { return memslice(ptr(), size()); }

    /**
     * Return the constant pointer and the length of the buffer.
     */
    inline const memslice cmem() const {
        return crypto::cmem(cptr(), size());
    }

    /**
     * Return a pointer to a subset of the string; returns nullmem if goes out
     * of bounds or if specified length is zero.
     */
    memslice slice(size_t offset, size_t len);

    /**
     * Create empty buffer.
     */
    bytestring() : std::basic_string<uint8_t>() {}

    /**
     * Create buffer by copying another buffer (C-style).
     */
    bytestring(const uint8_t *data, size_t size)
        : std::basic_string<uint8_t>(data, size) {}

    /**
     * Create buffer by copying another buffer (memslice).
     */
    bytestring(const memslice mem)
        : std::basic_string<uint8_t>(mem.cptr(), mem.size()) {}

    /**
     * Create a buffer from an initializer list of bytes.
     */
    bytestring(std::initializer_list<uint8_t> il)
        : std::basic_string<uint8_t>(il) {};

    /**
     * Create a bytestring from a C string.
     */
    bytestring(const char *str);

    /**
     * Constructor to upgrade basic_string<uint8_t> to bytestring.
     */
    bytestring(const std::basic_string<uint8_t> &val)
        : bytestring(::crypto::cmem(val.data(), val.size())) {}

    /**
     * Create a buffer of a specific size.
     */
    bytestring(size_t len) : std::basic_string<uint8_t>() {
        resize(len);
    }

    /**
     * Replace the contents of the buffer with the contents of the pointed
     * memory.
     */
    void copy_from(const memslice mem) {
        resize(mem.size());
        memcpy(ptr(), mem.cptr(), mem.size());
    }

    /**
     * Convert a well-formed hexadecimal string into corresponding bytestring.
     */
    static bytestring from_hex(const char *hex);

    /**
     * Convert the contents of this object to std::string.
     */
    inline std::string to_string() const {
        return std::string(ccharptr(), size());
    }
};
typedef std::unique_ptr<bytestring> bytestring_u;

/**
 * Basic base64 encoding functions.  Do not handle any whitespace.  In case if
 * whitespace or any other non-format data is present, base64_decode returns
 * nullptr.
 */
bytestring_u base64_encode(const memslice input);
bytestring_u base64_decode(const memslice input);

enum Endianness {
    BigEndian,
    LittleEndian
};

}

#endif /* __CRYPTO_COMMON_HH */
<commit_msg>Mark operator bool() as explicit<commit_after>#ifndef __CRYPTO_COMMON_HH
#define __CRYPTO_COMMON_HH

#include <cstdint>
#include <cstring>
#include <memory>
#include <string>

namespace crypto {

/**
 * A generic structure to represent a pointer to a bounded segment in the
 * memory without any assertions on the ownership of that segment.
 *
 * The class has two accessors: ptr() and cptr().  First returns a read-write
 * pointer, second returns read-only pointer, and it's the only one you can use
 * if you have a const memslice.  To create a const memslice, use cmem()
 * function.
 *
 * By convention, a null memory slice is represented as {nullptr, 0},
 * which is normally referred to as nullmem.
 */
struct memslice {
  private:
    uint8_t *ptr_;
    size_t size_;

  public:
    inline memslice(uint8_t *ptr, size_t size)
        : ptr_(ptr), size_(size) {}
    inline explicit operator bool() { return ptr_ != nullptr; }

    inline uint8_t *ptr() { return ptr_; }
    inline char *charptr() { return reinterpret_cast<char*>(ptr_); }
    inline const uint8_t *cptr() const { return ptr_; }
    inline const char *ccharptr() const { return reinterpret_cast<const char*>(ptr_); }
    inline const size_t size() const { return size_; }

    inline bool eq(const memslice other) const {
        return !(size() != other.size() || memcmp(cptr(), other.cptr(), size()));
    }
    inline int cmp(const memslice other) const {
        int cmp_shortest = memcmp(cptr(), other.cptr(), std::min(size(), other.size()));
        if (cmp_shortest == 0 && size() != other.size()) {
            return size() > other.size() ? 1 : -1;
        } else {
            return cmp_shortest;
        }
    }
};

const memslice nullmem = { nullptr, 0 };

// Convenience functions
inline memslice mem(uint8_t *ptr, size_t size) {
    return memslice(ptr, size);
}

inline const memslice cmem(const uint8_t *ptr, size_t size) {
    return memslice(const_cast<uint8_t*>(ptr), size);
}

/**
 * A generic class representing a buffer containing bytes.
 */
class bytestring : public std::basic_string<uint8_t> {
  public:
    /**
     * Returns a pointer to the contents of the buffer.
     */
    inline uint8_t *ptr() { return empty() ? nullptr : &*begin(); }

    /**
     * Returns a constant pointer to the contents of the buffer.
     */
    inline const uint8_t *cptr() const {
        return empty() ? nullptr : &*cbegin();
    }

    /**
     * Wrapper for functions which accept char* pointers.
     */
    inline char *charptr() {
        return reinterpret_cast<char*>(ptr());
    }

    /**
     * Wrapper for functions which accept const char* pointers.
     */
    inline const char *ccharptr() const {
        return reinterpret_cast<const char*>(cptr());
    }

    /**
     * Returns the pointer and the length of the buffer.
     */
    inline memslice mem() { return memslice(ptr(), size()); }

    /**
     * Return the constant pointer and the length of the buffer.
     */
    inline const memslice cmem() const {
        return crypto::cmem(cptr(), size());
    }

    /**
     * Return a pointer to a subset of the string; returns nullmem if goes out
     * of bounds or if specified length is zero.
     */
    memslice slice(size_t offset, size_t len);

    /**
     * Create empty buffer.
     */
    bytestring() : std::basic_string<uint8_t>() {}

    /**
     * Create buffer by copying another buffer (C-style).
     */
    bytestring(const uint8_t *data, size_t size)
        : std::basic_string<uint8_t>(data, size) {}

    /**
     * Create buffer by copying another buffer (memslice).
     */
    bytestring(const memslice mem)
        : std::basic_string<uint8_t>(mem.cptr(), mem.size()) {}

    /**
     * Create a buffer from an initializer list of bytes.
     */
    bytestring(std::initializer_list<uint8_t> il)
        : std::basic_string<uint8_t>(il) {};

    /**
     * Create a bytestring from a C string.
     */
    bytestring(const char *str);

    /**
     * Constructor to upgrade basic_string<uint8_t> to bytestring.
     */
    bytestring(const std::basic_string<uint8_t> &val)
        : bytestring(::crypto::cmem(val.data(), val.size())) {}

    /**
     * Create a buffer of a specific size.
     */
    bytestring(size_t len) : std::basic_string<uint8_t>() {
        resize(len);
    }

    /**
     * Replace the contents of the buffer with the contents of the pointed
     * memory.
     */
    void copy_from(const memslice mem) {
        resize(mem.size());
        memcpy(ptr(), mem.cptr(), mem.size());
    }

    /**
     * Convert a well-formed hexadecimal string into corresponding bytestring.
     */
    static bytestring from_hex(const char *hex);

    /**
     * Convert the contents of this object to std::string.
     */
    inline std::string to_string() const {
        return std::string(ccharptr(), size());
    }
};
typedef std::unique_ptr<bytestring> bytestring_u;

/**
 * Basic base64 encoding functions.  Do not handle any whitespace.  In case if
 * whitespace or any other non-format data is present, base64_decode returns
 * nullptr.
 */
bytestring_u base64_encode(const memslice input);
bytestring_u base64_decode(const memslice input);

enum Endianness {
    BigEndian,
    LittleEndian
};

}

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


<commit_before>#include "pch.h"
#include "Items.h"
#include "Resources\resource.h"

using namespace std;

Item::Item(const wchar_t * name, UINT count, int imageId) :
	Name(name),
	Count(count),
	ResourceId(imageId)
{
}

const std::vector<Item>& GetItems()
{
	static vector<Item> result =
	{
		Item(L"一等奖-iPhone7",						1,  IDR_ITEM1),
		Item(L"二等奖-机械键盘x2/Kindlex3",			5,  IDR_ITEM2),
		Item(L"三等奖x5-小米净化器x5/呼吸套装x5",		10, IDR_ITEM4),
		Item(L"阳光普照奖x30-小熊酸奶机",				30, IDR_ITEM6),
		Item(L"阳光普照奖x30-弓箭全钢化保鲜盒套装",	30, IDR_ITEM7),
		Item(L"阳光普照奖x30-立白洗衣液",				30, IDR_ITEM8),
		Item(L"特别奖-丁总-戴尔27寸曲面屏显示器",		1,  IDR_ITEM9),
		Item(L"特别奖-李茂-京东e卡",					1,  IDR_ITEM10),
		Item(L"特别奖-杨秀东-未定",					1,  IDR_ITEM11),
		Item(L"特别奖-吴晓研-SKⅡ神仙水 330ml",		1,  IDR_ITEM12),
	};
	return result;
}
<commit_msg>update item for Yang<commit_after>#include "pch.h"
#include "Items.h"
#include "Resources\resource.h"

using namespace std;

Item::Item(const wchar_t * name, UINT count, int imageId) :
	Name(name),
	Count(count),
	ResourceId(imageId)
{
}

const std::vector<Item>& GetItems()
{
	static vector<Item> result =
	{
		Item(L"一等奖-iPhone7",						1,  IDR_ITEM1),
		Item(L"二等奖-机械键盘x2/Kindlex3",			5,  IDR_ITEM2),
		Item(L"三等奖x5-小米净化器x5/呼吸套装x5",		10, IDR_ITEM4),
		Item(L"阳光普照奖x30-小熊酸奶机",				30, IDR_ITEM6),
		Item(L"阳光普照奖x30-弓箭全钢化保鲜盒套装",	30, IDR_ITEM7),
		Item(L"阳光普照奖x30-立白洗衣液",				30, IDR_ITEM8),
		Item(L"特别奖-丁总-戴尔27寸曲面屏显示器",		1,  IDR_ITEM9),
		Item(L"特别奖-李茂-京东e卡",					1,  IDR_ITEM10),
		Item(L"特别奖-杨秀东-iPad mini2",			1,  IDR_ITEM11),
		Item(L"特别奖-吴晓研-SKⅡ神仙水 330ml",		1,  IDR_ITEM12),
	};
	return result;
}
<|endoftext|>


<commit_before>// MGenTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "MGenTest.h"
#include "../MGen/GLibrary/GLib.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// The one and only application object

CWinApp theApp;

using namespace std;

CString current_dir, full_url, server, url;
DWORD service;
WORD port;
ofstream logfile;
int ci = 0;
int nRetCode = 0;

/*
string url_encode(const string &value) {
	ostringstream escaped;
	escaped.fill('0');
	escaped << hex;

	for (string::const_iterator i = value.begin(), n = value.end(); i != n; ++i) {
		string::value_type c = (*i);

		// Keep alphanumeric and other accepted characters intact
		if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
			escaped << c;
			continue;
		}

		// Any other characters are percent-encoded
		escaped << uppercase;
		escaped << '%' << setw(2) << int((unsigned char)c);
		escaped << nouppercase;
	}

	return escaped.str();
}

void HTTPPost(CString server, WORD port, CString url, CString data) {
	cout << "HTTPPost to server " << server << " port " << port << " url " << url << " : " << data << "\n";
	CString strHeaders = "Content-Type: application/x-www-form-urlencoded";
	try {
		char szBuf [2550];
		DWORD dwRet;
		CInternetSession session;
		CHttpConnection* pConnection = session.GetHttpConnection(server, port);
		CHttpFile* pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST, url);
		pFile->AddRequestHeaders(strHeaders);
		data = url_encode(data.GetBuffer()).c_str();
		cout << "HTTPPost to server " << server << " port " << port << " url " << url << " : " << data << "\n";
		pFile->SendRequestEx(data.GetLength());
		pFile->Write(data, data.GetLength());
		//BOOL result = pFile->SendRequest(strHeaders, (LPVOID)(LPCTSTR)data, data.GetLength());
		pFile->QueryInfoStatusCode(dwRet);
		cout << "HTTP return code: " << dwRet << "\n";
		if (dwRet == HTTP_STATUS_OK) {
			UINT nRead = pFile->Read(szBuf, 2550);
			if (nRead > 0) {
				cout << "HTTP result: " << szBuf << "\n";
			}
		}
	}
	catch (CInternetException *e) {
		//e->ReportError();
		TCHAR   szCause[2550];
		e->GetErrorMessage(szCause, 2550);
		cout << "Error when sending HTTP request: " << szCause << "\n";
		e->Delete();
	}
}
*/

void Run(CString fname, CString par, int delay) {
	SHELLEXECUTEINFO sei = { 0 };
	sei.cbSize = sizeof(SHELLEXECUTEINFO);
	sei.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI;
	sei.hwnd = NULL;
	sei.lpVerb = NULL;
	sei.lpFile = fname;
	sei.lpParameters = par;
	sei.lpDirectory = NULL;
	sei.nShow = SW_SHOWNORMAL;
	sei.hInstApp = NULL;
	ShellExecuteEx(&sei);
	WaitForSingleObject(sei.hProcess, delay);
}

void Log(CString st, int level = 0) {
	cout << st;
	logfile << st;
	if (ci && level > 0) {
		CString cat;
		if (level == 1) cat = "Information";
		if (level == 2) cat = "Warning";
		if (level == 3) cat = "Error";
		CString par = "AddMessage \"" + st + "\" -Category " + cat;
		Run("appveyor", par, 1000);
	}
}

CString file(CString fname) {
	CString st, st2;
	ifstream fs;
	// Check file exists
	if (!CGLib::fileExists(fname)) {
		cout << "Not found file " << fname << "\n";
	}
	fs.open(fname);
	char pch[2550];
	while (fs.good()) {
		// Get line
		fs.getline(pch, 2550);
		st2 = pch;
		if (st2 != "") {
			st += "- " + st2 + "\n";
		}
	}
	fs.close();
	return st;
}

void ClearBuffer() {
	fstream fs;
	fs.open("autotest\\buffer.log", ios::out);
	fs.close();
}

void PublishTest(CString tname, int result, int tpassed) {
	CString st;
	CString st2;
	st2.Format("%s: code %d in %d ms\n", tname, result, tpassed);
	if (result) {
		nRetCode = 2;
		Log(st2, 3);
	}
	else {
		Log(st2, 1);
	}

	// Show errors
	CString errors = file("autotest/buffer.log");
	cout << errors;

	if (ci) {
		errors.Replace("\n- ", "\\n ");
		CString cat = "Passed";
		if (result) cat = "Failed";
		st.Format("UpdateTest \"%s\" -Framework MSTest -FileName MGen.exe -Duration %d -Outcome %s -ErrorMessage \"%d. %s\"", tname, tpassed, cat, result, errors);
		Run("appveyor", st, 1000);
		st.Format("UpdateTest \"%s\" -StdErr \"%s\"", tname, errors);
		Run("appveyor", st, 1000);
	}

	/*
	// Send HTTP
	st.Format("{"
		" \"testName\": \"%s\","
		" \"testFramework\" : \"MSTest\","
		" \"fileName\" : \"MGen.exe\","
		" \"outcome\" : \"%s\","
		" \"durationMilliseconds\" : \"%d\","
		" \"ErrorMessage\" : \"%s\","
		" \"ErrorStackTrace\" : \"\","
		" \"StdOut\" : \"\","
		" \"StdErr\" : \"\""
		" }", tname, cat, tpassed, errors);
	if (ci) {
		HTTPPost(server, port, url + "api/tests", st);
	}
	*/
}

void LoadConfig() {
	milliseconds time_start, time_stop;
	CString fname = "autotest\\test.txt";
	// Check file exists
	if (!CGLib::fileExists(fname)) {
		cout << "Not found file " << fname << "\n";
	}
	ifstream fs;
	fs.open(fname);
	LPDWORD ecode = new DWORD;
	CString st, st2;
	char pch[2550];
	int pos = 0;
	int passed;
	while (fs.good()) {
		fs.getline(pch, 2550);
		st = pch;
		pos = st.Find("#");
		if (pos != -1) st = st.Left(pos);
		st.Trim();
		if (st.GetLength()) {
			ClearBuffer();
			if (ci) Run("appveyor", "AddTest \"" + st + "\" -Framework MSTest -FileName MGen.exe -Outcome Running", 1000);
			Log("Starting test config: " + st + "\n");
			//::ShellExecute(GetDesktopWindow(), "open", "MGen", "-test " + st, NULL, SW_SHOWNORMAL);
			st2 = "-test " + st;
			SHELLEXECUTEINFO sei = { 0 };
			sei.cbSize = sizeof(SHELLEXECUTEINFO);
			sei.fMask = SEE_MASK_NOCLOSEPROCESS;
			sei.hwnd = NULL;
			sei.lpVerb = NULL;
			sei.lpFile = "MGen.exe";
			sei.lpParameters = st2;
			sei.lpDirectory = NULL;
			sei.nShow = SW_SHOW;
			sei.hInstApp = NULL;
			time_start = duration_cast< milliseconds >(system_clock::now().time_since_epoch());
			ShellExecuteEx(&sei);
			if (WaitForSingleObject(sei.hProcess, 60000) == WAIT_TIMEOUT) {
				Log(st + ": Timeout waiting for process\n", 3);
				exit(1);
			}

			time_stop = duration_cast< milliseconds >(system_clock::now().time_since_epoch());
			passed = static_cast<int>((time_stop - time_start).count());
			GetExitCodeProcess(sei.hProcess, ecode);
			PublishTest(st, *ecode, passed);
		}
	}
	delete ecode;
	fs.close();
}

int test() {
	//full_url = "http://my.test.server:882/some/path/script.php?parameters=123";
	//AfxParseURL(full_url, service, server, url, port);
	//ci = 1;
	if (getenv("APPVEYOR_PROJECT_NAME") != NULL) {
		ci = 1;
		//if (getenv("APPVEYOR_API_URL") != NULL) full_url = getenv("APPVEYOR_API_URL");
		//AfxParseURL(full_url, service, server, url, port);
	}
	logfile.open("autotest\\test.log", ios_base::app);

	TCHAR buffer[MAX_PATH];
	GetCurrentDirectory(MAX_PATH, buffer);
	current_dir = string(buffer).c_str();
	Log("Current dir: " + current_dir + "\n");

	LoadConfig();
	logfile.close();
	// Do not pause if continuous integration
	if (!ci) {
		cout << "Press any key to continue... ";
		_getch();
	}
	return 0;
}

int main()
{
    HMODULE hModule = ::GetModuleHandle(nullptr);

    if (hModule != nullptr)
    {
        // initialize MFC and print and error on failure
        if (!AfxWinInit(hModule, nullptr, ::GetCommandLine(), 0))
        {
            // TODO: change error code to suit your needs
            wprintf(L"Fatal Error: MFC initialization failed\n");
            nRetCode = 1;
        }
        else
        {
					test();
				}
    }
    else
    {
        // TODO: change error code to suit your needs
        wprintf(L"Fatal Error: GetModuleHandle failed\n");
        nRetCode = 1;
    }

    return nRetCode;
}
<commit_msg>MgenTest: Try newline in errors<commit_after>// MGenTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "MGenTest.h"
#include "../MGen/GLibrary/GLib.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// The one and only application object

CWinApp theApp;

using namespace std;

CString current_dir, full_url, server, url;
DWORD service;
WORD port;
ofstream logfile;
int ci = 0;
int nRetCode = 0;

/*
string url_encode(const string &value) {
	ostringstream escaped;
	escaped.fill('0');
	escaped << hex;

	for (string::const_iterator i = value.begin(), n = value.end(); i != n; ++i) {
		string::value_type c = (*i);

		// Keep alphanumeric and other accepted characters intact
		if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
			escaped << c;
			continue;
		}

		// Any other characters are percent-encoded
		escaped << uppercase;
		escaped << '%' << setw(2) << int((unsigned char)c);
		escaped << nouppercase;
	}

	return escaped.str();
}

void HTTPPost(CString server, WORD port, CString url, CString data) {
	cout << "HTTPPost to server " << server << " port " << port << " url " << url << " : " << data << "\n";
	CString strHeaders = "Content-Type: application/x-www-form-urlencoded";
	try {
		char szBuf [2550];
		DWORD dwRet;
		CInternetSession session;
		CHttpConnection* pConnection = session.GetHttpConnection(server, port);
		CHttpFile* pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST, url);
		pFile->AddRequestHeaders(strHeaders);
		data = url_encode(data.GetBuffer()).c_str();
		cout << "HTTPPost to server " << server << " port " << port << " url " << url << " : " << data << "\n";
		pFile->SendRequestEx(data.GetLength());
		pFile->Write(data, data.GetLength());
		//BOOL result = pFile->SendRequest(strHeaders, (LPVOID)(LPCTSTR)data, data.GetLength());
		pFile->QueryInfoStatusCode(dwRet);
		cout << "HTTP return code: " << dwRet << "\n";
		if (dwRet == HTTP_STATUS_OK) {
			UINT nRead = pFile->Read(szBuf, 2550);
			if (nRead > 0) {
				cout << "HTTP result: " << szBuf << "\n";
			}
		}
	}
	catch (CInternetException *e) {
		//e->ReportError();
		TCHAR   szCause[2550];
		e->GetErrorMessage(szCause, 2550);
		cout << "Error when sending HTTP request: " << szCause << "\n";
		e->Delete();
	}
}
*/

void Run(CString fname, CString par, int delay) {
	SHELLEXECUTEINFO sei = { 0 };
	sei.cbSize = sizeof(SHELLEXECUTEINFO);
	sei.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI;
	sei.hwnd = NULL;
	sei.lpVerb = NULL;
	sei.lpFile = fname;
	sei.lpParameters = par;
	sei.lpDirectory = NULL;
	sei.nShow = SW_SHOWNORMAL;
	sei.hInstApp = NULL;
	ShellExecuteEx(&sei);
	WaitForSingleObject(sei.hProcess, delay);
}

void Log(CString st, int level = 0) {
	cout << st;
	logfile << st;
	if (ci && level > 0) {
		CString cat;
		if (level == 1) cat = "Information";
		if (level == 2) cat = "Warning";
		if (level == 3) cat = "Error";
		CString par = "AddMessage \"" + st + "\" -Category " + cat;
		Run("appveyor", par, 1000);
	}
}

CString file(CString fname) {
	CString st, st2;
	ifstream fs;
	// Check file exists
	if (!CGLib::fileExists(fname)) {
		cout << "Not found file " << fname << "\n";
	}
	fs.open(fname);
	char pch[2550];
	while (fs.good()) {
		// Get line
		fs.getline(pch, 2550);
		st2 = pch;
		if (st2 != "") {
			st += "- " + st2 + "\n";
		}
	}
	fs.close();
	return st;
}

void ClearBuffer() {
	fstream fs;
	fs.open("autotest\\buffer.log", ios::out);
	fs.close();
}

void PublishTest(CString tname, int result, int tpassed) {
	CString st;
	CString st2;
	st2.Format("%s: code %d in %d ms\n", tname, result, tpassed);
	if (result) {
		nRetCode = 2;
		Log(st2, 3);
	}
	else {
		Log(st2, 1);
	}

	// Show errors
	CString errors = file("autotest/buffer.log");
	cout << errors;

	if (ci) {
		//errors.Replace("\n- ", "\\n ");
		CString cat = "Passed";
		if (result) cat = "Failed";
		st.Format("UpdateTest \"%s\" -Framework MSTest -FileName MGen.exe -Duration %d -Outcome %s -ErrorMessage \"%d. %s\"", tname, tpassed, cat, result, errors);
		Run("appveyor", st, 1000);
		st.Format("UpdateTest \"%s\" -StdErr \"%s\"", tname, errors);
		Run("appveyor", st, 1000);
	}

	/*
	// Send HTTP
	st.Format("{"
		" \"testName\": \"%s\","
		" \"testFramework\" : \"MSTest\","
		" \"fileName\" : \"MGen.exe\","
		" \"outcome\" : \"%s\","
		" \"durationMilliseconds\" : \"%d\","
		" \"ErrorMessage\" : \"%s\","
		" \"ErrorStackTrace\" : \"\","
		" \"StdOut\" : \"\","
		" \"StdErr\" : \"\""
		" }", tname, cat, tpassed, errors);
	if (ci) {
		HTTPPost(server, port, url + "api/tests", st);
	}
	*/
}

void LoadConfig() {
	milliseconds time_start, time_stop;
	CString fname = "autotest\\test.txt";
	// Check file exists
	if (!CGLib::fileExists(fname)) {
		cout << "Not found file " << fname << "\n";
	}
	ifstream fs;
	fs.open(fname);
	LPDWORD ecode = new DWORD;
	CString st, st2;
	char pch[2550];
	int pos = 0;
	int passed;
	while (fs.good()) {
		fs.getline(pch, 2550);
		st = pch;
		pos = st.Find("#");
		if (pos != -1) st = st.Left(pos);
		st.Trim();
		if (st.GetLength()) {
			ClearBuffer();
			if (ci) Run("appveyor", "AddTest \"" + st + "\" -Framework MSTest -FileName MGen.exe -Outcome Running", 1000);
			Log("Starting test config: " + st + "\n");
			//::ShellExecute(GetDesktopWindow(), "open", "MGen", "-test " + st, NULL, SW_SHOWNORMAL);
			st2 = "-test " + st;
			SHELLEXECUTEINFO sei = { 0 };
			sei.cbSize = sizeof(SHELLEXECUTEINFO);
			sei.fMask = SEE_MASK_NOCLOSEPROCESS;
			sei.hwnd = NULL;
			sei.lpVerb = NULL;
			sei.lpFile = "MGen.exe";
			sei.lpParameters = st2;
			sei.lpDirectory = NULL;
			sei.nShow = SW_SHOW;
			sei.hInstApp = NULL;
			time_start = duration_cast< milliseconds >(system_clock::now().time_since_epoch());
			ShellExecuteEx(&sei);
			if (WaitForSingleObject(sei.hProcess, 60000) == WAIT_TIMEOUT) {
				Log(st + ": Timeout waiting for process\n", 3);
				exit(1);
			}

			time_stop = duration_cast< milliseconds >(system_clock::now().time_since_epoch());
			passed = static_cast<int>((time_stop - time_start).count());
			GetExitCodeProcess(sei.hProcess, ecode);
			PublishTest(st, *ecode, passed);
		}
	}
	delete ecode;
	fs.close();
}

int test() {
	//full_url = "http://my.test.server:882/some/path/script.php?parameters=123";
	//AfxParseURL(full_url, service, server, url, port);
	//ci = 1;
	if (getenv("APPVEYOR_PROJECT_NAME") != NULL) {
		ci = 1;
		//if (getenv("APPVEYOR_API_URL") != NULL) full_url = getenv("APPVEYOR_API_URL");
		//AfxParseURL(full_url, service, server, url, port);
	}
	logfile.open("autotest\\test.log", ios_base::app);

	TCHAR buffer[MAX_PATH];
	GetCurrentDirectory(MAX_PATH, buffer);
	current_dir = string(buffer).c_str();
	Log("Current dir: " + current_dir + "\n");

	LoadConfig();
	logfile.close();
	// Do not pause if continuous integration
	if (!ci) {
		cout << "Press any key to continue... ";
		_getch();
	}
	return 0;
}

int main()
{
    HMODULE hModule = ::GetModuleHandle(nullptr);

    if (hModule != nullptr)
    {
        // initialize MFC and print and error on failure
        if (!AfxWinInit(hModule, nullptr, ::GetCommandLine(), 0))
        {
            // TODO: change error code to suit your needs
            wprintf(L"Fatal Error: MFC initialization failed\n");
            nRetCode = 1;
        }
        else
        {
					test();
				}
    }
    else
    {
        // TODO: change error code to suit your needs
        wprintf(L"Fatal Error: GetModuleHandle failed\n");
        nRetCode = 1;
    }

    return nRetCode;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xdictionary.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: kz $ $Date: 2006-07-06 10:33:31 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// xdictionary.cpp: implementation of the xdictionary class.
//
//////////////////////////////////////////////////////////////////////

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#include <com/sun/star/i18n/WordType.hpp>
#include <xdictionary.hxx>
#include <i18nutil/unicode.hxx>
#include <string.h>
#include <breakiteratorImpl.hxx>

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

using namespace rtl;

namespace com { namespace sun { namespace star { namespace i18n {

xdictionary::xdictionary(const sal_Char *lang)
{
#ifdef SAL_DLLPREFIX
    OUStringBuffer aBuf( strlen(lang) + 7 + 6 );    // mostly "lib*.so" (with * == dict_zh)
    aBuf.appendAscii( SAL_DLLPREFIX );
#else
    OUStringBuffer aBuf( strlen(lang) + 7 + 4 );    // mostly "*.dll" (with * == dict_zh)
#endif
    aBuf.appendAscii( "dict_" ).appendAscii( lang ).appendAscii( SAL_DLLEXTENSION );
        hModule = osl_loadModule( aBuf.makeStringAndClear().pData, SAL_LOADMODULE_DEFAULT );
        if( hModule ) {
            sal_IntPtr (*func)();
            func = (sal_IntPtr(*)()) osl_getFunctionSymbol( hModule, OUString::createFromAscii("getExistMark").pData );
            existMark = (sal_uInt8*) (*func)();
            func = (sal_IntPtr(*)()) osl_getFunctionSymbol( hModule, OUString::createFromAscii("getIndex1").pData );
            index1 = (sal_Int16*) (*func)();
            func = (sal_IntPtr(*)()) osl_getFunctionSymbol( hModule, OUString::createFromAscii("getIndex2").pData );
            index2 = (sal_Int32*) (*func)();
            func = (sal_IntPtr(*)()) osl_getFunctionSymbol( hModule, OUString::createFromAscii("getLenArray").pData );
            lenArray = (sal_Int32*) (*func)();
            func = (sal_IntPtr(*)()) osl_getFunctionSymbol( hModule, OUString::createFromAscii("getDataArea").pData );
            dataArea = (sal_Unicode*) (*func)();
        }
        else
            existMark = NULL;
        for (sal_Int32 i = 0; i < CACHE_MAX; i++)
            cache[i].size = 0;

        // for CTL breakiterator, which the word boundary should not inside cell.
        useCellBoundary = sal_False;
        japaneseWordBreak = sal_False;
}

xdictionary::~xdictionary() {
        osl_unloadModule(hModule);
        for (sal_Int32 i = 0; i < CACHE_MAX; i++) {
            if (cache[i].size > 0) {
                delete cache[i].contents;
                delete cache[i].wordboundary;
            }
        }
}

void SAL_CALL xdictionary::setJapaneseWordBreak()
{
        japaneseWordBreak = sal_True;
}

sal_Bool xdictionary::exists(const sal_Unicode c) {
        sal_Bool exist = existMark ? sal::static_int_cast<sal_Bool>((existMark[c>>3] & (1<<(c&0x07))) != 0) : sal_False;
        if (!exist && japaneseWordBreak)
            return BreakIteratorImpl::getScriptClass(c) == ScriptType::ASIAN;
        else
            return exist;
}

sal_Int32 SAL_CALL
xdictionary::getLongestMatch(const sal_Unicode* str, sal_Int32 sLen) {

        sal_Int16 idx = index1[str[0] >> 8];

        if (idx == 0xFF) return 0;

        idx = (idx<<8) | (str[0]&0xff);

        sal_uInt32 begin = index2[idx], end = index2[idx+1];

        if (begin == 0) return 0;

        str++; sLen--; // first character is not stored in the dictionary
        for (sal_uInt32 i = end; i > begin; i--) {
            sal_Int32 len = lenArray[i] - lenArray[i - 1];
            if (sLen >= len) {
                const sal_Unicode *dstr = dataArea + lenArray[i-1];
                sal_Int32 pos = 0;

                while (pos < len && dstr[pos] == str[pos]) { pos++; }

                if (pos == len)
                    return len + 1;
            }
        }
        return 0;
}

/*
 * Compare two unicode string,
 */

sal_Bool SAL_CALL WordBreakCache::equals(const sal_Unicode* str, Boundary& boundary) {
        // Different length, different string.
        if (length != boundary.endPos - boundary.startPos) return sal_False;

        for (sal_Int32 i = 0; i < length; i++)
            if (contents[i] != str[i + boundary.startPos]) return sal_False;

        return sal_True;
}

/*
 * Retrieve the segment containing the character at pos.
 * @param pos : Position of the given character.
 * @return true if CJK.
 */
sal_Bool SAL_CALL xdictionary::seekSegment(const sal_Unicode *text, sal_Int32 pos,
                sal_Int32 len, Boundary& segBoundary) {
        for (segBoundary.startPos = pos - 1;
            segBoundary.startPos >= 0 &&
                (unicode::isWhiteSpace(text[segBoundary.startPos]) || exists(text[segBoundary.startPos]));
            segBoundary.startPos--);
        segBoundary.startPos++;

        for (segBoundary.endPos = pos;
            segBoundary.endPos < len &&
                    (unicode::isWhiteSpace(text[segBoundary.endPos]) || exists(text[segBoundary.endPos]));
            segBoundary.endPos++);

        return segBoundary.endPos > segBoundary.startPos + 1;
}

#define KANJA       1
#define KATAKANA    2
#define HIRAKANA    3

static sal_Int16 SAL_CALL JapaneseCharType(sal_Unicode c)
{
    if (0x3041 <= c && c <= 0x309e)
        return HIRAKANA;
    if (0x30a1 <= c && c <= 0x30fe || 0xff65 <= c && c <= 0xff9f)
        return KATAKANA;
    return KANJA;
}

WordBreakCache& SAL_CALL xdictionary::getCache(const sal_Unicode *text, Boundary& wordBoundary)
{

        WordBreakCache& aCache = cache[text[0] & 0x1f];

        if (aCache.size != 0 && aCache.equals(text, wordBoundary))
            return aCache;

        sal_Int32 len = wordBoundary.endPos - wordBoundary.startPos;

        if (aCache.size == 0 || len > aCache.size) {
            if (aCache.size != 0) {
                delete aCache.contents;
                delete aCache.wordboundary;
                aCache.size = len;
            }
            else
                aCache.size = len > DEFAULT_SIZE ? len : DEFAULT_SIZE;
            aCache.contents = new sal_Unicode[aCache.size + 1];
            aCache.wordboundary = new sal_Int32[aCache.size + 2];
        }
        aCache.length  = len;
        memcpy(aCache.contents, text + wordBoundary.startPos, len * sizeof(sal_Unicode));
        *(aCache.contents + len) = 0x0000;
        // reset the wordboundary in cache
        memset(aCache.wordboundary, '\0', sizeof(sal_Int32)*(len + 2));

        sal_Int32 i = 0;        // loop variable
        while (aCache.wordboundary[i] < aCache.length) {
            len = 0;
            // look the continuous white space as one word and cashe it
            while (unicode::isWhiteSpace(text[wordBoundary.startPos + aCache.wordboundary[i] + len]))
                len ++;

            if (len == 0) {
                const sal_Unicode *str = text + wordBoundary.startPos + aCache.wordboundary[i];
                sal_Int32 slen = aCache.length - aCache.wordboundary[i];
                sal_Int16 type = 0, count = 0;
                for (;len == 0 && slen > 0; str++, slen--) {
                    len = getLongestMatch(str, slen);
                    if (len == 0) {
                        if (!japaneseWordBreak) {
                            len = 1;
                        } else {
                            if (count == 0)
                                type = JapaneseCharType(*str);
                            else if (type != JapaneseCharType(*str))
                                break;
                            count++;
                        }
                    }
                }
                if (count) {
                    aCache.wordboundary[i+1] = aCache.wordboundary[i] + count;
                    i++;
                    if (useCellBoundary) {
                        sal_Int32 cBoundary = cellBoundary[aCache.wordboundary[i] + wordBoundary.startPos - 1];
                        if (cBoundary > 0)
                            aCache.wordboundary[i] = cBoundary - wordBoundary.startPos;
                    }
                }
            }

            if (len) {
                aCache.wordboundary[i+1] = aCache.wordboundary[i] + len;
                i++;

                if (useCellBoundary) {
                    sal_Int32 cBoundary = cellBoundary[aCache.wordboundary[i] + wordBoundary.startPos - 1];
                    if (cBoundary > 0)
                        aCache.wordboundary[i] = cBoundary - wordBoundary.startPos;
                }
            }
        }
        aCache.wordboundary[i + 1] = aCache.length + 1;

        return aCache;
}

Boundary SAL_CALL xdictionary::previousWord(const sal_Unicode *text, sal_Int32 anyPos, sal_Int32 len, sal_Int16 wordType)
{
        // looking for the first non-whitespace character from anyPos
        while (unicode::isWhiteSpace(text[anyPos - 1])) anyPos --;
        return getWordBoundary(text, anyPos - 1, len, wordType, true);
}

Boundary SAL_CALL xdictionary::nextWord(const sal_Unicode *text, sal_Int32 anyPos, sal_Int32 len, sal_Int16 wordType)
{
        boundary = getWordBoundary(text, anyPos, len, wordType, true);
        // looknig for the first non-whitespace character from anyPos
        anyPos = boundary.endPos;
        while (unicode::isWhiteSpace(text[anyPos])) anyPos ++;

        return getWordBoundary(text, anyPos, len, wordType, true);
}

Boundary SAL_CALL xdictionary::getWordBoundary(const sal_Unicode *text, sal_Int32 anyPos, sal_Int32 len, sal_Int16 wordType, sal_Bool bDirection)
{
        if (anyPos >= len || anyPos < 0) {
            boundary.startPos = boundary.endPos = anyPos < 0 ? 0 : len;
        } else if (seekSegment(text, anyPos, len, boundary)) {          // character in dict
            WordBreakCache& aCache = getCache(text, boundary);
            sal_Int32 i = 0;

            while (aCache.wordboundary[i] <= (sal_Int32)anyPos - boundary.startPos) i++;

            sal_Int32 startPos = aCache.wordboundary[i - 1];
            // if bDirection is false
            if (!bDirection && startPos > 0 && startPos == (anyPos - boundary.startPos) &&
                                                unicode::isWhiteSpace(text[anyPos - 1]))
                i--;
            boundary.endPos = aCache.wordboundary[i] + boundary.startPos;
            boundary.startPos += aCache.wordboundary[i - 1];
        } else {
            boundary.startPos = anyPos++;
            boundary.endPos = anyPos < len ? anyPos : len;
        }
        if (wordType == WordType::WORD_COUNT) {
            // skip punctuation for word count.
            while (boundary.endPos < len && unicode::isPunctuation(text[boundary.endPos]))
                boundary.endPos++;
        }

        return boundary;
}

void SAL_CALL xdictionary::setCellBoundary(sal_Int32* cellArray)
{
        useCellBoundary = sal_True;
        cellBoundary = cellArray;
}

} } } }
<commit_msg>INTEGRATION: CWS pchfix02 (1.13.12); FILE MERGED 2006/09/01 17:30:39 kaib 1.13.12.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xdictionary.cxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 09:14:44 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_i18npool.hxx"

// xdictionary.cpp: implementation of the xdictionary class.
//
//////////////////////////////////////////////////////////////////////

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#include <com/sun/star/i18n/WordType.hpp>
#include <xdictionary.hxx>
#include <i18nutil/unicode.hxx>
#include <string.h>
#include <breakiteratorImpl.hxx>

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

using namespace rtl;

namespace com { namespace sun { namespace star { namespace i18n {

xdictionary::xdictionary(const sal_Char *lang)
{
#ifdef SAL_DLLPREFIX
    OUStringBuffer aBuf( strlen(lang) + 7 + 6 );    // mostly "lib*.so" (with * == dict_zh)
    aBuf.appendAscii( SAL_DLLPREFIX );
#else
    OUStringBuffer aBuf( strlen(lang) + 7 + 4 );    // mostly "*.dll" (with * == dict_zh)
#endif
    aBuf.appendAscii( "dict_" ).appendAscii( lang ).appendAscii( SAL_DLLEXTENSION );
        hModule = osl_loadModule( aBuf.makeStringAndClear().pData, SAL_LOADMODULE_DEFAULT );
        if( hModule ) {
            sal_IntPtr (*func)();
            func = (sal_IntPtr(*)()) osl_getFunctionSymbol( hModule, OUString::createFromAscii("getExistMark").pData );
            existMark = (sal_uInt8*) (*func)();
            func = (sal_IntPtr(*)()) osl_getFunctionSymbol( hModule, OUString::createFromAscii("getIndex1").pData );
            index1 = (sal_Int16*) (*func)();
            func = (sal_IntPtr(*)()) osl_getFunctionSymbol( hModule, OUString::createFromAscii("getIndex2").pData );
            index2 = (sal_Int32*) (*func)();
            func = (sal_IntPtr(*)()) osl_getFunctionSymbol( hModule, OUString::createFromAscii("getLenArray").pData );
            lenArray = (sal_Int32*) (*func)();
            func = (sal_IntPtr(*)()) osl_getFunctionSymbol( hModule, OUString::createFromAscii("getDataArea").pData );
            dataArea = (sal_Unicode*) (*func)();
        }
        else
            existMark = NULL;
        for (sal_Int32 i = 0; i < CACHE_MAX; i++)
            cache[i].size = 0;

        // for CTL breakiterator, which the word boundary should not inside cell.
        useCellBoundary = sal_False;
        japaneseWordBreak = sal_False;
}

xdictionary::~xdictionary() {
        osl_unloadModule(hModule);
        for (sal_Int32 i = 0; i < CACHE_MAX; i++) {
            if (cache[i].size > 0) {
                delete cache[i].contents;
                delete cache[i].wordboundary;
            }
        }
}

void SAL_CALL xdictionary::setJapaneseWordBreak()
{
        japaneseWordBreak = sal_True;
}

sal_Bool xdictionary::exists(const sal_Unicode c) {
        sal_Bool exist = existMark ? sal::static_int_cast<sal_Bool>((existMark[c>>3] & (1<<(c&0x07))) != 0) : sal_False;
        if (!exist && japaneseWordBreak)
            return BreakIteratorImpl::getScriptClass(c) == ScriptType::ASIAN;
        else
            return exist;
}

sal_Int32 SAL_CALL
xdictionary::getLongestMatch(const sal_Unicode* str, sal_Int32 sLen) {

        sal_Int16 idx = index1[str[0] >> 8];

        if (idx == 0xFF) return 0;

        idx = (idx<<8) | (str[0]&0xff);

        sal_uInt32 begin = index2[idx], end = index2[idx+1];

        if (begin == 0) return 0;

        str++; sLen--; // first character is not stored in the dictionary
        for (sal_uInt32 i = end; i > begin; i--) {
            sal_Int32 len = lenArray[i] - lenArray[i - 1];
            if (sLen >= len) {
                const sal_Unicode *dstr = dataArea + lenArray[i-1];
                sal_Int32 pos = 0;

                while (pos < len && dstr[pos] == str[pos]) { pos++; }

                if (pos == len)
                    return len + 1;
            }
        }
        return 0;
}

/*
 * Compare two unicode string,
 */

sal_Bool SAL_CALL WordBreakCache::equals(const sal_Unicode* str, Boundary& boundary) {
        // Different length, different string.
        if (length != boundary.endPos - boundary.startPos) return sal_False;

        for (sal_Int32 i = 0; i < length; i++)
            if (contents[i] != str[i + boundary.startPos]) return sal_False;

        return sal_True;
}

/*
 * Retrieve the segment containing the character at pos.
 * @param pos : Position of the given character.
 * @return true if CJK.
 */
sal_Bool SAL_CALL xdictionary::seekSegment(const sal_Unicode *text, sal_Int32 pos,
                sal_Int32 len, Boundary& segBoundary) {
        for (segBoundary.startPos = pos - 1;
            segBoundary.startPos >= 0 &&
                (unicode::isWhiteSpace(text[segBoundary.startPos]) || exists(text[segBoundary.startPos]));
            segBoundary.startPos--);
        segBoundary.startPos++;

        for (segBoundary.endPos = pos;
            segBoundary.endPos < len &&
                    (unicode::isWhiteSpace(text[segBoundary.endPos]) || exists(text[segBoundary.endPos]));
            segBoundary.endPos++);

        return segBoundary.endPos > segBoundary.startPos + 1;
}

#define KANJA       1
#define KATAKANA    2
#define HIRAKANA    3

static sal_Int16 SAL_CALL JapaneseCharType(sal_Unicode c)
{
    if (0x3041 <= c && c <= 0x309e)
        return HIRAKANA;
    if (0x30a1 <= c && c <= 0x30fe || 0xff65 <= c && c <= 0xff9f)
        return KATAKANA;
    return KANJA;
}

WordBreakCache& SAL_CALL xdictionary::getCache(const sal_Unicode *text, Boundary& wordBoundary)
{

        WordBreakCache& aCache = cache[text[0] & 0x1f];

        if (aCache.size != 0 && aCache.equals(text, wordBoundary))
            return aCache;

        sal_Int32 len = wordBoundary.endPos - wordBoundary.startPos;

        if (aCache.size == 0 || len > aCache.size) {
            if (aCache.size != 0) {
                delete aCache.contents;
                delete aCache.wordboundary;
                aCache.size = len;
            }
            else
                aCache.size = len > DEFAULT_SIZE ? len : DEFAULT_SIZE;
            aCache.contents = new sal_Unicode[aCache.size + 1];
            aCache.wordboundary = new sal_Int32[aCache.size + 2];
        }
        aCache.length  = len;
        memcpy(aCache.contents, text + wordBoundary.startPos, len * sizeof(sal_Unicode));
        *(aCache.contents + len) = 0x0000;
        // reset the wordboundary in cache
        memset(aCache.wordboundary, '\0', sizeof(sal_Int32)*(len + 2));

        sal_Int32 i = 0;        // loop variable
        while (aCache.wordboundary[i] < aCache.length) {
            len = 0;
            // look the continuous white space as one word and cashe it
            while (unicode::isWhiteSpace(text[wordBoundary.startPos + aCache.wordboundary[i] + len]))
                len ++;

            if (len == 0) {
                const sal_Unicode *str = text + wordBoundary.startPos + aCache.wordboundary[i];
                sal_Int32 slen = aCache.length - aCache.wordboundary[i];
                sal_Int16 type = 0, count = 0;
                for (;len == 0 && slen > 0; str++, slen--) {
                    len = getLongestMatch(str, slen);
                    if (len == 0) {
                        if (!japaneseWordBreak) {
                            len = 1;
                        } else {
                            if (count == 0)
                                type = JapaneseCharType(*str);
                            else if (type != JapaneseCharType(*str))
                                break;
                            count++;
                        }
                    }
                }
                if (count) {
                    aCache.wordboundary[i+1] = aCache.wordboundary[i] + count;
                    i++;
                    if (useCellBoundary) {
                        sal_Int32 cBoundary = cellBoundary[aCache.wordboundary[i] + wordBoundary.startPos - 1];
                        if (cBoundary > 0)
                            aCache.wordboundary[i] = cBoundary - wordBoundary.startPos;
                    }
                }
            }

            if (len) {
                aCache.wordboundary[i+1] = aCache.wordboundary[i] + len;
                i++;

                if (useCellBoundary) {
                    sal_Int32 cBoundary = cellBoundary[aCache.wordboundary[i] + wordBoundary.startPos - 1];
                    if (cBoundary > 0)
                        aCache.wordboundary[i] = cBoundary - wordBoundary.startPos;
                }
            }
        }
        aCache.wordboundary[i + 1] = aCache.length + 1;

        return aCache;
}

Boundary SAL_CALL xdictionary::previousWord(const sal_Unicode *text, sal_Int32 anyPos, sal_Int32 len, sal_Int16 wordType)
{
        // looking for the first non-whitespace character from anyPos
        while (unicode::isWhiteSpace(text[anyPos - 1])) anyPos --;
        return getWordBoundary(text, anyPos - 1, len, wordType, true);
}

Boundary SAL_CALL xdictionary::nextWord(const sal_Unicode *text, sal_Int32 anyPos, sal_Int32 len, sal_Int16 wordType)
{
        boundary = getWordBoundary(text, anyPos, len, wordType, true);
        // looknig for the first non-whitespace character from anyPos
        anyPos = boundary.endPos;
        while (unicode::isWhiteSpace(text[anyPos])) anyPos ++;

        return getWordBoundary(text, anyPos, len, wordType, true);
}

Boundary SAL_CALL xdictionary::getWordBoundary(const sal_Unicode *text, sal_Int32 anyPos, sal_Int32 len, sal_Int16 wordType, sal_Bool bDirection)
{
        if (anyPos >= len || anyPos < 0) {
            boundary.startPos = boundary.endPos = anyPos < 0 ? 0 : len;
        } else if (seekSegment(text, anyPos, len, boundary)) {          // character in dict
            WordBreakCache& aCache = getCache(text, boundary);
            sal_Int32 i = 0;

            while (aCache.wordboundary[i] <= (sal_Int32)anyPos - boundary.startPos) i++;

            sal_Int32 startPos = aCache.wordboundary[i - 1];
            // if bDirection is false
            if (!bDirection && startPos > 0 && startPos == (anyPos - boundary.startPos) &&
                                                unicode::isWhiteSpace(text[anyPos - 1]))
                i--;
            boundary.endPos = aCache.wordboundary[i] + boundary.startPos;
            boundary.startPos += aCache.wordboundary[i - 1];
        } else {
            boundary.startPos = anyPos++;
            boundary.endPos = anyPos < len ? anyPos : len;
        }
        if (wordType == WordType::WORD_COUNT) {
            // skip punctuation for word count.
            while (boundary.endPos < len && unicode::isPunctuation(text[boundary.endPos]))
                boundary.endPos++;
        }

        return boundary;
}

void SAL_CALL xdictionary::setCellBoundary(sal_Int32* cellArray)
{
        useCellBoundary = sal_True;
        cellBoundary = cellArray;
}

} } } }
<|endoftext|>


<commit_before>/*** Copyright (c), The Regents of the University of California            ***
 *** For more information please refer to files in the COPYRIGHT directory ***/

/* miscServerFunct.h - header file for miscServerFunct.c
 */

#ifndef MISC_SERVER_FUNCT_HPP
#define MISC_SERVER_FUNCT_HPP

#include <sys/types.h>

#ifndef _WIN32
//#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif

#include "rods.hpp"
#include "rcConnect.hpp"
#include "initServer.hpp"
#include "fileOpen.hpp"
#include "dataObjInpOut.hpp"
#include "dataCopy.hpp"
#include "QUANTAnet_rbudpBase_c.hpp"
#include "QUANTAnet_rbudpSender_c.hpp"
#include "QUANTAnet_rbudpReceiver_c.hpp"

#include "structFileSync.hpp" /* JMC */

#include "irods_network_object.hpp"

#define MAX_RECON_ERROR_CNT	10

typedef struct PortalTransferInp {
    rsComm_t *rsComm;
    int destFd;
    int srcFd;
    int destRescTypeInx;
    int srcRescTypeInx;
    int threadNum;
    rodsLong_t size;
    rodsLong_t offset;
    rodsLong_t bytesWritten;
    int flags;
    int status;
    dataOprInp_t *dataOprInp;

    int  key_size;
    int  salt_size;
    int  num_hash_rounds;
    char encryption_algorithm[ NAME_LEN ];
    char shared_secret[ NAME_LEN ]; // JMC - shared secret for each portal thread

} portalTransferInp_t;

int
svrToSvrConnect( rsComm_t *rsComm, rodsServerHost_t *rodsServerHost );
int
svrToSvrConnect( rsComm_t *rsComm, rodsServerHost_t *rodsServerHost );
int
svrToSvrConnectNoLogin( rsComm_t *rsComm, rodsServerHost_t *rodsServerHost );
int
createSrvPortal( rsComm_t *rsComm, portList_t *thisPortList, int proto );
int
acceptSrvPortal( rsComm_t *rsComm, portList_t *thisPortList );
int
svrPortalPutGet( rsComm_t *rsComm );
void
partialDataPut( portalTransferInp_t *myInput );
void
partialDataGet( portalTransferInp_t *myInput );
int
fillPortalTransferInp( portalTransferInp_t *myInput, rsComm_t *rsComm,
                       int srcFd, int destFd, int destRescTypeInx, int srcRescTypeInx,
                       int threadNum, rodsLong_t size, rodsLong_t offset, int flags );
int
sameHostCopy( rsComm_t *rsComm, dataCopyInp_t *dataCopyInp );
void
sameHostPartialCopy( portalTransferInp_t *myInput );
int
rbudpRemLocCopy( rsComm_t *rsComm, dataCopyInp_t *dataCopyInp );
int
remLocCopy( rsComm_t *rsComm, dataCopyInp_t *dataCopyInp );
void
remToLocPartialCopy( portalTransferInp_t *myInput );
void
locToRemPartialCopy( portalTransferInp_t *myInput );
int
singleRemLocCopy( rsComm_t *rsComm, dataCopyInp_t *dataCopyInp );
int
singleRemToLocCopy( rsComm_t *rsComm, dataCopyInp_t *dataCopyInp );
int
singleLocToRemCopy( rsComm_t *rsComm, dataCopyInp_t *dataCopyInp );
int
isUserPrivileged( rsComm_t *rsComm );
#if !defined(solaris_platform)
char *regcmp( char *pat, char *end );
char *regex( char *rec, char *text, ... );
#endif
int intNoSupport( ... );
rodsLong_t longNoSupport( ... );
void getZoneServerId( char *zoneName, char *zoneSID );
int
svrPortalPutGetRbudp( rsComm_t *rsComm );
#ifndef windows_platform
void
reconnManager( rsComm_t *rsComm );
int
svrChkReconnAtReadStart( rsComm_t *rsComm );
int
svrChkReconnAtReadEnd( rsComm_t *rsComm );
int
svrChkReconnAtSendStart( rsComm_t *rsComm );
int
svrChkReconnAtSendEnd( rsComm_t *rsComm );
#endif
int
svrSockOpenForInConn( rsComm_t *rsComm, int *portNum, char **addr, int proto );
char *
getLocalSvrAddr();
char *
_getSvrAddr( rodsServerHost_t *rodsServerHost );
char *
getSvrAddr( rodsServerHost_t *rodsServerHost );
int
setLocalSrvAddr( char *outLocalAddr );
int
forkAndExec( char *av[] );
int
setupSrvPortalForParaOpr( rsComm_t *rsComm, dataOprInp_t *dataOprInp,
                          int oprType, portalOprOut_t **portalOprOut );
int
readStartupPack( irods::network_object_ptr, startupPack_t **startupPack, struct timeval *tv );
#ifdef RUN_SERVER_AS_ROOT
int
initServiceUser();
int
isServiceUserSet();
int
changeToRootUser();
int
changeToServiceUser();
#endif
#endif	/* MISC_SERVER_FUNCT_H */
<commit_msg>[#1880] turned on run_as_root code that was #ifdef'ed out<commit_after>/*** Copyright (c), The Regents of the University of California            ***
 *** For more information please refer to files in the COPYRIGHT directory ***/

/* miscServerFunct.h - header file for miscServerFunct.c
 */

#ifndef MISC_SERVER_FUNCT_HPP
#define MISC_SERVER_FUNCT_HPP

#include <sys/types.h>

#ifndef _WIN32
//#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif

#include "rods.hpp"
#include "rcConnect.hpp"
#include "initServer.hpp"
#include "fileOpen.hpp"
#include "dataObjInpOut.hpp"
#include "dataCopy.hpp"
#include "QUANTAnet_rbudpBase_c.hpp"
#include "QUANTAnet_rbudpSender_c.hpp"
#include "QUANTAnet_rbudpReceiver_c.hpp"

#include "structFileSync.hpp" /* JMC */

#include "irods_network_object.hpp"

#define MAX_RECON_ERROR_CNT	10

typedef struct PortalTransferInp {
    rsComm_t *rsComm;
    int destFd;
    int srcFd;
    int destRescTypeInx;
    int srcRescTypeInx;
    int threadNum;
    rodsLong_t size;
    rodsLong_t offset;
    rodsLong_t bytesWritten;
    int flags;
    int status;
    dataOprInp_t *dataOprInp;

    int  key_size;
    int  salt_size;
    int  num_hash_rounds;
    char encryption_algorithm[ NAME_LEN ];
    char shared_secret[ NAME_LEN ]; // JMC - shared secret for each portal thread

} portalTransferInp_t;

int
svrToSvrConnect( rsComm_t *rsComm, rodsServerHost_t *rodsServerHost );
int
svrToSvrConnect( rsComm_t *rsComm, rodsServerHost_t *rodsServerHost );
int
svrToSvrConnectNoLogin( rsComm_t *rsComm, rodsServerHost_t *rodsServerHost );
int
createSrvPortal( rsComm_t *rsComm, portList_t *thisPortList, int proto );
int
acceptSrvPortal( rsComm_t *rsComm, portList_t *thisPortList );
int
svrPortalPutGet( rsComm_t *rsComm );
void
partialDataPut( portalTransferInp_t *myInput );
void
partialDataGet( portalTransferInp_t *myInput );
int
fillPortalTransferInp( portalTransferInp_t *myInput, rsComm_t *rsComm,
                       int srcFd, int destFd, int destRescTypeInx, int srcRescTypeInx,
                       int threadNum, rodsLong_t size, rodsLong_t offset, int flags );
int
sameHostCopy( rsComm_t *rsComm, dataCopyInp_t *dataCopyInp );
void
sameHostPartialCopy( portalTransferInp_t *myInput );
int
rbudpRemLocCopy( rsComm_t *rsComm, dataCopyInp_t *dataCopyInp );
int
remLocCopy( rsComm_t *rsComm, dataCopyInp_t *dataCopyInp );
void
remToLocPartialCopy( portalTransferInp_t *myInput );
void
locToRemPartialCopy( portalTransferInp_t *myInput );
int
singleRemLocCopy( rsComm_t *rsComm, dataCopyInp_t *dataCopyInp );
int
singleRemToLocCopy( rsComm_t *rsComm, dataCopyInp_t *dataCopyInp );
int
singleLocToRemCopy( rsComm_t *rsComm, dataCopyInp_t *dataCopyInp );
int
isUserPrivileged( rsComm_t *rsComm );
#if !defined(solaris_platform)
char *regcmp( char *pat, char *end );
char *regex( char *rec, char *text, ... );
#endif
int intNoSupport( ... );
rodsLong_t longNoSupport( ... );
void getZoneServerId( char *zoneName, char *zoneSID );
int
svrPortalPutGetRbudp( rsComm_t *rsComm );
#ifndef windows_platform
void
reconnManager( rsComm_t *rsComm );
int
svrChkReconnAtReadStart( rsComm_t *rsComm );
int
svrChkReconnAtReadEnd( rsComm_t *rsComm );
int
svrChkReconnAtSendStart( rsComm_t *rsComm );
int
svrChkReconnAtSendEnd( rsComm_t *rsComm );
#endif
int
svrSockOpenForInConn( rsComm_t *rsComm, int *portNum, char **addr, int proto );
char *
getLocalSvrAddr();
char *
_getSvrAddr( rodsServerHost_t *rodsServerHost );
char *
getSvrAddr( rodsServerHost_t *rodsServerHost );
int
setLocalSrvAddr( char *outLocalAddr );
int
forkAndExec( char *av[] );
int
setupSrvPortalForParaOpr( rsComm_t *rsComm, dataOprInp_t *dataOprInp,
                          int oprType, portalOprOut_t **portalOprOut );
int
readStartupPack( irods::network_object_ptr, startupPack_t **startupPack, struct timeval *tv );

int
initServiceUser();
int
isServiceUserSet();
int
changeToRootUser();
int
changeToServiceUser();

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


<commit_before>#include <NeuralNetwork/Perceptron/Perceptron.h>
#include <NeuralNetwork/Neuron/Neuron.h>
#include <NeuralNetwork/NeuralLayer/NeuralLayer.h>
#include <NeuralNetwork/Neuron/ActivationFunction/SigmoidFunction.h>
#include <NeuralNetwork/Neuron/ActivationFunction/TanhFunction.h>
#include <NeuralNetwork/Neuron/ActivationFunction/SoftmaxFunction.h>
#include <NeuralNetwork/Neuron/ActivationFunction/BiopolarSigmoidFunction.h>
#include <NeuralNetwork/LearningAlgorithm/BackPropagation/BepAlgorithm.h>
#include <NeuralNetwork/Neuron/ActivationFunction/LogScaleSoftmaxFunction.h>
#include <NeuralNetwork/Config.h>

#ifndef BOOST_SYSTEM_NO_DEPRECATED
#define BOOST_SYSTEM_NO_DEPRECATED 1
#include <boost/filesystem.hpp>
#undef BOOST_SYSTEM_NO_DEPRECATED
#endif

#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <fstream>
#include <iomanip>
#include <set>

#define png_infopp_NULL (png_infopp)NULL
#define int_p_NULL (int*)NULL

#if defined(NN_CC_MSVC)
# pragma warning(push)
// This function or variable may be unsafe
# pragma warning(disable:4996)
#endif

#include <boost/gil/gil_all.hpp>
#include <boost/gil/channel_algorithm.hpp>
#include <boost/gil/channel.hpp>
#include <boost/gil/image.hpp>
#include <boost/gil/extension/io/png_dynamic_io.hpp>
#include <boost/gil/extension/io/dynamic_io.hpp>
#include <boost/gil/extension/dynamic_image/any_image.hpp>
#include <boost/gil/extension/dynamic_image/dynamic_image_all.hpp>
#include "gil/extension/numeric/sampler.hpp"
#include "gil/extension/numeric/resample.hpp"

#if defined(NN_CC_MSVC)
# pragma warning(pop)
#endif

#include "Var.h"

typedef double VarType;

using namespace boost::gil;
using namespace boost::gil::detail;
static const std::string alphabet("123456789");
static const unsigned int width = 49;
static const unsigned int height = 67;
static const unsigned int inputsNumber = width * height;

typedef nn::Perceptron< VarType,
			nn::NeuralLayer<nn::Neuron, nn::SigmoidFunction, 10 , inputsNumber, 1000 >,
			nn::NeuralLayer<nn::Neuron, nn::SigmoidFunction, 80, 10, 1000>,
			nn::NeuralLayer<nn::Neuron, nn::SoftmaxFunction, 9, 1000>
		       > Perceptron;

typedef nn::Perceptron< VarType,
			nn::NeuralLayer<nn::Neuron, nn::SigmoidFunction, 80, inputsNumber, 1000>,
			nn::NeuralLayer<nn::Neuron, nn::SoftmaxFunction,  inputsNumber, 80, 1000 >
		      > AutoEncoder;

typedef nn::bp::BepAlgorithm< AutoEncoder, nn::bp::CrossEntropyError> AutoEncAlgo;
typedef nn::bp::BepAlgorithm< Perceptron, nn::bp::CrossEntropyError> Algo;

template <typename Out>
struct halfdiff_cast_channels {
    template <typename T>
    Out operator()(const T& in1, const T& in2) const {
        return Out( (in1-in2)/2 );
    }
};

template <typename SrcView, typename DstView>
void convert_color(const SrcView& src, const DstView& dst) {
    typedef typename channel_type<DstView>::type d_channel_t;
    typedef typename channel_convert_to_unsigned<d_channel_t>::type channel_t;
    typedef pixel<channel_t, gray_layout_t>  gray_pixel_t;

    copy_pixels(color_converted_view<gray_pixel_t>(src), dst);
}

template<typename Iterator>
void readImage(std::string fileName, Iterator out) {
    using namespace boost::gil;
    using namespace nn;
    using namespace nn::bp;

    rgb8_image_t srcImg;
    png_read_image(fileName.c_str(), srcImg);

    gray8_image_t dstImg(srcImg.dimensions());
    gray8_pixel_t white(255);
    fill_pixels(view(dstImg), white);

    gray8_image_t grayImage(srcImg.dimensions());
    convert_color( view(srcImg), view(grayImage) );
    auto grayView = view(grayImage);

    gray8_image_t scaledImage(width, height);
    resize_view(grayView, view(scaledImage), bilinear_sampler() );
    auto srcView = view(scaledImage);

    for (int y=0; y<srcView.height(); ++y) {
        gray8c_view_t::x_iterator src_it( srcView.row_begin(y) );
        for (int x=0; x<srcView.width(); ++x) {
            *out = src_it[x]/255.f;// < 130? 1.f: -1.f;//255.f;
            out++;
        }
    }
}

Perceptron readPerceptron(std::string fileName) {
    Perceptron perceptron;
    if( boost::filesystem::exists(fileName.c_str()) ){
      std::ifstream file(fileName);
      if( file.good() ) {
	  Perceptron::Memento memento;
	  boost::archive::xml_iarchive ia ( file );
	  ia  >> BOOST_SERIALIZATION_NVP ( memento );

	  perceptron.setMemento ( memento );
      } else {
	  throw nn::NNException("Invalid perceptron file name", __FILE__, __LINE__);
      }
    }

    return perceptron;
}

void recognize(std::string perceptron, std::string image) {
    try {
        std::array<VarType, inputsNumber> inputs = {0};
        readImage(image, inputs.begin() );
        std::vector<VarType> result(alphabet.length(), VarType(0.f) );
        readPerceptron(perceptron).calculate(inputs.begin(), inputs.end(), result.begin() );
        for( unsigned int i = 0; i < result.size(); i++ ) {
	  std::cout << "Symbol: " <<
		       alphabet[i] <<
		       " " <<
		       result[i] <<
		       std::endl;
        }

    } catch( const nn::NNException& e) {
        std::cout << e.what() << std::endl;
    } catch( const std::exception& e) {
        std::cout << e.what() << std::endl;
    } catch(...) {
        std::cout << "Unknown error" << std::endl;
    }
}

template<typename Perc>
void save(const Perc& perc, std::string name)
{
    typename Perc::Memento memento = perc.getMemento();
    std::ofstream strm( name );
    boost::archive::xml_oarchive oa ( strm );
    oa << BOOST_SERIALIZATION_NVP ( memento );
    strm.flush();
}

template<typename Files>
AutoEncoder calculateAutoEncoder(Files files){
    std::cout << "AutoEncoder calculation started" << std::endl;
    std::vector<AutoEncAlgo::Prototype> prototypes;
    for( auto image : files) {
        if( !boost::filesystem::is_directory( image ) ) {
            try {
                AutoEncAlgo::Prototype proto;
                readImage( image, std::get<0>(proto).begin() );
		std::copy( std::get<0>(proto).begin(),
			   std::get<0>(proto).end(),
			   std::get<1>(proto).begin());

                prototypes.push_back(proto);
            } catch(const std::exception&) {
                std::cout << "Invalid image found :" << image << std::endl;
            }
        }
    }

    static AutoEncAlgo autoEncAlgo(0.005f, 0.01f);

    static std::size_t counter = 0;
    static AutoEncoder enc = autoEncAlgo.calculatePerceptron(prototypes.begin(),
							  prototypes.end(),
							  [](VarType error) {
							      counter++;
							      if(counter > 0){
								counter = 0;
								std::cout << error << std::endl;
							      }
							  });

    save(enc, "autoencoder.xml");
}

void calculateWeights(std::string imagesPath) {
    using namespace boost::filesystem;
    path directory(imagesPath);
    directory_iterator end_iter;

    std::vector< std::string > files;
    if ( exists(directory) && is_directory(directory))
    {
        for( directory_iterator dir_iter(directory) ; dir_iter != end_iter ; ++dir_iter)
        {
            if (is_regular_file(dir_iter->status()) )
            {
                files.push_back( dir_iter->path().string() );
            }
        }
    }

    //static AutoEncoder autoEnc = calculateAutoEncoder(files);

    std::cout << "Perceptron calculation started" << std::endl;
    static Perceptron tmp = readPerceptron("perceptron.xml");
    static Algo algorithm (0.003f, 0.001f );
    algorithm.setMemento( tmp.getMemento() );

    std::vector<Algo::Prototype> prototypes;
    for( auto image : files ) {
        if( !boost::filesystem::is_directory( image ) ) {
            try {
                Algo::Prototype proto;
                readImage( image, std::get<0>(proto).begin() );
                std::fill(std::get<1>(proto).begin(), std::get<1>(proto).end(), 0.f);
                char ch = path(image).filename().string()[0];
                size_t pos = alphabet.find(ch);
                std::get<1>(proto)[pos] = 1.0f;
                prototypes.push_back(proto);
            } catch(const std::exception&) {
                std::cout << "Invalid image found :" << image << std::endl;
            }
        }
    }

    static std::size_t counter = 0;
    static Perceptron perceptron = algorithm.calculatePerceptron(prototypes.begin(),
							  prototypes.end(),
							  [](VarType error) {
							      counter++;
							      if(counter > 1000){
								counter = 0;
								std::cout << error << std::endl;
							      }
							  });

    save(perceptron, "perceptron.xml");
}

int main(int argc, char** argv)
{
    int result = -1;
    if( argc == 3 ) {
        recognize(argv[1], argv[2]);
        result = 0;
    } else if( argc == 2 ) {
        calculateWeights(argv[1]);
        result = 0;
    } else {
        std::cout << std::endl << "Usage : " << std::endl << std::endl;
        std::cout << "./ocr [folder] where  [folder] is a directory with your samples, this command will generate a perceptron.xml file" << std::endl << std::endl;
        std::cout << "./ocr perceptron.xml [file] where [file] is a png image which has to be recognized" << std::endl << std::endl;
    }

    return result;
}

<commit_msg>ocr: fix missed 0 digit in alphabet<commit_after>#include <NeuralNetwork/Perceptron/Perceptron.h>
#include <NeuralNetwork/Neuron/Neuron.h>
#include <NeuralNetwork/NeuralLayer/NeuralLayer.h>
#include <NeuralNetwork/Neuron/ActivationFunction/SigmoidFunction.h>
#include <NeuralNetwork/Neuron/ActivationFunction/TanhFunction.h>
#include <NeuralNetwork/Neuron/ActivationFunction/SoftmaxFunction.h>
#include <NeuralNetwork/Neuron/ActivationFunction/BiopolarSigmoidFunction.h>
#include <NeuralNetwork/LearningAlgorithm/BackPropagation/BepAlgorithm.h>
#include <NeuralNetwork/Neuron/ActivationFunction/LogScaleSoftmaxFunction.h>
#include <NeuralNetwork/Config.h>

#ifndef BOOST_SYSTEM_NO_DEPRECATED
#define BOOST_SYSTEM_NO_DEPRECATED 1
#include <boost/filesystem.hpp>
#undef BOOST_SYSTEM_NO_DEPRECATED
#endif

#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <fstream>
#include <iomanip>
#include <set>

#define png_infopp_NULL (png_infopp)NULL
#define int_p_NULL (int*)NULL

#if defined(NN_CC_MSVC)
# pragma warning(push)
// This function or variable may be unsafe
# pragma warning(disable:4996)
#endif

#include <boost/gil/gil_all.hpp>
#include <boost/gil/channel_algorithm.hpp>
#include <boost/gil/channel.hpp>
#include <boost/gil/image.hpp>
#include <boost/gil/extension/io/png_dynamic_io.hpp>
#include <boost/gil/extension/io/dynamic_io.hpp>
#include <boost/gil/extension/dynamic_image/any_image.hpp>
#include <boost/gil/extension/dynamic_image/dynamic_image_all.hpp>
#include "gil/extension/numeric/sampler.hpp"
#include "gil/extension/numeric/resample.hpp"

#if defined(NN_CC_MSVC)
# pragma warning(pop)
#endif

#include "Var.h"

typedef double VarType;

using namespace boost::gil;
using namespace boost::gil::detail;
static const std::string alphabet("0123456789");
static const unsigned int width = 49;
static const unsigned int height = 67;
static const unsigned int inputsNumber = width * height;

typedef nn::Perceptron< VarType,
			nn::NeuralLayer<nn::Neuron, nn::SigmoidFunction, 10 , inputsNumber, 1000 >,
			nn::NeuralLayer<nn::Neuron, nn::SigmoidFunction, 80, 10, 1000>,
			nn::NeuralLayer<nn::Neuron, nn::SoftmaxFunction, 10, 1000>
		       > Perceptron;

typedef nn::Perceptron< VarType,
			nn::NeuralLayer<nn::Neuron, nn::SigmoidFunction, 80, inputsNumber, 1000>,
			nn::NeuralLayer<nn::Neuron, nn::SoftmaxFunction,  inputsNumber, 80, 1000 >
		      > AutoEncoder;

typedef nn::bp::BepAlgorithm< AutoEncoder, nn::bp::CrossEntropyError> AutoEncAlgo;
typedef nn::bp::BepAlgorithm< Perceptron, nn::bp::CrossEntropyError> Algo;

template <typename Out>
struct halfdiff_cast_channels {
    template <typename T>
    Out operator()(const T& in1, const T& in2) const {
        return Out( (in1-in2)/2 );
    }
};

template <typename SrcView, typename DstView>
void convert_color(const SrcView& src, const DstView& dst) {
    typedef typename channel_type<DstView>::type d_channel_t;
    typedef typename channel_convert_to_unsigned<d_channel_t>::type channel_t;
    typedef pixel<channel_t, gray_layout_t>  gray_pixel_t;

    copy_pixels(color_converted_view<gray_pixel_t>(src), dst);
}

template<typename Iterator>
void readImage(std::string fileName, Iterator out) {
    using namespace boost::gil;
    using namespace nn;
    using namespace nn::bp;

    rgb8_image_t srcImg;
    png_read_image(fileName.c_str(), srcImg);

    gray8_image_t dstImg(srcImg.dimensions());
    gray8_pixel_t white(255);
    fill_pixels(view(dstImg), white);

    gray8_image_t grayImage(srcImg.dimensions());
    convert_color( view(srcImg), view(grayImage) );
    auto grayView = view(grayImage);

    gray8_image_t scaledImage(width, height);
    resize_view(grayView, view(scaledImage), bilinear_sampler() );
    auto srcView = view(scaledImage);

    for (int y=0; y<srcView.height(); ++y) {
        gray8c_view_t::x_iterator src_it( srcView.row_begin(y) );
        for (int x=0; x<srcView.width(); ++x) {
            *out = src_it[x]/255.f;// < 130? 1.f: -1.f;//255.f;
            out++;
        }
    }
}

Perceptron readPerceptron(std::string fileName) {
    Perceptron perceptron;
    if( boost::filesystem::exists(fileName.c_str()) ){
      std::ifstream file(fileName);
      if( file.good() ) {
	  Perceptron::Memento memento;
	  boost::archive::xml_iarchive ia ( file );
	  ia  >> BOOST_SERIALIZATION_NVP ( memento );

	  perceptron.setMemento ( memento );
      } else {
	  throw nn::NNException("Invalid perceptron file name", __FILE__, __LINE__);
      }
    }

    return perceptron;
}

void recognize(std::string perceptron, std::string image) {
    try {
        std::array<VarType, inputsNumber> inputs = {0};
        readImage(image, inputs.begin() );
        std::vector<VarType> result(alphabet.length(), VarType(0.f) );
        readPerceptron(perceptron).calculate(inputs.begin(), inputs.end(), result.begin() );
        for( unsigned int i = 0; i < result.size(); i++ ) {
	  std::cout << "Symbol: " <<
		       alphabet[i] <<
		       " " <<
		       result[i] <<
		       std::endl;
        }

    } catch( const nn::NNException& e) {
        std::cout << e.what() << std::endl;
    } catch( const std::exception& e) {
        std::cout << e.what() << std::endl;
    } catch(...) {
        std::cout << "Unknown error" << std::endl;
    }
}

template<typename Perc>
void save(const Perc& perc, std::string name)
{
    typename Perc::Memento memento = perc.getMemento();
    std::ofstream strm( name );
    boost::archive::xml_oarchive oa ( strm );
    oa << BOOST_SERIALIZATION_NVP ( memento );
    strm.flush();
}

template<typename Files>
AutoEncoder calculateAutoEncoder(Files files){
    std::cout << "AutoEncoder calculation started" << std::endl;
    std::vector<AutoEncAlgo::Prototype> prototypes;
    for( auto image : files) {
        if( !boost::filesystem::is_directory( image ) ) {
            try {
                AutoEncAlgo::Prototype proto;
                readImage( image, std::get<0>(proto).begin() );
		std::copy( std::get<0>(proto).begin(),
			   std::get<0>(proto).end(),
			   std::get<1>(proto).begin());

                prototypes.push_back(proto);
            } catch(const std::exception&) {
                std::cout << "Invalid image found :" << image << std::endl;
            }
        }
    }

    static AutoEncAlgo autoEncAlgo(0.005f, 0.01f);

    static std::size_t counter = 0;
    static AutoEncoder enc = autoEncAlgo.calculatePerceptron(prototypes.begin(),
							  prototypes.end(),
							  [](VarType error) {
							      counter++;
							      if(counter > 0){
								counter = 0;
								std::cout << error << std::endl;
							      }
							  });

    save(enc, "autoencoder.xml");
}

void calculateWeights(std::string imagesPath) {
    using namespace boost::filesystem;
    path directory(imagesPath);
    directory_iterator end_iter;

    std::vector< std::string > files;
    if ( exists(directory) && is_directory(directory))
    {
        for( directory_iterator dir_iter(directory) ; dir_iter != end_iter ; ++dir_iter)
        {
            if (is_regular_file(dir_iter->status()) )
            {
                files.push_back( dir_iter->path().string() );
            }
        }
    }

    //static AutoEncoder autoEnc = calculateAutoEncoder(files);

    std::cout << "Perceptron calculation started" << std::endl;
    static Perceptron tmp = readPerceptron("perceptron.xml");
    static Algo algorithm (0.003f, 0.001f );
    algorithm.setMemento( tmp.getMemento() );

    std::vector<Algo::Prototype> prototypes;
    for( auto image : files ) {
        if( !boost::filesystem::is_directory( image ) ) {
            try {
                Algo::Prototype proto;
                readImage( image, std::get<0>(proto).begin() );
                std::fill(std::get<1>(proto).begin(), std::get<1>(proto).end(), 0.f);
                char ch = path(image).filename().string()[0];
                size_t pos = alphabet.find(ch);
                std::get<1>(proto)[pos] = 1.0f;
                prototypes.push_back(proto);
            } catch(const std::exception&) {
                std::cout << "Invalid image found :" << image << std::endl;
            }
        }
    }

    static std::size_t counter = 0;
    static Perceptron perceptron = algorithm.calculatePerceptron(prototypes.begin(),
							  prototypes.end(),
							  [](VarType error) {
							      counter++;
							      if(counter > 1000){
								counter = 0;
								std::cout << error << std::endl;
							      }
							  });

    save(perceptron, "perceptron.xml");
}

int main(int argc, char** argv)
{
    int result = -1;
    if( argc == 3 ) {
        recognize(argv[1], argv[2]);
        result = 0;
    } else if( argc == 2 ) {
        calculateWeights(argv[1]);
        result = 0;
    } else {
        std::cout << std::endl << "Usage : " << std::endl << std::endl;
        std::cout << "./ocr [folder] where  [folder] is a directory with your samples, this command will generate a perceptron.xml file" << std::endl << std::endl;
        std::cout << "./ocr perceptron.xml [file] where [file] is a png image which has to be recognized" << std::endl << std::endl;
    }

    return result;
}

<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Modified by ScyllaDB
 * Copyright (C) 2015 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "UUID_gen.hh"

#include <stdlib.h>
#include <atomic>

#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
#include <cryptopp/md5.h>

namespace utils {

#if 0
private static byte[] hash(Collection<InetAddress> data)
{
    try
    {
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        for(InetAddress addr : data)
            messageDigest.update(addr.getAddress());

        return messageDigest.digest();
    }
    catch (NoSuchAlgorithmException nsae)
    {
        throw new RuntimeException("MD5 digest algorithm is not available", nsae);
    }
}

static int64_t make_node()
{
   /*
    * We don't have access to the MAC address but need to generate a node part
    * that identify this host as uniquely as possible.
    * The spec says that one option is to take as many source that identify
    * this node as possible and hash them together. That's what we do here by
    * gathering all the ip of this host.
    * Note that FBUtilities.getBroadcastAddress() should be enough to uniquely
    * identify the node *in the cluster* but it triggers DatabaseDescriptor
    * instanciation and the UUID generator is used in Stress for instance,
    * where we don't want to require the yaml.
    */
    Collection<InetAddress> localAddresses = FBUtilities.getAllLocalAddresses();
    if (localAddresses.isEmpty())
        throw new RuntimeException("Cannot generate the node component of the UUID because cannot retrieve any IP addresses.");

    // ideally, we'd use the MAC address, but java doesn't expose that.
    byte[] hash = hash(localAddresses);
    long node = 0;
    for (int i = 0; i < Math.min(6, hash.length); i++)
        node |= (0x00000000000000ff & (long)hash[i]) << (5-i)*8;
    assert (0xff00000000000000L & node) == 0;

    // Since we don't use the mac address, the spec says that multicast
    // bit (least significant bit of the first octet of the node ID) must be 1.
    return node | 0x0000010000000000L;
}
#endif

static int64_t make_node()
{
    // FIXME: Mix-in node's address. See the above commented-out code
    // which is what Cassandra's UUIDGen.java did. We can also get the MAC address.

    // We should take current core number under consideration
    // because create_time_safe() doesn't synchronize across cores and
    // it's easy to get duplicates.
    static std::atomic<unsigned> core_counter;
    return core_counter.fetch_add(1);
}

static int64_t make_clock_seq_and_node()
{
    // The original Java code did this, shuffling the number of millis
    // since the epoch, and taking 14 bits of it. We don't do exactly
    // the same, but the idea is the same.
    //long clock = new Random(System.currentTimeMillis()).nextLong();
    unsigned int seed = std::chrono::system_clock::now().time_since_epoch().count();
    int clock = rand_r(&seed);

    long lsb = 0;
    lsb |= 0x8000000000000000L;                 // variant (2 bits)
    lsb |= (clock & 0x0000000000003FFFL) << 48; // clock sequence (14 bits)
    lsb |= make_node();                          // 6 bytes
    return lsb;
}

UUID UUID_gen::get_name_UUID(bytes_view b) {
    return get_name_UUID(reinterpret_cast<const unsigned char*>(b.begin()), b.size());
}

UUID UUID_gen::get_name_UUID(sstring_view s) {
    static_assert(sizeof(char) == sizeof(sstring_view::value_type), "Assumed that str.size() counts in chars");
    return get_name_UUID(reinterpret_cast<const unsigned char*>(s.begin()), s.size());
}

UUID UUID_gen::get_name_UUID(const unsigned char *s, size_t len) {
    static_assert(CryptoPP::Weak1::MD5::DIGESTSIZE == 16, "MD5 digests should be 16 bytes long");
    int8_t digest[16];

    CryptoPP::Weak::MD5 hash;
    static_assert(sizeof(char) == sizeof(int8_t), "Assumed that chars are bytes");
    hash.CalculateDigest(reinterpret_cast<unsigned char*>(digest), s, len);

    // set version to 3
    digest[6] &= 0x0f;
    digest[6] |= 0x30;

    // set variant to IETF variant
    digest[8] &= 0x3f;
    digest[8] |= 0x80;

    return get_UUID(digest);
}

const thread_local int64_t UUID_gen::clock_seq_and_node = make_clock_seq_and_node();
thread_local const std::unique_ptr<UUID_gen> UUID_gen::instance (new UUID_gen());

} // namespace utils
<commit_msg>Delete dead code<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Modified by ScyllaDB
 * Copyright (C) 2015 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "UUID_gen.hh"

#include <stdlib.h>
#include <atomic>

#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
#include <cryptopp/md5.h>

namespace utils {

static int64_t make_node()
{
    // FIXME: Mix-in node's address. See the above commented-out code
    // which is what Cassandra's UUIDGen.java did. We can also get the MAC address.

    // We should take current core number under consideration
    // because create_time_safe() doesn't synchronize across cores and
    // it's easy to get duplicates.
    static std::atomic<unsigned> core_counter;
    return core_counter.fetch_add(1);
}

static int64_t make_clock_seq_and_node()
{
    // The original Java code did this, shuffling the number of millis
    // since the epoch, and taking 14 bits of it. We don't do exactly
    // the same, but the idea is the same.
    //long clock = new Random(System.currentTimeMillis()).nextLong();
    unsigned int seed = std::chrono::system_clock::now().time_since_epoch().count();
    int clock = rand_r(&seed);

    long lsb = 0;
    lsb |= 0x8000000000000000L;                 // variant (2 bits)
    lsb |= (clock & 0x0000000000003FFFL) << 48; // clock sequence (14 bits)
    lsb |= make_node();                          // 6 bytes
    return lsb;
}

UUID UUID_gen::get_name_UUID(bytes_view b) {
    return get_name_UUID(reinterpret_cast<const unsigned char*>(b.begin()), b.size());
}

UUID UUID_gen::get_name_UUID(sstring_view s) {
    static_assert(sizeof(char) == sizeof(sstring_view::value_type), "Assumed that str.size() counts in chars");
    return get_name_UUID(reinterpret_cast<const unsigned char*>(s.begin()), s.size());
}

UUID UUID_gen::get_name_UUID(const unsigned char *s, size_t len) {
    static_assert(CryptoPP::Weak1::MD5::DIGESTSIZE == 16, "MD5 digests should be 16 bytes long");
    int8_t digest[16];

    CryptoPP::Weak::MD5 hash;
    static_assert(sizeof(char) == sizeof(int8_t), "Assumed that chars are bytes");
    hash.CalculateDigest(reinterpret_cast<unsigned char*>(digest), s, len);

    // set version to 3
    digest[6] &= 0x0f;
    digest[6] |= 0x30;

    // set variant to IETF variant
    digest[8] &= 0x3f;
    digest[8] |= 0x80;

    return get_UUID(digest);
}

const thread_local int64_t UUID_gen::clock_seq_and_node = make_clock_seq_and_node();
thread_local const std::unique_ptr<UUID_gen> UUID_gen::instance (new UUID_gen());

} // namespace utils
<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of NLE
(NonLinear Engine)
For the latest info, see https://github.com/AlexandrSachkov/NonLinearEngine

Copyright (c) 2014 Alexandr Sachkov & NonLinear Engine Team

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "stdafx.h"
#include "NLE.h"
#include "Application\NLEGlfwApplicationLayer.h"
#include "RenderingEngine\NLRE.h"
#include "Input\NLEInputProcessor.h"
#include "Input\NLEInputSupply.h"
#include "GUI\NLEGuiManager.h"

std::shared_ptr<NLE> NLE::_nle = NULL;

std::shared_ptr<NLE> NLE::instance()
{
	if (!_nle)
	{
		_nle.reset(new NLE());
	}
	return _nle;
}

NLE::NLE()
{
	NLRE_Log::registerDebugCallback(NLE::NLREdebugOutputHook);
	NLRE_Log::registerConsoleCallback(NLE::NLREconsoleOutputHook);
	NLRE_Log::registerErrorCallback(NLE::NLREerrorOutputHook);

	_applicationLayer = std::dynamic_pointer_cast<NLEApplicationLayer>(NLEGlfwApplicationLayer::instance(this));
	_inputSupply = std::dynamic_pointer_cast<NLEInputSupply>(NLEGlfwApplicationLayer::instance(this));

	_applicationLayer->getClientSize(_width, _height);

	_renderingEngine.reset(new NLRE(_applicationLayer->getWindowReference(), _width, _height));
	_guiManager = NLEGuiManager::instance(this, _applicationLayer);
	_inputProcessor = NLEInputProcessor::instance(this, _applicationLayer, _inputSupply);

	//======================= FOR TESTING PURPOSES =================
	std::wstring path = L"D:\\3DModels\\Altair Model\\altair2.dae";
	_renderingEngine->importAsset(path);
	//==============================================================

	if (!initialize())
	{
		NLE_Log::err(NLE_Log::CRITICAL, "NonLinear Engine failed to initialize");
		throw std::exception("NonLinear Engine failed to initialize");
	}

	NLE_Log::console("======> NLE successfully initialized.");
}

NLE::~NLE()
{

}

bool NLE::initialize()
{

	return true;
}

void NLE::NLREdebugOutputHook(char text[])
{
	NLE_Log::debug(text);
}

void NLE::NLREconsoleOutputHook(char text[])
{
	NLE_Log::console(text);
}

void NLE::NLREerrorOutputHook(NLRE_Log::ErrorFlag flag, char text[])
{
	NLE_Log::err((NLE_Log::ErrorFlag)flag, text);
}

void NLE::run()
{
	//======================= FOR TESTING PURPOSES =================
	_applicationLayer->runMessageLoop();
	//==============================================================
}

bool NLE::bindApplicationLayer(std::shared_ptr<NLEApplicationLayer> appLayer)
{
	if (!appLayer) return false;
	_applicationLayer = appLayer;
	return true;
}

bool NLE::bindInputSupply(std::shared_ptr<NLEInputSupply> inputSupply)
{

	return false;
}

std::shared_ptr<NLRE> NLE::getRenderingEngine()
{
	return _renderingEngine;
}

std::shared_ptr<NLEInputProcessor> NLE::getInputProcessor()
{
	return _inputProcessor;
}

std::shared_ptr<NLEApplicationLayer> NLE::getApplicationLayer()
{
	return _applicationLayer;
}

std::shared_ptr<NLEGuiManager> NLE::getGuiManager()
{
	return _guiManager;
}

<commit_msg>NLE bindInputSupply is now properly implemented<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of NLE
(NonLinear Engine)
For the latest info, see https://github.com/AlexandrSachkov/NonLinearEngine

Copyright (c) 2014 Alexandr Sachkov & NonLinear Engine Team

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "stdafx.h"
#include "NLE.h"
#include "Application\NLEGlfwApplicationLayer.h"
#include "RenderingEngine\NLRE.h"
#include "Input\NLEInputProcessor.h"
#include "Input\NLEInputSupply.h"
#include "GUI\NLEGuiManager.h"

std::shared_ptr<NLE> NLE::_nle = NULL;

std::shared_ptr<NLE> NLE::instance()
{
	if (!_nle)
	{
		_nle.reset(new NLE());
	}
	return _nle;
}

NLE::NLE()
{
	NLRE_Log::registerDebugCallback(NLE::NLREdebugOutputHook);
	NLRE_Log::registerConsoleCallback(NLE::NLREconsoleOutputHook);
	NLRE_Log::registerErrorCallback(NLE::NLREerrorOutputHook);

	_applicationLayer = std::dynamic_pointer_cast<NLEApplicationLayer>(NLEGlfwApplicationLayer::instance(this));
	_inputSupply = std::dynamic_pointer_cast<NLEInputSupply>(NLEGlfwApplicationLayer::instance(this));

	_applicationLayer->getClientSize(_width, _height);

	_renderingEngine.reset(new NLRE(_applicationLayer->getWindowReference(), _width, _height));
	_guiManager = NLEGuiManager::instance(this, _applicationLayer);
	_inputProcessor = NLEInputProcessor::instance(this, _applicationLayer, _inputSupply);

	//======================= FOR TESTING PURPOSES =================
	std::wstring path = L"D:\\3DModels\\Altair Model\\altair2.dae";
	_renderingEngine->importAsset(path);
	//==============================================================

	if (!initialize())
	{
		NLE_Log::err(NLE_Log::CRITICAL, "NonLinear Engine failed to initialize");
		throw std::exception("NonLinear Engine failed to initialize");
	}

	NLE_Log::console("======> NLE successfully initialized.");
}

NLE::~NLE()
{

}

bool NLE::initialize()
{

	return true;
}

void NLE::NLREdebugOutputHook(char text[])
{
	NLE_Log::debug(text);
}

void NLE::NLREconsoleOutputHook(char text[])
{
	NLE_Log::console(text);
}

void NLE::NLREerrorOutputHook(NLRE_Log::ErrorFlag flag, char text[])
{
	NLE_Log::err((NLE_Log::ErrorFlag)flag, text);
}

void NLE::run()
{
	//======================= FOR TESTING PURPOSES =================
	_applicationLayer->runMessageLoop();
	//==============================================================
}

bool NLE::bindApplicationLayer(std::shared_ptr<NLEApplicationLayer> appLayer)
{
	if (!appLayer) return false;
	_applicationLayer = appLayer;
	return true;
}

bool NLE::bindInputSupply(std::shared_ptr<NLEInputSupply> inputSupply)
{
	if (!inputSupply) return false;
	_inputSupply = inputSupply;
	return true;
}

std::shared_ptr<NLRE> NLE::getRenderingEngine()
{
	return _renderingEngine;
}

std::shared_ptr<NLEInputProcessor> NLE::getInputProcessor()
{
	return _inputProcessor;
}

std::shared_ptr<NLEApplicationLayer> NLE::getApplicationLayer()
{
	return _applicationLayer;
}

std::shared_ptr<NLEGuiManager> NLE::getGuiManager()
{
	return _guiManager;
}

<|endoftext|>