<commit_before>/*
 * v8cgi main file. Loosely based on V8's "shell" sample app.
 */

#include <v8.h>
#include "js_system.h"
#include "js_io.h"
#include "js_common.h"
#include "js_macros.h"
#include <sstream>

#ifndef windows
#	include <dlfcn.h>
#else
#	include <windows.h>
#	define dlopen(x,y) (void*)LoadLibrary(x)
#	define dlsym(x,y) (void*)GetProcAddress((HMODULE)x,y)
#	define dlclose(x) FreeLibrary((HMODULE)x)
#endif

#define _STRING(x) #x
#define STRING(x) _STRING(x)

// chdir()
#ifndef HAVE_CHDIR
#	include <direct.h>
#	define chdir(name) _chdir(name)
#endif

// getcwd()
#ifndef HAVE_GETCWD
#	include <direct.h>
#	define getcwd(name, bytes) _getcwd(name, bytes)
#endif

v8::Handle<v8::Array> __onexit;

void die(int code) {
	uint32_t max = __onexit->Length();
	v8::Handle<v8::Function> fun;
	for (unsigned int i=0;i<max;i++) {
		fun = v8::Handle<v8::Function>::Cast(__onexit->Get(JS_INT(i)));
		fun->Call(v8::Context::GetCurrent()->Global(), 0, NULL);
	}
	exit(code);
}

v8::Handle<v8::String> read_file(const char* name) {
	FILE* file = fopen(name, "rb");
	if (file == NULL) return v8::Handle<v8::String>();

	fseek(file, 0, SEEK_END);
	size_t size = ftell(file);
	rewind(file);

	char* chars = new char[size + 1];
	chars[size] = '\0';
	for (unsigned int i = 0; i < size;) {
		size_t read = fread(&chars[i], 1, size - i, file);
		i += read;
	}
	fclose(file);

	/* remove shebang line */
	std::string str = chars;
	if ( str.find('#',0) == 0 && str.find('!',1) == 1 ) {
		unsigned int pfix = str.find('\n',0);
		str.erase(0,pfix);
	};

	v8::Handle<v8::String> result = JS_STR(str.c_str());
	delete[] chars;
	return result;
}

void report_exception(v8::TryCatch* try_catch) {
	v8::HandleScope handle_scope;
	v8::String::Utf8Value exception(try_catch->Exception());
	v8::Handle<v8::Message> message = try_catch->Message();
	std::string msgstring = "";
	std::stringstream ss;
	std::string tmp;

	if (message.IsEmpty()) {
		msgstring += *exception;
		msgstring += "\n";
	} else {
		v8::String::Utf8Value filename(message->GetScriptResourceName());
		int linenum = message->GetLineNumber();
		msgstring += *filename;
		msgstring += ":";

		ss << linenum;
		ss >> tmp;

		msgstring += tmp;
		msgstring += ": ";
		msgstring += *exception;
		msgstring += "\n";
	}

	int cgi = 0;
	v8::Local<v8::Function> fun;
	v8::Local<v8::Value> context = v8::Context::GetCurrent()->Global()->Get(JS_STR("response"));
	if (context->IsObject()) {
		v8::Local<v8::Value> print = context->ToObject()->Get(JS_STR("error"));
		if (print->IsObject()) {
			fun = v8::Local<v8::Function>::Cast(print);
			cgi = 1;
		}
	}
	if (!cgi) {
		context = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
		fun = v8::Local<v8::Function>::Cast(context->ToObject()->Get(JS_STR("stdout")));
	}

	v8::Handle<v8::Value> data[1];
	data[0] = JS_STR(msgstring.c_str());
	fun->Call(context->ToObject(), 1, data);
}

int execute_file(const char * str, bool change) {
	v8::HandleScope handle_scope;
	v8::TryCatch try_catch;
	v8::Handle<v8::String> name = JS_STR(str);
	v8::Handle<v8::String> source = read_file(str);

	if (source.IsEmpty()) {
		printf("Error reading '%s'\n", str);
		return 1;
	}

	v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
	if (script.IsEmpty()) {
		report_exception(&try_catch);
		return 1;
	} else {
		char * old = getcwd(NULL, 0);
		char * end = strrchr((char *)str, '/');
		if (end == NULL) {
			end = strrchr((char *)str, '\\');
		}
		if (end != NULL && change) {
			int len = end-str;
			char * base = (char *) malloc(len+1);
			strncpy(base, str, len);
    		base[len] = '\0';
    		chdir(base);
			free(base);
		}

		v8::Handle<v8::Value> result = script->Run();

		chdir(old);
		if (result.IsEmpty()) {
			report_exception(&try_catch);
			return 1;
		}
	}
	return 0;
}

int library(char * name) {
	v8::HandleScope handle_scope;
	v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
	v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
	v8::String::Utf8Value pfx(prefix);
	std::string path = "";

	path += *pfx;
	path += "/";
	path += name;

	if (path.find(".so") != std::string::npos) {
		void * handle;
	    if (!(handle = dlopen(path.c_str(), RTLD_LAZY))) {
			printf("open");
			return 1;
		}
		void (*func) (v8::Handle<v8::Object>);
		if (!(func = reinterpret_cast<void (*)(v8::Handle<v8::Object>)>(dlsym(handle, "init")))) {
			printf("init");
			dlclose(handle);
			return 1;
		}
		func(v8::Context::GetCurrent()->Global());
		return 0;
	} else {
		return execute_file(path.c_str(), false);
	}
}

v8::Handle<v8::Value> _include(const v8::Arguments& args) {
	bool ok = true;
	int result;
	for (int i = 0; i < args.Length(); i++) {
		v8::HandleScope handle_scope;
		v8::String::Utf8Value file(args[i]);
		result = execute_file(*file, false);
		if (result != 0) { ok = false; }
	}
	return JS_BOOL(ok);
}

v8::Handle<v8::Value> _library(const v8::Arguments & args) {
	bool ok = true;
	int result;

	v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
	v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
	v8::String::Utf8Value pfx(prefix);

	for (int i = 0; i < args.Length(); i++) {
		v8::HandleScope handle_scope;
		v8::String::Utf8Value file(args[i]);
		result = library(*file);
		if (result != 0) { ok = false; }
	}
	return JS_BOOL(ok);
}

v8::Handle<v8::Value> _exit(const v8::Arguments& args) {
	die(args[0]->Int32Value());
	return v8::Undefined();
}

v8::Handle<v8::Value> _onexit(const v8::Arguments& args) {
	__onexit->Set(JS_INT(__onexit->Length()), args[0]);
	return v8::Undefined();
}

int library_autoload() {
	v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
	v8::Handle<v8::Array> list = v8::Handle<v8::Array>::Cast(config->ToObject()->Get(JS_STR("libraryAutoload")));
	int cnt = list->Length();
	for (int i=0;i<cnt;i++) {
		v8::Handle<v8::Value> item = list->Get(JS_INT(i));
		v8::String::Utf8Value name(item);
		if (library(*name)) { return 1; }
	}
	return 0;
}

void init(char * cfg) {
	int result = execute_file(cfg, false);
	if (result) {
		printf("Cannot load configuration, quitting...\n");
		die(1);
	}
	result = library_autoload();
	if (result) {
		printf("Cannot load default libraries, quitting...\n");
		die(1);
	}
}

int main(int argc, char ** argv, char ** envp) {
	v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
	v8::HandleScope handle_scope;

	v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
	v8::Handle<v8::Context> context = v8::Context::New(NULL, global);
	v8::Context::Scope context_scope(context);

	__onexit = v8::Array::New();
	context->Global()->Set(JS_STR("library"), v8::FunctionTemplate::New(_library)->GetFunction());
	context->Global()->Set(JS_STR("include"), v8::FunctionTemplate::New(_include)->GetFunction());
	context->Global()->Set(JS_STR("exit"), v8::FunctionTemplate::New(_exit)->GetFunction());
	context->Global()->Set(JS_STR("onexit"), v8::FunctionTemplate::New(_onexit)->GetFunction());
	context->Global()->Set(JS_STR("global"), context->Global());
	context->Global()->Set(JS_STR("Config"), v8::Object::New());

	setup_system(envp, context->Global());
	setup_io(context->Global());

	char * cfg = STRING(CONFIG_PATH);
	int argptr = 0;
	for (int i = 1; i < argc; i++) {
		const char* str = argv[i];
		argptr = i;
		if (strcmp(str, "-c") == 0 && i + 1 < argc) {
			cfg = argv[i+1];
			argptr = 0;
			i++;
		}
	}

	init(cfg);

	if (!argptr) {
		// try the PATH_TRANSLATED env var
		v8::Handle<v8::Value> sys = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
		v8::Handle<v8::Value> env = sys->ToObject()->Get(JS_STR("env"));
		v8::Handle<v8::Value> pt = env->ToObject()->Get(JS_STR("PATH_TRANSLATED"));
		if (pt->IsString()) {
			v8::String::Utf8Value name(pt);
			int result = execute_file(*name, true);
			if (result) { die(result); }
		} else {
			printf("Nothing to do.\n");
		}
	} else {
		int result = execute_file(argv[argptr], true);
		if (result) { die(result); }
	}
	die(0);
}
<commit_msg>dll<commit_after>/*
 * v8cgi main file. Loosely based on V8's "shell" sample app.
 */

#include <v8.h>
#include "js_system.h"
#include "js_io.h"
#include "js_common.h"
#include "js_macros.h"
#include <sstream>

#ifndef windows
#	include <dlfcn.h>
#else
#	include <windows.h>
#	define dlopen(x,y) (void*)LoadLibrary(x)
#	define dlsym(x,y) (void*)GetProcAddress((HMODULE)x,y)
#	define dlclose(x) FreeLibrary((HMODULE)x)
#endif

#define _STRING(x) #x
#define STRING(x) _STRING(x)

// chdir()
#ifndef HAVE_CHDIR
#	include <direct.h>
#	define chdir(name) _chdir(name)
#endif

// getcwd()
#ifndef HAVE_GETCWD
#	include <direct.h>
#	define getcwd(name, bytes) _getcwd(name, bytes)
#endif

v8::Handle<v8::Array> __onexit;

void die(int code) {
	uint32_t max = __onexit->Length();
	v8::Handle<v8::Function> fun;
	for (unsigned int i=0;i<max;i++) {
		fun = v8::Handle<v8::Function>::Cast(__onexit->Get(JS_INT(i)));
		fun->Call(v8::Context::GetCurrent()->Global(), 0, NULL);
	}
	exit(code);
}

v8::Handle<v8::String> read_file(const char* name) {
	FILE* file = fopen(name, "rb");
	if (file == NULL) return v8::Handle<v8::String>();

	fseek(file, 0, SEEK_END);
	size_t size = ftell(file);
	rewind(file);

	char* chars = new char[size + 1];
	chars[size] = '\0';
	for (unsigned int i = 0; i < size;) {
		size_t read = fread(&chars[i], 1, size - i, file);
		i += read;
	}
	fclose(file);

	/* remove shebang line */
	std::string str = chars;
	if ( str.find('#',0) == 0 && str.find('!',1) == 1 ) {
		unsigned int pfix = str.find('\n',0);
		str.erase(0,pfix);
	};

	v8::Handle<v8::String> result = JS_STR(str.c_str());
	delete[] chars;
	return result;
}

void report_exception(v8::TryCatch* try_catch) {
	v8::HandleScope handle_scope;
	v8::String::Utf8Value exception(try_catch->Exception());
	v8::Handle<v8::Message> message = try_catch->Message();
	std::string msgstring = "";
	std::stringstream ss;
	std::string tmp;

	if (message.IsEmpty()) {
		msgstring += *exception;
		msgstring += "\n";
	} else {
		v8::String::Utf8Value filename(message->GetScriptResourceName());
		int linenum = message->GetLineNumber();
		msgstring += *filename;
		msgstring += ":";

		ss << linenum;
		ss >> tmp;

		msgstring += tmp;
		msgstring += ": ";
		msgstring += *exception;
		msgstring += "\n";
	}

	int cgi = 0;
	v8::Local<v8::Function> fun;
	v8::Local<v8::Value> context = v8::Context::GetCurrent()->Global()->Get(JS_STR("response"));
	if (context->IsObject()) {
		v8::Local<v8::Value> print = context->ToObject()->Get(JS_STR("error"));
		if (print->IsObject()) {
			fun = v8::Local<v8::Function>::Cast(print);
			cgi = 1;
		}
	}
	if (!cgi) {
		context = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
		fun = v8::Local<v8::Function>::Cast(context->ToObject()->Get(JS_STR("stdout")));
	}

	v8::Handle<v8::Value> data[1];
	data[0] = JS_STR(msgstring.c_str());
	fun->Call(context->ToObject(), 1, data);
}

int execute_file(const char * str, bool change) {
	v8::HandleScope handle_scope;
	v8::TryCatch try_catch;
	v8::Handle<v8::String> name = JS_STR(str);
	v8::Handle<v8::String> source = read_file(str);

	if (source.IsEmpty()) {
		printf("Error reading '%s'\n", str);
		return 1;
	}

	v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
	if (script.IsEmpty()) {
		report_exception(&try_catch);
		return 1;
	} else {
		char * old = getcwd(NULL, 0);
		char * end = strrchr((char *)str, '/');
		if (end == NULL) {
			end = strrchr((char *)str, '\\');
		}
		if (end != NULL && change) {
			int len = end-str;
			char * base = (char *) malloc(len+1);
			strncpy(base, str, len);
    		base[len] = '\0';
    		chdir(base);
			free(base);
		}

		v8::Handle<v8::Value> result = script->Run();

		chdir(old);
		if (result.IsEmpty()) {
			report_exception(&try_catch);
			return 1;
		}
	}
	return 0;
}

int library(char * name) {
	v8::HandleScope handle_scope;
	v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
	v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
	v8::String::Utf8Value pfx(prefix);
	std::string path = "";

	path += *pfx;
	path += "/";
	path += name;

	if (path.find(".so") != std::string::npos || path.find(".dll") != std::string::npos) {
		void * handle;
	    if (!(handle = dlopen(path.c_str(), RTLD_LAZY))) {
			printf("open");
			return 1;
		}
		void (*func) (v8::Handle<v8::Object>);
		if (!(func = reinterpret_cast<void (*)(v8::Handle<v8::Object>)>(dlsym(handle, "init")))) {
			printf("init");
			dlclose(handle);
			return 1;
		}
		func(v8::Context::GetCurrent()->Global());
		return 0;
	} else {
		return execute_file(path.c_str(), false);
	}
}

v8::Handle<v8::Value> _include(const v8::Arguments& args) {
	bool ok = true;
	int result;
	for (int i = 0; i < args.Length(); i++) {
		v8::HandleScope handle_scope;
		v8::String::Utf8Value file(args[i]);
		result = execute_file(*file, false);
		if (result != 0) { ok = false; }
	}
	return JS_BOOL(ok);
}

v8::Handle<v8::Value> _library(const v8::Arguments & args) {
	bool ok = true;
	int result;

	v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
	v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
	v8::String::Utf8Value pfx(prefix);

	for (int i = 0; i < args.Length(); i++) {
		v8::HandleScope handle_scope;
		v8::String::Utf8Value file(args[i]);
		result = library(*file);
		if (result != 0) { ok = false; }
	}
	return JS_BOOL(ok);
}

v8::Handle<v8::Value> _exit(const v8::Arguments& args) {
	die(args[0]->Int32Value());
	return v8::Undefined();
}

v8::Handle<v8::Value> _onexit(const v8::Arguments& args) {
	__onexit->Set(JS_INT(__onexit->Length()), args[0]);
	return v8::Undefined();
}

int library_autoload() {
	v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
	v8::Handle<v8::Array> list = v8::Handle<v8::Array>::Cast(config->ToObject()->Get(JS_STR("libraryAutoload")));
	int cnt = list->Length();
	for (int i=0;i<cnt;i++) {
		v8::Handle<v8::Value> item = list->Get(JS_INT(i));
		v8::String::Utf8Value name(item);
		if (library(*name)) { return 1; }
	}
	return 0;
}

void init(char * cfg) {
	int result = execute_file(cfg, false);
	if (result) {
		printf("Cannot load configuration, quitting...\n");
		die(1);
	}
	result = library_autoload();
	if (result) {
		printf("Cannot load default libraries, quitting...\n");
		die(1);
	}
}

int main(int argc, char ** argv, char ** envp) {
	v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
	v8::HandleScope handle_scope;

	v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
	v8::Handle<v8::Context> context = v8::Context::New(NULL, global);
	v8::Context::Scope context_scope(context);

	__onexit = v8::Array::New();
	context->Global()->Set(JS_STR("library"), v8::FunctionTemplate::New(_library)->GetFunction());
	context->Global()->Set(JS_STR("include"), v8::FunctionTemplate::New(_include)->GetFunction());
	context->Global()->Set(JS_STR("exit"), v8::FunctionTemplate::New(_exit)->GetFunction());
	context->Global()->Set(JS_STR("onexit"), v8::FunctionTemplate::New(_onexit)->GetFunction());
	context->Global()->Set(JS_STR("global"), context->Global());
	context->Global()->Set(JS_STR("Config"), v8::Object::New());

	setup_system(envp, context->Global());
	setup_io(context->Global());

	char * cfg = STRING(CONFIG_PATH);
	int argptr = 0;
	for (int i = 1; i < argc; i++) {
		const char* str = argv[i];
		argptr = i;
		if (strcmp(str, "-c") == 0 && i + 1 < argc) {
			cfg = argv[i+1];
			argptr = 0;
			i++;
		}
	}

	init(cfg);

	if (!argptr) {
		// try the PATH_TRANSLATED env var
		v8::Handle<v8::Value> sys = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
		v8::Handle<v8::Value> env = sys->ToObject()->Get(JS_STR("env"));
		v8::Handle<v8::Value> pt = env->ToObject()->Get(JS_STR("PATH_TRANSLATED"));
		if (pt->IsString()) {
			v8::String::Utf8Value name(pt);
			int result = execute_file(*name, true);
			if (result) { die(result); }
		} else {
			printf("Nothing to do.\n");
		}
	} else {
		int result = execute_file(argv[argptr], true);
		if (result) { die(result); }
	}
	die(0);
}
<|endoftext|>


<commit_before>/*
 * v8cgi main file. Loosely based on V8's "shell" sample app.
 */

#include <v8.h>
#include "js_system.h"
#include "js_io.h"
#include "js_mysql.h"
#include "js_gd.h"
#include "js_common.h"

#include <sstream>

#define _STRING(x) #x
#define STRING(x) _STRING(x)

// chdir()
#ifndef HAVE_CHDIR
#	include <direct.h>
#       define chdir(name) _chdir(name)
#endif

// getcwd()
#ifndef HAVE_GETCWD
#	include <direct.h>
#       define getcwd(name, bytes) _getcwd(name, bytes)
#endif

v8::Handle<v8::Array> __onexit;

void die(int code) {
	uint32_t max = __onexit->Length();
	v8::Handle<v8::Function> fun;
	for (unsigned int i=0;i<max;i++) {
		fun = v8::Handle<v8::Function>::Cast(__onexit->Get(JS_INT(i)));
		fun->Call(v8::Context::GetCurrent()->Global(), 0, NULL);
	}
	exit(code);
}

v8::Handle<v8::String> read_file(const char* name) {
	printf("%s",name);
	FILE* file = fopen(name, "rb");
	if (file == NULL) return v8::Handle<v8::String>();

	fseek(file, 0, SEEK_END);
	size_t size = ftell(file);
	rewind(file);

	char* chars = new char[size + 1];
	chars[size] = '\0';
	for (unsigned int i = 0; i < size;) {
		size_t read = fread(&chars[i], 1, size - i, file);
		i += read;
	}
	fclose(file);

	/* remove shebang line */
	std::string str = chars;
	if ( str.find('#',0) == 0 && str.find('!',1) == 1 ) {
		unsigned int pfix = str.find('\n',0);
		str.erase(0,pfix);
	};

	v8::Handle<v8::String> result = JS_STR(str.c_str());
	delete[] chars;
	return result;
}

void report_exception(v8::TryCatch* try_catch) {
	v8::HandleScope handle_scope;
	v8::String::Utf8Value exception(try_catch->Exception());
	v8::Handle<v8::Message> message = try_catch->Message();
	std::string msgstring = "";
	std::stringstream ss;
	std::string tmp;

	if (message.IsEmpty()) {
		msgstring += *exception;
		msgstring += "\n";
	} else {
		v8::String::Utf8Value filename(message->GetScriptResourceName());
		int linenum = message->GetLineNumber();
		msgstring += *filename;
		msgstring += ":";

		ss << linenum;
		ss >> tmp;

		msgstring += tmp;
		msgstring += ": ";
		msgstring += *exception;
		msgstring += "\n";
		v8::String::Utf8Value sourceline(message->GetSourceLine());
		msgstring += *sourceline;
		msgstring += "\n";

		// Print wavy underline (GetUnderline is deprecated).
		int start = message->GetStartColumn();
		for (int i = 0; i < start; i++) {
			msgstring += " ";
		}
		int end = message->GetEndColumn();
		for (int i = start; i < end; i++) {
			msgstring += "^";
		}
		msgstring += "\n";
	}

	int cgi = 0;
	v8::Local<v8::Function> fun;
	v8::Local<v8::Value> context = v8::Context::GetCurrent()->Global()->Get(JS_STR("response"));
	if (context->IsObject()) {
		v8::Local<v8::Value> print = context->ToObject()->Get(JS_STR("error"));
		if (print->IsObject()) {
			fun = v8::Local<v8::Function>::Cast(print);
			cgi = 1;
		}
	}
	if (!cgi) {
		context = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
		fun = v8::Local<v8::Function>::Cast(context->ToObject()->Get(JS_STR("stdout")));
	}

	v8::Handle<v8::Value> data[1];
	data[0] = JS_STR(msgstring.c_str());
	fun->Call(context->ToObject(), 1, data);
}

int execute_file(const char * str) {
	v8::HandleScope handle_scope;
	v8::TryCatch try_catch;
	v8::Handle<v8::String> name = JS_STR(str);
	v8::Handle<v8::String> source = read_file(str);

	if (source.IsEmpty()) {
		printf("Error reading '%s'\n", str);
		return 1;
	}

	v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
	if (script.IsEmpty()) {
		report_exception(&try_catch);
		return 1;
	} else {

		char * old = getcwd(NULL, 0);
		char * end = strrchr(str, '/');
		if (end == NULL) {
			end = strrchr(str, '\\');
		}

		if (end != NULL) {
			int len = end-str;
			char * base = (char *) malloc(len+1);
			strncpy(base, str, len);
    			base[len] = '\0';
    			chdir(base);
		}
		v8::Handle<v8::Value> result = script->Run();
		chdir(old);
		if (result.IsEmpty()) {
			report_exception(&try_catch);
			return 1;
		}
	}
	return 0;
}

int library(char * name) {
	v8::HandleScope handle_scope;
	v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
	v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
	v8::String::Utf8Value pfx(prefix);
	std::string path = "";

	path += *pfx;
	path += "/";
	path += name;
	return execute_file(path.c_str());
}

v8::Handle<v8::Value> _include(const v8::Arguments& args) {
	bool ok = true;
	int result;
	for (int i = 0; i < args.Length(); i++) {
		v8::HandleScope handle_scope;
		v8::String::Utf8Value file(args[i]);
		result = execute_file(*file);
		if (result != 0) { ok = false; }
	}
	return JS_BOOL(ok);
}

v8::Handle<v8::Value> _library(const v8::Arguments & args) {
	bool ok = true;
	int result;

	v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
	v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
	v8::String::Utf8Value pfx(prefix);

	for (int i = 0; i < args.Length(); i++) {
		v8::HandleScope handle_scope;
		v8::String::Utf8Value file(args[i]);
		result = library(*file);
		if (result != 0) { ok = false; }
	}
	return JS_BOOL(ok);
}

v8::Handle<v8::Value> _exit(const v8::Arguments& args) {
	die(args[0]->Int32Value());
	return v8::Undefined();
}

v8::Handle<v8::Value> _onexit(const v8::Arguments& args) {
	__onexit->Set(JS_INT(__onexit->Length()), args[0]);
	return v8::Undefined();
}

int library_autoload() {
	v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
	v8::Handle<v8::Array> list = v8::Handle<v8::Array>::Cast(config->ToObject()->Get(JS_STR("libraryAutoload")));
	int cnt = list->Length();
	for (int i=0;i<cnt;i++) {
		v8::Handle<v8::Value> item = list->Get(JS_INT(i));
		v8::String::Utf8Value name(item);
		if (library(*name)) { return 1; }
	}
	return 0;
}

void init(char * cfg) {
	int result = execute_file(cfg);
	if (result) {
		printf("Cannot load configuration, quitting...\n");
		die(1);
	}
	result = library_autoload();
	if (result) {
		printf("Cannot load default libraries, quitting...\n");
		die(1);
	}
}

int main(int argc, char ** argv, char ** envp) {
	v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
	v8::HandleScope handle_scope;

	v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
	v8::Handle<v8::Context> context = v8::Context::New(NULL, global);
	v8::Context::Scope context_scope(context);

	__onexit = v8::Array::New();
	context->Global()->Set(JS_STR("library"), v8::FunctionTemplate::New(_library)->GetFunction());
	context->Global()->Set(JS_STR("include"), v8::FunctionTemplate::New(_include)->GetFunction());
	context->Global()->Set(JS_STR("exit"), v8::FunctionTemplate::New(_exit)->GetFunction());
	context->Global()->Set(JS_STR("onexit"), v8::FunctionTemplate::New(_onexit)->GetFunction());
	context->Global()->Set(JS_STR("global"), context->Global());
	context->Global()->Set(JS_STR("Config"), v8::Object::New());

	setup_system(envp, context->Global());
	setup_io(context->Global());

	#ifdef HAVE_MYSQL
	setup_mysql(context->Global());
	#endif

	#ifdef HAVE_GD
	setup_gd(context->Global());
	#endif

	char * cfg = STRING(CONFIG_PATH);
	int argptr = 0;
	for (int i = 1; i < argc; i++) {
		const char* str = argv[i];
		argptr = i;
		if (strcmp(str, "-c") == 0 && i + 1 < argc) {
			cfg = argv[i+1];
			argptr = 0;
			i++;
		}
	}

	init(cfg);

	if (!argptr) {
		// try the PATH_TRANSLATED env var
		v8::Handle<v8::Value> sys = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
		v8::Handle<v8::Value> env = sys->ToObject()->Get(JS_STR("env"));
		v8::Handle<v8::Value> pt = env->ToObject()->Get(JS_STR("PATH_TRANSLATED"));
		if (pt->IsString()) {
			v8::String::Utf8Value name(pt);
			int result = execute_file(*name);
			if (result) { die(result); }
		} else {
			printf("Nothing to do.\n");
		}
	} else {
		int result = execute_file(argv[argptr]);
		if (result) { die(result); }
	}
	die(0);
}
<commit_msg>chdir, getcwd for msve<commit_after>/*
 * v8cgi main file. Loosely based on V8's "shell" sample app.
 */

#include <v8.h>
#include "js_system.h"
#include "js_io.h"
#include "js_mysql.h"
#include "js_gd.h"
#include "js_common.h"

#include <sstream>

#define _STRING(x) #x
#define STRING(x) _STRING(x)

// chdir()
#ifndef HAVE_CHDIR
#	include <direct.h>
#       define chdir(name) _chdir(name)
#endif

// getcwd()
#ifndef HAVE_GETCWD
#	include <direct.h>
#       define getcwd(name, bytes) _getcwd(name, bytes)
#endif

v8::Handle<v8::Array> __onexit;

void die(int code) {
	uint32_t max = __onexit->Length();
	v8::Handle<v8::Function> fun;
	for (unsigned int i=0;i<max;i++) {
		fun = v8::Handle<v8::Function>::Cast(__onexit->Get(JS_INT(i)));
		fun->Call(v8::Context::GetCurrent()->Global(), 0, NULL);
	}
	exit(code);
}

v8::Handle<v8::String> read_file(const char* name) {
	printf("%s",name);
	FILE* file = fopen(name, "rb");
	if (file == NULL) return v8::Handle<v8::String>();

	fseek(file, 0, SEEK_END);
	size_t size = ftell(file);
	rewind(file);

	char* chars = new char[size + 1];
	chars[size] = '\0';
	for (unsigned int i = 0; i < size;) {
		size_t read = fread(&chars[i], 1, size - i, file);
		i += read;
	}
	fclose(file);

	/* remove shebang line */
	std::string str = chars;
	if ( str.find('#',0) == 0 && str.find('!',1) == 1 ) {
		unsigned int pfix = str.find('\n',0);
		str.erase(0,pfix);
	};

	v8::Handle<v8::String> result = JS_STR(str.c_str());
	delete[] chars;
	return result;
}

void report_exception(v8::TryCatch* try_catch) {
	v8::HandleScope handle_scope;
	v8::String::Utf8Value exception(try_catch->Exception());
	v8::Handle<v8::Message> message = try_catch->Message();
	std::string msgstring = "";
	std::stringstream ss;
	std::string tmp;

	if (message.IsEmpty()) {
		msgstring += *exception;
		msgstring += "\n";
	} else {
		v8::String::Utf8Value filename(message->GetScriptResourceName());
		int linenum = message->GetLineNumber();
		msgstring += *filename;
		msgstring += ":";

		ss << linenum;
		ss >> tmp;

		msgstring += tmp;
		msgstring += ": ";
		msgstring += *exception;
		msgstring += "\n";
		v8::String::Utf8Value sourceline(message->GetSourceLine());
		msgstring += *sourceline;
		msgstring += "\n";

		// Print wavy underline (GetUnderline is deprecated).
		int start = message->GetStartColumn();
		for (int i = 0; i < start; i++) {
			msgstring += " ";
		}
		int end = message->GetEndColumn();
		for (int i = start; i < end; i++) {
			msgstring += "^";
		}
		msgstring += "\n";
	}

	int cgi = 0;
	v8::Local<v8::Function> fun;
	v8::Local<v8::Value> context = v8::Context::GetCurrent()->Global()->Get(JS_STR("response"));
	if (context->IsObject()) {
		v8::Local<v8::Value> print = context->ToObject()->Get(JS_STR("error"));
		if (print->IsObject()) {
			fun = v8::Local<v8::Function>::Cast(print);
			cgi = 1;
		}
	}
	if (!cgi) {
		context = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
		fun = v8::Local<v8::Function>::Cast(context->ToObject()->Get(JS_STR("stdout")));
	}

	v8::Handle<v8::Value> data[1];
	data[0] = JS_STR(msgstring.c_str());
	fun->Call(context->ToObject(), 1, data);
}

int execute_file(const char * str) {
	v8::HandleScope handle_scope;
	v8::TryCatch try_catch;
	v8::Handle<v8::String> name = JS_STR(str);
	v8::Handle<v8::String> source = read_file(str);

	if (source.IsEmpty()) {
		printf("Error reading '%s'\n", str);
		return 1;
	}

	v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
	if (script.IsEmpty()) {
		report_exception(&try_catch);
		return 1;
	} else {

		char * old = getcwd(NULL, 0);
		char * end = strrchr((char *)str, '/');
		if (end == NULL) {
			end = strrchr((char *)str, '\\');
		}

		if (end != NULL) {
			int len = end-str;
			char * base = (char *) malloc(len+1);
			strncpy(base, str, len);
    			base[len] = '\0';
    			chdir(base);
		}
		v8::Handle<v8::Value> result = script->Run();
		chdir(old);
		if (result.IsEmpty()) {
			report_exception(&try_catch);
			return 1;
		}
	}
	return 0;
}

int library(char * name) {
	v8::HandleScope handle_scope;
	v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
	v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
	v8::String::Utf8Value pfx(prefix);
	std::string path = "";

	path += *pfx;
	path += "/";
	path += name;
	return execute_file(path.c_str());
}

v8::Handle<v8::Value> _include(const v8::Arguments& args) {
	bool ok = true;
	int result;
	for (int i = 0; i < args.Length(); i++) {
		v8::HandleScope handle_scope;
		v8::String::Utf8Value file(args[i]);
		result = execute_file(*file);
		if (result != 0) { ok = false; }
	}
	return JS_BOOL(ok);
}

v8::Handle<v8::Value> _library(const v8::Arguments & args) {
	bool ok = true;
	int result;

	v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
	v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
	v8::String::Utf8Value pfx(prefix);

	for (int i = 0; i < args.Length(); i++) {
		v8::HandleScope handle_scope;
		v8::String::Utf8Value file(args[i]);
		result = library(*file);
		if (result != 0) { ok = false; }
	}
	return JS_BOOL(ok);
}

v8::Handle<v8::Value> _exit(const v8::Arguments& args) {
	die(args[0]->Int32Value());
	return v8::Undefined();
}

v8::Handle<v8::Value> _onexit(const v8::Arguments& args) {
	__onexit->Set(JS_INT(__onexit->Length()), args[0]);
	return v8::Undefined();
}

int library_autoload() {
	v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
	v8::Handle<v8::Array> list = v8::Handle<v8::Array>::Cast(config->ToObject()->Get(JS_STR("libraryAutoload")));
	int cnt = list->Length();
	for (int i=0;i<cnt;i++) {
		v8::Handle<v8::Value> item = list->Get(JS_INT(i));
		v8::String::Utf8Value name(item);
		if (library(*name)) { return 1; }
	}
	return 0;
}

void init(char * cfg) {
	int result = execute_file(cfg);
	if (result) {
		printf("Cannot load configuration, quitting...\n");
		die(1);
	}
	result = library_autoload();
	if (result) {
		printf("Cannot load default libraries, quitting...\n");
		die(1);
	}
}

int main(int argc, char ** argv, char ** envp) {
	v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
	v8::HandleScope handle_scope;

	v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
	v8::Handle<v8::Context> context = v8::Context::New(NULL, global);
	v8::Context::Scope context_scope(context);

	__onexit = v8::Array::New();
	context->Global()->Set(JS_STR("library"), v8::FunctionTemplate::New(_library)->GetFunction());
	context->Global()->Set(JS_STR("include"), v8::FunctionTemplate::New(_include)->GetFunction());
	context->Global()->Set(JS_STR("exit"), v8::FunctionTemplate::New(_exit)->GetFunction());
	context->Global()->Set(JS_STR("onexit"), v8::FunctionTemplate::New(_onexit)->GetFunction());
	context->Global()->Set(JS_STR("global"), context->Global());
	context->Global()->Set(JS_STR("Config"), v8::Object::New());

	setup_system(envp, context->Global());
	setup_io(context->Global());

	#ifdef HAVE_MYSQL
	setup_mysql(context->Global());
	#endif

	#ifdef HAVE_GD
	setup_gd(context->Global());
	#endif

	char * cfg = STRING(CONFIG_PATH);
	int argptr = 0;
	for (int i = 1; i < argc; i++) {
		const char* str = argv[i];
		argptr = i;
		if (strcmp(str, "-c") == 0 && i + 1 < argc) {
			cfg = argv[i+1];
			argptr = 0;
			i++;
		}
	}

	init(cfg);

	if (!argptr) {
		// try the PATH_TRANSLATED env var
		v8::Handle<v8::Value> sys = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
		v8::Handle<v8::Value> env = sys->ToObject()->Get(JS_STR("env"));
		v8::Handle<v8::Value> pt = env->ToObject()->Get(JS_STR("PATH_TRANSLATED"));
		if (pt->IsString()) {
			v8::String::Utf8Value name(pt);
			int result = execute_file(*name);
			if (result) { die(result); }
		} else {
			printf("Nothing to do.\n");
		}
	} else {
		int result = execute_file(argv[argptr]);
		if (result) { die(result); }
	}
	die(0);
}
<|endoftext|>


<commit_before>#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"

#include <iostream>

using namespace cv;
using namespace std;

const auto RED = cv::Scalar(0,0,255);
const auto PINK = cv::Scalar(230,130,255);
const auto BLUE = cv::Scalar(255,0,0);
const auto LIGHTBLUE = cv::Scalar(255,255,160);
const auto GREEN = cv::Scalar(0,255,0);
const auto IMAGE_SCALE = .25;

class MyData
{
public:
  const cv::Mat original_image;
  cv::Mat image;
  MyData( cv::Mat _image ) : original_image(_image)
  {
    original_image.copyTo(image);
  }
  void reset() { original_image.copyTo(image); };
  void update(auto _newImage) { _newImage.copyTo(image); };

};

class MyWindow
{
protected:
  const string winName;
  MyData d;

public:
  /* enum{ NOT_SET = 0, IN_PROCESS = 1, SET = 2 }; */
  MyWindow( const string&  _winName, const cv::Mat&  _image ):
    winName( _winName ), d( _image )
  {
    cv::namedWindow( winName, WINDOW_AUTOSIZE );
  }
  virtual ~MyWindow();
  void showImage();
  void reset();
};

MyWindow::~MyWindow()
{
  cv::destroyWindow( winName );
}

void MyWindow::reset()
{
  d.reset();
  showImage();
}

void MyWindow::showImage()
{
  cv::imshow( winName, d.image );
}

class MyOperationWindow : public MyWindow
{
protected:
  /* virtual void setControls(){}; */
  virtual string getDescription() {}
public:
  MyOperationWindow( auto _winName, auto _image) : MyWindow( _winName, _image ) {}
  void apply( MyData& _d, std::vector<string>& _process_pile )
  {
    _d.update(d.image);
    _process_pile.push_back(getDescription());
  }
};

class MyThreshold : public MyOperationWindow
{
  enum ThresholdType : int {BINARY, BINARY_INVERTED, THRESHOLD_TRUNCATED,
                      THRESHOLD_TO_ZERO, THRESHOLD_TO_ZERO_INVERTED };
  int th;
  ThresholdType threshold_type;
public:
  MyThreshold( auto _winName, auto _image)
    : MyOperationWindow( _winName, _image ), th(125), threshold_type(BINARY_INVERTED) { _initWindow(); }
  MyThreshold( auto _winName, auto _image, auto _th )
    : MyOperationWindow( _winName, _image ), th(_th), threshold_type(BINARY) { _initWindow(); }
  static void thresholdCallback( int _th, void* ptr);
private:
  string getDescription() override;
  void setControls(); //
  void thresholdImage();
  void _initWindow();
  static void _typeWorkaround( int _type, void* ptr);
};

void MyThreshold::_initWindow()
{
  setControls();
  thresholdImage();
  showImage();
}

void MyThreshold::_typeWorkaround( int _type, void* ptr)
{
  MyThreshold* that = (MyThreshold*) (ptr);
        switch (_type)
        {
        case 0:
                that->threshold_type = BINARY;
                break;
        case 1:
                that->threshold_type = BINARY_INVERTED;
                break;
        case 2:
                that->threshold_type = THRESHOLD_TRUNCATED;
                break;
        case 3:
                that->threshold_type = THRESHOLD_TO_ZERO;
                break;
        case 4:
                that->threshold_type = THRESHOLD_TO_ZERO_INVERTED;
                break;
        default:
                that->threshold_type = BINARY;
        }

        that->thresholdImage();
        that->showImage();
}

void MyThreshold::setControls()
{

  const std::string val_bar = winName + "_thValueBar";
  const std::string type_bar = winName + "_thTypeBar";
  int puta = BINARY;

  cv::createTrackbar( type_bar, winName, &puta, 5, MyThreshold::_typeWorkaround,this);
  cv::createTrackbar( val_bar, winName, &th, 255, MyThreshold::thresholdCallback,this);
}

void MyThreshold::thresholdCallback( int _th, void* ptr)
{
  MyThreshold* that = (MyThreshold*) (ptr);
  // that->th = _th; /// there's no need for this assignation since the trackbar was initialized with a reference to th
  that->thresholdImage();
  that->showImage();
}

string MyThreshold::getDescription()
{
  return "th " + std::to_string(th);
}

void MyThreshold::thresholdImage()
{
  int const max_BINARY_value = 255;
  threshold( d.original_image, d.image, th, max_BINARY_value, threshold_type );
}

class MyApp : public MyWindow
{
  vector<string> process;
  // std::unique_ptr<MyOperationWindow> current_operation;
  MyOperationWindow* current_operation;
public:
  MyApp(const std::string& _winName, const cv::Mat&  _image);

  char option(char _option);
  ~MyApp();
};

MyApp::~MyApp()
{
  if (current_operation != nullptr)
    delete(current_operation);
  //cv::destroyWindow( winName );
}

MyApp::MyApp(const string &_winName, const Mat &_image) :
  MyWindow( _winName, _image ),
  current_operation(nullptr)
{
  showImage();
}

char MyApp::option( char _option )
{

  switch(_option)
  {
  case 't': case 'd':
      /// create the threshold window
      if (current_operation == nullptr)
          current_operation = new MyThreshold("theshold", d.image);
      break;
  case 'R': case 's':
      /// reset the whole application
      reset();
  case 'r': case 'f':
      /// reset the threshold window
      if (current_operation != nullptr)
          current_operation->reset();
      break;
  case 'L': case 'a':
      /// print the processes applied to the image until now
      for (const auto& p : process)
          std::cout << p << std::endl;
      break;
  case 'g':
      if (current_operation != nullptr)
      {
          current_operation->apply(d, process);
          delete(current_operation);
      }
      break;
  case 'h':
      if (current_operation != nullptr)
          delete(current_operation);
      break;
  }
  showImage();
  return _option;
}

const char* keys =
{
  "{help h||}{@image|../../testdata/A/A05_38.bmp|input image file}"
};

static void help();

int main( int argc, const char** argv )
{
  cv::CommandLineParser parser(argc, argv, keys);
  if (parser.has("help"))
    {
      help();
      return 0;
    }
  std::string inputImage = parser.get<string>(0);

  // Load the source image. HighGUI use.
  cv::Mat image = imread( inputImage, CV_LOAD_IMAGE_GRAYSCALE );
  if(image.empty())
    {
      std::cerr << "Cannot read image file: " << inputImage << std::endl;
      return -1;
    }

  // TODO: check size and reduce it only if needed
  cv::resize(image, image, cv::Size(), IMAGE_SCALE, IMAGE_SCALE);
  help();

  /// Create the GUI
  std::string winName = "main window";
  MyApp appHandle = MyApp(winName, image);
  appHandle.option('t');

  /// Loop until the user kills the program
  const auto ESC_KEY = '\x1b';
  while ( appHandle.option((char) waitKey(0)) != ESC_KEY )
    {
      /* until ESC */
    }
  std::cout << "Exit" << std::endl;
  return 0;
}

static void help()
{
  cout << "L (or a) - list image transformations\n"
       << "R (or s) - restore original image\n"
       << "t (or d) - activate threshold window\n"
       << "r (or f) - reset the operation window\n"
       << "(enter) (or g) - accept changes and kill the operation window\n"
       << "(backspace) (or h)- ignore changes and kill the operation window\n"
       << endl;
}
<commit_msg>Check technological depth<commit_after>#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"

#include <iostream>

using namespace cv;
using namespace std;

const auto RED = cv::Scalar(0,0,255);
const auto PINK = cv::Scalar(230,130,255);
const auto BLUE = cv::Scalar(255,0,0);
const auto LIGHTBLUE = cv::Scalar(255,255,160);
const auto GREEN = cv::Scalar(0,255,0);
const auto IMAGE_SCALE = .25;

class MyData
{
public:
  const cv::Mat original_image;
  cv::Mat image;
  MyData( cv::Mat _image ) : original_image(_image)
  {
    original_image.copyTo(image);
  }
  void reset() { original_image.copyTo(image); };
  void update(auto _newImage) { _newImage.copyTo(image); };

};

class MyWindow
{
protected:
  const string winName;
  MyData d;

public:
  /* enum{ NOT_SET = 0, IN_PROCESS = 1, SET = 2 }; */
  MyWindow( const string&  _winName, const cv::Mat&  _image ):
    winName( _winName ), d( _image )
  {
    cv::namedWindow( winName, WINDOW_AUTOSIZE );
  }
  virtual ~MyWindow();
  void showImage();
  void reset();
};

MyWindow::~MyWindow()
{
  cv::destroyWindow( winName );
}

void MyWindow::reset()
{
  d.reset();
  showImage();
}

void MyWindow::showImage()
{
  cv::imshow( winName, d.image );
}

class MyOperationWindow : public MyWindow
{
protected:
  /* virtual void setControls(){}; */
  virtual string getDescription() {}
public:
  MyOperationWindow( auto _winName, auto _image) : MyWindow( _winName, _image ) {}
  void apply( MyData& _d, std::vector<string>& _process_pile )
  {
    _d.update(d.image);
    _process_pile.push_back(getDescription());
  }
};

class MyThreshold : public MyOperationWindow
{
  enum ThresholdType : int {BINARY, BINARY_INVERTED, THRESHOLD_TRUNCATED,
                      THRESHOLD_TO_ZERO, THRESHOLD_TO_ZERO_INVERTED };
  int th;
  ThresholdType threshold_type;
public:
  MyThreshold( auto _winName, auto _image)
    : MyOperationWindow( _winName, _image ), th(125), threshold_type(BINARY_INVERTED) { _initWindow(); }
  MyThreshold( auto _winName, auto _image, auto _th )
    : MyOperationWindow( _winName, _image ), th(_th), threshold_type(BINARY) { _initWindow(); }
  static void thresholdCallback( int _th, void* ptr);
private:
  string getDescription() override;
  void setControls(); //
  void thresholdImage();
  void _initWindow();
  static void _typeWorkaround( int _type, void* ptr);
};

void MyThreshold::_initWindow()
{
  setControls();
  thresholdImage();
  showImage();
}

void MyThreshold::_typeWorkaround( int _type, void* ptr)
{
  MyThreshold* that = (MyThreshold*) (ptr);
        switch (_type)
        {
        case 0:
                that->threshold_type = BINARY;
                break;
        case 1:
                that->threshold_type = BINARY_INVERTED;
                break;
        case 2:
                that->threshold_type = THRESHOLD_TRUNCATED;
                break;
        case 3:
                that->threshold_type = THRESHOLD_TO_ZERO;
                break;
        case 4:
                that->threshold_type = THRESHOLD_TO_ZERO_INVERTED;
                break;
        default:
                that->threshold_type = BINARY;
        }

        that->thresholdImage();
        that->showImage();
}

void MyThreshold::setControls()
{

  const std::string val_bar = winName + "_thValueBar";
  const std::string type_bar = winName + "_thTypeBar";
  int puta = BINARY;

  cv::createTrackbar( type_bar, winName, &puta, 5, MyThreshold::_typeWorkaround,this);
  cv::createTrackbar( val_bar, winName, &th, 255, MyThreshold::thresholdCallback,this);
}

void MyThreshold::thresholdCallback( int _th, void* ptr)
{
  MyThreshold* that = (MyThreshold*) (ptr);
  // that->th = _th; /// there's no need for this assignation since the trackbar was initialized with a reference to th
  that->thresholdImage();
  that->showImage();
}

string MyThreshold::getDescription()
{
  return "threshold, type: " + std::to_string(threshold_type) + ", val: " + std::to_string(th);
}

void MyThreshold::thresholdImage()
{
  int const max_BINARY_value = 255;
  threshold( d.original_image, d.image, th, max_BINARY_value, threshold_type );
}

class MyMorphology : public MyOperationWindow
{
	enum OperationType { OPENING=2, CLOSING, GRADIENT, TOP_HAT, BLACK_HAT }; // morphology operation codes are 2-6
	enum ElementType { RECTANGLE, CROSS, ELIPSE};
	OperationType operation;
	ElementType element;
	int morph_size;
public:
	MyMorphology( auto _winName, auto _image)
		: MyOperationWindow( _winName, _image ),
		  operation(OPENING),
		  element(RECTANGLE),
		  morph_size(5) { _initWindow(); }
	static void morphologyCallback( int _th, void* ptr);
private:
	string getDescription() override;
	void setControls();
	void morphImage();
	void _initWindow();
	static void _elementWorkaround( int _elem, void* ptr);
	static void _operationWorkaround( int _op, void* ptr);
};

string MyMorphology::getDescription()
{
  return "morph, op:" + std::to_string(operation) + ", " +
            "elem: " + std::to_string(element) + ", " +
            "size: " + std::to_string(morph_size);
}

class MyApp : public MyWindow
{
  vector<string> process;
  // std::unique_ptr<MyOperationWindow> current_operation;
  MyOperationWindow* current_operation;
public:
  MyApp(const std::string& _winName, const cv::Mat&  _image);

  char option(char _option);
  ~MyApp();
};

MyApp::~MyApp()
{
  if (current_operation != nullptr)
    delete(current_operation);
  //cv::destroyWindow( winName );
}

MyApp::MyApp(const string &_winName, const Mat &_image) :
  MyWindow( _winName, _image ),
  current_operation(nullptr)
{
  showImage();
}

char MyApp::option( char _option )
{

  switch(_option)
{
  case 't': case 'd':
      /// create the threshold window
      if (current_operation == nullptr)
          current_operation = new MyThreshold("theshold", d.image);
      else
        cout << "there's already an operation being done" << endl;
      break;
  case 'm':
      /// create the morpholy window
      if (current_operation == nullptr)
          current_operation = new MyMorphology("morphology", d.image);
      else
        cout << "there's already an operation being done" << endl;
      break;
  case 'R': case 's':
      /// reset the whole application
      reset();
  case 'r': case 'f':
      /// reset the operation window
      if (current_operation != nullptr)
          current_operation->reset();
      break;
  case 'L': case 'a':
      /// print the processes applied to the image until now
      for (const auto& p : process)
          std::cout << p << std::endl;
      break;
  case 'g':
      if (current_operation != nullptr)
      {
          current_operation->apply(d, process);
          delete(current_operation);
      }
      break;
  case 'h':
      if (current_operation != nullptr)
          delete(current_operation);
      break;
  }
  showImage();
  return _option;
}

//void preprocessImage(cv::Mat& image)// const Mat& _inImage, Mat& _outImage )
//// TODO: add image->copy(out)
//{
//    const string bkgPath = "../../testdata/A/background.bmp";
//    Mat background = imread( bkgPath, CV_LOAD_IMAGE_GRAYSCALE );
//    if(background.empty())
//    {
//        std::cerr << "Cannot read image file: " << bkgPath << std::endl;
//    }

//    cv::resize(background, background, cv::Size(), IMAGE_SCALE, IMAGE_SCALE);
//    /* _inImage.copyTo( _outImage ); */
//    /* _outImage -= background; */
//    /* cv::absdiff(background, _outImage, _outImage); */
//    cv::absdiff(background, image, image);
//}

void MyMorphology::morphImage()
{
    /// The morph_size is considered to be the length between the center of the structural element and its border
    /// morph_size = (structural_element size / 2) - 1
    const auto size = cv::Size( 2*morph_size + 1, 2*morph_size+1 );
    const auto p = Point (morph_size, morph_size);

    cv::Mat structure_element = getStructuringElement(element, size, p );
    cv::Mat _midleImage;

    morphologyEx(  d.original_image, _midleImage, operation, structure_element );
    d.update(_midleImage);
}

void MyMorphology::_initWindow()
{
  setControls();
  morphImage();
  showImage();
}

void MyMorphology::_operationWorkaround( int _op, void* ptr)
{
  MyMorphology* that = (MyMorphology*) (ptr);
        switch (_op)
        {
        case 0:
                that->operation = OPENING;
                break;
        case 1:
                that->operation = CLOSING;
                break;
        case 2:
                that->operation = GRADIENT;
                break;
        case 3:
                that->operation = TOP_HAT;
                break;
        case 4:
                that->operation = BLACK_HAT;
                break;
        default:
                that->operation = OPENING;
        }

        that->morphImage();
        that->showImage();
}

void MyMorphology::_elementWorkaround( int _elem, void* ptr)
{
  MyMorphology* that = (MyMorphology*) (ptr);
        switch (_elem)
        {
        case 0:
                that->element = RECTANGLE;
                break;
        case 1:
                that->element = CROSS;
                break;
        case 2:
                that->element = ELIPSE;
                break;
        default:
                that->element = RECTANGLE;
        }

        that->morphImage();
        that->showImage();
}

void MyMorphology::setControls()
{

  const std::string operation_bar = winName + "_morphOperationBar";
  const std::string element_bar = winName + "_thElementBar";
  const std::string size_bar = winName + "_thSizeBar";
  int op;
  int elem;
  const int max_size = 30;

  cv::createTrackbar( operation_bar, winName, &op, 5, MyMorphology::_operationWorkaround,this);
  cv::createTrackbar( element_bar, winName, &elem, 3, MyMorphology::_elementWorkaround,this);
  cv::createTrackbar( size_bar, winName, &morph_size, max_size, MyMorphology::morphologyCallback,this);
}

void MyMorphology::morphologyCallback( int _th, void* ptr)
{
	MyMorphology* that = (MyMorphology*) (ptr);
	that->morphImage();
	that->showImage();
}

const char* keys =
{
  "{help h||}{@image|../../testdata/A/A05_38.bmp|input image file}"
};

static void help();

int main( int argc, const char** argv )
{
  cv::CommandLineParser parser(argc, argv, keys);
  if (parser.has("help"))
    {
      help();
      return 0;
    }
  std::string inputImage = parser.get<string>(0);

  // Load the source image. HighGUI use.
  cv::Mat image = imread( inputImage, CV_LOAD_IMAGE_GRAYSCALE );
  if(image.empty())
    {
      std::cerr << "Cannot read image file: " << inputImage << std::endl;
      return -1;
    }

  // TODO: check size and reduce it only if needed
  cv::resize(image, image, cv::Size(), IMAGE_SCALE, IMAGE_SCALE);
  help();

  /// Create the GUI
  std::string winName = "main window";
  MyApp appHandle = MyApp(winName, image);
  appHandle.option('m');

  /// Loop until the user kills the program
  const auto ESC_KEY = '\x1b';
  while ( appHandle.option((char) waitKey(0)) != ESC_KEY )
    {
      /* until ESC */
    }
  std::cout << "Exit" << std::endl;
  return 0;
}

static void help()
{
  cout << "L (or a) - list image transformations\n"
       << "R (or s) - restore original image\n"
       << "t (or d) - activate threshold window\n"
       << "m - activate morphology window\n"
       << "r (or f) - reset the operation window\n"
       << "(enter) (or g) - accept changes and kill the operation window\n"
       << "(backspace) (or h)- ignore changes and kill the operation window\n"
       << endl;
}
<|endoftext|>


<commit_before>// Measurements
// Source: ./examples/measurements2.cpp
#include <iostream>
#include <tuple>
#include <vector>

#include "qpp.h"

int main() {
    using namespace qpp;

    ket psi = st.b00;
    std::vector<idx> subsys = {0};
    idx result;
    std::vector<double> probs;
    std::vector<cmat> states;

    // measures the first subsystem of the Bell state (|00> + |11>) / sqrt(2)
    // in the X basis
    std::tie(result, probs, states) = measure(psi, gt.H, {0});
    std::cout << ">> Measuring part " << disp(subsys, " ")
              << " of the state:\n";
    std::cout << disp(psi) << '\n';
    std::cout << ">> Measurement result: " << result << '\n';
    std::cout << ">> Probabilities: " << disp(probs, ", ") << '\n';
    std::cout << ">> Resulting normalized post-measurement states:\n";

    for (auto&& it : states)
        std::cout << disp(it) << "\n\n";

    // measure 2 subsystems out of a 4-qubit random density matrix
    cmat rho = randrho(16);
    subsys = {1, 2};
    cmat U = randU(4); // random basis on 2 qubits

    std::cout << ">> Measuring qubits " << disp(subsys, " ")
              << " of a 4-qubit random state in the random basis:\n";
    std::cout << disp(U) << '\n';

    std::tie(result, probs, states) = measure(rho, U, {1, 2});
    std::cout << ">> Measurement result: " << result << '\n';
    std::cout << ">> Probabilities: " << disp(probs, ", ") << '\n';
    std::cout << ">> Sum of the probabilities: "
              << sum(probs.begin(), probs.end()) << '\n';
    std::cout << ">> Resulting normalized post-measurement states:\n";

    for (auto&& it : states)
        std::cout << disp(it) << "\n\n";

    // check now how the state after the measurement "looks"
    // on the left over subsystems {0, 3}

    // it should be the same as the partial trace over {1, 2}
    // of the initial state (before the measurement), as local CPTP maps
    // do not influence the complementary subsystems

    cmat rho_bar = ptrace(rho, subsys);
    cmat rho_out_bar = cmat::Zero(4, 4);

    // compute the resulting mixed state after the measurement
    for (idx i = 0; i < probs.size(); ++i)
        rho_out_bar += probs[i] * states[i];

    // verification
    std::cout << ">> Norm difference: " << norm(rho_bar - rho_out_bar) << '\n';

    // random Kraus
    std::cout << ">> Random channel on part of the state\n";
    rho_bar = ptrace(rho, {1, 3});
    rho_out_bar = ptrace(apply(rho, randkraus(3, 4), {1, 3}), {1, 3});

    // verification
    std::cout << ">> Norm difference: " << norm(rho_bar - rho_out_bar) << '\n';

    std::cout << ">> Sequential measurements on the state/density matrix:\n";
    psi = 0.8 * 01_ket + 0.6 * 10_ket;
    rho = psi * adjoint(psi);
    std::cout << disp(psi) << '\n';

    std::vector<idx> subsys_ket{0};
    std::vector<idx> subsys_rho{1};

    auto measured_ket = measure_seq(psi, subsys_ket);
    auto measured_rho = measure_seq(rho, subsys_rho);

    // ket
    std::cout << ">> Ket, measuring subsystem(s) ";
    std::cout << disp(subsys_ket, " ") << '\n';
    std::cout << ">> Outcome(s): " << disp(std::get<RES>(measured_ket), " ")
              << '\n';
    std::cout << ">> Probability:  " << std::get<PROB>(measured_ket) << '\n';
    std::cout << ">> Resulting state:\n";
    std::cout << disp(std::get<ST>(measured_ket)) << '\n';

    // density matrix
    std::cout << ">> Density matrix, measuring subsystem(s) ";
    std::cout << disp(subsys_rho, " ") << '\n';
    std::cout << ">> Outcome(s): " << disp(std::get<RES>(measured_rho), " ")
              << '\n';
    std::cout << ">> Probability:  " << std::get<PROB>(measured_rho) << '\n';
    std::cout << ">> Resulting state:\n";
    std::cout << disp(std::get<ST>(measured_rho)) << '\n';
}
<commit_msg>Update measurements2.cpp<commit_after>// Measurements
// Source: ./examples/measurements2.cpp
#include <iostream>
#include <tuple>
#include <vector>

#include "qpp.h"

int main() {
    using namespace qpp;

    ket psi = st.b00;
    std::vector<idx> subsys = {0};
    idx result;
    std::vector<double> probs;
    std::vector<ket> states;

    // measures the first subsystem of the Bell state (|00> + |11>) / sqrt(2)
    // in the X basis
    std::tie(result, probs, states) = measure(psi, gt.H, {0});
    std::cout << ">> Measuring part " << disp(subsys, " ")
              << " of the state:\n";
    std::cout << disp(psi) << '\n';
    std::cout << ">> Measurement result: " << result << '\n';
    std::cout << ">> Probabilities: " << disp(probs, ", ") << '\n';
    std::cout << ">> Resulting normalized post-measurement states:\n";

    for (auto&& it : states)
        std::cout << disp(it) << "\n\n";

    // measure 2 subsystems out of a 4-qubit random density matrix
    cmat rho = randrho(16);
    subsys = {1, 2};
    cmat U = randU(4); // random basis on 2 qubits

    std::cout << ">> Measuring qubits " << disp(subsys, " ")
              << " of a 4-qubit random state in the random basis:\n";
    std::cout << disp(U) << '\n';

    std::tie(result, probs, states) = measure(rho, U, {1, 2});
    std::cout << ">> Measurement result: " << result << '\n';
    std::cout << ">> Probabilities: " << disp(probs, ", ") << '\n';
    std::cout << ">> Sum of the probabilities: "
              << sum(probs.begin(), probs.end()) << '\n';
    std::cout << ">> Resulting normalized post-measurement states:\n";

    for (auto&& it : states)
        std::cout << disp(it) << "\n\n";

    // check now how the state after the measurement "looks"
    // on the left over subsystems {0, 3}

    // it should be the same as the partial trace over {1, 2}
    // of the initial state (before the measurement), as local CPTP maps
    // do not influence the complementary subsystems

    cmat rho_bar = ptrace(rho, subsys);
    cmat rho_out_bar = cmat::Zero(4, 4);

    // compute the resulting mixed state after the measurement
    for (idx i = 0; i < probs.size(); ++i)
        rho_out_bar += probs[i] * states[i];

    // verification
    std::cout << ">> Norm difference: " << norm(rho_bar - rho_out_bar) << '\n';

    // random Kraus
    std::cout << ">> Random channel on part of the state\n";
    rho_bar = ptrace(rho, {1, 3});
    rho_out_bar = ptrace(apply(rho, randkraus(3, 4), {1, 3}), {1, 3});

    // verification
    std::cout << ">> Norm difference: " << norm(rho_bar - rho_out_bar) << '\n';

    std::cout << ">> Sequential measurements on the state/density matrix:\n";
    psi = 0.8 * 01_ket + 0.6 * 10_ket;
    rho = psi * adjoint(psi);
    std::cout << disp(psi) << '\n';

    std::vector<idx> subsys_ket{0};
    std::vector<idx> subsys_rho{1};

    auto measured_ket = measure_seq(psi, subsys_ket);
    auto measured_rho = measure_seq(rho, subsys_rho);

    // ket
    std::cout << ">> Ket, measuring subsystem(s) ";
    std::cout << disp(subsys_ket, " ") << '\n';
    std::cout << ">> Outcome(s): " << disp(std::get<RES>(measured_ket), " ")
              << '\n';
    std::cout << ">> Probability:  " << std::get<PROB>(measured_ket) << '\n';
    std::cout << ">> Resulting state:\n";
    std::cout << disp(std::get<ST>(measured_ket)) << '\n';

    // density matrix
    std::cout << ">> Density matrix, measuring subsystem(s) ";
    std::cout << disp(subsys_rho, " ") << '\n';
    std::cout << ">> Outcome(s): " << disp(std::get<RES>(measured_rho), " ")
              << '\n';
    std::cout << ">> Probability:  " << std::get<PROB>(measured_rho) << '\n';
    std::cout << ">> Resulting state:\n";
    std::cout << disp(std::get<ST>(measured_rho)) << '\n';
}
<|endoftext|>


<commit_before>/*
 * Copyright 2014 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * This file contains explicit instantiations of stats template types.
 *
 * This allows most users to avoid having to include the template definition
 * header files.
 */

#include <folly/stats/BucketedTimeSeries.h>
#include <folly/stats/BucketedTimeSeries-defs.h>

#include <folly/stats/Histogram.h>
#include <folly/stats/Histogram-defs.h>

#include <folly/stats/MultiLevelTimeSeries.h>
#include <folly/stats/MultiLevelTimeSeries-defs.h>

#include <folly/stats/TimeseriesHistogram.h>
#include <folly/stats/TimeseriesHistogram-defs.h>

namespace folly {

template class BucketedTimeSeries<int64_t>;
template class Histogram<int64_t>;
template class detail::HistogramBuckets<int64_t, Histogram<int64_t>::Bucket>;
template class MultiLevelTimeSeries<int64_t>;
template class TimeseriesHistogram<int64_t>;

} // folly
<commit_msg>Add additional instantiations in Instantiations.cpp<commit_after>/*
 * Copyright 2014 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * This file contains explicit instantiations of stats template types.
 *
 * This allows most users to avoid having to include the template definition
 * header files.
 */

#include <folly/stats/BucketedTimeSeries.h>
#include <folly/stats/BucketedTimeSeries-defs.h>

#include <folly/stats/Histogram.h>
#include <folly/stats/Histogram-defs.h>

#include <folly/stats/MultiLevelTimeSeries.h>
#include <folly/stats/MultiLevelTimeSeries-defs.h>

#include <folly/stats/TimeseriesHistogram.h>
#include <folly/stats/TimeseriesHistogram-defs.h>

namespace folly {

template class BucketedTimeSeries<int64_t>;
template class Histogram<int64_t>;
template class detail::HistogramBuckets<int64_t, Histogram<int64_t>::Bucket>;
template class MultiLevelTimeSeries<int64_t>;
template class TimeseriesHistogram<int64_t>;

// Histogram::getPercentileBucketIdx() and Histogram::getPercentileEstimate()
// are implemented using template methods.  Instantiate the default versions of
// these methods too, so anyone using them won't also need to explicitly
// include Histogram-defs.h
template unsigned int detail::HistogramBuckets<
  int64_t, Histogram<int64_t>::Bucket>::
  getPercentileBucketIdx<Histogram<int64_t>::CountFromBucket>(
      double pct,
      Histogram<int64_t>::CountFromBucket countFromBucket,
      double* lowPct,
      double* highPct) const;
template int64_t detail::HistogramBuckets<int64_t, Histogram<int64_t>::Bucket>
  ::getPercentileEstimate<Histogram<int64_t>::CountFromBucket,
                          Histogram<int64_t>::AvgFromBucket>(
    double pct,
    Histogram<int64_t>::CountFromBucket countFromBucket,
    Histogram<int64_t>::AvgFromBucket avgFromBucket) const;

} // folly
<|endoftext|>


<commit_before>#include <Socket/server/Server.hpp>

#include <csignal>
#include <iostream>

#include "functions.hpp"

ntw::srv::Server* server = nullptr;

void stop_server_handler(int sig)
{
    std::cout<<"Recv signal "<<sig<<". Stoping server.\n Please wait."<<std::endl;
    if(server)
        server->stop();
}

#define SERVER_PORT 1

int main(int argc,char* argv[])
{
        if(argc < SERVER_PORT +1)
    {
        std::cout<<"Usage are: "<<argv[0]<<"[server-port]"<<std::endl;
        return 1;
    }

    const unsigned int max_client = 100;

    std::cout<<"[Server start] on:"
        <<"\n\tPort : "<<argv[SERVER_PORT]
        <<std::endl;

    std::signal(SIGINT, stop_server_handler);

    try
    {
        ntw::Socket::init();
        server = new ntw::srv::Server(atoi(argv[SERVER_PORT]),"",dispatch,max_client);
        server->on_new_client = register_client;
        server->on_delete_client = unregister_client;

        server->start();
        server->wait();
        delete server;
        ntw::Socket::close();
    }
    catch(ntw::SocketExeption& e)
    {
        std::cout<<e.what()<<std::endl;
    }

    std::cout<<"Server is close"<<std::endl;
    std::cout<<"Good bye"<<std::endl;

    return 0;
}

<commit_msg>maj server example<commit_after>#include <Socket/server/Server.hpp>

#include <csignal>
#include <iostream>

#include "functions.hpp"

ntw::srv::Server* server = nullptr;

void stop_server_handler(int sig)
{
    std::cout<<"Recv signal "<<sig<<". Stoping server.\n Please wait."<<std::endl;
    if(server)
        server->stop();
}

#define SERVER_PORT 1

int main(int argc,char* argv[])
{
        if(argc < SERVER_PORT +1)
    {
        std::cout<<"Usage are: "<<argv[0]<<"[server-port]"<<std::endl;
        return 1;
    }

    const unsigned int max_client = 100;

    std::cout<<"[Server start] on:"
        <<"\n\tPort : "<<argv[SERVER_PORT]
        <<std::endl;

    std::signal(SIGINT, stop_server_handler);

    try
    {
        ntw::Socket::init();
        server = new ntw::srv::Server(atoi(argv[SERVER_PORT]),"127.0.0.1",dispatch,max_client);
        server->on_new_client = register_client;
        server->on_delete_client = unregister_client;

        server->start();
        server->wait();
        delete server;
        ntw::Socket::close();
    }
    catch(ntw::SocketExeption& e)
    {
        std::cout<<e.what()<<std::endl;
    }

    std::cout<<"Server is close"<<std::endl;
    std::cout<<"Good bye"<<std::endl;

    return 0;
}

<|endoftext|>


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <os>
#include <vga>
#include <cassert>
#include <net/inet4>
#include <hw/ps2.hpp>

#include "snake.hpp"

std::unique_ptr<net::Inet4<VirtioNet> > inet;
ConsoleVGA vga;

void begin_snake()
{
  hw::KBM::init();
  static Snake snake(vga);

  hw::KBM::set_virtualkey_handler(
  [] (int key) {

    if (key == hw::KBM::VK_RIGHT) {
      snake.set_dir(Snake::RIGHT);
    }
    if (key == hw::KBM::VK_LEFT) {
      snake.set_dir(Snake::LEFT);
    }
    if (key == hw::KBM::VK_UP) {
      snake.set_dir(Snake::UP);
    }
    if (key == hw::KBM::VK_DOWN) {
      snake.set_dir(Snake::DOWN);
    }
    if (key == hw::KBM::VK_SPACE) {
      if (snake.is_gameover())
        snake.reset();
    }

  });
}

void Service::start()
{
  // redirect stdout to vga screen
  // ... even though we aren't really using it after the game starts

  OS::set_rsprint(
  [] (const char* data, size_t len)
  {
    vga.write(data, len);
  });

  // we have to start snake later to avoid late text output
  hw::PIT::on_timeout(0.25, [] { begin_snake(); });

  // boilerplate
  hw::Nic<VirtioNet>& eth0 = hw::Dev::eth<0,VirtioNet>();
  inet = std::make_unique<net::Inet4<VirtioNet> >(eth0, 0.15);
  inet->network_config(
    { 10,0,0,42 },      // IP
    { 255,255,255,0 },  // Netmask
    { 10,0,0,1 },       // Gateway
    { 8,8,8,8 } );      // DNS

  printf("*** TEST SERVICE STARTED *** \n");
}
<commit_msg>Removed whitespace from output<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <os>
#include <vga>
#include <cassert>
#include <net/inet4>
#include <hw/ps2.hpp>

#include "snake.hpp"

std::unique_ptr<net::Inet4<VirtioNet> > inet;
ConsoleVGA vga;

void begin_snake()
{
  hw::KBM::init();
  static Snake snake(vga);

  hw::KBM::set_virtualkey_handler(
  [] (int key) {

    if (key == hw::KBM::VK_RIGHT) {
      snake.set_dir(Snake::RIGHT);
    }
    if (key == hw::KBM::VK_LEFT) {
      snake.set_dir(Snake::LEFT);
    }
    if (key == hw::KBM::VK_UP) {
      snake.set_dir(Snake::UP);
    }
    if (key == hw::KBM::VK_DOWN) {
      snake.set_dir(Snake::DOWN);
    }
    if (key == hw::KBM::VK_SPACE) {
      if (snake.is_gameover())
        snake.reset();
    }

  });
}

void Service::start()
{
  // redirect stdout to vga screen
  // ... even though we aren't really using it after the game starts

  OS::set_rsprint(
  [] (const char* data, size_t len)
  {
    vga.write(data, len);
  });

  // we have to start snake later to avoid late text output
  hw::PIT::on_timeout(0.25, [] { begin_snake(); });

  // boilerplate
  hw::Nic<VirtioNet>& eth0 = hw::Dev::eth<0,VirtioNet>();
  inet = std::make_unique<net::Inet4<VirtioNet> >(eth0, 0.15);
  inet->network_config(
    { 10,0,0,42 },      // IP
    { 255,255,255,0 },  // Netmask
    { 10,0,0,1 },       // Gateway
    { 8,8,8,8 } );      // DNS

  printf("*** TEST SERVICE STARTED ***\n");
}
<|endoftext|>


<commit_before>#include "Binding.h"
#include <iostream>
#include <vector>
#include "MyActor.h"
#include "MyActorBinding.h"

using std::cout;
using std::endl;

static void stackDump (lua_State *L) {
    int i=lua_gettop(L);
    cout << " ----------------  Stack Dump ----------------\n";
    while(  i   ) {
        int t = lua_type(L, i);
        switch (t) {
            case LUA_TSTRING:
                printf("%d: “%s”\n", i, lua_tostring(L, i));
                break;
            case LUA_TBOOLEAN:
                printf("%d: %s\n",i,lua_toboolean(L, i) ? "true" : "false");
                break;
            case LUA_TNUMBER:
                printf("%d: %g\n",  i, lua_tonumber(L, i));
                break;
            default:
                printf("%d: %s 0x%x\n", i, lua_typename(L, t), lua_topointer(L, i));
                break;
        }
        i--;
    }
    cout << "--------------- Stack Dump Finished ---------------\n";
}

void run( lua_State *L, const char *code )
{
    cout << "code> " << code << endl;

    if( luaL_dostring( L, code ) )
    {
        cout << lua_tostring( L, -1 ) << endl;
        lua_pop( L, 1 );
    }
}

typedef std::vector<MyActorPtr> MyActorPtrList;

MyActorPtrList createList()
{
    const char* names[] = {
        "James",
        "Who? Random extra",
        "Harry",
        "Mike",
        nullptr
    };

    MyActorPtrList actors;

    for( int i = 0; names[i] != nullptr; i++ )
    {
        actors.push_back( std::make_shared<MyActor>( names[i] ) );
    }

    return actors;
}

void pushToLua( lua_State* L, MyActorPtrList list )
{
    lua_newtable( L );

    int index = 1;
    for( auto ap = list.begin(); ap != list.end(); ap++ ) {
        MyActorBinding::push( L, *ap );
        lua_rawseti( L, -2, index++ );
    }
}

MyActorPtrList pullFromLua( lua_State* L )
{
    // Note this only stores the values, not the keys/indexes,
    // which are usually just numbers.
    MyActorPtrList list;

    if( lua_istable( L, -1 ) )
    {
        lua_pushnil( L );

        while( lua_next( L, -2 ) )
        {
            if( luaL_testudata( L, -1, "MyActor" ) )
            {
                list.push_back( MyActorBinding::fromStack( L, -1 ) );
            }
            lua_pop( L, 1 );
        }
    }

    return list;
}

int main()
{
    lua_State* L = luaL_newstate();
    luaL_openlibs( L );

    MyActorBinding::register_class( L );

    {
        cout << "Pushing actor list to Lua." << endl;
        MyActorPtrList actors = createList();
        pushToLua( L, actors );
        lua_setglobal( L, "actors" );
    }

    cout << "Editing actor list..." << endl;
    run( L, "actors[2] = nil                    -- Who is this? Pfft, delete." );
    run( L, "collectgarbage()" );
    run( L, "actors['test'] = MyActor('Bob')    -- Hey Bob welcome." );

    run( L, "for k,v in pairs(actors) do print( k, v.name ) end" );

    {
        cout << "Pull list back into C++ vector, and list..." << endl;
        lua_getglobal( L, "actors" );
        MyActorPtrList actors = pullFromLua( L );
        lua_pop( L, 1 );

        for( auto ap = actors.begin(); ap != actors.end(); ap++ )
        {
            cout << (*ap)->_name << endl;
        }
    }

    lua_close(L);
}
<commit_msg>We don't need stackDump in this example<commit_after>#include "Binding.h"
#include <iostream>
#include <vector>
#include "MyActor.h"
#include "MyActorBinding.h"

using std::cout;
using std::endl;

void run( lua_State *L, const char *code )
{
    cout << "code> " << code << endl;

    if( luaL_dostring( L, code ) )
    {
        cout << lua_tostring( L, -1 ) << endl;
        lua_pop( L, 1 );
    }
}

typedef std::vector<MyActorPtr> MyActorPtrList;

MyActorPtrList createList()
{
    const char* names[] = {
        "James",
        "Who? Random extra",
        "Harry",
        "Mike",
        nullptr
    };

    MyActorPtrList actors;

    for( int i = 0; names[i] != nullptr; i++ )
    {
        actors.push_back( std::make_shared<MyActor>( names[i] ) );
    }

    return actors;
}

void pushToLua( lua_State* L, MyActorPtrList list )
{
    lua_newtable( L );

    int index = 1;
    for( auto ap = list.begin(); ap != list.end(); ap++ ) {
        MyActorBinding::push( L, *ap );
        lua_rawseti( L, -2, index++ );
    }
}

MyActorPtrList pullFromLua( lua_State* L )
{
    // Note this only stores the values, not the keys/indexes,
    // which are usually just numbers.
    MyActorPtrList list;

    if( lua_istable( L, -1 ) )
    {
        lua_pushnil( L );

        while( lua_next( L, -2 ) )
        {
            if( luaL_testudata( L, -1, "MyActor" ) )
            {
                list.push_back( MyActorBinding::fromStack( L, -1 ) );
            }
            lua_pop( L, 1 );
        }
    }

    return list;
}

int main()
{
    lua_State* L = luaL_newstate();
    luaL_openlibs( L );

    MyActorBinding::register_class( L );

    {
        cout << "Pushing actor list to Lua." << endl;
        MyActorPtrList actors = createList();
        pushToLua( L, actors );
        lua_setglobal( L, "actors" );
    }

    cout << "Editing actor list..." << endl;
    run( L, "actors[2] = nil                    -- Who is this? Pfft, delete." );
    run( L, "collectgarbage()" );
    run( L, "actors['test'] = MyActor('Bob')    -- Hey Bob welcome." );

    run( L, "for k,v in pairs(actors) do print( k, v.name ) end" );

    {
        cout << "Pull list back into C++ vector, and list..." << endl;
        lua_getglobal( L, "actors" );
        MyActorPtrList actors = pullFromLua( L );
        lua_pop( L, 1 );

        for( auto ap = actors.begin(); ap != actors.end(); ap++ )
        {
            cout << (*ap)->_name << endl;
        }
    }

    lua_close(L);
}
<|endoftext|>


<commit_before>/*
Copyright (C) 2016 - Gbor "Razzie" Grzsny

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 <iostream>
#include "raz/thread.hpp"

struct Loopable
{
	void operator()()
	{
		std::cout << "loop" << std::endl;
	}
};

struct Worker
{
	void operator()(int a, int b)
	{
		std::cout << (a + b) << std::endl;
	}
};

void example01()
{
	raz::Thread<Loopable> thread;
	std::this_thread::sleep_for(std::chrono::milliseconds(200));
}

void example02()
{
	raz::Thread<Worker> thread;

	thread(1, 2);
	std::this_thread::sleep_for(std::chrono::milliseconds(200));

	thread(2, 3);
	std::this_thread::sleep_for(std::chrono::milliseconds(200));

	thread(3, 4);
	std::this_thread::sleep_for(std::chrono::milliseconds(200));
}

int main()
{
	example01();
	example02();

	return 0;
}
<commit_msg>Updated thread example<commit_after>/*
Copyright (C) 2016 - Gbor "Razzie" Grzsny

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 <iostream>
#include <stdexcept>
#include "raz/thread.hpp"

class Loopable
{
public:
	void operator()()
	{
		std::cout << "loop" << std::endl;
	}
};

class Worker
{
	int base_value;

public:
	Worker(int base_value) : base_value(base_value)
	{
	}

	void operator()(int value)
	{
		std::cout << (base_value + value) << std::endl;
	}
};

class WorkerWithException
{
public:
	void operator()(bool throw_exception)
	{
		if (throw_exception)
			throw std::runtime_error("this is an exception");
	}

	void operator()(std::exception& e)
	{
		std::cerr << e.what() << std::endl;
	}
};

void example01()
{
	raz::Thread<Loopable> thread;
	std::this_thread::sleep_for(std::chrono::milliseconds(200));
}

void example02()
{
	raz::Thread<Worker> thread(123);

	thread(1);
	std::this_thread::sleep_for(std::chrono::milliseconds(200));

	thread(2);
	std::this_thread::sleep_for(std::chrono::milliseconds(200));

	thread(3);
	std::this_thread::sleep_for(std::chrono::milliseconds(200));
}

void example03()
{
	raz::Thread<WorkerWithException> thread;

	thread(false);
	thread(true);

	std::this_thread::sleep_for(std::chrono::milliseconds(200));
}

int main()
{
	example01();
	example02();
	example03();

	return 0;
}
<|endoftext|>


<commit_before>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "MooseInit.h"
#include "Moose.h"
#include "ParallelUniqueId.h"
#include "Factory.h"
#include "ActionFactory.h"

MooseInit::MooseInit(int argc, char *argv[]) :
	LibMeshInit(argc, argv)
{
  ParallelUniqueId::initialize();

  std::cout << "Using " << libMesh::n_threads() << " thread(s)" << std::endl;

  Moose::command_line = new GetPot(argc, argv);

  Moose::registerObjects();
}

MooseInit::~MooseInit()
{
  delete Moose::command_line;
  Factory::release();
  ActionFactory::release();
}

namespace Moose
{

GetPot *command_line = NULL;

}
<commit_msg>Get rid of PetscErrorHandler<commit_after>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "MooseInit.h"
#include "Moose.h"
#include "ParallelUniqueId.h"
#include "Factory.h"
#include "ActionFactory.h"

MooseInit::MooseInit(int argc, char *argv[]) :
	LibMeshInit(argc, argv)
{
  PetscPushSignalHandler(NULL, NULL);           // get rid off Petsc error handler
  ParallelUniqueId::initialize();

  std::cout << "Using " << libMesh::n_threads() << " thread(s)" << std::endl;

  Moose::command_line = new GetPot(argc, argv);

  Moose::registerObjects();
}

MooseInit::~MooseInit()
{
  delete Moose::command_line;
  Factory::release();
  ActionFactory::release();
}

namespace Moose
{

GetPot *command_line = NULL;

}
<|endoftext|>


<commit_before>#include "kernel.h"
#include "raster.h"
#include "simpelgeoreference.h"
#include "cornersgeoreference.h"
#include "symboltable.h"
#include "ilwisoperation.h"
#include "pixeliterator.h"
#include "columndefinition.h"
#include "table.h"
#include "attributerecord.h"
#include "selection.h"

using namespace Ilwis;
using namespace BaseOperations;

Selection::Selection()
{
}

Selection::Selection(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr)
{
}

Selection::~Selection()
{
}

bool Selection::execute(ExecutionContext *ctx, SymbolTable& symTable)
{
    if (_prepState == sNOTPREPARED)
        if((_prepState = prepare(ctx, symTable)) != sPREPARED)
            return false;
    IGridCoverage outputGC = _outputObj.get<GridCoverage>();
    IGridCoverage inputGC = _inputObj.get<GridCoverage>();

    BoxedAsyncFunc selection = [&](const Box3D<qint32>& box ) -> bool {
        Box3D<qint32> inpbox = box.size();
        inpbox += _base;
        inpbox += std::vector<qint32>{0, box.min_corner().y(),0};
        inpbox.copyFrom(box, Box3D<>::dimZ);
        PixelIterator iterOut(outputGC, box);
        PixelIterator iterIn(inputGC, inpbox);

        AttributeRecord rec;
        if ( _attribColumn != "")
            rec = AttributeRecord(inputGC->attributeTable(itCOVERAGE), "coverage_key");

        double v_in = 0;
        for_each(iterOut, iterOut.end(), [&](double& v){
            v_in = *iterIn;
            if ( v_in != rUNDEF) {
                if ( rec.isValid()) {
                    QVariant var = rec.cellByKey(v_in,_attribColumn);
                    v = var.toDouble();
                    if ( isNumericalUndef(v))
                        v = rUNDEF;
                } else {
                    v = v_in;
                }
            }
            ++iterIn;
            ++iterOut;
        }
        );
        return true;
    };

    bool res = OperationHelper::execute(ctx,selection, outputGC, _box);

    if ( res && ctx != 0) {
        QVariant value;
        value.setValue<IGridCoverage>(outputGC);
        ctx->addOutput(symTable, value, outputGC->name(), itGRIDCOVERAGE,outputGC->source());
    }
    return res;

}

Ilwis::OperationImplementation *Selection::create(quint64 metaid, const Ilwis::OperationExpression &expr)
{
    return new Selection(metaid, expr);
}

Ilwis::OperationImplementation::State Selection::prepare(ExecutionContext *, const SymbolTable &)
{
    if ( _expression.parameterCount() != 2) {
        ERROR3(ERR_ILLEGAL_NUM_PARM3,"rasvalue","1",QString::number(_expression.parameterCount()));
        return sPREPAREFAILED;
    }
    IlwisTypes inputType = itGRIDCOVERAGE;
    QString gc = _expression.parm(0).value();
    if (!_inputObj.prepare(gc, inputType)) {
        ERROR2(ERR_COULD_NOT_LOAD_2,gc,"");
        return sPREPAREFAILED;
    }
    IGridCoverage inputGC = _inputObj.get<GridCoverage>();
    quint64 copylist = itCOORDSYSTEM;

    QString selector = _expression.parm(1).value();
    selector = selector.remove('"');

    int index = selector.indexOf("box=");
    Box2D<double> box;
    if ( index != -1) {
        QString crdlist = "box(" + selector.mid(index+4) + ")";
        _box = Box3D<qint32>(crdlist);
        box = inputGC->georeference()->pixel2Coord(_box);
        copylist |= itDOMAIN | itTABLE;
        std::vector<qint32> vec{_box.min_corner().x(), _box.min_corner().y(),_box.min_corner().z()};
        _base = vec;

    }
    index = selector.indexOf("polygon=");
    if ( index != -1)
    {
        //TODO
        copylist |= itDOMAIN | itTABLE;
    }
    index = selector.indexOf("attribute=");
    if ( index != -1 ) {
        if (! inputGC->attributeTable(itCOVERAGE).isValid()) {
            ERROR2(ERR_NO_FOUND2,"attribute-table", "coverage");
            return sPREPAREFAILED;
        }
        _attribColumn =  selector.mid(index+10);
        copylist |= itGRIDSIZE | itGEOREF | itENVELOPE;
    }

     _outputObj = OperationHelper::initialize(_inputObj,inputType, copylist);
     if ( !_outputObj.isValid()) {
         ERROR1(ERR_NO_INITIALIZED_1, "output coverage");
         return sPREPAREFAILED;
     }
     IGridCoverage outputGC = _outputObj.get<GridCoverage>();
     if ( (copylist & itDOMAIN) == 0) {
         outputGC->datadef() = _attribColumn != "" ? inputGC->attributeTable(itCOVERAGE)->columndefinition(_attribColumn).datadef()
                                                   : outputGC->datadef() = inputGC->datadef();
     }
     QString outputName = _expression.parm(0,false).value();
     if ( outputName != sUNDEF)
         _outputObj->setName(outputName);
     if ( (copylist & itGEOREF) == 0) {
        Resource res(QUrl("ilwis://internal/georeference"),itCORNERSGEOREF);
        res.addProperty("size", IVARIANT(_box.size()));
        res.addProperty("envelope", IVARIANT(box));
        res.addProperty("coordinatesystem", IVARIANT(inputGC->coordinateSystem()));
        res.addProperty("name", _outputObj->name());
        res.addProperty("centerofpixel",inputGC->georeference()->centerOfPixel());
        IGeoReference  grf;
        grf.prepare(res);
        outputGC->georeference(grf);
        outputGC->envelope(box);
    }

    return sPREPARED;
}

quint64 Selection::createMetadata()
{
    QString url = QString("ilwis://operations/selection");
    Resource res(QUrl(url), itOPERATIONMETADATA);
    res.addProperty("namespace","ilwis");
    res.addProperty("longname","selection");
    res.addProperty("syntax","selection(coverage,selection-definition)");
    res.addProperty("inparameters","2");
    res.addProperty("pin_1_type", itCOVERAGE);
    res.addProperty("pin_1_name", TR("input coverage"));
    res.addProperty("pin_1_desc",TR("input gridcoverage with a domain as specified by the selection"));
    res.addProperty("pin_2_type", itSTRING);
    res.addProperty("pin_2_name", TR("selection-definition"));
    res.addProperty("pin_2_desc",TR("Selection can either be attribute, layer index or area definition (e.g. box)"));
    res.addProperty("pout_1_type", itCOVERAGE);
    res.addProperty("pout_1_name", TR("coverage were the selection has been applied"));
    res.addProperty("pout_1_desc",TR(""));
    res.prepare();
    url += "=" + QString::number(res.id());
    res.setUrl(url);

    mastercatalog()->addItems({res});
    return res.id();

}

<commit_msg>changed helper name<commit_after>#include "kernel.h"
#include "raster.h"
#include "simpelgeoreference.h"
#include "cornersgeoreference.h"
#include "symboltable.h"
#include "ilwisoperation.h"
#include "pixeliterator.h"
#include "columndefinition.h"
#include "table.h"
#include "attributerecord.h"
#include "selection.h"

using namespace Ilwis;
using namespace BaseOperations;

Selection::Selection()
{
}

Selection::Selection(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr)
{
}

Selection::~Selection()
{
}

bool Selection::execute(ExecutionContext *ctx, SymbolTable& symTable)
{
    if (_prepState == sNOTPREPARED)
        if((_prepState = prepare(ctx, symTable)) != sPREPARED)
            return false;
    IGridCoverage outputGC = _outputObj.get<GridCoverage>();
    IGridCoverage inputGC = _inputObj.get<GridCoverage>();

    BoxedAsyncFunc selection = [&](const Box3D<qint32>& box ) -> bool {
        Box3D<qint32> inpbox = box.size();
        inpbox += _base;
        inpbox += std::vector<qint32>{0, box.min_corner().y(),0};
        inpbox.copyFrom(box, Box3D<>::dimZ);
        PixelIterator iterOut(outputGC, box);
        PixelIterator iterIn(inputGC, inpbox);

        AttributeRecord rec;
        if ( _attribColumn != "")
            rec = AttributeRecord(inputGC->attributeTable(itCOVERAGE), "coverage_key");

        double v_in = 0;
        for_each(iterOut, iterOut.end(), [&](double& v){
            v_in = *iterIn;
            if ( v_in != rUNDEF) {
                if ( rec.isValid()) {
                    QVariant var = rec.cellByKey(v_in,_attribColumn);
                    v = var.toDouble();
                    if ( isNumericalUndef(v))
                        v = rUNDEF;
                } else {
                    v = v_in;
                }
            }
            ++iterIn;
            ++iterOut;
        }
        );
        return true;
    };

    bool res = OperationHelperRaster::execute(ctx,selection, outputGC, _box);

    if ( res && ctx != 0) {
        QVariant value;
        value.setValue<IGridCoverage>(outputGC);
        ctx->addOutput(symTable, value, outputGC->name(), itGRIDCOVERAGE,outputGC->source());
    }
    return res;

}

Ilwis::OperationImplementation *Selection::create(quint64 metaid, const Ilwis::OperationExpression &expr)
{
    return new Selection(metaid, expr);
}

Ilwis::OperationImplementation::State Selection::prepare(ExecutionContext *, const SymbolTable &)
{
    if ( _expression.parameterCount() != 2) {
        ERROR3(ERR_ILLEGAL_NUM_PARM3,"rasvalue","1",QString::number(_expression.parameterCount()));
        return sPREPAREFAILED;
    }
    IlwisTypes inputType = itGRIDCOVERAGE;
    QString gc = _expression.parm(0).value();
    if (!_inputObj.prepare(gc, inputType)) {
        ERROR2(ERR_COULD_NOT_LOAD_2,gc,"");
        return sPREPAREFAILED;
    }
    IGridCoverage inputGC = _inputObj.get<GridCoverage>();
    quint64 copylist = itCOORDSYSTEM;

    QString selector = _expression.parm(1).value();
    selector = selector.remove('"');

    int index = selector.indexOf("box=");
    Box2D<double> box;
    if ( index != -1) {
        QString crdlist = "box(" + selector.mid(index+4) + ")";
        _box = Box3D<qint32>(crdlist);
        box = inputGC->georeference()->pixel2Coord(_box);
        copylist |= itDOMAIN | itTABLE;
        std::vector<qint32> vec{_box.min_corner().x(), _box.min_corner().y(),_box.min_corner().z()};
        _base = vec;

    }
    index = selector.indexOf("polygon=");
    if ( index != -1)
    {
        //TODO
        copylist |= itDOMAIN | itTABLE;
    }
    index = selector.indexOf("attribute=");
    if ( index != -1 ) {
        if (! inputGC->attributeTable(itCOVERAGE).isValid()) {
            ERROR2(ERR_NO_FOUND2,"attribute-table", "coverage");
            return sPREPAREFAILED;
        }
        _attribColumn =  selector.mid(index+10);
        copylist |= itGRIDSIZE | itGEOREF | itENVELOPE;
    }

     _outputObj = OperationHelperRaster::initialize(_inputObj,inputType, copylist);
     if ( !_outputObj.isValid()) {
         ERROR1(ERR_NO_INITIALIZED_1, "output coverage");
         return sPREPAREFAILED;
     }
     IGridCoverage outputGC = _outputObj.get<GridCoverage>();
     if ( (copylist & itDOMAIN) == 0) {
         outputGC->datadef() = _attribColumn != "" ? inputGC->attributeTable(itCOVERAGE)->columndefinition(_attribColumn).datadef()
                                                   : outputGC->datadef() = inputGC->datadef();
     }
     QString outputName = _expression.parm(0,false).value();
     if ( outputName != sUNDEF)
         _outputObj->setName(outputName);
     if ( (copylist & itGEOREF) == 0) {
        Resource res(QUrl("ilwis://internal/georeference"),itCORNERSGEOREF);
        res.addProperty("size", IVARIANT(_box.size()));
        res.addProperty("envelope", IVARIANT(box));
        res.addProperty("coordinatesystem", IVARIANT(inputGC->coordinateSystem()));
        res.addProperty("name", _outputObj->name());
        res.addProperty("centerofpixel",inputGC->georeference()->centerOfPixel());
        IGeoReference  grf;
        grf.prepare(res);
        outputGC->georeference(grf);
        outputGC->envelope(box);
    }

    return sPREPARED;
}

quint64 Selection::createMetadata()
{
    QString url = QString("ilwis://operations/selection");
    Resource res(QUrl(url), itOPERATIONMETADATA);
    res.addProperty("namespace","ilwis");
    res.addProperty("longname","selection");
    res.addProperty("syntax","selection(coverage,selection-definition)");
    res.addProperty("inparameters","2");
    res.addProperty("pin_1_type", itCOVERAGE);
    res.addProperty("pin_1_name", TR("input coverage"));
    res.addProperty("pin_1_desc",TR("input gridcoverage with a domain as specified by the selection"));
    res.addProperty("pin_2_type", itSTRING);
    res.addProperty("pin_2_name", TR("selection-definition"));
    res.addProperty("pin_2_desc",TR("Selection can either be attribute, layer index or area definition (e.g. box)"));
    res.addProperty("pout_1_type", itCOVERAGE);
    res.addProperty("pout_1_name", TR("coverage were the selection has been applied"));
    res.addProperty("pout_1_desc",TR(""));
    res.prepare();
    url += "=" + QString::number(res.id());
    res.setUrl(url);

    mastercatalog()->addItems({res});
    return res.id();

}

<|endoftext|>


<commit_before><commit_msg>Initialize the runtime properly in authentication-test<commit_after><|endoftext|>