text
stringlengths
54
60.6k
<commit_before>74a2c592-5216-11e5-9995-6c40088e03e4<commit_msg>74a96618-5216-11e5-8594-6c40088e03e4<commit_after>74a96618-5216-11e5-8594-6c40088e03e4<|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <string> #include <cstring> #include <string.h> #include <stdio.h> #include <sstream> using namespace std; //TODO: // Create parse function // Add execute functionality to both classes // Write loop in main function class Shell{ public: Shell* first; Shell* second; Shell(){}; virtual bool execute() = 0; }; class Connector : public Shell{ public: Shell* first; Shell* second; Connector() : Shell(){}; Connector(Shell* f, Shell* s) : first(f), second(s){}; virtual bool execute() = 0; // for compiler }; class Bars : public Connector{ public: Bars() : Connector (){}; Bars(Shell* f, Shell* s) : Connector(f, s){}; bool execute(){ if(!first->execute()){ return second->execute(); } return true; } }; class Semi : public Connector{ public: Semi() : Connector (){}; Semi(Shell* f, Shell* s) : Connector(f, s){}; bool execute(){ first->execute(); return second->execute(); } }; class Amp : public Connector{ public: Amp() : Connector (){}; Amp(Shell* f, Shell* s) : Connector(f, s){}; bool execute(){ if(first->execute()){ return second->execute(); } return false; // else } }; class Command : public Shell{ public: const char* cmd; vector<string> args; Command() : Shell(){}; Command(char c[], vector<string> a) : Shell(), cmd(c), args(a) {}; bool execute(){ cout << "executed command" << endl; return true; } }; Shell* stringToCommand(string commandLine){ stringstream ss; ss << commandLine; // //sets up everything to use strtok // char* cmdLine = new char[cmd.length() + 1]; // const char s[2] = " "; // char *token; // token = strtok(cmdLine, s); //builds new command Command* temp = new Command; string tempString; ss >> tempString; temp->cmd = tempString.c_str(); while(ss >> tempString){ temp->args.push_back(tempString); } // if(token != NULL){ // } // while(token != NULL){ // temp->args.push_back(token); // token = strtok(NULL, s); // } return temp; } void parse(string commandLine){ Shell* top = NULL; vector<string> commands; vector<string> connectors; for(int i = 0; i < commandLine.size(); ++i){ string temp; if(commandLine.at(i) == ';'){ //make substr temp = commandLine.substr(0, i); //delete what we took commandLine.erase(0, i); //reset i i = 0; if(top = NULL){ Shell* connect = new Semi; top = connect; connect->first = stringToCommand(temp); } else{ Shell* connect = new Semi; connect->first = top; top->second = stringToCommand(temp); top = connect; } } else if(commandLine.at(i) == '|'){ if(commandLine.at(i + 1) == '|'){ //make substr temp = commandLine.substr(0, i); //delete what we took commandLine.erase(0, i); //reset i i = 0; if(top = NULL){ Shell* connect = new Bars; top = connect; connect->first = stringToCommand(temp); } else{ Shell* connect = new Bars; connect->first = top; top->second = stringToCommand(temp); top = connect; } } } else if(commandLine.at(i) == '&'){ if(commandLine.at(i + 1) == '&'){ //make substr temp = commandLine.substr(0, i); //delete what we took commandLine.erase(0, i); //reset i i = 0; if(top = NULL){ Shell* connect = new Amp; top = connect; connect->first = stringToCommand(temp); } else{ Shell* connect = new Amp; connect->first = top; top->second = stringToCommand(temp); top = connect; } } } else{ //make substr temp = commandLine.substr(0, i); //if top != null, top->second = stringToCommand if(top == NULL){ top = stringToCommand(temp); } else{ top->second = stringToCommand(temp); } //if top == null, top = stringToCommand } } } int main() { string commandLine; while(commandLine != "exit"){ cout << '$'; getline(cin, commandLine); parse(commandLine); } return 0; } <commit_msg>bug finding<commit_after>#include <iostream> #include <vector> #include <string> #include <cstring> #include <string.h> #include <stdio.h> #include <sstream> using namespace std; //TODO: // Create parse function // Add execute functionality to both classes // Write loop in main function class Shell{ public: Shell* first; Shell* second; Shell(){}; virtual bool execute() = 0; }; class Connector : public Shell{ public: Shell* first; Shell* second; Connector() : Shell(){}; Connector(Shell* f, Shell* s) : first(f), second(s){}; virtual bool execute() = 0; // for compiler }; class Bars : public Connector{ public: Bars() : Connector (){}; Bars(Shell* f, Shell* s) : Connector(f, s){}; bool execute(){ if(!first->execute()){ return second->execute(); } return true; } }; class Semi : public Connector{ public: Semi() : Connector (){}; Semi(Shell* f, Shell* s) : Connector(f, s){}; bool execute(){ first->execute(); return second->execute(); } }; class Amp : public Connector{ public: Amp() : Connector (){}; Amp(Shell* f, Shell* s) : Connector(f, s){}; bool execute(){ if(first->execute()){ return second->execute(); } return false; // else } }; class Command : public Shell{ public: const char* cmd; vector<string> args; Command() : Shell(){}; Command(char c[], vector<string> a) : Shell(), cmd(c), args(a) {}; bool execute(){ cout << "executed command" << endl; return true; } }; Shell* stringToCommand(string commandLine){ stringstream ss; ss << commandLine; // //sets up everything to use strtok // char* cmdLine = new char[cmd.length() + 1]; // const char s[2] = " "; // char *token; // token = strtok(cmdLine, s); //builds new command Command* temp = new Command; string tempString; ss >> tempString; temp->cmd = tempString.c_str(); while(ss >> tempString){ temp->args.push_back(tempString); } // if(token != NULL){ // } // while(token != NULL){ // temp->args.push_back(token); // token = strtok(NULL, s); // } return temp; } void parse(string commandLine){ Shell* top = NULL; vector<string> commands; vector<string> connectors; for(int i = 0; i < commandLine.size(); ++i){ cout << "current: " << i << endl; string temp; if(commandLine.at(i) == ';'){ cout << "found semi" << endl; //make substr cout << "created substr" << endl; temp = commandLine.substr(0, i); cout << "substr: " << temp << endl; //delete what we took cout << "erased substr from master string" << endl; commandLine.erase(0, i + 1); cout << "new master string: " << commandLine << endl; //reset i i = 0; cout << "top: " << top << endl; // if(top = NULL){ cout << "top is empty" << endl; Shell* connect = new Semi; top = connect; connect->first = stringToCommand(temp); // } // else{ // cout << "top is not empty" << endl; // Shell* connect = new Semi; // connect->first = top; // top->second = stringToCommand(temp); // top = connect; // } } else if(commandLine.at(i) == '|'){ if(commandLine.at(i + 1) == '|'){ //make substr temp = commandLine.substr(0, i); //delete what we took commandLine.erase(0, i); //reset i i = 0; if(top = NULL){ Shell* connect = new Bars; top = connect; connect->first = stringToCommand(temp); } else{ Shell* connect = new Bars; connect->first = top; top->second = stringToCommand(temp); top = connect; } } } else if(commandLine.at(i) == '&'){ if(commandLine.at(i + 1) == '&'){ //make substr temp = commandLine.substr(0, i); //delete what we took commandLine.erase(0, i); //need to change it so that it deletes both connectors //reset i i = 0; if(top = NULL){ Shell* connect = new Amp; top = connect; connect->first = stringToCommand(temp); } else{ Shell* connect = new Amp; connect->first = top; top->second = stringToCommand(temp); top = connect; } } } // else{ //this needs to get moved outside of the loop // //this gets called every i that is not a connector // cout << "no connector found!" << endl; // //make substr // temp = commandLine.substr(0, i); // //if top != null, top->second = stringToCommand // if(top == NULL){ // top = stringToCommand(temp); // } // else{ // top->second = stringToCommand(temp); // } // //if top == null, top = stringToCommand // } // } cout << "no connector found!" << endl; string temp = commandLine; if(top == NULL){ top = stringToCommand(temp); } else{ top->second = stringToCommand(temp); } } int main() { string commandLine; while(commandLine != "exit"){ cout << '$'; getline(cin, commandLine); parse(commandLine); } return 0; } <|endoftext|>
<commit_before>7dd8ddc5-2e4f-11e5-a10a-28cfe91dbc4b<commit_msg>7de0615e-2e4f-11e5-a794-28cfe91dbc4b<commit_after>7de0615e-2e4f-11e5-a794-28cfe91dbc4b<|endoftext|>
<commit_before>#include "sgct.h" #include "ParticleSystem.h" #include "Snow.h" #include "World.h" #include "HelperFunctions.h" #include "Field.h" #include "DebugField.h" #include "Gravity.h" #include "Wind.h" #include "ObjSystem.h" #include "SoapBubble.h" #include "Vortex.h" #include <iostream> #include "SimplexNoise.h" //our beautiful global variables sgct::Engine* gEngine; Snow* gParticles; World* gWorld; DebugField* gDebugField; Object* gObject; Object* tree; SoapBubble* gBubble; Wind* gWind; Gravity* gGrav; Vortex* gTurbine; sgct::SharedDouble curr_time(0.0); void initialize(); void draw(); void myPreSyncFun(); void statsDrawFun(); void externalControlCallback(const char * receivedChars, int size, int clientId); void sendMessageToExternalControl(void * data, int length); int main(int argc, char *argv[]) { initRandom(); gEngine = new sgct::Engine(argc, argv); gEngine->setInitOGLFunction(initialize); gEngine->setDrawFunction(draw); gEngine->setPreSyncFunction(myPreSyncFun); gEngine->setPostSyncPreDrawFunction(statsDrawFun); gEngine->setExternalControlCallback(externalControlCallback); gParticles = new Snow(gEngine); gWorld = new World(gEngine); gDebugField = new DebugField(gEngine); gBubble = new SoapBubble(gEngine); gObject = new Object(gEngine); tree = new Object(gEngine); gGrav = new Gravity(); gGrav->init(-9.81f); gParticles->addField(gGrav); gWind = new Wind(); //wind->init(getRandom(-0.2, 0.2), 0.0f, getRandom(-0.2, 0.2)); gWind->setAcceleration(0.0f, 0.0f, 0.0f); gParticles->addField(gWind); gTurbine = new Vortex(); gTurbine->init(0.0f, 0.0f, 0.0f); gParticles->addField(gTurbine); //Not working yet... :( SimplexNoise* noise = new SimplexNoise(); noise->init(glm::vec3(0), glm::vec3(0)); gParticles->addField(noise); if(!gEngine->init(sgct::Engine::OpenGL_3_3_Core_Profile)) { delete gEngine; return EXIT_FAILURE; } cout << "---- Fields active on gParticles ----" << endl; gParticles->printFields(); cout << "---------------" << endl << endl; gEngine->render(); gParticles->destroy(); gObject->deleteObject(); delete gObject; delete gEngine; delete gParticles; delete gWorld; delete gBubble; delete gWind; delete gTurbine; exit(EXIT_SUCCESS); } void initialize() { if(!gParticles->initialize()) { std::cout << "Error Initialzing Particle System:" << std::endl; exit(EXIT_FAILURE); } gWorld->initializeWorld(); gDebugField->init(); gObject->loadObj("road/road.obj", "road/road.png"); gObject->scale(0.2f,0.2f,0.2f); gObject->translate(0.0f, -2.0f, 5.0f); tree->loadObj("road/tree.obj","road/tree.png"); tree->scale(0.05f,0.05f,0.05f); tree->translate(0.0f, -1.0f, -6.0f); gBubble->createSphere(1.5f, 100); } void draw() { double delta = gEngine->getDt(); gWorld->drawWorld(); gBubble->drawBubble(); //gObject->draw(); //tree->draw(); gParticles->move(delta); gParticles->draw(delta); } //Checking the time since the program started, not sure if we need this either. void myPreSyncFun() { //Checks so the gEnginenode is actually the master. if( gEngine->isMaster() ) { //Sets the current time since the program started curr_time.setVal(sgct::Engine::getTime()); } } //Shows stats and graph depending on if the variables are true or not. Dont know if we need this? Currently set to false. void statsDrawFun() { gEngine->setDisplayInfoVisibility(false); gEngine->setStatsGraphVisibility(false); gEngine->setWireframe(false); } //Used to alter certain values when sent from GUI. This way we can alter the fields or change gravity in realtime! void externalControlCallback(const char * receivedChars, int size, int clientId) { //Checks so the gEnginenode is actually the master. if(gEngine->isMaster()) { if(size >= 6 && strncmp(receivedChars, "winX", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); gWind->setAcceleration((tmpVal*0.01f), (tmpVal*0.01f), (tmpVal*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "winY", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); gWind->setAcceleration((tmpVal*0.01f), (tmpVal*0.01f), (tmpVal*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "winZ", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); gWind->setAcceleration((tmpVal*0.01f), (tmpVal*0.01f), (tmpVal*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "vorX", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); gTurbine->setForce((tmpVal*0.01f), (tmpVal*0.01f), (tmpVal*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "vorY", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); gTurbine->setForce((tmpVal*0.01f), (tmpVal*0.01f), (tmpVal*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "vorZ", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); gTurbine->setForce((tmpVal*0.01f), (tmpVal*0.01f), (tmpVal*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "grav", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); gGrav->init(-tmpVal); } } } <commit_msg>new implementation for gui<commit_after>#include "sgct.h" #include "ParticleSystem.h" #include "Snow.h" #include "World.h" #include "HelperFunctions.h" #include "Field.h" #include "DebugField.h" #include "Gravity.h" #include "Wind.h" #include "ObjSystem.h" #include "SoapBubble.h" #include "Vortex.h" #include <iostream> #include "SimplexNoise.h" //our beautiful global variables sgct::Engine* gEngine; Snow* gParticles; World* gWorld; DebugField* gDebugField; Object* gObject; Object* tree; SoapBubble* gBubble; Wind* gWind; Gravity* gGrav; Vortex* gTurbine; sgct::SharedDouble curr_time(0.0); sgct::SharedDouble sizeFactorX(0.0); sgct::SharedDouble sizeFactorY(0.0); sgct::SharedDouble sizeFactorZ(0.0); sgct::SharedDouble vortFactorX(0.0); sgct::SharedDouble vortFactorY(0.0); sgct::SharedDouble vortFactorZ(0.0); sgct::SharedDouble positionX(0.0); sgct::SharedDouble positionZ(0.0); sgct::SharedDouble radius(0.0); void initialize(); void draw(); void myPreSyncFun(); void statsDrawFun(); void myEncodeFun(); void myDecodeFun(); void externalControlCallback(const char * receivedChars, int size, int clientId); void sendMessageToExternalControl(void * data, int length); int main(int argc, char *argv[]) { initRandom(); gEngine = new sgct::Engine(argc, argv); gEngine->setInitOGLFunction(initialize); gEngine->setDrawFunction(draw); gEngine->setPreSyncFunction(myPreSyncFun); gEngine->setPostSyncPreDrawFunction(statsDrawFun); gEngine->setExternalControlCallback(externalControlCallback); sgct::SharedData::instance()->setEncodeFunction(myEncodeFun); sgct::SharedData::instance()->setDecodeFunction(myDecodeFun); gParticles = new Snow(gEngine); gWorld = new World(gEngine); gDebugField = new DebugField(gEngine); gBubble = new SoapBubble(gEngine); gObject = new Object(gEngine); tree = new Object(gEngine); gGrav = new Gravity(); gGrav->init(-9.81f); gParticles->addField(gGrav); gWind = new Wind(); //wind->init(getRandom(-0.2, 0.2), 0.0f, getRandom(-0.2, 0.2)); gWind->setAcceleration(0.0f, 0.0f, 0.0f); gParticles->addField(gWind); gTurbine = new Vortex(); gTurbine->init(0.0f, 0.0f, 0.0f); gParticles->addField(gTurbine); //Not working yet... :( SimplexNoise* noise = new SimplexNoise(); noise->init(glm::vec3(0), glm::vec3(0)); gParticles->addField(noise); if(!gEngine->init(sgct::Engine::OpenGL_3_3_Core_Profile)) { delete gEngine; return EXIT_FAILURE; } cout << "---- Fields active on gParticles ----" << endl; gParticles->printFields(); cout << "---------------" << endl << endl; gEngine->render(); gParticles->destroy(); gObject->deleteObject(); delete gObject; delete gEngine; delete gParticles; delete gWorld; delete gBubble; delete gWind; delete gTurbine; exit(EXIT_SUCCESS); } void initialize() { if(!gParticles->initialize()) { std::cout << "Error Initialzing Particle System:" << std::endl; exit(EXIT_FAILURE); } gWorld->initializeWorld(); gDebugField->init(); gObject->loadObj("road/road.obj", "road/road.png"); gObject->scale(0.2f,0.2f,0.2f); gObject->translate(0.0f, -2.0f, 5.0f); tree->loadObj("road/tree.obj","road/tree.png"); tree->scale(0.05f,0.05f,0.05f); tree->translate(0.0f, -1.0f, -6.0f); gBubble->createSphere(1.5f, 100); } void draw() { double delta = gEngine->getDt(); gWorld->drawWorld(); gBubble->drawBubble(); //gObject->draw(); //tree->draw(); gParticles->move(delta); gParticles->draw(delta); } //Checking the time since the program started, not sure if we need this either. void myPreSyncFun() { //Checks so the gEnginenode is actually the master. if( gEngine->isMaster() ) { //Sets the current time since the program started curr_time.setVal(sgct::Engine::getTime()); } } void myEncodeFun() { sgct::SharedData::instance()->writeDouble(&curr_time); sgct::SharedData::instance()->writeDouble(&sizeFactorX); sgct::SharedData::instance()->writeDouble(&sizeFactorY); sgct::SharedData::instance()->writeDouble(&sizeFactorZ); sgct::SharedData::instance()->writeDouble(&vortFactorX); sgct::SharedData::instance()->writeDouble(&vortFactorY); sgct::SharedData::instance()->writeDouble(&vortFactorZ); sgct::SharedData::instance()->writeDouble(&positionX); sgct::SharedData::instance()->writeDouble(&positionZ); sgct::SharedData::instance()->writeDouble(&radius); } void myDecodeFun() { sgct::SharedData::instance()->readDouble(&curr_time); sgct::SharedData::instance()->readDouble(&sizeFactorX); sgct::SharedData::instance()->readDouble(&sizeFactorY); sgct::SharedData::instance()->readDouble(&sizeFactorZ); sgct::SharedData::instance()->readDouble(&vortFactorX); sgct::SharedData::instance()->readDouble(&vortFactorY); sgct::SharedData::instance()->readDouble(&vortFactorZ); sgct::SharedData::instance()->readDouble(&positionX); sgct::SharedData::instance()->readDouble(&positionZ); sgct::SharedData::instance()->readDouble(&radius); } //Shows stats and graph depending on if the variables are true or not. Dont know if we need this? Currently set to false. void statsDrawFun() { gEngine->setDisplayInfoVisibility(false); gEngine->setStatsGraphVisibility(false); gEngine->setWireframe(false); } //Used to alter certain values when sent from GUI. This way we can alter the fields or change gravity in realtime! void externalControlCallback(const char * receivedChars, int size, int clientId) { //Checks so the gEnginenode is actually the master. if(gEngine->isMaster()) { if(size >= 6 && strncmp(receivedChars, "winX", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); sizeFactorX.setVal(tmpVal); gWind->setAcceleration((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "winY", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); sizeFactorY.setVal(tmpVal); gWind->setAcceleration((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "winZ", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); sizeFactorZ.setVal(tmpVal); gWind->setAcceleration((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "vorX", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); gTurbine->setForce((tmpVal*0.01f), (tmpVal*0.01f), (tmpVal*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "vorY", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); vortFactorY.setVal(tmpVal); gTurbine->setForce((vortFactorX.getVal()*0.01f), (vortFactorY.getVal()*0.01f), (vortFactorZ.getVal()*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "vorZ", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); vortFactorZ.setVal(tmpVal); gTurbine->setForce((vortFactorX.getVal()*0.01f), (vortFactorY.getVal()*0.01f), (vortFactorZ.getVal()*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "posX", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); positionX.setVal(tmpVal); gTurbine->setPosition((positionX.getVal()*0.01f),(positionZ.getVal()*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "posZ", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); positionZ.setVal(tmpVal); gTurbine->setPosition((positionX.getVal()*0.01f),(positionZ.getVal()*0.01f)); } else if(size >= 6 && strncmp(receivedChars, "r", 1) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); radius.setVal(tmpVal); gTurbine->setRadius(radius.getVal()); } else if(size >= 6 && strcmp(receivedChars, "pause") != 0) { gParticles->togglePause(); } else if(size >= 6 && strncmp(receivedChars, "grav", 4) == 0) { //We need an int. int tmpVal = atoi(receivedChars + 5); gGrav->init(-tmpVal); } } } <|endoftext|>
<commit_before>8431fce3-2d15-11e5-af21-0401358ea401<commit_msg>8431fce4-2d15-11e5-af21-0401358ea401<commit_after>8431fce4-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>2040c44a-2e3a-11e5-9b98-c03896053bdd<commit_msg>2050095a-2e3a-11e5-97cf-c03896053bdd<commit_after>2050095a-2e3a-11e5-97cf-c03896053bdd<|endoftext|>
<commit_before>4340d17a-2d3d-11e5-88f4-c82a142b6f9b<commit_msg>43c7b06e-2d3d-11e5-b2af-c82a142b6f9b<commit_after>43c7b06e-2d3d-11e5-b2af-c82a142b6f9b<|endoftext|>
<commit_before>541cf236-2e3a-11e5-94eb-c03896053bdd<commit_msg>5435127e-2e3a-11e5-aa51-c03896053bdd<commit_after>5435127e-2e3a-11e5-aa51-c03896053bdd<|endoftext|>
<commit_before>2c3113b3-2e4f-11e5-a53c-28cfe91dbc4b<commit_msg>2c375d6b-2e4f-11e5-af63-28cfe91dbc4b<commit_after>2c375d6b-2e4f-11e5-af63-28cfe91dbc4b<|endoftext|>
<commit_before>2ddc6cc0-2e4f-11e5-a7f7-28cfe91dbc4b<commit_msg>2de496a1-2e4f-11e5-82e0-28cfe91dbc4b<commit_after>2de496a1-2e4f-11e5-82e0-28cfe91dbc4b<|endoftext|>
<commit_before>5d286578-2d16-11e5-af21-0401358ea401<commit_msg>5d286579-2d16-11e5-af21-0401358ea401<commit_after>5d286579-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>5a314024-2e3a-11e5-b5d2-c03896053bdd<commit_msg>5a3f2558-2e3a-11e5-9ff9-c03896053bdd<commit_after>5a3f2558-2e3a-11e5-9ff9-c03896053bdd<|endoftext|>
<commit_before>adb56b7a-35ca-11e5-addf-6c40088e03e4<commit_msg>adbc0f7a-35ca-11e5-a223-6c40088e03e4<commit_after>adbc0f7a-35ca-11e5-a223-6c40088e03e4<|endoftext|>
<commit_before>d17d8db3-2d3e-11e5-a090-c82a142b6f9b<commit_msg>d1d799ba-2d3e-11e5-9540-c82a142b6f9b<commit_after>d1d799ba-2d3e-11e5-9540-c82a142b6f9b<|endoftext|>
<commit_before>69dca45c-2e3a-11e5-b50d-c03896053bdd<commit_msg>69eb25f4-2e3a-11e5-bf89-c03896053bdd<commit_after>69eb25f4-2e3a-11e5-bf89-c03896053bdd<|endoftext|>
<commit_before>#include "XmlRpcHttpd.h" #include <string.h> #include <string.h> int opterr = 1; int optind = 1; int optopt; char *optarg; static int getopt(int argc, char** argv, const char* opts) { static int sp = 1; register int c; register char *cp; if(sp == 1) { if(optind >= argc || argv[optind][0] != '-' || argv[optind][1] == '\0') return(EOF); else if(strcmp(argv[optind], "--") == 0) { optind++; return(EOF); } } optopt = c = argv[optind][sp]; if(c == ':' || (cp=strchr((char*)opts, c)) == NULL) { if(argv[optind][++sp] == '\0') { optind++; sp = 1; } return('?'); } if(*++cp == ':') { if(argv[optind][sp+1] != '\0') optarg = &argv[optind++][sp+1]; else if(++optind >= argc) { sp = 1; return('?'); } else optarg = argv[optind++]; sp = 1; } else { if(argv[optind][++sp] == '\0') { sp = 1; optind++; } optarg = NULL; } return(c); } void logFunc(const XmlRpc::XmlRpcHttpd::HttpdInfo* httpd_info, const tstring& request) { printf("%s\n", request.c_str()); } typedef std::map<std::string, std::string> Config; typedef std::map<std::string, Config> ConfigList; ConfigList loadConfigs(const char* filename) { ConfigList configs; Config config; char buffer[BUFSIZ]; FILE* fp = fopen(filename, "r"); std::string profile = "global"; while(fp && fgets(buffer, sizeof(buffer), fp)) { char* line = buffer; char* ptr = strpbrk(line, "\r\n"); if (ptr) *ptr = 0; ptr = strchr(line, ']'); if (*line == '[' && ptr) { *ptr = 0; if (config.size()) configs[profile] = config; config.clear(); profile = line+1; continue; } ptr = strchr(line, '='); if (ptr && *line != ';') { *ptr++ = 0; config[line] = ptr; } } configs[profile] = config; if (fp) fclose(fp); return configs; } int main(int argc, char* argv[]) { int c; const char* root = "./public_html"; unsigned short port = 80; const char* cfg = NULL; #ifdef _WIN32 WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); #endif opterr = 0; while ((c = getopt(argc, (char**)argv, "p:c:d:") != -1)) { switch (optopt) { case 'p': port = (unsigned short)atol(optarg); break; case 'c': cfg = optarg; break; case 'd': root = optarg; break; case '?': break; default: argc = 0; break; } optarg = NULL; } XmlRpc::XmlRpcHttpd httpd(port); httpd.loggerfunc = logFunc; httpd.bindRoot(root); if (cfg) { ConfigList configs = loadConfigs(cfg); Config config; Config::iterator it; std::string val; val = configs["global"]["root"]; if (val.size()) httpd.bindRoot(val); val = configs["global"]["port"]; if (val.size()) httpd.port = atol(val.c_str()); val = configs["global"]["indexpages"]; if (val.size()) httpd.default_pages = XmlRpc::split_string(val, ","); val = configs["global"]["charset"]; if (val.size()) httpd.fs_charset = val; config = configs["mime/types"]; for (it = config.begin(); it != config.end(); it++) httpd.mime_types[it->first] = it->second; } else { #ifdef _WIN32 httpd.mime_types["cgi"] = "@c:/strawberry/perl/bin/perl.exe"; httpd.mime_types["php"] = "@c:/progra~1/php/php.exe"; #else httpd.mime_types["cgi"] = "@/usr/bin/perl"; httpd.mime_types["php"] = "@/usr/bin/php-cgi"; #endif } httpd.start(); httpd.wait(); // Ctrl-C to break } <commit_msg>fixed php executable.<commit_after>#include "XmlRpcHttpd.h" #include <string.h> #include <string.h> int opterr = 1; int optind = 1; int optopt; char *optarg; static int getopt(int argc, char** argv, const char* opts) { static int sp = 1; register int c; register char *cp; if(sp == 1) { if(optind >= argc || argv[optind][0] != '-' || argv[optind][1] == '\0') return(EOF); else if(strcmp(argv[optind], "--") == 0) { optind++; return(EOF); } } optopt = c = argv[optind][sp]; if(c == ':' || (cp=strchr((char*)opts, c)) == NULL) { if(argv[optind][++sp] == '\0') { optind++; sp = 1; } return('?'); } if(*++cp == ':') { if(argv[optind][sp+1] != '\0') optarg = &argv[optind++][sp+1]; else if(++optind >= argc) { sp = 1; return('?'); } else optarg = argv[optind++]; sp = 1; } else { if(argv[optind][++sp] == '\0') { sp = 1; optind++; } optarg = NULL; } return(c); } void logFunc(const XmlRpc::XmlRpcHttpd::HttpdInfo* httpd_info, const tstring& request) { printf("%s\n", request.c_str()); } typedef std::map<std::string, std::string> Config; typedef std::map<std::string, Config> ConfigList; ConfigList loadConfigs(const char* filename) { ConfigList configs; Config config; char buffer[BUFSIZ]; FILE* fp = fopen(filename, "r"); std::string profile = "global"; while(fp && fgets(buffer, sizeof(buffer), fp)) { char* line = buffer; char* ptr = strpbrk(line, "\r\n"); if (ptr) *ptr = 0; ptr = strchr(line, ']'); if (*line == '[' && ptr) { *ptr = 0; if (config.size()) configs[profile] = config; config.clear(); profile = line+1; continue; } ptr = strchr(line, '='); if (ptr && *line != ';') { *ptr++ = 0; config[line] = ptr; } } configs[profile] = config; if (fp) fclose(fp); return configs; } int main(int argc, char* argv[]) { int c; const char* root = "./public_html"; unsigned short port = 80; const char* cfg = NULL; #ifdef _WIN32 WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); #endif opterr = 0; while ((c = getopt(argc, (char**)argv, "p:c:d:") != -1)) { switch (optopt) { case 'p': port = (unsigned short)atol(optarg); break; case 'c': cfg = optarg; break; case 'd': root = optarg; break; case '?': break; default: argc = 0; break; } optarg = NULL; } XmlRpc::XmlRpcHttpd httpd(port); httpd.loggerfunc = logFunc; httpd.bindRoot(root); if (cfg) { ConfigList configs = loadConfigs(cfg); Config config; Config::iterator it; std::string val; val = configs["global"]["root"]; if (val.size()) httpd.bindRoot(val); val = configs["global"]["port"]; if (val.size()) httpd.port = atol(val.c_str()); val = configs["global"]["indexpages"]; if (val.size()) httpd.default_pages = XmlRpc::split_string(val, ","); val = configs["global"]["charset"]; if (val.size()) httpd.fs_charset = val; config = configs["mime/types"]; for (it = config.begin(); it != config.end(); it++) httpd.mime_types[it->first] = it->second; } else { #ifdef _WIN32 httpd.mime_types["cgi"] = "@c:/strawberry/perl/bin/perl.exe"; httpd.mime_types["php"] = "@c:/progra~1/php/php-cgi.exe"; #else httpd.mime_types["cgi"] = "@/usr/bin/perl"; httpd.mime_types["php"] = "@/usr/bin/php-cgi"; #endif } httpd.start(); httpd.wait(); // Ctrl-C to break } <|endoftext|>
<commit_before>b7ebb722-35ca-11e5-809c-6c40088e03e4<commit_msg>b7f27334-35ca-11e5-9dff-6c40088e03e4<commit_after>b7f27334-35ca-11e5-9dff-6c40088e03e4<|endoftext|>
<commit_before>38c1669e-2e3a-11e5-88c4-c03896053bdd<commit_msg>38cf24c0-2e3a-11e5-b1fa-c03896053bdd<commit_after>38cf24c0-2e3a-11e5-b1fa-c03896053bdd<|endoftext|>
<commit_before>856278c7-2d15-11e5-af21-0401358ea401<commit_msg>856278c8-2d15-11e5-af21-0401358ea401<commit_after>856278c8-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>0c92f2f6-585b-11e5-b8ec-6c40088e03e4<commit_msg>0c9adcbe-585b-11e5-a0f3-6c40088e03e4<commit_after>0c9adcbe-585b-11e5-a0f3-6c40088e03e4<|endoftext|>
<commit_before>906d2e42-35ca-11e5-ab22-6c40088e03e4<commit_msg>9073949e-35ca-11e5-8275-6c40088e03e4<commit_after>9073949e-35ca-11e5-8275-6c40088e03e4<|endoftext|>
<commit_before>67b9cd8f-2e4f-11e5-ac7d-28cfe91dbc4b<commit_msg>67c19ec2-2e4f-11e5-99f7-28cfe91dbc4b<commit_after>67c19ec2-2e4f-11e5-99f7-28cfe91dbc4b<|endoftext|>
<commit_before>c57ee1e3-2e4e-11e5-97d2-28cfe91dbc4b<commit_msg>c585dceb-2e4e-11e5-8333-28cfe91dbc4b<commit_after>c585dceb-2e4e-11e5-8333-28cfe91dbc4b<|endoftext|>
<commit_before>2bd3fc7a-2e4f-11e5-aa02-28cfe91dbc4b<commit_msg>2bdaa7de-2e4f-11e5-8bed-28cfe91dbc4b<commit_after>2bdaa7de-2e4f-11e5-8bed-28cfe91dbc4b<|endoftext|>
<commit_before>a7e2d2d4-35ca-11e5-aa0f-6c40088e03e4<commit_msg>a7ea972e-35ca-11e5-a335-6c40088e03e4<commit_after>a7ea972e-35ca-11e5-a335-6c40088e03e4<|endoftext|>
<commit_before>7c26b26c-5216-11e5-a796-6c40088e03e4<commit_msg>7c2d843e-5216-11e5-8db9-6c40088e03e4<commit_after>7c2d843e-5216-11e5-8db9-6c40088e03e4<|endoftext|>
<commit_before> /* _______ _______ _ _______ _______ _______ _______ _______________________ _______ ( ____ ( ___ ( ( /( ____ \ ( ____ ( ____ ( ____ ( ___ \__ __( ___ ( ____ ) | ( \| ( ) | \ ( | ( \/ | ( \| ( )| ( \| ( ) | ) ( | ( ) | ( )| | | | | | | \ | | (__ | | | (____)| (__ | (___) | | | | | | | (____)| | | | | | | (\ \) | __) | | | __| __) | ___ | | | | | | | __) | | | | | | | \ | ( | | | (\ ( | ( | ( ) | | | | | | | (\ ( | (____/| (___) | ) \ | (____/\ | (____/| ) \ \_| (____/| ) ( | | | | (___) | ) \ \__ (_______(_______|/ )_(_______/ (_______|/ \__(_______|/ \| )_( (_______|/ \__/ Cone Creator : A stupidly simple program that creates a 3D cone as a seris of 2D slices Created to scatch an itch, and to stop someone asking me to write this for them If this is in anyway useful to you, please use it with me best wishes. Useage : Compile with clang or gcc, run. By default it will create an 8 megabyte file called cone.bin in the current directory. You can change the 3D image size by changing the X, Y and Z Size values. A sequential file is written out in [XY],Z format. */ #include <vector> #include <iostream> #include <fstream> #include "tomhead.h" using namespace std; unsigned int XSize,XCentre,YCentre,YSize,ZSize,Radius; #define CurrentVoxel z*ZSize*YSize+y*YSize+x int main() { XSize = 600; YSize = 600; ZSize = 600; XCentre = XSize/2; YCentre = YSize/2; vector<uint8_t> canvas; canvas.resize(XSize*YSize*ZSize); thead TomHead; TomHead.xsize = XSize; TomHead.ysize = YSize; TomHead.zsize = ZSize; //TomHead.owner = "DM"; //TomHead.comment = "A Computed Cone"; for (unsigned int z = 2; z < ZSize; z++) { cout<<"Slice : " <<z<<endl; for (unsigned int y = 0; y < YSize; y++) { for (unsigned int x=0; x < XSize; x++) { Radius = z/2; if (((x - XCentre) * (x - XCentre)) + ((y - YCentre) * (y - YCentre)) <= (Radius * Radius)) { canvas.at(CurrentVoxel) = 254; cout << "X = " << x <<endl; cout << "Y = " << y <<endl; } else canvas.at(CurrentVoxel) = 0; } } } cout << "Xcentre : " <<XCentre<<endl; cout << "Ycentre : " <<YCentre<<endl; fstream file; file.open("cone.tom",ios::in|ios::out|ios::binary|ios::trunc); file.write((char *) &TomHead, sizeof(struct thead)); //for(unsigned long i=0;i<canvas.size();i++) //{ // file<<canvas[i]; //} file.write((char*)&*(canvas.begin()),canvas.size() * sizeof(uint8_t)); file.close(); exit(1); } <commit_msg>Some tweeks<commit_after> /* _______ _______ _ _______ _______ _______ _______ _______________________ _______ ( ____ ( ___ ( ( /( ____ \ ( ____ ( ____ ( ____ ( ___ \__ __( ___ ( ____ ) | ( \| ( ) | \ ( | ( \/ | ( \| ( )| ( \| ( ) | ) ( | ( ) | ( )| | | | | | | \ | | (__ | | | (____)| (__ | (___) | | | | | | | (____)| | | | | | | (\ \) | __) | | | __| __) | ___ | | | | | | | __) | | | | | | | \ | ( | | | (\ ( | ( | ( ) | | | | | | | (\ ( | (____/| (___) | ) \ | (____/\ | (____/| ) \ \_| (____/| ) ( | | | | (___) | ) \ \__ (_______(_______|/ )_(_______/ (_______|/ \__(_______|/ \| )_( (_______|/ \__/ Cone Creator : A stupidly simple program that creates a 3D cone as a seris of 2D slices Created to scatch an itch, and to stop someone asking me to write this for them If this is in anyway useful to you, please use it with me best wishes. Useage : Compile with clang or gcc, run. By default it will create an 8 megabyte file called cone.bin in the current directory. You can change the 3D image size by changing the X, Y and Z Size values. A sequential file is written out in [XY],Z format. */ #include <vector> #include <iostream> #include <fstream> #include "tomhead.h" using namespace std; unsigned int XSize,XCentre,YCentre,YSize,ZSize,Radius; #define CurrentVoxel z*ZSize*YSize+y*YSize+x int main() { XSize = 200; YSize = 200; ZSize = 200; XCentre = XSize/2; YCentre = YSize/2; vector<uint8_t> canvas; canvas.resize(XSize*YSize*ZSize); thead TomHead; TomHead.xsize = XSize; TomHead.ysize = YSize; TomHead.zsize = ZSize; //TomHead.owner = "DM"; //TomHead.comment = "A Computed Cone"; for (unsigned int z = 2; z < ZSize; z++) { cout<<"Slice : " <<z<<endl; for (unsigned int y = 0; y < YSize; y++) { for (unsigned int x=0; x < XSize; x++) { Radius = z/2; if (((x - XCentre) * (x - XCentre)) + ((y - YCentre) * (y - YCentre)) <= (Radius * Radius)) { canvas.at(CurrentVoxel) = 254; cout << "X = " << x <<endl; cout << "Y = " << y <<endl; } else canvas.at(CurrentVoxel) = 0; } } } cout << "Xcentre : " <<XCentre<<endl; cout << "Ycentre : " <<YCentre<<endl; fstream file; file.open("cone.tom",ios::in|ios::out|ios::binary|ios::trunc); file.write((char *) &TomHead, sizeof(struct thead)); //for(unsigned long i=0;i<canvas.size();i++) //{ // file<<canvas[i]; //} file.write((char*)&*(canvas.begin()),canvas.size() * sizeof(uint8_t)); file.close(); exit(1); } <|endoftext|>
<commit_before>f4e2babd-2e4e-11e5-918e-28cfe91dbc4b<commit_msg>f4ecf5d7-2e4e-11e5-8b0f-28cfe91dbc4b<commit_after>f4ecf5d7-2e4e-11e5-8b0f-28cfe91dbc4b<|endoftext|>
<commit_before>f0e7c8a6-585a-11e5-b71c-6c40088e03e4<commit_msg>f0eea37e-585a-11e5-9438-6c40088e03e4<commit_after>f0eea37e-585a-11e5-9438-6c40088e03e4<|endoftext|>
<commit_before>7677596b-2d3d-11e5-8c4e-c82a142b6f9b<commit_msg>76d8982e-2d3d-11e5-816a-c82a142b6f9b<commit_after>76d8982e-2d3d-11e5-816a-c82a142b6f9b<|endoftext|>
<commit_before>82e03f8a-2e4f-11e5-b7e0-28cfe91dbc4b<commit_msg>82e65b70-2e4f-11e5-b3d8-28cfe91dbc4b<commit_after>82e65b70-2e4f-11e5-b3d8-28cfe91dbc4b<|endoftext|>
<commit_before>991a5561-2e4f-11e5-836b-28cfe91dbc4b<commit_msg>9920f4ee-2e4f-11e5-83d3-28cfe91dbc4b<commit_after>9920f4ee-2e4f-11e5-83d3-28cfe91dbc4b<|endoftext|>
<commit_before>a850b611-327f-11e5-8a32-9cf387a8033e<commit_msg>a857560c-327f-11e5-8e72-9cf387a8033e<commit_after>a857560c-327f-11e5-8e72-9cf387a8033e<|endoftext|>
<commit_before>8d6dfd04-2d14-11e5-af21-0401358ea401<commit_msg>8d6dfd05-2d14-11e5-af21-0401358ea401<commit_after>8d6dfd05-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>d119bbd1-ad5c-11e7-b57f-ac87a332f658<commit_msg>more fixes<commit_after>d1b25a61-ad5c-11e7-b01f-ac87a332f658<|endoftext|>
<commit_before>8fd048e1-2d14-11e5-af21-0401358ea401<commit_msg>8fd048e2-2d14-11e5-af21-0401358ea401<commit_after>8fd048e2-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>0d0b0c40-2d3f-11e5-b0bc-c82a142b6f9b<commit_msg>0d8e5c8c-2d3f-11e5-b50b-c82a142b6f9b<commit_after>0d8e5c8c-2d3f-11e5-b50b-c82a142b6f9b<|endoftext|>
<commit_before>0518a2d7-2e4f-11e5-9383-28cfe91dbc4b<commit_msg>051f49a6-2e4f-11e5-a320-28cfe91dbc4b<commit_after>051f49a6-2e4f-11e5-a320-28cfe91dbc4b<|endoftext|>
<commit_before>7f6cf5d1-2d15-11e5-af21-0401358ea401<commit_msg>7f6cf5d2-2d15-11e5-af21-0401358ea401<commit_after>7f6cf5d2-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>92323b86-2d14-11e5-af21-0401358ea401<commit_msg>92323b87-2d14-11e5-af21-0401358ea401<commit_after>92323b87-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>#include <iostream> #include <memory> #include <sstream> #include <string> #include <utility> #include "parse/Parse.hpp" #include "eval/Eval.hpp" using namespace parse; using namespace eval; using std::cout; class TreePrinter : public tree::TermVisitor { public: virtual void acceptTerm(const tree::Abstraction& term) override { cout << "(^"; for (const std::string& arg : term.arguments) { cout << arg << " "; } cout << ". "; term.body->applyVisitor(*this); cout << ")"; } virtual void acceptTerm(const tree::Application& term) override { cout << "("; bool isFirst = true; for (unsigned int termNdx = 0; termNdx < term.terms.size(); ++termNdx) { if (!isFirst) { cout << " "; } isFirst = false; term.terms[termNdx]->applyVisitor(*this); } cout << ")"; } virtual void acceptTerm(const tree::Variable& term) override { cout << term.name; } }; class ASTPrinter : public ast::TermVisitor { public: virtual void acceptTerm(const ast::Abstraction& term) override { cout << "(^" << term.argumentName << ". "; term.body->applyVisitor(*this); cout << ")"; } virtual void acceptTerm(const ast::Application& term) override { cout << "("; term.left->applyVisitor(*this); cout << " "; term.right->applyVisitor(*this); cout << ")"; } virtual void acceptTerm(const ast::BoundVariable& term) override { cout << "_" << term.index; } virtual void acceptTerm(const ast::FreeVariable& term) override { cout << term.name; } }; int main() { std::string input; while (getline(std::cin, input) && input.size() > 0) { std::istringstream is(input); try { std::unique_ptr<tree::Term> tree = parseTerm(is); TreePrinter treePrinter; tree->applyVisitor(treePrinter); cout << "\n"; std::unique_ptr<ast::Term> ast = convertParseTree(*tree); ASTPrinter astPrinter; ast->applyVisitor(astPrinter); cout << "\n\n"; } catch (std::runtime_error& e) { cout << e.what() << "\n"; } } } <commit_msg>Test beta reductions<commit_after>#include <iostream> #include <memory> #include <sstream> #include <string> #include <utility> #include "parse/Parse.hpp" #include "eval/Eval.hpp" using namespace parse; using namespace eval; using std::cout; class TreePrinter : public tree::TermVisitor { public: virtual void acceptTerm(const tree::Abstraction& term) override { cout << "(^"; for (const std::string& arg : term.arguments) { cout << arg << " "; } cout << ". "; term.body->applyVisitor(*this); cout << ")"; } virtual void acceptTerm(const tree::Application& term) override { cout << "("; bool isFirst = true; for (unsigned int termNdx = 0; termNdx < term.terms.size(); ++termNdx) { if (!isFirst) { cout << " "; } isFirst = false; term.terms[termNdx]->applyVisitor(*this); } cout << ")"; } virtual void acceptTerm(const tree::Variable& term) override { cout << term.name; } }; class ASTPrinter : public ast::TermVisitor { public: virtual void acceptTerm(const ast::Abstraction& term) override { cout << "(^" << term.argumentName << ". "; term.body->applyVisitor(*this); cout << ")"; } virtual void acceptTerm(const ast::Application& term) override { cout << "("; term.left->applyVisitor(*this); cout << " "; term.right->applyVisitor(*this); cout << ")"; } virtual void acceptTerm(const ast::BoundVariable& term) override { cout << "_" << term.index; } virtual void acceptTerm(const ast::FreeVariable& term) override { cout << term.name; } }; int main() { std::string input; while (getline(std::cin, input) && input.size() > 0) { std::istringstream is(input); try { std::unique_ptr<tree::Term> tree = parseTerm(is); TreePrinter treePrinter; tree->applyVisitor(treePrinter); cout << "\n\n"; std::unique_ptr<ast::Term> ast = convertParseTree(*tree); bool isDone = false; while (!isDone) { ASTPrinter astPrinter; ast->applyVisitor(astPrinter); cout << "\n\n"; std::unique_ptr<ast::Term> reduced = betaReduce(*ast); if (reduced) { ast = std::move(reduced); } else { isDone = true; } } } catch (std::runtime_error& e) { cout << e.what() << "\n"; } } } <|endoftext|>
<commit_before>#include "gameloop.hpp" #include "glhead.hpp" #include "input.hpp" #include "glresource.hpp" #include "spinner/vector.hpp" #include "gpu.hpp" #include "glx.hpp" #include "camera.hpp" // void test0() { // auto fc = mgr_ft.newFace(mgr_rw.fromFile("/home/slice/.fonts/msgothic.ttc", "r", true), 2); // auto& f = fc.ref(); // f.setPixelSizes(0, 64); // f.setSizeFromLine(16); // f.prepareGlyph(U'𠀋', FTFace::RenderMode::Normal); // const auto& a = f.getGlyphInfo(); // // const void* data = a.data; // int pitch = a.pitch; // spn::ByteBuff buff; // if(a.nlevel == 2) { // buff = Convert1Bit_8Bit(data, a.width, pitch, a.height); // pitch *= 8; // data = &buff[0]; // } // buff = Convert8Bit_Packed24Bit(data, a.width, pitch, a.height); // auto sf = Surface::Create(std::move(buff), 0, a.width, a.height, Color::RGB8); // sf->saveAsPNG(mgr_rw.fromFile("/tmp/kusoge.png","w",true)); // auto& gi = f.getGlyphInfo(); // } // CCoreID id = gen.makeCoreID("MS Gothic", CCoreID(0, 16, 0, false, 0)); // HLText hlText = gen.createText(id, "HELLO,WORLD"); // MainThread と DrawThread 間のデータ置き場 struct Mth_DthData { rs::HLInput hlIk, hlIm; rs::HLAct actQuit, actButton, actLeft, actRight, actUp, actDown, actMoveX, actMoveY; rs::HLCam hlCam; }; #define shared (Mth_Dth::_ref()) class Mth_Dth : public spn::Singleton<Mth_Dth>, public rs::SpinLock<Mth_DthData> {}; class MyDraw : public rs::IDrawProc { rs::HLFx _hlFx; rs::HLVb _hlVb; rs::HLIb _hlIb; rs::HLTex _hlTex; public: MyDraw() { struct TmpV { spn::Vec3 pos; spn::Vec4 tex; }; TmpV tmpV[] = { { spn::Vec3{-1,-1,0}, spn::Vec4{0,1,0,0} }, { spn::Vec3{-1,1,0}, spn::Vec4{0,0,0,0} }, { spn::Vec3{1,1,0}, spn::Vec4{1,0,0,0} }, { spn::Vec3{1,-1,0}, spn::Vec4{1,1,0,0} } }; // インデックス定義 GLubyte tmpI[] = { 0,1,2, 2,3,0 }; mgr_rw.addUriHandler(rs::SPUriHandler(new rs::UriH_File(u8"/"))); _hlVb = mgr_gl.makeVBuffer(GL_STATIC_DRAW); _hlVb.ref()->use()->initData(tmpV, countof(tmpV), sizeof(TmpV)); _hlIb = mgr_gl.makeIBuffer(GL_STATIC_DRAW); _hlIb.ref()->use()->initData(tmpI, countof(tmpI)); _hlTex = mgr_gl.loadTexture(spn::URI("file:///home/slice/test.png")); _hlTex.ref()->use()->setFilter(rs::IGLTexture::MipmapLinear, true,true); rs::GPUInfo info; info.onDeviceReset(); std::cout << info; _hlFx = mgr_gl.loadEffect(spn::URI("file:///home/slice/test.glx")); auto& pFx = *_hlFx.ref(); GLint techID = pFx.getTechID("TheTech"); pFx.setTechnique(techID, true); GLint passID = pFx.getPassID("P0"); pFx.setPass(passID); // 頂点フォーマット定義 rs::SPVDecl decl(new rs::VDecl{ {0,0, GL_FLOAT, GL_FALSE, 3, (GLuint)rs::VSem::POSITION}, {0,12, GL_FLOAT, GL_FALSE, 4, (GLuint)rs::VSem::TEXCOORD0} }); pFx.setVDecl(std::move(decl)); pFx.setUniform(spn::Vec4{1,2,3,4}, pFx.getUniformID("lowVal")); _hlTex.ref()->save("/tmp/test.png"); rs::SetSwapInterval(1); } bool runU(uint64_t accum) override { glClearColor(0,0,1,1); glClearDepth(1.0f); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); int w = 640, h = 480; glViewport(0,0,w,h); auto* pFx = _hlFx.ref().get(); GLint id = pFx->getUniformID("mTrans"); auto lk = shared.lock(); constexpr float speed = 0.25f; float mvF=0, mvS=0; if(mgr_input.isKeyPressing(lk->actUp)) mvF += speed; if(mgr_input.isKeyPressing(lk->actDown)) mvF -= speed; if(mgr_input.isKeyPressing(lk->actLeft)) mvS -= speed; if(mgr_input.isKeyPressing(lk->actRight)) mvS += speed; float xv = mgr_input.getKeyValue(lk->actMoveX)/4.f, yv = mgr_input.getKeyValue(lk->actMoveY)/4.f; rs::CamData& cd = lk->hlCam.ref(); cd.addRot(spn::Quat::RotationY(spn::DEGtoRAD(-xv))); cd.addRot(spn::Quat::RotationX(spn::DEGtoRAD(-yv))); cd.moveFwd3D(mvF); cd.moveSide3D(mvS); cd.setFOV(spn::DEGtoRAD(60)); cd.setZPlane(0.01f, 100.f); cd.setAspect(float(w)/h); pFx->setUniform(cd.getViewProjMatrix().convert44(), id); id = pFx->getUniformID("tDiffuse"); pFx->setUniform(_hlTex, id); pFx->setVStream(_hlVb.get(), 0); pFx->setIStream(_hlIb.get()); pFx->drawIndexed(GL_TRIANGLES, 6, 0); return true; } }; class MyMain : public rs::IMainProc { Mth_Dth _mth; public: MyMain() { auto lk = shared.lock(); lk->hlIk = rs::Keyboard::OpenKeyboard(); lk->actQuit = mgr_input.addAction("quit"); mgr_input.link(lk->actQuit, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_ESCAPE)); lk->actButton = mgr_input.addAction("button"); mgr_input.link(lk->actQuit, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_LSHIFT)); lk->actLeft = mgr_input.addAction("left"); lk->actRight = mgr_input.addAction("right"); lk->actUp = mgr_input.addAction("up"); lk->actDown = mgr_input.addAction("down"); lk->actMoveX = mgr_input.addAction("moveX"); lk->actMoveY = mgr_input.addAction("moveY"); mgr_input.link(lk->actLeft, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_A)); mgr_input.link(lk->actRight, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_D)); mgr_input.link(lk->actUp, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_W)); mgr_input.link(lk->actDown, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_S)); lk->hlIm = rs::Mouse::OpenMouse(0); lk->hlIm.ref()->setMouseMode(rs::MouseMode::Relative); lk->hlIm.ref()->setDeadZone(0, 1.f, 0.f); lk->hlIm.ref()->setDeadZone(1, 1.f, 0.f); mgr_input.link(lk->actMoveX, rs::InF::AsAxis(lk->hlIm, 0)); mgr_input.link(lk->actMoveY, rs::InF::AsAxis(lk->hlIm, 1)); mgr_input.link(lk->actQuit, rs::InF::AsAxisNegative(lk->hlIm, 0)); lk->hlCam = mgr_cam.emplace(); rs::CamData& cd = lk->hlCam.ref(); cd.setOfs(0,0,-3); } bool runU() override { auto lk = shared.lock(); if(mgr_input.isKeyPressed(lk->actQuit)) return false; return true; } rs::IDrawProc* initDraw() override { return new MyDraw; } }; using namespace rs; int main(int argc, char **argv) { return GameLoop([](){ return new MyMain; }, "HelloSDL2", 640, 480, SDL_WINDOW_SHOWN, 2,0,24); } <commit_msg>テストコードの修正: ウィンドウサイズをハードコードじゃなくした<commit_after>#include "gameloop.hpp" #include "glhead.hpp" #include "input.hpp" #include "glresource.hpp" #include "spinner/vector.hpp" #include "gpu.hpp" #include "glx.hpp" #include "camera.hpp" // void test0() { // auto fc = mgr_ft.newFace(mgr_rw.fromFile("/home/slice/.fonts/msgothic.ttc", "r", true), 2); // auto& f = fc.ref(); // f.setPixelSizes(0, 64); // f.setSizeFromLine(16); // f.prepareGlyph(U'𠀋', FTFace::RenderMode::Normal); // const auto& a = f.getGlyphInfo(); // // const void* data = a.data; // int pitch = a.pitch; // spn::ByteBuff buff; // if(a.nlevel == 2) { // buff = Convert1Bit_8Bit(data, a.width, pitch, a.height); // pitch *= 8; // data = &buff[0]; // } // buff = Convert8Bit_Packed24Bit(data, a.width, pitch, a.height); // auto sf = Surface::Create(std::move(buff), 0, a.width, a.height, Color::RGB8); // sf->saveAsPNG(mgr_rw.fromFile("/tmp/kusoge.png","w",true)); // auto& gi = f.getGlyphInfo(); // } // CCoreID id = gen.makeCoreID("MS Gothic", CCoreID(0, 16, 0, false, 0)); // HLText hlText = gen.createText(id, "HELLO,WORLD"); // MainThread と DrawThread 間のデータ置き場 struct Mth_DthData { rs::HLInput hlIk, hlIm; rs::HLAct actQuit, actButton, actLeft, actRight, actUp, actDown, actMoveX, actMoveY; rs::HLCam hlCam; rs::SPWindow spWin; }; #define shared (Mth_Dth::_ref()) class Mth_Dth : public spn::Singleton<Mth_Dth>, public rs::SpinLock<Mth_DthData> {}; class MyDraw : public rs::IDrawProc { rs::HLFx _hlFx; rs::HLVb _hlVb; rs::HLIb _hlIb; rs::HLTex _hlTex; spn::Size _size; public: MyDraw() { struct TmpV { spn::Vec3 pos; spn::Vec4 tex; }; TmpV tmpV[] = { { spn::Vec3{-1,-1,0}, spn::Vec4{0,1,0,0} }, { spn::Vec3{-1,1,0}, spn::Vec4{0,0,0,0} }, { spn::Vec3{1,1,0}, spn::Vec4{1,0,0,0} }, { spn::Vec3{1,-1,0}, spn::Vec4{1,1,0,0} } }; // インデックス定義 GLubyte tmpI[] = { 0,1,2, 2,3,0 }; mgr_rw.addUriHandler(rs::SPUriHandler(new rs::UriH_File(u8"/"))); _hlVb = mgr_gl.makeVBuffer(GL_STATIC_DRAW); _hlVb.ref()->use()->initData(tmpV, countof(tmpV), sizeof(TmpV)); _hlIb = mgr_gl.makeIBuffer(GL_STATIC_DRAW); _hlIb.ref()->use()->initData(tmpI, countof(tmpI)); _hlTex = mgr_gl.loadTexture(spn::URI("file:///home/slice/test.png")); _hlTex.ref()->use()->setFilter(rs::IGLTexture::MipmapLinear, true,true); rs::GPUInfo info; info.onDeviceReset(); std::cout << info; _hlFx = mgr_gl.loadEffect(spn::URI("file:///home/slice/test.glx")); auto& pFx = *_hlFx.ref(); GLint techID = pFx.getTechID("TheTech"); pFx.setTechnique(techID, true); GLint passID = pFx.getPassID("P0"); pFx.setPass(passID); // 頂点フォーマット定義 rs::SPVDecl decl(new rs::VDecl{ {0,0, GL_FLOAT, GL_FALSE, 3, (GLuint)rs::VSem::POSITION}, {0,12, GL_FLOAT, GL_FALSE, 4, (GLuint)rs::VSem::TEXCOORD0} }); pFx.setVDecl(std::move(decl)); pFx.setUniform(spn::Vec4{1,2,3,4}, pFx.getUniformID("lowVal")); _hlTex.ref()->save("/tmp/test.png"); rs::SetSwapInterval(1); _size *= 0; auto lk = shared.lock(); auto& cd = lk->hlCam.ref(); cd.setFOV(spn::DEGtoRAD(60)); cd.setZPlane(0.01f, 500.f); } bool runU(uint64_t accum) override { glClearColor(0,0,1,1); glClearDepth(1.0f); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); auto lk = shared.lock(); auto& cd = lk->hlCam.ref(); auto sz = lk->spWin->getSize(); if(sz != _size) { _size = sz; cd.setAspect(float(_size.width)/_size.height); glViewport(0,0,_size.width, _size.height); } auto* pFx = _hlFx.ref().get(); GLint id = pFx->getUniformID("mTrans"); constexpr float speed = 0.25f; float mvF=0, mvS=0; if(mgr_input.isKeyPressing(lk->actUp)) mvF += speed; if(mgr_input.isKeyPressing(lk->actDown)) mvF -= speed; if(mgr_input.isKeyPressing(lk->actLeft)) mvS -= speed; if(mgr_input.isKeyPressing(lk->actRight)) mvS += speed; float xv = mgr_input.getKeyValue(lk->actMoveX)/4.f, yv = mgr_input.getKeyValue(lk->actMoveY)/4.f; cd.addRot(spn::Quat::RotationY(spn::DEGtoRAD(-xv))); cd.addRot(spn::Quat::RotationX(spn::DEGtoRAD(-yv))); cd.moveFwd3D(mvF); cd.moveSide3D(mvS); pFx->setUniform(cd.getViewProjMatrix().convert44(), id); id = pFx->getUniformID("tDiffuse"); pFx->setUniform(_hlTex, id); pFx->setVStream(_hlVb.get(), 0); pFx->setIStream(_hlIb.get()); pFx->drawIndexed(GL_TRIANGLES, 6, 0); return true; } }; class MyMain : public rs::IMainProc { Mth_Dth _mth; public: MyMain(const rs::SPWindow& sp) { auto lk = shared.lock(); lk->hlIk = rs::Keyboard::OpenKeyboard(); lk->spWin = sp; lk->actQuit = mgr_input.addAction("quit"); mgr_input.link(lk->actQuit, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_ESCAPE)); lk->actButton = mgr_input.addAction("button"); mgr_input.link(lk->actQuit, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_LSHIFT)); lk->actLeft = mgr_input.addAction("left"); lk->actRight = mgr_input.addAction("right"); lk->actUp = mgr_input.addAction("up"); lk->actDown = mgr_input.addAction("down"); lk->actMoveX = mgr_input.addAction("moveX"); lk->actMoveY = mgr_input.addAction("moveY"); mgr_input.link(lk->actLeft, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_A)); mgr_input.link(lk->actRight, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_D)); mgr_input.link(lk->actUp, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_W)); mgr_input.link(lk->actDown, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_S)); lk->hlIm = rs::Mouse::OpenMouse(0); lk->hlIm.ref()->setMouseMode(rs::MouseMode::Relative); lk->hlIm.ref()->setDeadZone(0, 1.f, 0.f); lk->hlIm.ref()->setDeadZone(1, 1.f, 0.f); mgr_input.link(lk->actMoveX, rs::InF::AsAxis(lk->hlIm, 0)); mgr_input.link(lk->actMoveY, rs::InF::AsAxis(lk->hlIm, 1)); mgr_input.link(lk->actQuit, rs::InF::AsAxisNegative(lk->hlIm, 0)); lk->hlCam = mgr_cam.emplace(); rs::CamData& cd = lk->hlCam.ref(); cd.setOfs(0,0,-3); } bool runU() override { auto lk = shared.lock(); if(mgr_input.isKeyPressed(lk->actQuit)) return false; return true; } rs::IDrawProc* initDraw() override { return new MyDraw; } }; using namespace rs; int main(int argc, char **argv) { return GameLoop([](const rs::SPWindow& sp){ return new MyMain(sp); }, "HelloSDL2", 1024, 768, SDL_WINDOW_SHOWN, 2,0,24); } <|endoftext|>
<commit_before>a6ecc4ae-2e4f-11e5-89ca-28cfe91dbc4b<commit_msg>a6f3930c-2e4f-11e5-9109-28cfe91dbc4b<commit_after>a6f3930c-2e4f-11e5-9109-28cfe91dbc4b<|endoftext|>
<commit_before>#include <stdio.h> int main(int ac, char **av) { printf("Hello, World\n"); } <commit_msg>Trying to fix git user settings. Deleted .gitconfig by accident.<commit_after>// fixing commit settings. #include <stdio.h> int main(int ac, char **av) { printf("Hello, World\n"); } <|endoftext|>
<commit_before>272a7f34-2f67-11e5-862d-6c40088e03e4<commit_msg>27323cec-2f67-11e5-ad9a-6c40088e03e4<commit_after>27323cec-2f67-11e5-ad9a-6c40088e03e4<|endoftext|>
<commit_before>5f8949c7-2d16-11e5-af21-0401358ea401<commit_msg>5f8949c8-2d16-11e5-af21-0401358ea401<commit_after>5f8949c8-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>917350d1-2e4f-11e5-8ea7-28cfe91dbc4b<commit_msg>917b8c02-2e4f-11e5-882e-28cfe91dbc4b<commit_after>917b8c02-2e4f-11e5-882e-28cfe91dbc4b<|endoftext|>
<commit_before>42262834-5216-11e5-b9cf-6c40088e03e4<commit_msg>42304594-5216-11e5-adf0-6c40088e03e4<commit_after>42304594-5216-11e5-adf0-6c40088e03e4<|endoftext|>
<commit_before>364048e3-ad5c-11e7-bc09-ac87a332f658<commit_msg>lets try again<commit_after>36e4bb5e-ad5c-11e7-926a-ac87a332f658<|endoftext|>
<commit_before>21d45314-2f67-11e5-9d72-6c40088e03e4<commit_msg>21db216e-2f67-11e5-99ae-6c40088e03e4<commit_after>21db216e-2f67-11e5-99ae-6c40088e03e4<|endoftext|>
<commit_before>37bb69cf-2e4f-11e5-a12f-28cfe91dbc4b<commit_msg>37c327d7-2e4f-11e5-88c7-28cfe91dbc4b<commit_after>37c327d7-2e4f-11e5-88c7-28cfe91dbc4b<|endoftext|>
<commit_before> #include <string> #include <iostream> #include <libdevcore/Common.h> #include <libdevcore/CommonData.h> #include <libdevcore/CommonIO.h> #include <libsolidity/Scanner.h> #include <libsolidity/Parser.h> #include <libsolidity/ASTPrinter.h> #include <libsolidity/NameAndTypeResolver.h> #include <libsolidity/Exceptions.h> #include <libsolidity/Compiler.h> #include <libsolidity/SourceReferenceFormatter.h> using namespace dev; using namespace solidity; void help() { std::cout << "Usage solc [OPTIONS] <file>" << std::endl << "Options:" << std::endl << " -h,--help Show this help message and exit." << std::endl << " -V,--version Show the version and exit." << std::endl; exit(0); } void version() { std::cout << "solc, the solidity complier commandline interface " << dev::Version << std::endl << " by Christian <c@ethdev.com>, (c) 2014." << std::endl << "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << std::endl; exit(0); } /// Helper class that extracts the first expression in an AST. class FirstExpressionExtractor: private ASTVisitor { public: FirstExpressionExtractor(ASTNode& _node): m_expression(nullptr) { _node.accept(*this); } Expression* getExpression() const { return m_expression; } private: virtual bool visit(Expression& _expression) override { return checkExpression(_expression); } virtual bool visit(Assignment& _expression) override { return checkExpression(_expression); } virtual bool visit(UnaryOperation& _expression) override { return checkExpression(_expression); } virtual bool visit(BinaryOperation& _expression) override { return checkExpression(_expression); } virtual bool visit(FunctionCall& _expression) override { return checkExpression(_expression); } virtual bool visit(MemberAccess& _expression) override { return checkExpression(_expression); } virtual bool visit(IndexAccess& _expression) override { return checkExpression(_expression); } virtual bool visit(PrimaryExpression& _expression) override { return checkExpression(_expression); } virtual bool visit(Identifier& _expression) override { return checkExpression(_expression); } virtual bool visit(ElementaryTypeNameExpression& _expression) override { return checkExpression(_expression); } virtual bool visit(Literal& _expression) override { return checkExpression(_expression); } bool checkExpression(Expression& _expression) { if (m_expression == nullptr) m_expression = &_expression; return false; } private: Expression* m_expression; }; int main(int argc, char** argv) { std::string infile; for (int i = 1; i < argc; ++i) { std::string arg = argv[i]; if (arg == "-h" || arg == "--help") help(); else if (arg == "-V" || arg == "--version") version(); else infile = argv[i]; } std::string sourceCode; if (infile.empty()) { std::string s; while (!std::cin.eof()) { getline(std::cin, s); sourceCode.append(s); } } else sourceCode = asString(dev::contents(infile)); ASTPointer<ContractDefinition> ast; std::shared_ptr<Scanner> scanner = std::make_shared<Scanner>(CharStream(sourceCode)); Parser parser; try { ast = parser.parse(scanner); } catch (ParserError const& exception) { SourceReferenceFormatter::printExceptionInformation(std::cerr, exception, "Parser error", *scanner); return -1; } dev::solidity::NameAndTypeResolver resolver; try { resolver.resolveNamesAndTypes(*ast.get()); } catch (DeclarationError const& exception) { SourceReferenceFormatter::printExceptionInformation(std::cerr, exception, "Declaration error", *scanner); return -1; } catch (TypeError const& exception) { SourceReferenceFormatter::printExceptionInformation(std::cerr, exception, "Type error", *scanner); return -1; } std::cout << "Syntax tree for the contract:" << std::endl; dev::solidity::ASTPrinter printer(ast, sourceCode); printer.print(std::cout); FirstExpressionExtractor extractor(*ast); CompilerContext context; ExpressionCompiler compiler(context); compiler.compile(*extractor.getExpression()); bytes instructions = compiler.getAssembledBytecode(); // debug std::cout << "Bytecode for the first expression: " << std::endl; std::cout << eth::disassemble(instructions) << std::endl; return 0; } <commit_msg>Asterisk-syntax for doxygen class documentation.<commit_after> #include <string> #include <iostream> #include <libdevcore/Common.h> #include <libdevcore/CommonData.h> #include <libdevcore/CommonIO.h> #include <libsolidity/Scanner.h> #include <libsolidity/Parser.h> #include <libsolidity/ASTPrinter.h> #include <libsolidity/NameAndTypeResolver.h> #include <libsolidity/Exceptions.h> #include <libsolidity/Compiler.h> #include <libsolidity/SourceReferenceFormatter.h> using namespace dev; using namespace solidity; void help() { std::cout << "Usage solc [OPTIONS] <file>" << std::endl << "Options:" << std::endl << " -h,--help Show this help message and exit." << std::endl << " -V,--version Show the version and exit." << std::endl; exit(0); } void version() { std::cout << "solc, the solidity complier commandline interface " << dev::Version << std::endl << " by Christian <c@ethdev.com>, (c) 2014." << std::endl << "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << std::endl; exit(0); } /** * Helper class that extracts the first expression in an AST. */ class FirstExpressionExtractor: private ASTVisitor { public: FirstExpressionExtractor(ASTNode& _node): m_expression(nullptr) { _node.accept(*this); } Expression* getExpression() const { return m_expression; } private: virtual bool visit(Expression& _expression) override { return checkExpression(_expression); } virtual bool visit(Assignment& _expression) override { return checkExpression(_expression); } virtual bool visit(UnaryOperation& _expression) override { return checkExpression(_expression); } virtual bool visit(BinaryOperation& _expression) override { return checkExpression(_expression); } virtual bool visit(FunctionCall& _expression) override { return checkExpression(_expression); } virtual bool visit(MemberAccess& _expression) override { return checkExpression(_expression); } virtual bool visit(IndexAccess& _expression) override { return checkExpression(_expression); } virtual bool visit(PrimaryExpression& _expression) override { return checkExpression(_expression); } virtual bool visit(Identifier& _expression) override { return checkExpression(_expression); } virtual bool visit(ElementaryTypeNameExpression& _expression) override { return checkExpression(_expression); } virtual bool visit(Literal& _expression) override { return checkExpression(_expression); } bool checkExpression(Expression& _expression) { if (m_expression == nullptr) m_expression = &_expression; return false; } private: Expression* m_expression; }; int main(int argc, char** argv) { std::string infile; for (int i = 1; i < argc; ++i) { std::string arg = argv[i]; if (arg == "-h" || arg == "--help") help(); else if (arg == "-V" || arg == "--version") version(); else infile = argv[i]; } std::string sourceCode; if (infile.empty()) { std::string s; while (!std::cin.eof()) { getline(std::cin, s); sourceCode.append(s); } } else sourceCode = asString(dev::contents(infile)); ASTPointer<ContractDefinition> ast; std::shared_ptr<Scanner> scanner = std::make_shared<Scanner>(CharStream(sourceCode)); Parser parser; try { ast = parser.parse(scanner); } catch (ParserError const& exception) { SourceReferenceFormatter::printExceptionInformation(std::cerr, exception, "Parser error", *scanner); return -1; } dev::solidity::NameAndTypeResolver resolver; try { resolver.resolveNamesAndTypes(*ast.get()); } catch (DeclarationError const& exception) { SourceReferenceFormatter::printExceptionInformation(std::cerr, exception, "Declaration error", *scanner); return -1; } catch (TypeError const& exception) { SourceReferenceFormatter::printExceptionInformation(std::cerr, exception, "Type error", *scanner); return -1; } std::cout << "Syntax tree for the contract:" << std::endl; dev::solidity::ASTPrinter printer(ast, sourceCode); printer.print(std::cout); FirstExpressionExtractor extractor(*ast); CompilerContext context; ExpressionCompiler compiler(context); compiler.compile(*extractor.getExpression()); bytes instructions = compiler.getAssembledBytecode(); // debug std::cout << "Bytecode for the first expression: " << std::endl; std::cout << eth::disassemble(instructions) << std::endl; return 0; } <|endoftext|>
<commit_before>/* Copyright (C) 2011 by Nurettin Onur TUĞCU (onur.tugcu@gmail.com) 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. */ /* Project: WinStream */ #include <iostream> #include <ostream> #include <string> int main() { std::cout<< "Adınız Nedir? "; std::string str; std::getline(std::cin,str); std::cout<< "Selâmü Aleyküm "<< str<< '\n'; } <commit_msg>added pause<commit_after>/* Copyright (C) 2011 by Nurettin Onur TUĞCU (onur.tugcu@gmail.com) 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. */ /* Project: WinStream */ #include <iostream> #include <ostream> #include <string> #include <windows.h> int main() { std::cout<< "Adınız Nedir? "; std::string str; std::getline(std::cin, str); std::cout<< "Selâmü Aleyküm "<< str<< '\n'; std::cin.get(); } <|endoftext|>
<commit_before>83000dbd-2d15-11e5-af21-0401358ea401<commit_msg>83000dbe-2d15-11e5-af21-0401358ea401<commit_after>83000dbe-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>1e0c2e30-585b-11e5-952a-6c40088e03e4<commit_msg>1e12d9c6-585b-11e5-a9d1-6c40088e03e4<commit_after>1e12d9c6-585b-11e5-a9d1-6c40088e03e4<|endoftext|>
<commit_before>72781e05-2e4f-11e5-aa26-28cfe91dbc4b<commit_msg>727e663a-2e4f-11e5-acd1-28cfe91dbc4b<commit_after>727e663a-2e4f-11e5-acd1-28cfe91dbc4b<|endoftext|>
<commit_before>f2b11cf0-585a-11e5-b785-6c40088e03e4<commit_msg>f2b768d2-585a-11e5-9233-6c40088e03e4<commit_after>f2b768d2-585a-11e5-9233-6c40088e03e4<|endoftext|>
<commit_before>dddf3da8-327f-11e5-b4bd-9cf387a8033e<commit_msg>dde5d991-327f-11e5-9286-9cf387a8033e<commit_after>dde5d991-327f-11e5-9286-9cf387a8033e<|endoftext|>
<commit_before>472b4f6c-5216-11e5-afe7-6c40088e03e4<commit_msg>4733ce94-5216-11e5-ad61-6c40088e03e4<commit_after>4733ce94-5216-11e5-ad61-6c40088e03e4<|endoftext|>
<commit_before>#include <algorithm> #include <fstream> #include <iostream> #include <string> #include <unordered_set> #include <vector> bool isIsogram(const std::string& word) { std::unordered_set<char> hash; for (auto c : word) if (!hash.insert(c).second || c == ' ') return false; return true; } bool compareString(const std::string& lhs, const std::string& rhs) { if (lhs.size() < rhs.size()) return true; if (rhs.size() < lhs.size()) return false; if (lhs < rhs) return true; if (rhs < lhs) return false; return false; } std::vector<std::string> extractFile(const std::string& fileName, const unsigned min, const unsigned max) { std::vector<std::string> list; std::ifstream file(fileName); if (file.is_open()) { for (std::string line; file >> line;) { std::transform(line.begin(), line.end(), line.begin(), tolower); if (isIsogram(line) && min <= line.size() && line.size() <= max) list.push_back(line); } } else throw std::runtime_error("Couldn't read from file"); file.close(); return list; } void outputFile(const std::vector<std::string>& vec, const std::string& fileName) { std::ofstream file(fileName); if (file.is_open()) { for (auto str : vec) file << str << std::endl; } else throw std::runtime_error("Couldn't write to file"); file.close(); } void process(const std::string& inFileName, const unsigned min = 4U, const unsigned max = 26U, const std::string& outFileName = "isograms.txt") { std::cout << "Extracting isograms from the word list..." << std::endl; std::vector<std::string>vec = extractFile(inFileName, min, max); std::cout << "Sorting the list..." << std::endl; std::sort(vec.begin(), vec.end(), compareString); std::cout << "Writing to file..." << std::endl; outputFile(vec, outFileName); std::cout << "Finished!" << std::endl; } int main(int argc, char** argv) { try { if (argc < 2) { std::cerr << "Too few arguments\n"; std::cerr << "Useage: Isogrammer.exe [inputfile] OPTIONAL: [minlength] [maxlength] [outputfile]\n"; std::cerr << "Example: Isogrammer.exe wordlist.txt 4 7 isograms.txt" << std::endl; return EXIT_FAILURE; } if (argc > 5) { std::cerr << "Too many arguments\n"; std::cerr << "Useage: Isogrammer.exe [inputfile] OPTIONAL: [minlength] [maxlength] [outputfile]\n"; std::cerr << "Example: Isogrammer.exe wordlist.txt 4 7 isograms.txt" << std::endl; return EXIT_FAILURE; } if (argc == 2) process(argv[1]); if (argc == 3) process(argv[1], std::stoi(argv[2])); if (argc == 4) process(argv[1], std::stoi(argv[2]), std::stoi(argv[3])); if (argc == 5) process(argv[1], std::stoi(argv[2]), std::stoi(argv[3]), argv[4]); } catch (std::exception& e) { std::cerr << "Process failed: " << e.what() << std::endl; return EXIT_FAILURE; } } <commit_msg>Changed std::vector to std::set so only unique words are added.<commit_after>#include <algorithm> #include <fstream> #include <iostream> #include <set> #include <string> #include <unordered_set> #include <vector> bool isIsogram(const std::string& word) { std::unordered_set<char> hash; for (auto c : word) if (!hash.insert(c).second || c == ' ') return false; return true; } struct compare { bool operator()(const std::string& lhs, const std::string& rhs) const { if (lhs.size() < rhs.size()) return true; if (rhs.size() < lhs.size()) return false; if (lhs < rhs) return true; if (rhs < lhs) return false; return false; } }; std::set<std::string, compare> extractFile(const std::string& fileName, const unsigned min, const unsigned max) { std::set<std::string, compare> list; std::ifstream file(fileName); if (file.is_open()) { for (std::string line; file >> line;) { std::transform(line.begin(), line.end(), line.begin(), tolower); if (isIsogram(line) && min <= line.size() && line.size() <= max) list.insert(line); } } else throw std::runtime_error("Couldn't read from file"); file.close(); return list; } void outputFile(const std::set<std::string, compare>& vec, const std::string& fileName) { std::ofstream file(fileName); if (file.is_open()) { for (auto str : vec) file << str << std::endl; } else throw std::runtime_error("Couldn't write to file"); file.close(); } void process(const std::string& inFileName, const unsigned min = 4U, const unsigned max = 26U, const std::string& outFileName = "isograms.txt") { std::cout << "Extracting isograms from the word list..." << std::endl; std::set<std::string, compare>vec = extractFile(inFileName, min, max); std::cout << "Sorting the list..." << std::endl; std::cout << "Writing to file..." << std::endl; outputFile(vec, outFileName); std::cout << "Finished!" << std::endl; } int main(int argc, char** argv) { try { if (argc < 2) { std::cerr << "Too few arguments\n"; std::cerr << "Useage: Isogrammer.exe [inputfile] OPTIONAL: [minlength] [maxlength] [outputfile]\n"; std::cerr << "Example: Isogrammer.exe wordlist.txt 4 7 isograms.txt" << std::endl; return EXIT_FAILURE; } if (argc > 5) { std::cerr << "Too many arguments\n"; std::cerr << "Useage: Isogrammer.exe [inputfile] OPTIONAL: [minlength] [maxlength] [outputfile]\n"; std::cerr << "Example: Isogrammer.exe wordlist.txt 4 7 isograms.txt" << std::endl; return EXIT_FAILURE; } if (argc == 2) process(argv[1]); if (argc == 3) process(argv[1], std::stoi(argv[2])); if (argc == 4) process(argv[1], std::stoi(argv[2]), std::stoi(argv[3])); if (argc == 5) process(argv[1], std::stoi(argv[2]), std::stoi(argv[3]), argv[4]); } catch (std::exception& e) { std::cerr << "Process failed: " << e.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>7953edb8-ad5a-11e7-9556-ac87a332f658<commit_msg>My Backup<commit_after>79d9ad19-ad5a-11e7-905a-ac87a332f658<|endoftext|>
<commit_before>5f8949c2-2d16-11e5-af21-0401358ea401<commit_msg>5f8949c3-2d16-11e5-af21-0401358ea401<commit_after>5f8949c3-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>2008dbd0-2f67-11e5-802f-6c40088e03e4<commit_msg>200fbe6c-2f67-11e5-a246-6c40088e03e4<commit_after>200fbe6c-2f67-11e5-a246-6c40088e03e4<|endoftext|>
<commit_before>ff273a91-2e4e-11e5-89af-28cfe91dbc4b<commit_msg>ff2daab0-2e4e-11e5-ab01-28cfe91dbc4b<commit_after>ff2daab0-2e4e-11e5-ab01-28cfe91dbc4b<|endoftext|>
<commit_before>78d71276-5216-11e5-a508-6c40088e03e4<commit_msg>78ddb1c8-5216-11e5-826a-6c40088e03e4<commit_after>78ddb1c8-5216-11e5-826a-6c40088e03e4<|endoftext|>
<commit_before>a6f2225e-4b02-11e5-b645-28cfe9171a43<commit_msg>testing<commit_after>a6fd0733-4b02-11e5-ac41-28cfe9171a43<|endoftext|>
<commit_before>73b8ad11-2e4f-11e5-9718-28cfe91dbc4b<commit_msg>73c0b2dc-2e4f-11e5-acaa-28cfe91dbc4b<commit_after>73c0b2dc-2e4f-11e5-acaa-28cfe91dbc4b<|endoftext|>
<commit_before>/** * math.cpp - I got tired of writing flash cards over and over, * and my son was quite distracted by all the flashy math games. * I suspect he was paying far more attention to the graphics than * he was the math. I built this and it was almost an instant hit and * he seems to be getting far faster with his arithmetic. I'll eventually * clean up the code if he sticks to it. I wrote this in about 10 minutes * so it's fairly basic and well....by my standards quite messy, so * please excuse. * * @author: Jonathan Beard * @version: Sun Oct 25 16:58:29 2015 * * Copyright 2015 Jonathan Beard * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include <cstdlib> #include <cstdint> #include <array> #include <random> #include <unistd.h> #include <sstream> #include <fstream> #include <chrono> #include <functional> #include <cassert> /** if you don't have this one, grab CmdArgs from my repo **/ #include <cmd> #include <signal.h> #include <unistd.h> #include <iomanip> /** unfortunate, but sig handler so...**/ static std::ofstream userlog; static double fraction_correct = 0.0; static void sig_handler( int sig ) { if( userlog.is_open() ) { userlog << std::flush; userlog.close(); } std::cout << "\n\n"; std::cout << "Your % correct is: " << std::setprecision( 5 ) << fraction_correct << std::endl; //just in case we interrupted the say cmd unlink( "/tmp/speach" ); exit( EXIT_SUCCESS ); } class problem { public: problem( std::ostream &logstream ) : output_stream( std::cout ), logstream( logstream ) { } virtual ~problem() = default; virtual bool run( const std::int64_t a, const std::int64_t b ) = 0; virtual bool constrain( const std::int64_t a, const std::int64_t b ) { return( true ); } protected: /** vars **/ const std::string what = { "What does: " }; std::ostream &output_stream; std::ostream &logstream; /** funcs **/ static std::string make_prob( const std::int64_t a, const std::int64_t b, const std::string &op ) { return( std::to_string( a ) + " " + op + " " + std::to_string( b ) ); } static void do_speech( const std::string str ) { std::ofstream ofs( "/tmp/speach" ); ofs << str; ofs.close(); system( "say -f /tmp/speach" ); unlink( "/tmp/speach" ); return; } /** * check_ans - check the ans against the key. If they match * then return true, else false. If the answer is correct * then say it's correct, else say try again. * @param ans - const T&, answer given by user * @param key - const T&, supplied correct answer * @return bool, true if correct */ template < typename T, typename std::enable_if< std::is_fundamental< T >::value >::type* = nullptr > bool check_ans( const T &ans, const T &key ) { if( ans == key ) { const auto goodstr( std::to_string( ans ) + " is correct, GOOD JOB!!" ); output_stream << goodstr << std::endl; do_speech( goodstr ); return( true ); } const auto badstr( std::to_string( ans ) + " is incorrect, lets try another" ); output_stream << badstr << std::endl; do_speech( badstr ); return( false ); } /** * ask_prob - asks the problem from the user via * output_stream and via speech. * @param prob - const std::string&, problem to ask about */ void ask_prob( const std::string &prob ) { output_stream << what << prob << " = " << std::flush; } }; /** end problem **/ class board { public: board( const std::int64_t min, const std::int64_t max ) : gen( std::chrono::system_clock::now().time_since_epoch().count() ), min( min ), max( max ) { } virtual ~board() { for( auto *ptr : probs ) { delete( ptr ); } } void add( problem * const p ) { assert( p != nullptr ); probs.push_back( p ); } void operator ()() { /** pick random type **/ problem *p( nullptr ); if( probs.size() == 1 ) { p = probs[ 0 ]; } else { std::uniform_int_distribution< std::uint32_t > type_index( 0, probs.size() - 1 ); p = probs[ type_index( gen ) ]; } assert( p != nullptr ); /** feed random numbers **/ std::uniform_int_distribution< std::int64_t > num_gen( min, max ); auto num_a( num_gen( gen ) ); auto num_b( num_gen( gen ) ); while( ! p->constrain( num_a, num_b ) ) { num_a = num_gen( gen ); num_b = num_gen( gen ); } count++; if( p->run( num_a, num_b ) ) { correct++; } } std::uint32_t getCount() { return( count ); } double getPercentageCorrect() { if( count == 0 ) { return( 0.0 ); } else { return( ( (double)correct / (double)count ) * 100.00 ); } } private: std::vector< problem* > probs; std::default_random_engine gen; const std::int64_t min; const std::int64_t max; std::uint32_t correct = 0; std::uint32_t count = 0; }; class add : public problem { public: add( std::ostream &logstream ) : problem( logstream ){} virtual bool run( const std::int64_t a, const std::int64_t b ) { const auto prob( make_prob( a, b, "+" ) ); const auto key( a + b ); ask_prob( prob ); do_speech( what + prob + " equal" ); std::int64_t ans( 0 ); std::cin >> ans; if( check_ans( ans, key ) ) { if( logstream.good() ) { logstream << "correct, " << prob << ", " << ans << std::endl; } return( true ); } else { if( logstream.good() ) { logstream << "incorrect, " << prob << ", " << ans << std::endl; } return( false ); } } }; class sub : public problem { public: sub( std::ostream &logstream, const bool noneg ) : problem ( logstream ), noneg( noneg ){} virtual bool constrain( const std::int64_t a, const std::int64_t b ) { if( noneg ) { if( b > a ) { return( false ); } } return( true ); } virtual bool run( const std::int64_t a, const std::int64_t b ) { const auto prob( make_prob( a, b, "-" ) ); const auto prob_spoken( make_prob( a, b, "minus" ) ); const auto key( a - b ); ask_prob( prob ); do_speech( what + prob_spoken + " equal" ); std::int64_t ans( 0 ); std::cin >> ans; if( check_ans( ans, key ) ) { if( logstream.good() ) { logstream << "correct, " << prob << ", " << ans << std::endl; } return( true ); } else { if( logstream.good() ) { logstream << "incorrect, " << prob << ", " << ans << std::endl; } return( false ); } } private: const bool noneg; }; //add op selector via cmd line args int main( int argc, char **argv ) { if( signal( SIGINT, sig_handler ) == SIG_ERR ) { perror( "Failed to set signal handler, exiting!" ); exit( EXIT_FAILURE ); } bool addition( true ); bool subtraction( false ); bool multiplication( false ); bool help( false ); std::int64_t max( 9 ); std::int64_t min( -9 ); std::int64_t num_problems( 20 ); double frac_to_exit( .75 ); bool noneg( false ); std::string logfile( "" ); CmdArgs cmd( argv[ 0 ], std::cout, std::cerr ); cmd.addOption( new Option< bool >( addition, "-add", "Include addition problems" ) ); cmd.addOption( new Option< bool >( subtraction, "-sub", "Include subtraction problems" ) ); cmd.addOption( new Option< bool >( multiplication, "-mult", "Include multiplication problems" ) ); cmd.addOption( new Option< std::int64_t >( num_problems, "-number", "Set total number of problems" ) ); cmd.addOption( new Option< double >( frac_to_exit, "-frac_success", "Set fraction .xx to get correct before exiting" ) ); cmd.addOption( new Option< std::int64_t >( min, "-min", "Set minimum digit to use" ) ); cmd.addOption( new Option< std::int64_t >( max, "-max", "Set maximum digit to use" ) ); cmd.addOption( new Option< std::string >( logfile, "-log", "Set a log file, .csv extension added by default" ) ); cmd.addOption( new Option< bool >( help, "-h", "Print menu and exit" ) ); cmd.addOption( new Option< bool >( noneg, "-noneg", "prevent the user from getting negative numbers" ) ); cmd.processArgs( argc, argv ); if( help ) { cmd.printArgs(); std::exit( EXIT_SUCCESS ); } /** open logfile **/ if( logfile.length() > 0 ) { /** log is global **/ userlog.open( logfile + ".csv" ); } board blackboard( min, max ); if( addition ) { blackboard.add( new add( userlog ) ); } if( subtraction ) { blackboard.add( new sub( userlog, noneg ) ); } while( blackboard.getCount() < num_problems or fraction_correct < frac_to_exit ) { blackboard(); fraction_correct = blackboard.getPercentageCorrect(); } if( userlog.is_open() ) { userlog.close(); } return( EXIT_SUCCESS ); } <commit_msg>updates<commit_after>/** * math.cpp - I got tired of writing flash cards over and over, * and my son was quite distracted by all the flashy math games. * I suspect he was paying far more attention to the graphics than * he was the math. I built this and it was almost an instant hit and * he seems to be getting far faster with his arithmetic. I'll eventually * clean up the code if he sticks to it. I wrote this in about 10 minutes * so it's fairly basic and well....by my standards quite messy, so * please excuse. * * @author: Jonathan Beard * @version: Sun Oct 25 16:58:29 2015 * * Copyright 2015 Jonathan Beard * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include <cstdlib> #include <cstdint> #include <iomanip> #include <array> #include <random> #include <unistd.h> #include <sstream> #include <fstream> #include <chrono> #include <functional> #include <cassert> /** if you don't have this one, grab CmdArgs from my repo **/ #include <cmd> #include <signal.h> #include <unistd.h> #include <iomanip> #include <thread> /** unfortunate, but sig handler so...**/ static std::ofstream userlog; static double fraction_correct = 0.0; decltype( std::chrono::system_clock::now() ) start; static void sig_handler( int sig ) { if( userlog.is_open() ) { userlog << std::flush; userlog.close(); } std::cout << "\n\n"; std::cout << "Your % correct is: " << std::setprecision( 5 ) << fraction_correct << std::endl; //just in case we interrupted the say cmd unlink( "/tmp/speach" ); exit( EXIT_SUCCESS ); } class problem { public: problem( std::ostream &logstream ) : output_stream( std::cout ), logstream( logstream ) { } virtual ~problem() = default; virtual bool run( const std::int64_t a, const std::int64_t b ) = 0; virtual bool constrain( const std::int64_t a, const std::int64_t b ) { return( true ); } protected: /** vars **/ const std::string what = { "What does: " }; std::ostream &output_stream; std::ostream &logstream; /** funcs **/ static std::string make_prob( const std::int64_t a, const std::int64_t b, const std::string &op ) { return( std::to_string( a ) + " " + op + " " + std::to_string( b ) ); } static void do_speech( const std::string str ) { std::ofstream ofs( "/tmp/speach" ); ofs << str; ofs.close(); system( "say -f /tmp/speach" ); unlink( "/tmp/speach" ); return; } /** * check_ans - check the ans against the key. If they match * then return true, else false. If the answer is correct * then say it's correct, else say try again. * @param ans - const T&, answer given by user * @param key - const T&, supplied correct answer * @return bool, true if correct */ template < typename T, typename std::enable_if< std::is_fundamental< T >::value >::type* = nullptr > bool check_ans( const T &ans, const T &key ) { auto end = std::chrono::system_clock::now(); std::chrono::duration< double > diff = end-start; if( ans == key ) { std::stringstream ss; ss << ans << " is correct in " << std::setprecision(2) << diff.count() << " seconds , GOOD JOB!!" << std::endl; output_stream << ss.str() << "\n"; do_speech( ss.str() ); return( true ); } std::stringstream ss; ss << ans << " is incorrect in " << std::setprecision( 2 ) << diff.count() << " seconds, lets maybe try another" << std::endl; output_stream << ss.str() << "\n"; do_speech( ss.str() ); return( false ); } /** * ask_prob - asks the problem from the user via * output_stream and via speech. * @param prob - const std::string&, problem to ask about */ void ask_prob( const std::string &prob ) { output_stream << what << prob << " = " << std::flush; } }; /** end problem **/ class board { public: board( const std::int64_t min, const std::int64_t max ) : gen( std::chrono::system_clock::now().time_since_epoch().count() ), min( min ), max( max ) { } virtual ~board() { for( auto *ptr : probs ) { delete( ptr ); } } void add( problem * const p ) { assert( p != nullptr ); probs.push_back( p ); } void operator ()() { /** pick random type **/ problem *p( nullptr ); if( probs.size() == 1 ) { p = probs[ 0 ]; } else { std::uniform_int_distribution< std::uint32_t > type_index( 0, probs.size() - 1 ); p = probs[ type_index( gen ) ]; } assert( p != nullptr ); /** feed random numbers **/ std::uniform_int_distribution< std::int64_t > num_gen( min, max ); auto num_a( num_gen( gen ) ); auto num_b( num_gen( gen ) ); while( ! p->constrain( num_a, num_b ) ) { num_a = num_gen( gen ); num_b = num_gen( gen ); } count++; auto function([&]( const std::int64_t numA, const std::int64_t numB ) -> void { if( p->run( numA, numB ) ) { correct++; } return; } ); start = std::chrono::system_clock::now(); std::thread th( function, num_a, num_b ); //FIXME, come back here th.join(); } std::uint32_t getCount() { return( count ); } double getPercentageCorrect() { if( count == 0 ) { return( 0.0 ); } else { return( ( (double)correct / (double)count ) * 100.00 ); } } private: std::vector< problem* > probs; std::default_random_engine gen; const std::int64_t min; const std::int64_t max; std::uint32_t correct = 0; std::uint32_t count = 0; }; class add : public problem { public: add( std::ostream &logstream ) : problem( logstream ){} virtual bool run( const std::int64_t a, const std::int64_t b ) { const auto prob( make_prob( a, b, "+" ) ); const auto key( a + b ); ask_prob( prob ); do_speech( what + prob + " equal" ); std::int64_t ans( 0 ); std::cin >> ans; if( check_ans( ans, key ) ) { if( logstream.good() ) { logstream << "correct, " << prob << ", " << ans << std::endl; } return( true ); } else { if( logstream.good() ) { logstream << "incorrect, " << prob << ", " << ans << std::endl; } return( false ); } } }; class sub : public problem { public: sub( std::ostream &logstream, const bool noneg ) : problem ( logstream ), noneg( noneg ){} virtual bool constrain( const std::int64_t a, const std::int64_t b ) { if( noneg ) { if( b > a ) { return( false ); } } return( true ); } virtual bool run( const std::int64_t a, const std::int64_t b ) { const auto prob( make_prob( a, b, "-" ) ); const auto prob_spoken( make_prob( a, b, "minus" ) ); const auto key( a - b ); ask_prob( prob ); do_speech( what + prob_spoken + " equal" ); std::int64_t ans( 0 ); std::cin >> ans; if( check_ans( ans, key ) ) { if( logstream.good() ) { logstream << "correct, " << prob << ", " << ans << std::endl; } return( true ); } else { if( logstream.good() ) { logstream << "incorrect, " << prob << ", " << ans << std::endl; } return( false ); } } private: const bool noneg; }; //add op selector via cmd line args int main( int argc, char **argv ) { if( signal( SIGINT, sig_handler ) == SIG_ERR ) { perror( "Failed to set signal handler, exiting!" ); exit( EXIT_FAILURE ); } bool addition( true ); bool subtraction( false ); bool multiplication( false ); bool help( false ); std::int64_t max( 9 ); std::int64_t min( -9 ); std::int64_t num_problems( 20 ); double frac_to_exit( .75 ); bool noneg( false ); std::string logfile( "" ); CmdArgs cmd( argv[ 0 ], std::cout, std::cerr ); cmd.addOption( new Option< bool >( addition, "-add", "Include addition problems" ) ); cmd.addOption( new Option< bool >( subtraction, "-sub", "Include subtraction problems" ) ); cmd.addOption( new Option< bool >( multiplication, "-mult", "Include multiplication problems" ) ); cmd.addOption( new Option< std::int64_t >( num_problems, "-number", "Set total number of problems" ) ); cmd.addOption( new Option< double >( frac_to_exit, "-frac_success", "Set fraction .xx to get correct before exiting" ) ); cmd.addOption( new Option< std::int64_t >( min, "-min", "Set minimum digit to use" ) ); cmd.addOption( new Option< std::int64_t >( max, "-max", "Set maximum digit to use" ) ); cmd.addOption( new Option< std::string >( logfile, "-log", "Set a log file, .csv extension added by default" ) ); cmd.addOption( new Option< bool >( help, "-h", "Print menu and exit" ) ); cmd.addOption( new Option< bool >( noneg, "-noneg", "prevent the user from getting negative numbers" ) ); cmd.processArgs( argc, argv ); if( help ) { cmd.printArgs(); std::exit( EXIT_SUCCESS ); } /** open logfile **/ if( logfile.length() > 0 ) { /** log is global **/ userlog.open( logfile + ".csv" ); } board blackboard( min, max ); if( addition ) { blackboard.add( new add( userlog ) ); } if( subtraction ) { blackboard.add( new sub( userlog, noneg ) ); } while( blackboard.getCount() < num_problems || fraction_correct < frac_to_exit ) { blackboard(); fraction_correct = blackboard.getPercentageCorrect(); } if( userlog.is_open() ) { userlog.close(); } return( EXIT_SUCCESS ); } <|endoftext|>
<commit_before>// @(#)root/base:$Id$ // Author: Philippe Canal 13/05/2003 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun, Fons Rademakers and al. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ //////////////////////////////////////////////////////////////////////////// // // // TBranchProxyDirector // // // // This class is used to 'drive' and hold a serie of TBranchProxy objects // // which represent and give access to the content of TTree object. // // This is intended to be used as part of a generate Selector class // // which will hold the directory and its associate // // // //////////////////////////////////////////////////////////////////////////// #include "TBranchProxyDirector.h" #include "TBranchProxy.h" #include "TFriendProxy.h" #include "TTree.h" #include "TEnv.h" #include "TH1F.h" #include "TPad.h" #include "TList.h" #include <algorithm> namespace std {} using namespace std; ClassImp(ROOT::TBranchProxyDirector); namespace ROOT { // Helper function to call Reset on each TBranchProxy void Reset(TBranchProxy *x) { x->Reset(); } // Helper function to call SetReadEntry on all TFriendProxy void ResetReadEntry(TFriendProxy *x) { x->ResetReadEntry(); } // Helper class to call Update on all TFriendProxy struct Update { Update(TTree *newtree) : fNewTree(newtree) {} TTree *fNewTree; void operator()(TFriendProxy *x) { x->Update(fNewTree); } }; TBranchProxyDirector::TBranchProxyDirector(TTree* tree, Long64_t i) : fTree(tree), fEntry(i) { // Simple constructor } TBranchProxyDirector::TBranchProxyDirector(TTree* tree, Int_t i) : // cint has a problem casting int to long long fTree(tree), fEntry(i) { // Simple constructor } void TBranchProxyDirector::Attach(TBranchProxy* p) { // Attach a TBranchProxy object to this director. The director just // 'remembers' this BranchProxy and does not own it. It will be use // to apply Tree wide operation (like reseting). fDirected.push_back(p); } void TBranchProxyDirector::Attach(TFriendProxy* p) { // Attach a TFriendProxy object to this director. The director just // 'remembers' this BranchProxy and does not own it. It will be use // to apply Tree wide operation (like reseting). fFriends.push_back(p); } TH1F* TBranchProxyDirector::CreateHistogram(const char *options) { // Create a temporary 1D histogram. Int_t nbins = gEnv->GetValue("Hist.Binning.1D.x",100); Double_t vmin=0, vmax=0; Double_t xmin=0, xmax=0; Bool_t canRebin = kFALSE; TString opt( options ); Bool_t optSame = opt.Contains("same"); if (gPad && optSame) { TListIter np(gPad->GetListOfPrimitives()); TObject *op; TH1 *oldhtemp = 0; while ((op = np()) && !oldhtemp) { if (op->InheritsFrom(TH1::Class())) oldhtemp = (TH1 *)op; } if (oldhtemp) { nbins = oldhtemp->GetXaxis()->GetNbins(); vmin = oldhtemp->GetXaxis()->GetXmin(); vmax = oldhtemp->GetXaxis()->GetXmax(); } else { vmin = gPad->GetUxmin(); vmax = gPad->GetUxmax(); } } else { vmin = xmin; vmax = xmax; if (xmin < xmax) canRebin = kFALSE; } TH1F *hist = new TH1F("htemp","htemp",nbins,vmin,vmax); hist->SetLineColor(fTree->GetLineColor()); hist->SetLineWidth(fTree->GetLineWidth()); hist->SetLineStyle(fTree->GetLineStyle()); hist->SetFillColor(fTree->GetFillColor()); hist->SetFillStyle(fTree->GetFillStyle()); hist->SetMarkerStyle(fTree->GetMarkerStyle()); hist->SetMarkerColor(fTree->GetMarkerColor()); hist->SetMarkerSize(fTree->GetMarkerSize()); if (canRebin) hist->SetBit(TH1::kCanRebin); hist->GetXaxis()->SetTitle("var"); hist->SetBit(kCanDelete); hist->SetDirectory(0); if (opt.Length() && opt.Contains("e")) hist->Sumw2(); return hist; } void TBranchProxyDirector::SetReadEntry(Long64_t entry) { // move to a new entry to read fEntry = entry; if (!fFriends.empty()) { for_each(fFriends.begin(),fFriends.end(),ResetReadEntry); } } TTree* TBranchProxyDirector::SetTree(TTree *newtree) { // Set the BranchProxy to be looking at a new tree. // Reset all. // Return the old tree. TTree* oldtree = fTree; fTree = newtree; fEntry = -1; //if (fInitialized) fInitialized = setup(); //fprintf(stderr,"calling SetTree for %p\n",this); for_each(fDirected.begin(),fDirected.end(),Reset); Update update(fTree); for_each(fFriends.begin(),fFriends.end(),update); return oldtree; } } // namespace ROOT <commit_msg>Fix cov 11532 (deadcode) by turning on the auto-rebinning of the default histogram in MakeProxy<commit_after>// @(#)root/base:$Id$ // Author: Philippe Canal 13/05/2003 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun, Fons Rademakers and al. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ //////////////////////////////////////////////////////////////////////////// // // // TBranchProxyDirector // // // // This class is used to 'drive' and hold a serie of TBranchProxy objects // // which represent and give access to the content of TTree object. // // This is intended to be used as part of a generate Selector class // // which will hold the directory and its associate // // // //////////////////////////////////////////////////////////////////////////// #include "TBranchProxyDirector.h" #include "TBranchProxy.h" #include "TFriendProxy.h" #include "TTree.h" #include "TEnv.h" #include "TH1F.h" #include "TPad.h" #include "TList.h" #include <algorithm> namespace std {} using namespace std; ClassImp(ROOT::TBranchProxyDirector); namespace ROOT { // Helper function to call Reset on each TBranchProxy void Reset(TBranchProxy *x) { x->Reset(); } // Helper function to call SetReadEntry on all TFriendProxy void ResetReadEntry(TFriendProxy *x) { x->ResetReadEntry(); } // Helper class to call Update on all TFriendProxy struct Update { Update(TTree *newtree) : fNewTree(newtree) {} TTree *fNewTree; void operator()(TFriendProxy *x) { x->Update(fNewTree); } }; TBranchProxyDirector::TBranchProxyDirector(TTree* tree, Long64_t i) : fTree(tree), fEntry(i) { // Simple constructor } TBranchProxyDirector::TBranchProxyDirector(TTree* tree, Int_t i) : // cint has a problem casting int to long long fTree(tree), fEntry(i) { // Simple constructor } void TBranchProxyDirector::Attach(TBranchProxy* p) { // Attach a TBranchProxy object to this director. The director just // 'remembers' this BranchProxy and does not own it. It will be use // to apply Tree wide operation (like reseting). fDirected.push_back(p); } void TBranchProxyDirector::Attach(TFriendProxy* p) { // Attach a TFriendProxy object to this director. The director just // 'remembers' this BranchProxy and does not own it. It will be use // to apply Tree wide operation (like reseting). fFriends.push_back(p); } TH1F* TBranchProxyDirector::CreateHistogram(const char *options) { // Create a temporary 1D histogram. Int_t nbins = gEnv->GetValue("Hist.Binning.1D.x",100); Double_t vmin=0, vmax=0; Double_t xmin=0, xmax=0; Bool_t canRebin = kTRUE; TString opt( options ); Bool_t optSame = opt.Contains("same"); if (optSame) canRebin = kFALSE; if (gPad && optSame) { TListIter np(gPad->GetListOfPrimitives()); TObject *op; TH1 *oldhtemp = 0; while ((op = np()) && !oldhtemp) { if (op->InheritsFrom(TH1::Class())) oldhtemp = (TH1 *)op; } if (oldhtemp) { nbins = oldhtemp->GetXaxis()->GetNbins(); vmin = oldhtemp->GetXaxis()->GetXmin(); vmax = oldhtemp->GetXaxis()->GetXmax(); } else { vmin = gPad->GetUxmin(); vmax = gPad->GetUxmax(); } } else { vmin = xmin; vmax = xmax; if (xmin < xmax) canRebin = kFALSE; } TH1F *hist = new TH1F("htemp","htemp",nbins,vmin,vmax); hist->SetLineColor(fTree->GetLineColor()); hist->SetLineWidth(fTree->GetLineWidth()); hist->SetLineStyle(fTree->GetLineStyle()); hist->SetFillColor(fTree->GetFillColor()); hist->SetFillStyle(fTree->GetFillStyle()); hist->SetMarkerStyle(fTree->GetMarkerStyle()); hist->SetMarkerColor(fTree->GetMarkerColor()); hist->SetMarkerSize(fTree->GetMarkerSize()); if (canRebin) hist->SetBit(TH1::kCanRebin); hist->GetXaxis()->SetTitle("var"); hist->SetBit(kCanDelete); hist->SetDirectory(0); if (opt.Length() && opt.Contains("e")) hist->Sumw2(); return hist; } void TBranchProxyDirector::SetReadEntry(Long64_t entry) { // move to a new entry to read fEntry = entry; if (!fFriends.empty()) { for_each(fFriends.begin(),fFriends.end(),ResetReadEntry); } } TTree* TBranchProxyDirector::SetTree(TTree *newtree) { // Set the BranchProxy to be looking at a new tree. // Reset all. // Return the old tree. TTree* oldtree = fTree; fTree = newtree; fEntry = -1; //if (fInitialized) fInitialized = setup(); //fprintf(stderr,"calling SetTree for %p\n",this); for_each(fDirected.begin(),fDirected.end(),Reset); Update update(fTree); for_each(fFriends.begin(),fFriends.end(),update); return oldtree; } } // namespace ROOT <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2019-2020 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <modules/python3/pythonprocessorfolderobserver.h> #include <modules/python3/pythonprocessorfactoryobject.h> #include <inviwo/core/common/inviwoapplication.h> #include <inviwo/core/util/filesystem.h> #include <algorithm> namespace inviwo { PythonProcessorFolderObserver::PythonProcessorFolderObserver(InviwoApplication* app, const std::string& directory, InviwoModule& module) : FileObserver(app), app_(app), directory_{directory}, module_{module} { if (filesystem::directoryExists(directory)) { const auto files = filesystem::getDirectoryContents(directory); for (const auto& file : files) { if (filesystem::getFileExtension(file) == "py") { if (!registerFile(directory + "/" + file)) { startFileObservation(directory_ + "/" + file); } } } } startFileObservation(directory); } bool PythonProcessorFolderObserver::registerFile(const std::string& filename) { const auto isEmpty = [](const std::string& file) { auto ifs = filesystem::ifstream(file); ifs.seekg(0, std::ios::end); return ifs.tellg() == std::streampos(0); }; if (std::count(registeredFiles_.begin(), registeredFiles_.end(), filename) == 0) { if (!filesystem::fileExists(filename)) return false; if (isEmpty(filename)) return false; try { auto pfo = std::make_unique<PythonProcessorFactoryObject>(app_, filename); module_.registerProcessor(std::move(pfo)); registeredFiles_.push_back(filename); return true; } catch (const std::exception& e) { LogError(e.what()); } } return false; } void PythonProcessorFolderObserver::fileChanged(const std::string& changed) { if (changed == directory_) { if (filesystem::directoryExists(directory_)) { auto files = filesystem::getDirectoryContents(directory_); for (const auto& file : files) { if (isObserved(directory_ + "/" + file)) continue; if (filesystem::getFileExtension(file) != "py") continue; if (registerFile(directory_ + "/" + file)) { LogInfo("Loaded python processor: " << directory_ + "/" + file); stopFileObservation(directory_ + "/" + file); } else { startFileObservation(directory_ + "/" + file); } } } } else { if (filesystem::getFileExtension(changed) == "py") { if (registerFile(changed)) { LogInfo("Loaded python processor: " << directory_ + "/" + changed); stopFileObservation(directory_ + "/" + changed); } } } } } // namespace inviwo <commit_msg>Python: Relax message, warn instead of error<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2019-2020 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <modules/python3/pythonprocessorfolderobserver.h> #include <modules/python3/pythonprocessorfactoryobject.h> #include <inviwo/core/common/inviwoapplication.h> #include <inviwo/core/util/filesystem.h> #include <algorithm> namespace inviwo { PythonProcessorFolderObserver::PythonProcessorFolderObserver(InviwoApplication* app, const std::string& directory, InviwoModule& module) : FileObserver(app), app_(app), directory_{directory}, module_{module} { if (filesystem::directoryExists(directory)) { const auto files = filesystem::getDirectoryContents(directory); for (const auto& file : files) { if (filesystem::getFileExtension(file) == "py") { if (!registerFile(directory + "/" + file)) { startFileObservation(directory_ + "/" + file); } } } } startFileObservation(directory); } bool PythonProcessorFolderObserver::registerFile(const std::string& filename) { const auto isEmpty = [](const std::string& file) { auto ifs = filesystem::ifstream(file); ifs.seekg(0, std::ios::end); return ifs.tellg() == std::streampos(0); }; if (std::count(registeredFiles_.begin(), registeredFiles_.end(), filename) == 0) { if (!filesystem::fileExists(filename)) return false; if (isEmpty(filename)) return false; try { auto pfo = std::make_unique<PythonProcessorFactoryObject>(app_, filename); module_.registerProcessor(std::move(pfo)); registeredFiles_.push_back(filename); return true; } catch (const Exception& e) { util::log(e.getContext(), e.getMessage(), LogLevel::Warn); } catch (const std::exception& e) { LogWarn(e.what()); } } return false; } void PythonProcessorFolderObserver::fileChanged(const std::string& changed) { if (changed == directory_) { if (filesystem::directoryExists(directory_)) { auto files = filesystem::getDirectoryContents(directory_); for (const auto& file : files) { if (isObserved(directory_ + "/" + file)) continue; if (filesystem::getFileExtension(file) != "py") continue; if (registerFile(directory_ + "/" + file)) { LogInfo("Loaded python processor: " << directory_ + "/" + file); stopFileObservation(directory_ + "/" + file); } else { startFileObservation(directory_ + "/" + file); } } } } else { if (filesystem::getFileExtension(changed) == "py") { if (registerFile(changed)) { LogInfo("Loaded python processor: " << directory_ + "/" + changed); stopFileObservation(directory_ + "/" + changed); } } } } } // namespace inviwo <|endoftext|>
<commit_before>#include "opt/unroll/unroll_pass.h" #include "iroha/i_design.h" #include "iroha/resource_params.h" #include "opt/loop/loop_block.h" #include "opt/optimizer_log.h" #include "opt/unroll/unroller.h" namespace iroha { namespace opt { namespace unroll { UnrollPass::~UnrollPass() {} Pass *UnrollPass::Create() { return new UnrollPass(); } bool UnrollPass::ApplyForTable(const string &key, ITable *table) { int n = 0; for (IRegister *reg : table->registers_) { auto *params = reg->GetParams(false); if (params == nullptr) { continue; } int unroll_count = params->GetLoopUnroll(); if (unroll_count <= 1) { // 1 for no unroll. 0 for auto (TBD). continue; } loop::LoopBlock lb(table, reg); if (!lb.Build()) { continue; } ++n; Unroller unroller(table, &lb, unroll_count); unroller.Unroll(); } ostream &os = opt_log_->GetDumpStream(); os << "Applied " << n << " unrolls<br/>\n"; return true; } } // namespace unroll } // namespace opt } // namespace iroha <commit_msg>Fix not to touch vector in unroll_pass.cpp<commit_after>#include "opt/unroll/unroll_pass.h" #include "iroha/i_design.h" #include "iroha/resource_params.h" #include "opt/loop/loop_block.h" #include "opt/optimizer_log.h" #include "opt/unroll/unroller.h" namespace iroha { namespace opt { namespace unroll { UnrollPass::~UnrollPass() {} Pass *UnrollPass::Create() { return new UnrollPass(); } bool UnrollPass::ApplyForTable(const string &key, ITable *table) { int n = 0; vector<IRegister *> loop_regs; for (IRegister *reg : table->registers_) { auto *params = reg->GetParams(false); if (params == nullptr) { continue; } int unroll_count = params->GetLoopUnroll(); if (unroll_count <= 1) { // 1 for no unroll. 0 for auto (TBD). continue; } loop_regs.push_back(reg); } for (IRegister *reg : loop_regs) { loop::LoopBlock lb(table, reg); if (!lb.Build()) { continue; } ++n; auto *params = reg->GetParams(false); int unroll_count = params->GetLoopUnroll(); Unroller unroller(table, &lb, unroll_count); unroller.Unroll(); } ostream &os = opt_log_->GetDumpStream(); os << "Applied " << n << " unrolls<br/>\n"; return true; } } // namespace unroll } // namespace opt } // namespace iroha <|endoftext|>
<commit_before>#include "orwell/BroadcastServer.hpp" #include <string> #include <cstring> #include <netinet/udp.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netdb.h> #include <iostream> #include <unistd.h> #include <stdlib.h> #include "orwell/support/GlobalLogger.hpp" #define UDP_MESSAGE_LIMIT 512 #define MULTICAST_GROUP "225.0.0.42" namespace orwell { BroadcastServer::BroadcastServer( uint16_t const iBroadcastPort, std::string const & iPullerUrl, std::string const & iPublisherUrl, std::string const & iReplierUrl, std::string const & iAgentUrl) : _mainLoopRunning(false) , _forcedStop(false) , m_broadcastPort(iBroadcastPort) , _pullerUrl(iPullerUrl) , _publisherUrl(iPublisherUrl) , _replierUrl(iReplierUrl) , _agentUrl(iAgentUrl) { } BroadcastServer::~BroadcastServer() { ORWELL_LOG_INFO("DESTRUCTOR: ~BroadcastServer"); } void BroadcastServer::runBroadcastReceiver() { int aBsdSocket; struct sockaddr_in aBroadcastServerAddress; struct sockaddr_in aClientAddress; struct ip_mreq aGroup; unsigned int aClientLength = sizeof(aClientAddress); /* This is used to set a RCV Timeout on the socket */ struct timeval tv; tv.tv_sec = 3; tv.tv_usec = 1000; /* Create the socket */ aBsdSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); // Just to be sure, init the two structs to zeroes. bzero(&aBroadcastServerAddress, sizeof(aBroadcastServerAddress)); bzero(&aClientAddress, sizeof(aClientAddress)); bzero(&aGroup, sizeof(aGroup)); /* Fill in structure for server's address */ aBroadcastServerAddress.sin_family = AF_INET; aBroadcastServerAddress.sin_addr.s_addr = htonl(INADDR_ANY); aBroadcastServerAddress.sin_port = htons(m_broadcastPort); /* Bind server socket */ bind(aBsdSocket, (struct sockaddr *) &aBroadcastServerAddress, sizeof(aBroadcastServerAddress)); /* use setsockopt() to request that the kernel join a multicast group */ aGroup.imr_multiaddr.s_addr = inet_addr(MULTICAST_GROUP); aGroup.imr_interface.s_addr = htonl(INADDR_ANY); if (setsockopt(aBsdSocket, IPPROTO_IP, IP_ADD_MEMBERSHIP, &aGroup, sizeof(aGroup)) < 0) { perror("setsockopt"); exit(1); } /* Set the RCV Timeout */ setsockopt(aBsdSocket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); _mainLoopRunning = true; ssize_t aReadSize; int aVersion; char aMessageBuffer[UDP_MESSAGE_LIMIT]; memset(aMessageBuffer, 0, UDP_MESSAGE_LIMIT); while (_mainLoopRunning) { // Wait for message and fill the ClientAddress structure we will use to reply aReadSize = recvfrom( aBsdSocket, aMessageBuffer, UDP_MESSAGE_LIMIT, 0, (struct sockaddr *) &aClientAddress, &aClientLength); aVersion = 0; if (aReadSize == -1) { // Receive timeout, let's check if we should keep running.. continue; } else if (aReadSize > 0) { aVersion = atoi(aMessageBuffer); memset(aMessageBuffer, 0, aReadSize); } ORWELL_LOG_INFO("Received an UDP broadcast version (" << aVersion << ")"); // Reply with PULLER and PUBLISHER url // Since in UDP Discovery we are limited to 32 bytes (like ICMP_ECHO), build a binary message std::ostringstream aOstream; if (aVersion >= 0) { aOstream << (uint8_t) 0xA0; // A0 identifies the Puller ( 1 byte ) aOstream << (uint8_t) _pullerUrl.size(); // size of puller url ( 1 byte ) aOstream << (const char *) _pullerUrl.c_str(); // Address of puller url (12 bytes) aOstream << (uint8_t) 0xA1; // A1 is the Publisher ( 1 byte ) aOstream << (uint8_t) _publisherUrl.size(); // size of publisher url ( 1 byte ) aOstream << (const char *) _publisherUrl.c_str(); // Address of publisher (12 bytes) } if (aVersion >= 1) { aOstream << (uint8_t) 0xA2; // A2 is the REQ/REP ( 1 byte ) aOstream << (uint8_t) _replierUrl.size(); // size of REQ/REP url ( 1 byte ) aOstream << (const char *) _replierUrl.c_str(); // Address of REQ/REP (12 bytes) // the rumour said 32 bytes was the limit but this still works even if bigger } if (aVersion >= 2) { aOstream << (uint8_t) 0xA3; // A3 is the agent ( 1 byte ) aOstream << (uint8_t) _agentUrl.size(); // size of agent url ( 1 byte ) aOstream << (const char *) _agentUrl.c_str(); // Address of agent (12 bytes) } aOstream << (uint8_t) 0x00; // End of message ( 1 byte ) ssize_t aMessageLength = sendto( aBsdSocket, aOstream.str().c_str(), aOstream.str().size(), 0, (struct sockaddr *) &aClientAddress, sizeof(aClientAddress)); ORWELL_LOG_INFO("sendto returned length " << aMessageLength); } ORWELL_LOG_INFO("Closing broadcast service"); close(aBsdSocket); } void BroadcastServer::stop() { ORWELL_LOG_INFO("Terminating server main loop"); _forcedStop = true; _mainLoopRunning = false; } } <commit_msg>Update comments<commit_after>#include "orwell/BroadcastServer.hpp" #include <string> #include <cstring> #include <netinet/udp.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netdb.h> #include <iostream> #include <unistd.h> #include <stdlib.h> #include "orwell/support/GlobalLogger.hpp" #define UDP_MESSAGE_LIMIT 512 #define MULTICAST_GROUP "225.0.0.42" namespace orwell { BroadcastServer::BroadcastServer( uint16_t const iBroadcastPort, std::string const & iPullerUrl, std::string const & iPublisherUrl, std::string const & iReplierUrl, std::string const & iAgentUrl) : _mainLoopRunning(false) , _forcedStop(false) , m_broadcastPort(iBroadcastPort) , _pullerUrl(iPullerUrl) , _publisherUrl(iPublisherUrl) , _replierUrl(iReplierUrl) , _agentUrl(iAgentUrl) { } BroadcastServer::~BroadcastServer() { ORWELL_LOG_INFO("DESTRUCTOR: ~BroadcastServer"); } void BroadcastServer::runBroadcastReceiver() { int aBsdSocket; struct sockaddr_in aBroadcastServerAddress; struct sockaddr_in aClientAddress; struct ip_mreq aGroup; unsigned int aClientLength = sizeof(aClientAddress); /* This is used to set a RCV Timeout on the socket */ struct timeval tv; tv.tv_sec = 3; tv.tv_usec = 1000; /* Create the socket */ aBsdSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); // Just to be sure, init the two structs to zeroes. bzero(&aBroadcastServerAddress, sizeof(aBroadcastServerAddress)); bzero(&aClientAddress, sizeof(aClientAddress)); bzero(&aGroup, sizeof(aGroup)); /* Fill in structure for server's address */ aBroadcastServerAddress.sin_family = AF_INET; aBroadcastServerAddress.sin_addr.s_addr = htonl(INADDR_ANY); aBroadcastServerAddress.sin_port = htons(m_broadcastPort); /* Bind server socket */ bind(aBsdSocket, (struct sockaddr *) &aBroadcastServerAddress, sizeof(aBroadcastServerAddress)); /* use setsockopt() to request that the kernel joins a multicast group */ aGroup.imr_multiaddr.s_addr = inet_addr(MULTICAST_GROUP); aGroup.imr_interface.s_addr = htonl(INADDR_ANY); if (setsockopt(aBsdSocket, IPPROTO_IP, IP_ADD_MEMBERSHIP, &aGroup, sizeof(aGroup)) < 0) { perror("setsockopt"); exit(1); } /* Set the RCV Timeout */ setsockopt(aBsdSocket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); _mainLoopRunning = true; ssize_t aReadSize; int aVersion; char aMessageBuffer[UDP_MESSAGE_LIMIT]; memset(aMessageBuffer, 0, UDP_MESSAGE_LIMIT); while (_mainLoopRunning) { // Wait for message and fill the ClientAddress structure we will use to reply aReadSize = recvfrom( aBsdSocket, aMessageBuffer, UDP_MESSAGE_LIMIT, 0, (struct sockaddr *) &aClientAddress, &aClientLength); aVersion = 0; if (aReadSize == -1) { // Receive timeout, let's check if we should keep running.. continue; } else if (aReadSize > 0) { aVersion = atoi(aMessageBuffer); memset(aMessageBuffer, 0, aReadSize); } ORWELL_LOG_INFO("Received an UDP broadcast version (" << aVersion << ")"); // Reply with PULLER and PUBLISHER url // Since in UDP Discovery we are limited to 32 bytes (like ICMP_ECHO), build a binary message std::ostringstream aOstream; if (aVersion >= 0) { aOstream << (uint8_t) 0xA0; // A0 identifies the Puller ( 1 byte ) aOstream << (uint8_t) _pullerUrl.size(); // size of puller url ( 1 byte ) aOstream << (const char *) _pullerUrl.c_str(); // Address of puller url (12 bytes) aOstream << (uint8_t) 0xA1; // A1 is the Publisher ( 1 byte ) aOstream << (uint8_t) _publisherUrl.size(); // size of publisher url ( 1 byte ) aOstream << (const char *) _publisherUrl.c_str(); // Address of publisher (12 bytes) } if (aVersion >= 1) { aOstream << (uint8_t) 0xA2; // A2 is the REQ/REP ( 1 byte ) aOstream << (uint8_t) _replierUrl.size(); // size of REQ/REP url ( 1 byte ) aOstream << (const char *) _replierUrl.c_str(); // Address of REQ/REP (12 bytes) // the rumour said 32 bytes was the limit but this still works even if bigger } if (aVersion >= 2) { aOstream << (uint8_t) 0xA3; // A3 is the agent ( 1 byte ) aOstream << (uint8_t) _agentUrl.size(); // size of agent url ( 1 byte ) aOstream << (const char *) _agentUrl.c_str(); // Address of agent (12 bytes) } aOstream << (uint8_t) 0x00; // End of message ( 1 byte ) // Total (57 bytes) ssize_t aMessageLength = sendto( aBsdSocket, aOstream.str().c_str(), aOstream.str().size(), 0, (struct sockaddr *) &aClientAddress, sizeof(aClientAddress)); ORWELL_LOG_INFO("sendto returned length " << aMessageLength); } ORWELL_LOG_INFO("Closing broadcast service"); close(aBsdSocket); } void BroadcastServer::stop() { ORWELL_LOG_INFO("Terminating server main loop"); _forcedStop = true; _mainLoopRunning = false; } } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <atlbase.h> #include "base/command_line.h" #include "base/process_util.h" #include "base/test/test_suite.h" #include "base/threading/platform_thread.h" #include "chrome/common/chrome_paths.h" #include "chrome_frame/test/chrome_frame_test_utils.h" #include "chrome_frame/test/chrome_frame_ui_test_utils.h" #include "chrome_frame/test_utils.h" #include "chrome_frame/utils.h" // To enable ATL-based code to run in this module class ChromeFrameUnittestsModule : public CAtlExeModuleT<ChromeFrameUnittestsModule> { public: static HRESULT InitializeCom() { return CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); } }; ChromeFrameUnittestsModule _AtlModule; const char kNoRegistrationSwitch[] = "no-registration"; void PureCall() { __debugbreak(); } // This class implements the Run method and registers an exception handler to // ensure that any ChromeFrame processes like IE, Firefox, etc are terminated // if there is a crash in the chrome frame test suite. class ChromeFrameTestSuite : public base::TestSuite { public: ChromeFrameTestSuite(int argc, char** argv) : base::TestSuite(argc, argv) {} int Run() { int ret = -1; __try { ret = base::TestSuite::Run(); } _except(EXCEPTION_EXECUTE_HANDLER) { LOG(ERROR) << "ChromeFrame tests crashed"; chrome_frame_test::KillProcesses(L"iexplore.exe", 0, false); chrome_frame_test::KillProcesses(L"firefox.exe", 0, false); } return ret; } }; int main(int argc, char **argv) { base::EnableTerminationOnHeapCorruption(); base::PlatformThread::SetName("ChromeFrame tests"); _set_purecall_handler(PureCall); ChromeFrameTestSuite test_suite(argc, argv); SetConfigBool(kChromeFrameHeadlessMode, true); SetConfigBool(kChromeFrameAccessibleMode, true); base::ProcessHandle crash_service = chrome_frame_test::StartCrashService(); int ret = -1; // If mini_installer is used to register CF, we use the switch // --no-registration to avoid repetitive registration. if (CommandLine::ForCurrentProcess()->HasSwitch(kNoRegistrationSwitch)) { ret = test_suite.Run(); } else { // Register paths needed by the ScopedChromeFrameRegistrar. chrome::RegisterPathProvider(); // This will register the chrome frame in the build directory. It currently // leaves that chrome frame registered once the tests are done. It must be // constructed AFTER the TestSuite is created since TestSuites create THE // AtExitManager. // TODO(robertshield): Make these tests restore the original registration // once done. ScopedChromeFrameRegistrar registrar; // Register IAccessible2 proxy stub DLL, needed for some tests. ScopedChromeFrameRegistrar ia2_registrar( chrome_frame_test::GetIAccessible2ProxyStubPath().value()); ret = test_suite.Run(); } DeleteConfigValue(kChromeFrameHeadlessMode); DeleteConfigValue(kChromeFrameAccessibleMode); if (crash_service) base::KillProcess(crash_service, 0, false); } <commit_msg>Revert 70981 - Relanding this patch.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <atlbase.h> #include "base/command_line.h" #include "base/process_util.h" #include "base/test/test_suite.h" #include "base/threading/platform_thread.h" #include "chrome/common/chrome_paths.h" #include "chrome_frame/test/chrome_frame_test_utils.h" #include "chrome_frame/test/chrome_frame_ui_test_utils.h" #include "chrome_frame/test_utils.h" #include "chrome_frame/utils.h" // To enable ATL-based code to run in this module class ChromeFrameUnittestsModule : public CAtlExeModuleT<ChromeFrameUnittestsModule> { public: static HRESULT InitializeCom() { return CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); } }; ChromeFrameUnittestsModule _AtlModule; const char kNoRegistrationSwitch[] = "no-registration"; void PureCall() { __debugbreak(); } int main(int argc, char **argv) { base::EnableTerminationOnHeapCorruption(); base::PlatformThread::SetName("ChromeFrame tests"); _set_purecall_handler(PureCall); TestSuite test_suite(argc, argv); SetConfigBool(kChromeFrameHeadlessMode, true); SetConfigBool(kChromeFrameAccessibleMode, true); base::ProcessHandle crash_service = chrome_frame_test::StartCrashService(); int ret = -1; // If mini_installer is used to register CF, we use the switch // --no-registration to avoid repetitive registration. if (CommandLine::ForCurrentProcess()->HasSwitch(kNoRegistrationSwitch)) { ret = test_suite.Run(); } else { // Register paths needed by the ScopedChromeFrameRegistrar. chrome::RegisterPathProvider(); // This will register the chrome frame in the build directory. It currently // leaves that chrome frame registered once the tests are done. It must be // constructed AFTER the TestSuite is created since TestSuites create THE // AtExitManager. // TODO(robertshield): Make these tests restore the original registration // once done. ScopedChromeFrameRegistrar registrar; // Register IAccessible2 proxy stub DLL, needed for some tests. ScopedChromeFrameRegistrar ia2_registrar( chrome_frame_test::GetIAccessible2ProxyStubPath().value()); ret = test_suite.Run(); } DeleteConfigValue(kChromeFrameHeadlessMode); DeleteConfigValue(kChromeFrameAccessibleMode); if (crash_service) base::KillProcess(crash_service, 0, false); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <atlbase.h> #include "base/command_line.h" #include "base/process_util.h" #include "base/test/test_suite.h" #include "base/threading/platform_thread.h" #include "chrome/common/chrome_paths.h" #include "chrome_frame/test/chrome_frame_test_utils.h" #include "chrome_frame/test/chrome_frame_ui_test_utils.h" #include "chrome_frame/test_utils.h" #include "chrome_frame/utils.h" // To enable ATL-based code to run in this module class ChromeFrameUnittestsModule : public CAtlExeModuleT<ChromeFrameUnittestsModule> { public: static HRESULT InitializeCom() { return CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); } }; ChromeFrameUnittestsModule _AtlModule; const char kNoRegistrationSwitch[] = "no-registration"; void PureCall() { __debugbreak(); } int main(int argc, char **argv) { base::EnableTerminationOnHeapCorruption(); base::PlatformThread::SetName("ChromeFrame tests"); _set_purecall_handler(PureCall); TestSuite test_suite(argc, argv); SetConfigBool(kChromeFrameHeadlessMode, true); SetConfigBool(kChromeFrameAccessibleMode, true); base::ProcessHandle crash_service = chrome_frame_test::StartCrashService(); int ret = -1; // If mini_installer is used to register CF, we use the switch // --no-registration to avoid repetitive registration. if (CommandLine::ForCurrentProcess()->HasSwitch(kNoRegistrationSwitch)) { ret = test_suite.Run(); } else { // Register paths needed by the ScopedChromeFrameRegistrar. chrome::RegisterPathProvider(); // This will register the chrome frame in the build directory. It currently // leaves that chrome frame registered once the tests are done. It must be // constructed AFTER the TestSuite is created since TestSuites create THE // AtExitManager. // TODO(robertshield): Make these tests restore the original registration // once done. ScopedChromeFrameRegistrar registrar; // Register IAccessible2 proxy stub DLL, needed for some tests. ScopedChromeFrameRegistrar ia2_registrar( chrome_frame_test::GetIAccessible2ProxyStubPath().value()); ret = test_suite.Run(); } DeleteConfigValue(kChromeFrameHeadlessMode); DeleteConfigValue(kChromeFrameAccessibleMode); if (crash_service) base::KillProcess(crash_service, 0, false); } <commit_msg>Relanding this patch.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <atlbase.h> #include "base/command_line.h" #include "base/process_util.h" #include "base/test/test_suite.h" #include "base/threading/platform_thread.h" #include "chrome/common/chrome_paths.h" #include "chrome_frame/test/chrome_frame_test_utils.h" #include "chrome_frame/test/chrome_frame_ui_test_utils.h" #include "chrome_frame/test_utils.h" #include "chrome_frame/utils.h" // To enable ATL-based code to run in this module class ChromeFrameUnittestsModule : public CAtlExeModuleT<ChromeFrameUnittestsModule> { public: static HRESULT InitializeCom() { return CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); } }; ChromeFrameUnittestsModule _AtlModule; const char kNoRegistrationSwitch[] = "no-registration"; void PureCall() { __debugbreak(); } // This class implements the Run method and registers an exception handler to // ensure that any ChromeFrame processes like IE, Firefox, etc are terminated // if there is a crash in the chrome frame test suite. class ChromeFrameTestSuite : public base::TestSuite { public: ChromeFrameTestSuite(int argc, char** argv) : base::TestSuite(argc, argv) {} int Run() { int ret = -1; __try { ret = base::TestSuite::Run(); } _except(EXCEPTION_EXECUTE_HANDLER) { LOG(ERROR) << "ChromeFrame tests crashed"; chrome_frame_test::KillProcesses(L"iexplore.exe", 0, false); chrome_frame_test::KillProcesses(L"firefox.exe", 0, false); } return ret; } }; int main(int argc, char **argv) { base::EnableTerminationOnHeapCorruption(); base::PlatformThread::SetName("ChromeFrame tests"); _set_purecall_handler(PureCall); ChromeFrameTestSuite test_suite(argc, argv); SetConfigBool(kChromeFrameHeadlessMode, true); SetConfigBool(kChromeFrameAccessibleMode, true); base::ProcessHandle crash_service = chrome_frame_test::StartCrashService(); int ret = -1; // If mini_installer is used to register CF, we use the switch // --no-registration to avoid repetitive registration. if (CommandLine::ForCurrentProcess()->HasSwitch(kNoRegistrationSwitch)) { ret = test_suite.Run(); } else { // Register paths needed by the ScopedChromeFrameRegistrar. chrome::RegisterPathProvider(); // This will register the chrome frame in the build directory. It currently // leaves that chrome frame registered once the tests are done. It must be // constructed AFTER the TestSuite is created since TestSuites create THE // AtExitManager. // TODO(robertshield): Make these tests restore the original registration // once done. ScopedChromeFrameRegistrar registrar; // Register IAccessible2 proxy stub DLL, needed for some tests. ScopedChromeFrameRegistrar ia2_registrar( chrome_frame_test::GetIAccessible2ProxyStubPath().value()); ret = test_suite.Run(); } DeleteConfigValue(kChromeFrameHeadlessMode); DeleteConfigValue(kChromeFrameAccessibleMode); if (crash_service) base::KillProcess(crash_service, 0, false); } <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osgSim/VisibilityGroup> #include <osgUtil/CullVisitor> #include <osgUtil/IntersectVisitor> using namespace osgSim; using namespace osg; VisibilityGroup::VisibilityGroup(): _volumeIntersectionMask(0xFFFFFFFF), _segmentLength(0.f) { } VisibilityGroup::VisibilityGroup(const VisibilityGroup& sw,const osg::CopyOp& copyop): osg::Group(sw,copyop), _volumeIntersectionMask(0xFFFFFFFF), _segmentLength(0.f) { } void VisibilityGroup::traverse(osg::NodeVisitor& nv) { if (nv.getTraversalMode()==osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN && nv.getVisitorType() == osg::NodeVisitor::CULL_VISITOR) { // cast to cullvisitor osgUtil::CullVisitor& cv = (osgUtil::CullVisitor&) nv; // here we test if we are inside the visibilityvolume // first get the eyepoint and in local coordinates osg::Vec3 eye = cv.getEyeLocal(); osg::Vec3 look = cv.getLookVectorLocal(); // now scale the segment to the segment length - if 0 use the group bounding sphere radius float length = _segmentLength; if(length == 0.f) length = getBound().radius(); look *= length; osg::Vec3 center = eye + look; osg::Vec3 seg = center - eye; // perform the intersection using the given mask osgUtil::IntersectVisitor iv; osg::ref_ptr<osg::LineSegment> lineseg = new osg::LineSegment; lineseg->set(eye, center); iv.addLineSegment(lineseg.get()); iv.setTraversalMask(_volumeIntersectionMask); if(_visibilityVolume.valid()) _visibilityVolume->accept(iv); // now examine the hit record if(iv.hits()) { osgUtil::IntersectVisitor::HitList& hitList = iv.getHitList(lineseg.get()); if(!hitList.empty()) // we actually hit something { // notify(INFO) << "Hit obstruction"<< std::endl; osg::Vec3 normal = hitList.front().getLocalIntersectNormal(); if((normal*seg) > 0.f ) // we are inside Group::traverse(nv); } } } else { Group::traverse(nv); } } <commit_msg>From Michael Gronager, fix to an orientation bug.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osgSim/VisibilityGroup> #include <osgUtil/CullVisitor> #include <osgUtil/IntersectVisitor> using namespace osgSim; using namespace osg; VisibilityGroup::VisibilityGroup(): _volumeIntersectionMask(0xFFFFFFFF), _segmentLength(0.f) { } VisibilityGroup::VisibilityGroup(const VisibilityGroup& sw,const osg::CopyOp& copyop): osg::Group(sw,copyop), _volumeIntersectionMask(0xFFFFFFFF), _segmentLength(0.f) { } void VisibilityGroup::traverse(osg::NodeVisitor& nv) { if (nv.getTraversalMode()==osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN && nv.getVisitorType() == osg::NodeVisitor::CULL_VISITOR) { // cast to cullvisitor osgUtil::CullVisitor& cv = (osgUtil::CullVisitor&) nv; // here we test if we are inside the visibilityvolume // first get the eyepoint and in local coordinates osg::Vec3 eye = cv.getEyeLocal(); osg::Vec3 look = cv.getLookVectorLocal(); // now scale the segment to the segment length - if 0 use the group bounding sphere radius float length = _segmentLength; if(length == 0.f) length = getBound().radius(); look *= length; osg::Vec3 center = eye + look; osg::Vec3 seg = center - eye; // perform the intersection using the given mask osgUtil::IntersectVisitor iv; osg::ref_ptr<osg::LineSegment> lineseg = new osg::LineSegment; lineseg->set(eye, center); iv.addLineSegment(lineseg.get()); iv.setTraversalMask(_volumeIntersectionMask); if(_visibilityVolume.valid()) _visibilityVolume->accept(iv); // now examine the hit record if(iv.hits()) { osgUtil::IntersectVisitor::HitList& hitList = iv.getHitList(lineseg.get()); if(!hitList.empty()) // we actually hit something { // notify(INFO) << "Hit obstruction"<< std::endl; osg::Vec3 normal = hitList.front().getWorldIntersectNormal(); if((normal*seg) > 0.f ) // we are inside Group::traverse(nv); } } } else { Group::traverse(nv); } } <|endoftext|>
<commit_before>// $Id$ // The libMesh Finite Element Library. // Copyright (C) 2002-2007 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ Includes ----------------------------------- // Local Includes ----------------------------------- #include "partitioner.h" #include "mesh_base.h" #include "elem.h" // ------------------------------------------------------------ // Partitioner implementation void Partitioner::partition (MeshBase& mesh, const unsigned int n) { // Set the number of partitions in the mesh mesh.set_n_partitions()=n; // Call the partitioning function this->_do_partition(mesh,n); // Set the node's processor ids this->_set_node_processor_ids(mesh); } void Partitioner::repartition (MeshBase& mesh, const unsigned int n) { // Set the number of partitions in the mesh mesh.set_n_partitions()=n; // Call the partitioning function this->_do_repartition(mesh,n); // Set the node's processor ids this->_set_node_processor_ids(mesh); } void Partitioner::single_partition (MeshBase& mesh) { // Loop over all the elements and assign them to processor 0. MeshBase::element_iterator elem_it = mesh.elements_begin(); const MeshBase::element_iterator elem_end = mesh.elements_end(); for ( ; elem_it != elem_end; ++elem_it) (*elem_it)->processor_id() = 0; // For a single partition, all the nodes are on processor 0 MeshBase::node_iterator node_it = mesh.nodes_begin(); const MeshBase::node_iterator node_end = mesh.nodes_end(); for ( ; node_it != node_end; ++node_it) (*node_it)->processor_id() = 0; } void Partitioner::_set_node_processor_ids(MeshBase& mesh) { // Unset any previously-set node processor ids // (maybe from previous partitionings). MeshBase::node_iterator node_it = mesh.nodes_begin(); const MeshBase::node_iterator node_end = mesh.nodes_end(); for ( ; node_it != node_end; ++node_it) (*node_it)->invalidate_processor_id(); // Loop over all the elements MeshBase::element_iterator elem_it = mesh.active_elements_begin(); const MeshBase::element_iterator elem_end = mesh.active_elements_end(); for ( ; elem_it != elem_end; ++elem_it) { Elem* elem = *elem_it; // For each node, set the processor ID to the min of // its current value and this Element's processor id. for (unsigned int n=0; n<elem->n_nodes(); ++n) elem->get_node(n)->processor_id() = std::min(elem->get_node(n)->processor_id(), elem->processor_id()); } } <commit_msg>Add sanity check to look for unpartitioned nodes<commit_after>// $Id$ // The libMesh Finite Element Library. // Copyright (C) 2002-2007 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ Includes ----------------------------------- // Local Includes ----------------------------------- #include "partitioner.h" #include "mesh_base.h" #include "elem.h" // ------------------------------------------------------------ // Partitioner implementation void Partitioner::partition (MeshBase& mesh, const unsigned int n) { // Set the number of partitions in the mesh mesh.set_n_partitions()=n; // Call the partitioning function this->_do_partition(mesh,n); // Set the node's processor ids this->_set_node_processor_ids(mesh); } void Partitioner::repartition (MeshBase& mesh, const unsigned int n) { // Set the number of partitions in the mesh mesh.set_n_partitions()=n; // Call the partitioning function this->_do_repartition(mesh,n); // Set the node's processor ids this->_set_node_processor_ids(mesh); } void Partitioner::single_partition (MeshBase& mesh) { // Loop over all the elements and assign them to processor 0. MeshBase::element_iterator elem_it = mesh.elements_begin(); const MeshBase::element_iterator elem_end = mesh.elements_end(); for ( ; elem_it != elem_end; ++elem_it) (*elem_it)->processor_id() = 0; // For a single partition, all the nodes are on processor 0 MeshBase::node_iterator node_it = mesh.nodes_begin(); const MeshBase::node_iterator node_end = mesh.nodes_end(); for ( ; node_it != node_end; ++node_it) (*node_it)->processor_id() = 0; } void Partitioner::_set_node_processor_ids(MeshBase& mesh) { // Unset any previously-set node processor ids // (maybe from previous partitionings). MeshBase::node_iterator node_it = mesh.nodes_begin(); const MeshBase::node_iterator node_end = mesh.nodes_end(); for ( ; node_it != node_end; ++node_it) (*node_it)->invalidate_processor_id(); // Loop over all the elements MeshBase::element_iterator elem_it = mesh.active_elements_begin(); const MeshBase::element_iterator elem_end = mesh.active_elements_end(); for ( ; elem_it != elem_end; ++elem_it) { Elem* elem = *elem_it; // For each node, set the processor ID to the min of // its current value and this Element's processor id. for (unsigned int n=0; n<elem->n_nodes(); ++n) elem->get_node(n)->processor_id() = std::min(elem->get_node(n)->processor_id(), elem->processor_id()); } #ifdef DEBUG // Make sure we hit all the nodes for ( ; node_it != node_end; ++node_it) assert((*node_it)->processor_id() != DofObject::invalid_id); #endif } <|endoftext|>
<commit_before>/// @file /// @version 3.5 /// /// @section LICENSE /// /// This program is free software; you can redistribute it and/or modify it under /// the terms of the BSD license: http://opensource.org/licenses/BSD-3-Clause #ifdef _ANDROID #include <jni.h> #include <hltypes/harray.h> #include <hltypes/hlog.h> #include <hltypes/hltypesUtil.h> #include <hltypes/hresource.h> #include <hltypes/hstring.h> #define __NATIVE_INTERFACE_CLASS "com/april/NativeInterface" #include "androidUtilJNI.h" #include "april.h" #include "Keys.h" #include "main_base.h" #include "Platform.h" #include "RenderSystem.h" #include "Window.h" #include "AndroidJNI_Keys.h" #define PROTECTED_WINDOW_CALL(methodCall) \ if (april::window != NULL) \ { \ april::window->methodCall; \ } #define PROTECTED_RENDERSYS_CALL(methodCall) \ if (april::rendersys != NULL) \ { \ april::rendersys->methodCall; \ } namespace april { extern void* javaVM; extern void (*dialogCallback)(MessageBoxButton); void (*aprilInit)(const harray<hstr>&) = NULL; void (*aprilDestroy)() = NULL; extern jobject classLoader; void JNICALL _JNI_setVariables(JNIEnv* env, jclass classe, jstring jDataPath, jstring jForcedArchivePath) { hstr dataPath = _JSTR_TO_HSTR(jDataPath); hstr archivePath = _JSTR_TO_HSTR(jForcedArchivePath); hlog::write(april::logTag, "System path: " + april::getUserDataPath()); if (!hresource::hasZip()) // if not using APK as data file archive { #ifndef _OPENKODE // set the resources CWD hresource::setCwd(hrdir::joinPath(hrdir::joinPath(dataPath, "Android/data"), april::getPackageName())); hresource::setArchive(""); // not used anyway when hasZip() returns false hlog::write(april::logTag, "Using no-zip: " + hresource::getCwd()); #else hlog::write(april::logTag, "Using KD file system: " + hresource::getCwd()); #endif } else if (archivePath != "") { // using APK file as archive hresource::setCwd("assets"); hresource::setArchive(archivePath); hlog::write(april::logTag, "Using assets: " + hresource::getArchive()); } else { // using OBB file as archive hresource::setCwd("."); // using Google Play's "Expansion File" system hresource::setArchive(dataPath); hlog::write(april::logTag, "Using obb: " + hresource::getArchive()); } } void JNICALL _JNI_init(JNIEnv* env, jclass classe, jobjectArray jArgs) { harray<hstr> args; int length = env->GetArrayLength(jArgs); jstring string; for_iter (i, 0, length) { string = (jstring)env->GetObjectArrayElement(jArgs, i); args += _JSTR_TO_HSTR(string); env->DeleteLocalRef(string); } hlog::debug(april::logTag, "Got args:"); foreach (hstr, it, args) { hlog::debug(april::logTag, " " + (*it)); } (*aprilInit)(args); } void JNICALL _JNI_destroy(JNIEnv* env, jclass classe) { (*aprilDestroy)(); } bool JNICALL _JNI_render(JNIEnv* env, jclass classe) { bool result = true; if (april::window != NULL) { try { result = april::window->updateOneFrame(); } catch (hexception& e) { hlog::error("FATAL", e.getMessage()); throw e; } } return result; } void JNICALL _JNI_onKeyDown(JNIEnv* env, jclass classe, jint keyCode, jint charCode) { PROTECTED_WINDOW_CALL(queueKeyEvent(april::Window::KEY_DOWN, android2april((int)keyCode), (unsigned int)charCode)); } void JNICALL _JNI_onKeyUp(JNIEnv* env, jclass classe, jint keyCode) { PROTECTED_WINDOW_CALL(queueKeyEvent(april::Window::KEY_UP, android2april((int)keyCode), 0)); } void JNICALL _JNI_onTouch(JNIEnv* env, jclass classe, jint type, jfloat x, jfloat y, jint index) { PROTECTED_WINDOW_CALL(queueTouchEvent((april::Window::MouseEventType)type, gvec2((float)x, (float)y), (int)index)); } void JNICALL _JNI_onButtonDown(JNIEnv* env, jclass classe, jint keyCode, jint charCode) { PROTECTED_WINDOW_CALL(queueControllerEvent(april::Window::CONTROLLER_DOWN, (Button)(int)keyCode)); } void JNICALL _JNI_onButtonUp(JNIEnv* env, jclass classe, jint keyCode) { PROTECTED_WINDOW_CALL(queueControllerEvent(april::Window::CONTROLLER_UP, (Button)(int)keyCode)); } void JNICALL _JNI_onControllerAxis(JNIEnv* env, jclass classe, jint keyCode, jfloat axisValue) { PROTECTED_WINDOW_CALL(queueControllerAxisEvent(april::Window::CONTROLLER_AXIS, (Button)(int)keyCode, (float) axisValue)); } void JNICALL _JNI_onWindowFocusChanged(JNIEnv* env, jclass classe, jboolean jFocused) { bool focused = (jFocused != JNI_FALSE); hlog::write(april::logTag, "onWindowFocusChanged(" + hstr(focused) + ")"); PROTECTED_WINDOW_CALL(handleFocusChangeEvent(focused)); } void JNICALL _JNI_onVirtualKeyboardChanged(JNIEnv* env, jclass classe, jboolean jVisible, jfloat jHeightRatio) { bool visible = (jVisible != JNI_FALSE); float heightRatio = (float)jHeightRatio; hlog::write(april::logTag, "onVirtualKeyboardChanged(" + hstr(visible) + "," + hstr(heightRatio) + ")"); PROTECTED_WINDOW_CALL(handleVirtualKeyboardChangeEvent(visible, heightRatio)); } void JNICALL _JNI_onLowMemory(JNIEnv* env, jclass classe) { hlog::write(april::logTag, "onLowMemoryWarning()"); PROTECTED_WINDOW_CALL(handleLowMemoryWarning()); } void JNICALL _JNI_onSurfaceCreated(JNIEnv* env, jclass classe) { hlog::write(april::logTag, "Android View::onSurfaceCreated()"); PROTECTED_RENDERSYS_CALL(reset()); } void JNICALL _JNI_activityOnCreate(JNIEnv* env, jclass classe) { hlog::write(april::logTag, "Android Activity::onCreate()"); } void JNICALL _JNI_activityOnStart(JNIEnv* env, jclass classe) { hlog::write(april::logTag, "Android Activity::onStart()"); } void JNICALL _JNI_activityOnResume(JNIEnv* env, jclass classe) { hlog::write(april::logTag, "Android Activity::onResume()"); PROTECTED_WINDOW_CALL(handleActivityChangeEvent(true)); } void JNICALL _JNI_activityOnPause(JNIEnv* env, jclass classe) { hlog::write(april::logTag, "Android Activity::onPause()"); PROTECTED_WINDOW_CALL(handleActivityChangeEvent(false)); PROTECTED_RENDERSYS_CALL(unloadTextures()); } void JNICALL _JNI_activityOnStop(JNIEnv* env, jclass classe) { hlog::write(april::logTag, "Android Activity::onStop()"); } void JNICALL _JNI_activityOnDestroy(JNIEnv* env, jclass classe) { hlog::write(april::logTag, "Android Activity::onDestroy()"); if (april::classLoader != NULL) { env->DeleteGlobalRef(april::classLoader); april::classLoader = NULL; } } void JNICALL _JNI_activityOnRestart(JNIEnv* env, jclass classe) { hlog::write(april::logTag, "Android Activity::onRestart()"); } void JNICALL _JNI_onDialogOk(JNIEnv* env, jclass classe) { if (dialogCallback != NULL) { (*dialogCallback)(MESSAGE_BUTTON_OK); } } void JNICALL _JNI_onDialogYes(JNIEnv* env, jclass classe) { if (dialogCallback != NULL) { (*dialogCallback)(MESSAGE_BUTTON_YES); } } void JNICALL _JNI_onDialogNo(JNIEnv* env, jclass classe) { if (dialogCallback != NULL) { (*dialogCallback)(MESSAGE_BUTTON_NO); } } void JNICALL _JNI_onDialogCancel(JNIEnv* env, jclass classe) { if (dialogCallback != NULL) { (*dialogCallback)(MESSAGE_BUTTON_CANCEL); } } #define METHOD_COUNT 25 // make sure this fits static JNINativeMethod methods[METHOD_COUNT] = { {"setVariables", _JARGS(_JVOID, _JSTR _JSTR), (void*)&april::_JNI_setVariables }, {"init", _JARGS(_JVOID, _JARR(_JSTR)), (void*)&april::_JNI_init }, {"destroy", _JARGS(_JVOID, ), (void*)&april::_JNI_destroy }, {"render", _JARGS(_JBOOL, ), (void*)&april::_JNI_render }, {"onKeyDown", _JARGS(_JVOID, _JINT _JINT), (bool*)&april::_JNI_onKeyDown }, {"onKeyUp", _JARGS(_JVOID, _JINT), (bool*)&april::_JNI_onKeyUp }, {"onTouch", _JARGS(_JVOID, _JINT _JFLOAT _JFLOAT _JINT), (void*)&april::_JNI_onTouch }, {"onButtonDown", _JARGS(_JVOID, _JINT), (bool*)&april::_JNI_onButtonDown }, {"onButtonUp", _JARGS(_JVOID, _JINT), (bool*)&april::_JNI_onButtonUp }, {"onControllerAxis", _JARGS(_JVOID, _JINT _JFLOAT), (bool*)&april::_JNI_onControllerAxis }, {"onWindowFocusChanged", _JARGS(_JVOID, _JBOOL), (void*)&april::_JNI_onWindowFocusChanged }, {"onVirtualKeyboardChanged", _JARGS(_JVOID, _JBOOL _JFLOAT), (void*)&april::_JNI_onVirtualKeyboardChanged }, {"onLowMemory", _JARGS(_JVOID, ), (void*)&april::_JNI_onLowMemory }, {"onSurfaceCreated", _JARGS(_JVOID, ), (void*)&april::_JNI_onSurfaceCreated }, {"activityOnCreate", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnCreate }, {"activityOnStart", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnStart }, {"activityOnResume", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnResume }, {"activityOnPause", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnPause }, {"activityOnStop", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnStop }, {"activityOnDestroy", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnDestroy }, {"activityOnRestart", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnRestart }, {"onDialogOk", _JARGS(_JVOID, ), (void*)&april::_JNI_onDialogOk }, {"onDialogYes", _JARGS(_JVOID, ), (void*)&april::_JNI_onDialogYes }, {"onDialogNo", _JARGS(_JVOID, ), (void*)&april::_JNI_onDialogNo }, {"onDialogCancel", _JARGS(_JVOID, ), (void*)&april::_JNI_onDialogCancel } }; jint __JNI_OnLoad(void (*anAprilInit)(const harray<hstr>&), void (*anAprilDestroy)(), JavaVM* vm, void* reserved) { april::javaVM = (void*)vm; april::aprilInit = anAprilInit; april::aprilDestroy = anAprilDestroy; JNIEnv* env = NULL; if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) { return -1; } jclass classNativeInterface = env->FindClass(__NATIVE_INTERFACE_CLASS); if (env->RegisterNatives(classNativeInterface, methods, METHOD_COUNT) != 0) { return -1; } #ifdef _OPENKODE // not really needed when OpenKODE isn't used jclass classClass = env->FindClass("java/lang/Class"); jmethodID methodGetClassLoader = env->GetMethodID(classClass, "getClassLoader", _JARGS(_JCLASS("java/lang/ClassLoader"), )); jobject classLoader = env->CallObjectMethod(classNativeInterface, methodGetClassLoader); april::classLoader = env->NewGlobalRef(classLoader); #endif return JNI_VERSION_1_6; } } #endif <commit_msg>- small fix<commit_after>/// @file /// @version 3.5 /// /// @section LICENSE /// /// This program is free software; you can redistribute it and/or modify it under /// the terms of the BSD license: http://opensource.org/licenses/BSD-3-Clause #ifdef _ANDROID #include <jni.h> #include <hltypes/harray.h> #include <hltypes/hlog.h> #include <hltypes/hltypesUtil.h> #include <hltypes/hrdir.h> #include <hltypes/hresource.h> #include <hltypes/hstring.h> #define __NATIVE_INTERFACE_CLASS "com/april/NativeInterface" #include "androidUtilJNI.h" #include "april.h" #include "Keys.h" #include "main_base.h" #include "Platform.h" #include "RenderSystem.h" #include "Window.h" #include "AndroidJNI_Keys.h" #define PROTECTED_WINDOW_CALL(methodCall) \ if (april::window != NULL) \ { \ april::window->methodCall; \ } #define PROTECTED_RENDERSYS_CALL(methodCall) \ if (april::rendersys != NULL) \ { \ april::rendersys->methodCall; \ } namespace april { extern void* javaVM; extern void (*dialogCallback)(MessageBoxButton); void (*aprilInit)(const harray<hstr>&) = NULL; void (*aprilDestroy)() = NULL; extern jobject classLoader; void JNICALL _JNI_setVariables(JNIEnv* env, jclass classe, jstring jDataPath, jstring jForcedArchivePath) { hstr dataPath = _JSTR_TO_HSTR(jDataPath); hstr archivePath = _JSTR_TO_HSTR(jForcedArchivePath); hlog::write(april::logTag, "System path: " + april::getUserDataPath()); if (!hresource::hasZip()) // if not using APK as data file archive { #ifndef _OPENKODE // set the resources CWD hresource::setCwd(hrdir::joinPath(hrdir::joinPath(dataPath, "Android/data"), april::getPackageName())); hresource::setArchive(""); // not used anyway when hasZip() returns false hlog::write(april::logTag, "Using no-zip: " + hresource::getCwd()); #else hlog::write(april::logTag, "Using KD file system: " + hresource::getCwd()); #endif } else if (archivePath != "") { // using APK file as archive hresource::setCwd("assets"); hresource::setArchive(archivePath); hlog::write(april::logTag, "Using assets: " + hresource::getArchive()); } else { // using OBB file as archive hresource::setCwd("."); // using Google Play's "Expansion File" system hresource::setArchive(dataPath); hlog::write(april::logTag, "Using obb: " + hresource::getArchive()); } } void JNICALL _JNI_init(JNIEnv* env, jclass classe, jobjectArray jArgs) { harray<hstr> args; int length = env->GetArrayLength(jArgs); jstring string; for_iter (i, 0, length) { string = (jstring)env->GetObjectArrayElement(jArgs, i); args += _JSTR_TO_HSTR(string); env->DeleteLocalRef(string); } hlog::debug(april::logTag, "Got args:"); foreach (hstr, it, args) { hlog::debug(april::logTag, " " + (*it)); } (*aprilInit)(args); } void JNICALL _JNI_destroy(JNIEnv* env, jclass classe) { (*aprilDestroy)(); } bool JNICALL _JNI_render(JNIEnv* env, jclass classe) { bool result = true; if (april::window != NULL) { try { result = april::window->updateOneFrame(); } catch (hexception& e) { hlog::error("FATAL", e.getMessage()); throw e; } } return result; } void JNICALL _JNI_onKeyDown(JNIEnv* env, jclass classe, jint keyCode, jint charCode) { PROTECTED_WINDOW_CALL(queueKeyEvent(april::Window::KEY_DOWN, android2april((int)keyCode), (unsigned int)charCode)); } void JNICALL _JNI_onKeyUp(JNIEnv* env, jclass classe, jint keyCode) { PROTECTED_WINDOW_CALL(queueKeyEvent(april::Window::KEY_UP, android2april((int)keyCode), 0)); } void JNICALL _JNI_onTouch(JNIEnv* env, jclass classe, jint type, jfloat x, jfloat y, jint index) { PROTECTED_WINDOW_CALL(queueTouchEvent((april::Window::MouseEventType)type, gvec2((float)x, (float)y), (int)index)); } void JNICALL _JNI_onButtonDown(JNIEnv* env, jclass classe, jint keyCode, jint charCode) { PROTECTED_WINDOW_CALL(queueControllerEvent(april::Window::CONTROLLER_DOWN, (Button)(int)keyCode)); } void JNICALL _JNI_onButtonUp(JNIEnv* env, jclass classe, jint keyCode) { PROTECTED_WINDOW_CALL(queueControllerEvent(april::Window::CONTROLLER_UP, (Button)(int)keyCode)); } void JNICALL _JNI_onControllerAxis(JNIEnv* env, jclass classe, jint keyCode, jfloat axisValue) { PROTECTED_WINDOW_CALL(queueControllerAxisEvent(april::Window::CONTROLLER_AXIS, (Button)(int)keyCode, (float) axisValue)); } void JNICALL _JNI_onWindowFocusChanged(JNIEnv* env, jclass classe, jboolean jFocused) { bool focused = (jFocused != JNI_FALSE); hlog::write(april::logTag, "onWindowFocusChanged(" + hstr(focused) + ")"); PROTECTED_WINDOW_CALL(handleFocusChangeEvent(focused)); } void JNICALL _JNI_onVirtualKeyboardChanged(JNIEnv* env, jclass classe, jboolean jVisible, jfloat jHeightRatio) { bool visible = (jVisible != JNI_FALSE); float heightRatio = (float)jHeightRatio; hlog::write(april::logTag, "onVirtualKeyboardChanged(" + hstr(visible) + "," + hstr(heightRatio) + ")"); PROTECTED_WINDOW_CALL(handleVirtualKeyboardChangeEvent(visible, heightRatio)); } void JNICALL _JNI_onLowMemory(JNIEnv* env, jclass classe) { hlog::write(april::logTag, "onLowMemoryWarning()"); PROTECTED_WINDOW_CALL(handleLowMemoryWarning()); } void JNICALL _JNI_onSurfaceCreated(JNIEnv* env, jclass classe) { hlog::write(april::logTag, "Android View::onSurfaceCreated()"); PROTECTED_RENDERSYS_CALL(reset()); } void JNICALL _JNI_activityOnCreate(JNIEnv* env, jclass classe) { hlog::write(april::logTag, "Android Activity::onCreate()"); } void JNICALL _JNI_activityOnStart(JNIEnv* env, jclass classe) { hlog::write(april::logTag, "Android Activity::onStart()"); } void JNICALL _JNI_activityOnResume(JNIEnv* env, jclass classe) { hlog::write(april::logTag, "Android Activity::onResume()"); PROTECTED_WINDOW_CALL(handleActivityChangeEvent(true)); } void JNICALL _JNI_activityOnPause(JNIEnv* env, jclass classe) { hlog::write(april::logTag, "Android Activity::onPause()"); PROTECTED_WINDOW_CALL(handleActivityChangeEvent(false)); PROTECTED_RENDERSYS_CALL(unloadTextures()); } void JNICALL _JNI_activityOnStop(JNIEnv* env, jclass classe) { hlog::write(april::logTag, "Android Activity::onStop()"); } void JNICALL _JNI_activityOnDestroy(JNIEnv* env, jclass classe) { hlog::write(april::logTag, "Android Activity::onDestroy()"); if (april::classLoader != NULL) { env->DeleteGlobalRef(april::classLoader); april::classLoader = NULL; } } void JNICALL _JNI_activityOnRestart(JNIEnv* env, jclass classe) { hlog::write(april::logTag, "Android Activity::onRestart()"); } void JNICALL _JNI_onDialogOk(JNIEnv* env, jclass classe) { if (dialogCallback != NULL) { (*dialogCallback)(MESSAGE_BUTTON_OK); } } void JNICALL _JNI_onDialogYes(JNIEnv* env, jclass classe) { if (dialogCallback != NULL) { (*dialogCallback)(MESSAGE_BUTTON_YES); } } void JNICALL _JNI_onDialogNo(JNIEnv* env, jclass classe) { if (dialogCallback != NULL) { (*dialogCallback)(MESSAGE_BUTTON_NO); } } void JNICALL _JNI_onDialogCancel(JNIEnv* env, jclass classe) { if (dialogCallback != NULL) { (*dialogCallback)(MESSAGE_BUTTON_CANCEL); } } #define METHOD_COUNT 25 // make sure this fits static JNINativeMethod methods[METHOD_COUNT] = { {"setVariables", _JARGS(_JVOID, _JSTR _JSTR), (void*)&april::_JNI_setVariables }, {"init", _JARGS(_JVOID, _JARR(_JSTR)), (void*)&april::_JNI_init }, {"destroy", _JARGS(_JVOID, ), (void*)&april::_JNI_destroy }, {"render", _JARGS(_JBOOL, ), (void*)&april::_JNI_render }, {"onKeyDown", _JARGS(_JVOID, _JINT _JINT), (bool*)&april::_JNI_onKeyDown }, {"onKeyUp", _JARGS(_JVOID, _JINT), (bool*)&april::_JNI_onKeyUp }, {"onTouch", _JARGS(_JVOID, _JINT _JFLOAT _JFLOAT _JINT), (void*)&april::_JNI_onTouch }, {"onButtonDown", _JARGS(_JVOID, _JINT), (bool*)&april::_JNI_onButtonDown }, {"onButtonUp", _JARGS(_JVOID, _JINT), (bool*)&april::_JNI_onButtonUp }, {"onControllerAxis", _JARGS(_JVOID, _JINT _JFLOAT), (bool*)&april::_JNI_onControllerAxis }, {"onWindowFocusChanged", _JARGS(_JVOID, _JBOOL), (void*)&april::_JNI_onWindowFocusChanged }, {"onVirtualKeyboardChanged", _JARGS(_JVOID, _JBOOL _JFLOAT), (void*)&april::_JNI_onVirtualKeyboardChanged }, {"onLowMemory", _JARGS(_JVOID, ), (void*)&april::_JNI_onLowMemory }, {"onSurfaceCreated", _JARGS(_JVOID, ), (void*)&april::_JNI_onSurfaceCreated }, {"activityOnCreate", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnCreate }, {"activityOnStart", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnStart }, {"activityOnResume", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnResume }, {"activityOnPause", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnPause }, {"activityOnStop", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnStop }, {"activityOnDestroy", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnDestroy }, {"activityOnRestart", _JARGS(_JVOID, ), (void*)&april::_JNI_activityOnRestart }, {"onDialogOk", _JARGS(_JVOID, ), (void*)&april::_JNI_onDialogOk }, {"onDialogYes", _JARGS(_JVOID, ), (void*)&april::_JNI_onDialogYes }, {"onDialogNo", _JARGS(_JVOID, ), (void*)&april::_JNI_onDialogNo }, {"onDialogCancel", _JARGS(_JVOID, ), (void*)&april::_JNI_onDialogCancel } }; jint __JNI_OnLoad(void (*anAprilInit)(const harray<hstr>&), void (*anAprilDestroy)(), JavaVM* vm, void* reserved) { april::javaVM = (void*)vm; april::aprilInit = anAprilInit; april::aprilDestroy = anAprilDestroy; JNIEnv* env = NULL; if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) { return -1; } jclass classNativeInterface = env->FindClass(__NATIVE_INTERFACE_CLASS); if (env->RegisterNatives(classNativeInterface, methods, METHOD_COUNT) != 0) { return -1; } #ifdef _OPENKODE // not really needed when OpenKODE isn't used jclass classClass = env->FindClass("java/lang/Class"); jmethodID methodGetClassLoader = env->GetMethodID(classClass, "getClassLoader", _JARGS(_JCLASS("java/lang/ClassLoader"), )); jobject classLoader = env->CallObjectMethod(classNativeInterface, methodGetClassLoader); april::classLoader = env->NewGlobalRef(classLoader); #endif return JNI_VERSION_1_6; } } #endif <|endoftext|>
<commit_before>/* * bacteria-core, core for cellular automaton * Copyright (C) 2016 Pavel Dolgov * * See the LICENSE file for terms of use. */ #include <boost/foreach.hpp> #include <boost/test/unit_test.hpp> #include "Model.hpp" typedef int (Implementation::Model::*IntOneArgMethod) ( const Abstract::Point& coordinates ) const; typedef Abstract::CellState (Implementation::Model::*OneArgMethod2) ( const Abstract::Point& coordinates ) const; typedef void (Implementation::Model::*OneArgMethod) ( const Abstract::Point& coordinates ); typedef void (Implementation::Model::*TwoArgsMethod) ( const Abstract::Point& coordinates, int change ); typedef void (Implementation::Model::*IntThreeArgsMethod) ( int team, int bacterium_index, int spec ); typedef void (Implementation::Model::*ThreeArgsMethod) ( int team, int bacterium_index, const Abstract::Point& coordinates ); typedef void (Implementation::Model::*MultiArgsMethod) ( const Abstract::Point& coordinates, int mass, int direction, int team, int instruction ); template<typename Func> static void checkOneArgMethod( Implementation::Model* model, Func model_method, int arg1, int arg2 ) { Abstract::Point coordinates(arg1, arg2); BOOST_REQUIRE_THROW( ((*model).*model_method)(coordinates), Exception ); } template<typename Func> void checkModelMethodForThrow( Implementation::Model* model, Func model_method, int arg1, int arg2 ) { BOOST_REQUIRE_THROW( ((*model).*model_method)(arg1, arg2), Exception ); } template<> void checkModelMethodForThrow<IntOneArgMethod>( Implementation::Model* model, IntOneArgMethod model_method, int arg1, int arg2 ) { checkOneArgMethod(model, model_method, arg1, arg2); } template<> void checkModelMethodForThrow<OneArgMethod2>( Implementation::Model* model, OneArgMethod2 model_method, int arg1, int arg2 ) { checkOneArgMethod(model, model_method, arg1, arg2); } template<> void checkModelMethodForThrow<OneArgMethod>( Implementation::Model* model, OneArgMethod model_method, int arg1, int arg2 ) { checkOneArgMethod(model, model_method, arg1, arg2); } template<> void checkModelMethodForThrow<TwoArgsMethod>( Implementation::Model* model, TwoArgsMethod model_method, int arg1, int arg2 ) { Abstract::Point coordinates(arg1, arg2); BOOST_REQUIRE_THROW( ((*model).*model_method)(coordinates, 0), Exception ); } template<> void checkModelMethodForThrow<MultiArgsMethod>( Implementation::Model* model, MultiArgsMethod model_method, int arg1, int arg2 ) { Abstract::Point coordinates(arg1, arg2); BOOST_REQUIRE_THROW( ((*model).*model_method)( coordinates, DEFAULT_MASS, 0, 0, 0 ), Exception ); } // "dead" test: attempt to do something with dead bacterium template<typename Func> static void deadTest( Implementation::Model* model, Func model_method ) { model->kill(0, 0); checkModelMethodForThrow( model, model_method, 0, 0 ); } template<typename Func> static void checkErrorHandling( Implementation::Model* model, Func model_method, bool dead_test ) { // Range errors: test all combinations of // "wrong" (outside of correct range) arguments. // This solution works for coordinates and non-coordinates // methods of Model. (< 0, = 0, > MAX) int wrong_args[] = {-1, 0, MIN_WIDTH}; BOOST_FOREACH (int arg1, wrong_args) { BOOST_FOREACH (int arg2, wrong_args) { if ((arg1 != 0) || (arg2 != 0)) { // (0, 0) is correct checkModelMethodForThrow( model, model_method, arg1, arg2 ); } } } if (dead_test) { // "dead" error // (attempt to do something with dead bacterium) deadTest(model, model_method); } } static Abstract::Point createInBaseCoordinates( Implementation::Model* model ) { Abstract::Point coordinates(0, 0); model->createNewByCoordinates( coordinates, DEFAULT_MASS, 0, 0, 0 ); return coordinates; } static Implementation::Model* createBaseModel( int bacteria = 0, int teams = 1 ) { Implementation::Model* model = Abstract::makeModel<Implementation::Model>( MIN_WIDTH, MIN_HEIGHT, bacteria, teams ); return model; } BOOST_AUTO_TEST_CASE (get_team_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); int team = model->getTeamByCoordinates(coordinates); BOOST_REQUIRE(team == 0); checkErrorHandling<IntOneArgMethod>( model, &Implementation::Model::getTeamByCoordinates, true ); delete model; } BOOST_AUTO_TEST_CASE (width_test) { Implementation::Model* model = createBaseModel(); BOOST_REQUIRE(model->getWidth() == MIN_WIDTH); delete model; } BOOST_AUTO_TEST_CASE (height_test) { Implementation::Model* model = createBaseModel(); BOOST_REQUIRE(model->getHeight() == MIN_HEIGHT); delete model; } BOOST_AUTO_TEST_CASE (bacteria_number_test) { Implementation::Model* model = createBaseModel(); int bacteria_number = model->getBacteriaNumber(0); BOOST_REQUIRE(bacteria_number == 0); createInBaseCoordinates(model); bacteria_number = model->getBacteriaNumber(0); BOOST_REQUIRE(bacteria_number == 1); // range errors BOOST_REQUIRE_THROW(model->getBacteriaNumber(-1), Exception); BOOST_REQUIRE_THROW(model->getBacteriaNumber(1), Exception); delete model; } BOOST_AUTO_TEST_CASE (is_alive_test) { Implementation::Model* model = createBaseModel(1, 1); checkErrorHandling( model, &Implementation::Model::isAlive, false ); BOOST_REQUIRE(model->isAlive(0, 0) == true); model->kill(0, 0); BOOST_REQUIRE(model->isAlive(0, 0) == false); delete model; } BOOST_AUTO_TEST_CASE (get_instruction_test) { Implementation::Model* model = createBaseModel(1, 1); int instruction = model->getInstruction(0, 0); BOOST_REQUIRE(instruction == 0); checkErrorHandling( model, &Implementation::Model::getInstruction, true ); delete model; } BOOST_AUTO_TEST_CASE (get_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); Abstract::Point derived_coordinates = model->getCoordinates(0, 0); BOOST_REQUIRE(derived_coordinates == coordinates); checkErrorHandling( model, &Implementation::Model::getCoordinates, true ); delete model; } BOOST_AUTO_TEST_CASE (get_direction_test) { Implementation::Model* model = createBaseModel(); createInBaseCoordinates(model); int direction = model->getDirection(0, 0); BOOST_REQUIRE(direction == Abstract::LEFT); checkErrorHandling( model, &Implementation::Model::getDirection, true ); delete model; } BOOST_AUTO_TEST_CASE (get_mass_test) { Implementation::Model* model = createBaseModel(1, 1); int mass = model->getMass(0, 0); BOOST_REQUIRE(mass == DEFAULT_MASS); checkErrorHandling( model, &Implementation::Model::getMass, true ); delete model; } BOOST_AUTO_TEST_CASE (kill_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); model->kill(0, 0); Abstract::CellState state = model->cellState(coordinates); BOOST_REQUIRE(state == Abstract::EMPTY); BOOST_REQUIRE(model->isAlive(0, 0) == false); // error handling checks createInBaseCoordinates(model); model->clearBeforeMove(0); checkErrorHandling( model, &Implementation::Model::kill, true ); delete model; } BOOST_AUTO_TEST_CASE (kill_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); model->killByCoordinates(coordinates); Abstract::CellState state = model->cellState(coordinates); BOOST_REQUIRE(state == Abstract::EMPTY); BOOST_REQUIRE(model->isAlive(0, 0) == false); // error handling checks createInBaseCoordinates(model); model->clearBeforeMove(0); checkErrorHandling<OneArgMethod>( model, &Implementation::Model::killByCoordinates, true ); delete model; } BOOST_AUTO_TEST_CASE (change_mass_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); int test_val = 1; model->changeMassByCoordinates(coordinates, test_val); int new_mass = model->getMassByCoordinates(coordinates); BOOST_REQUIRE(new_mass == (DEFAULT_MASS + test_val)); model->changeMassByCoordinates(coordinates, -test_val); new_mass = model->getMassByCoordinates(coordinates); BOOST_REQUIRE(new_mass == DEFAULT_MASS); checkErrorHandling<TwoArgsMethod>( model, &Implementation::Model::changeMassByCoordinates, true ); delete model; } BOOST_AUTO_TEST_CASE (create_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); Abstract::CellState state = model->cellState(coordinates); BOOST_REQUIRE(state == Abstract::BACTERIUM); checkErrorHandling<MultiArgsMethod>( model, &Implementation::Model::createNewByCoordinates, false ); delete model; } <commit_msg>Implement checkModelMethodForThrow <IntThreeArgsMethod><commit_after>/* * bacteria-core, core for cellular automaton * Copyright (C) 2016 Pavel Dolgov * * See the LICENSE file for terms of use. */ #include <boost/foreach.hpp> #include <boost/test/unit_test.hpp> #include "Model.hpp" typedef int (Implementation::Model::*IntOneArgMethod) ( const Abstract::Point& coordinates ) const; typedef Abstract::CellState (Implementation::Model::*OneArgMethod2) ( const Abstract::Point& coordinates ) const; typedef void (Implementation::Model::*OneArgMethod) ( const Abstract::Point& coordinates ); typedef void (Implementation::Model::*TwoArgsMethod) ( const Abstract::Point& coordinates, int change ); typedef void (Implementation::Model::*IntThreeArgsMethod) ( int team, int bacterium_index, int spec ); typedef void (Implementation::Model::*ThreeArgsMethod) ( int team, int bacterium_index, const Abstract::Point& coordinates ); typedef void (Implementation::Model::*MultiArgsMethod) ( const Abstract::Point& coordinates, int mass, int direction, int team, int instruction ); template<typename Func> static void checkOneArgMethod( Implementation::Model* model, Func model_method, int arg1, int arg2 ) { Abstract::Point coordinates(arg1, arg2); BOOST_REQUIRE_THROW( ((*model).*model_method)(coordinates), Exception ); } template<typename Func> void checkModelMethodForThrow( Implementation::Model* model, Func model_method, int arg1, int arg2 ) { BOOST_REQUIRE_THROW( ((*model).*model_method)(arg1, arg2), Exception ); } template<> void checkModelMethodForThrow<IntOneArgMethod>( Implementation::Model* model, IntOneArgMethod model_method, int arg1, int arg2 ) { checkOneArgMethod(model, model_method, arg1, arg2); } template<> void checkModelMethodForThrow<OneArgMethod2>( Implementation::Model* model, OneArgMethod2 model_method, int arg1, int arg2 ) { checkOneArgMethod(model, model_method, arg1, arg2); } template<> void checkModelMethodForThrow<OneArgMethod>( Implementation::Model* model, OneArgMethod model_method, int arg1, int arg2 ) { checkOneArgMethod(model, model_method, arg1, arg2); } template<> void checkModelMethodForThrow<TwoArgsMethod>( Implementation::Model* model, TwoArgsMethod model_method, int arg1, int arg2 ) { Abstract::Point coordinates(arg1, arg2); BOOST_REQUIRE_THROW( ((*model).*model_method)(coordinates, 0), Exception ); } template<> void checkModelMethodForThrow<IntThreeArgsMethod>( Implementation::Model* model, IntThreeArgsMethod model_method, int arg1, int arg2 ) { int spec = 0; BOOST_REQUIRE_THROW( ((*model).*model_method)(arg1, arg2, spec), Exception ); } template<> void checkModelMethodForThrow<MultiArgsMethod>( Implementation::Model* model, MultiArgsMethod model_method, int arg1, int arg2 ) { Abstract::Point coordinates(arg1, arg2); BOOST_REQUIRE_THROW( ((*model).*model_method)( coordinates, DEFAULT_MASS, 0, 0, 0 ), Exception ); } // "dead" test: attempt to do something with dead bacterium template<typename Func> static void deadTest( Implementation::Model* model, Func model_method ) { model->kill(0, 0); checkModelMethodForThrow( model, model_method, 0, 0 ); } template<typename Func> static void checkErrorHandling( Implementation::Model* model, Func model_method, bool dead_test ) { // Range errors: test all combinations of // "wrong" (outside of correct range) arguments. // This solution works for coordinates and non-coordinates // methods of Model. (< 0, = 0, > MAX) int wrong_args[] = {-1, 0, MIN_WIDTH}; BOOST_FOREACH (int arg1, wrong_args) { BOOST_FOREACH (int arg2, wrong_args) { if ((arg1 != 0) || (arg2 != 0)) { // (0, 0) is correct checkModelMethodForThrow( model, model_method, arg1, arg2 ); } } } if (dead_test) { // "dead" error // (attempt to do something with dead bacterium) deadTest(model, model_method); } } static Abstract::Point createInBaseCoordinates( Implementation::Model* model ) { Abstract::Point coordinates(0, 0); model->createNewByCoordinates( coordinates, DEFAULT_MASS, 0, 0, 0 ); return coordinates; } static Implementation::Model* createBaseModel( int bacteria = 0, int teams = 1 ) { Implementation::Model* model = Abstract::makeModel<Implementation::Model>( MIN_WIDTH, MIN_HEIGHT, bacteria, teams ); return model; } BOOST_AUTO_TEST_CASE (get_team_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); int team = model->getTeamByCoordinates(coordinates); BOOST_REQUIRE(team == 0); checkErrorHandling<IntOneArgMethod>( model, &Implementation::Model::getTeamByCoordinates, true ); delete model; } BOOST_AUTO_TEST_CASE (width_test) { Implementation::Model* model = createBaseModel(); BOOST_REQUIRE(model->getWidth() == MIN_WIDTH); delete model; } BOOST_AUTO_TEST_CASE (height_test) { Implementation::Model* model = createBaseModel(); BOOST_REQUIRE(model->getHeight() == MIN_HEIGHT); delete model; } BOOST_AUTO_TEST_CASE (bacteria_number_test) { Implementation::Model* model = createBaseModel(); int bacteria_number = model->getBacteriaNumber(0); BOOST_REQUIRE(bacteria_number == 0); createInBaseCoordinates(model); bacteria_number = model->getBacteriaNumber(0); BOOST_REQUIRE(bacteria_number == 1); // range errors BOOST_REQUIRE_THROW(model->getBacteriaNumber(-1), Exception); BOOST_REQUIRE_THROW(model->getBacteriaNumber(1), Exception); delete model; } BOOST_AUTO_TEST_CASE (is_alive_test) { Implementation::Model* model = createBaseModel(1, 1); checkErrorHandling( model, &Implementation::Model::isAlive, false ); BOOST_REQUIRE(model->isAlive(0, 0) == true); model->kill(0, 0); BOOST_REQUIRE(model->isAlive(0, 0) == false); delete model; } BOOST_AUTO_TEST_CASE (get_instruction_test) { Implementation::Model* model = createBaseModel(1, 1); int instruction = model->getInstruction(0, 0); BOOST_REQUIRE(instruction == 0); checkErrorHandling( model, &Implementation::Model::getInstruction, true ); delete model; } BOOST_AUTO_TEST_CASE (get_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); Abstract::Point derived_coordinates = model->getCoordinates(0, 0); BOOST_REQUIRE(derived_coordinates == coordinates); checkErrorHandling( model, &Implementation::Model::getCoordinates, true ); delete model; } BOOST_AUTO_TEST_CASE (get_direction_test) { Implementation::Model* model = createBaseModel(); createInBaseCoordinates(model); int direction = model->getDirection(0, 0); BOOST_REQUIRE(direction == Abstract::LEFT); checkErrorHandling( model, &Implementation::Model::getDirection, true ); delete model; } BOOST_AUTO_TEST_CASE (get_mass_test) { Implementation::Model* model = createBaseModel(1, 1); int mass = model->getMass(0, 0); BOOST_REQUIRE(mass == DEFAULT_MASS); checkErrorHandling( model, &Implementation::Model::getMass, true ); delete model; } BOOST_AUTO_TEST_CASE (kill_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); model->kill(0, 0); Abstract::CellState state = model->cellState(coordinates); BOOST_REQUIRE(state == Abstract::EMPTY); BOOST_REQUIRE(model->isAlive(0, 0) == false); // error handling checks createInBaseCoordinates(model); model->clearBeforeMove(0); checkErrorHandling( model, &Implementation::Model::kill, true ); delete model; } BOOST_AUTO_TEST_CASE (kill_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); model->killByCoordinates(coordinates); Abstract::CellState state = model->cellState(coordinates); BOOST_REQUIRE(state == Abstract::EMPTY); BOOST_REQUIRE(model->isAlive(0, 0) == false); // error handling checks createInBaseCoordinates(model); model->clearBeforeMove(0); checkErrorHandling<OneArgMethod>( model, &Implementation::Model::killByCoordinates, true ); delete model; } BOOST_AUTO_TEST_CASE (change_mass_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); int test_val = 1; model->changeMassByCoordinates(coordinates, test_val); int new_mass = model->getMassByCoordinates(coordinates); BOOST_REQUIRE(new_mass == (DEFAULT_MASS + test_val)); model->changeMassByCoordinates(coordinates, -test_val); new_mass = model->getMassByCoordinates(coordinates); BOOST_REQUIRE(new_mass == DEFAULT_MASS); checkErrorHandling<TwoArgsMethod>( model, &Implementation::Model::changeMassByCoordinates, true ); delete model; } BOOST_AUTO_TEST_CASE (create_coordinates_test) { Implementation::Model* model = createBaseModel(); Abstract::Point coordinates = createInBaseCoordinates(model); Abstract::CellState state = model->cellState(coordinates); BOOST_REQUIRE(state == Abstract::BACTERIUM); checkErrorHandling<MultiArgsMethod>( model, &Implementation::Model::createNewByCoordinates, false ); delete model; } <|endoftext|>
<commit_before>/** * @file * * @brief This file contains a function to convert a YAML file to a key set. * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ // -- Imports ------------------------------------------------------------------ #include "convert.hpp" #include "listener.hpp" #include "parser.hpp" #include "state.hpp" #include "walk.hpp" #define TAO_PEGTL_NAMESPACE yaypeg #include <tao/pegtl/contrib/parse_tree.hpp> namespace yaypeg { using kdb::Key; using kdb::KeySet; using std::string; // -- Function ----------------------------------------------------------------- /** * @brief This function converts the given YAML file to keys and adds the * result to `keySet`. * * @param keySet The function adds the converted keys to this variable. * @param parent The function uses this parent key of `keySet` to emit error * information. * @param filename This parameter stores the path of the YAML file this * function converts. * * @retval -1 if there was an error converting the YAML file * @retval 0 if parsing was successful and the function did not change the * given keyset * @retval 1 if parsing was successful and the function did change `keySet` */ int addToKeySet (KeySet & keySet, Key & parent, string const & filename) { using std::runtime_error; using tao::TAO_PEGTL_NAMESPACE::analyze; using tao::TAO_PEGTL_NAMESPACE::file_input; using tao::TAO_PEGTL_NAMESPACE::normal; using tao::TAO_PEGTL_NAMESPACE::parse_error; using tao::TAO_PEGTL_NAMESPACE::parse_tree::parse; State state; // Check grammar for problematic code if (analyze<yaml> () != 0) { throw runtime_error ("PEGTLs analyze function found problems while checking the top level grammar rule `yaml`!"); return -1; } file_input<> input{ filename }; /* For detailed debugging information, please use the control class `tracer` instead of `normal`. */ auto root = parse<yaml, selector, action, normal> (input, state); Listener listener{ parent }; walk (listener, *root); auto keys = listener.getKeySet (); int status = (keys.size () <= 0) ? 0 : 1; keySet.append (keys); return status; } } // namespace yaypeg <commit_msg>YAy PEG: Analyze grammar if debug mode is enabled<commit_after>/** * @file * * @brief This file contains a function to convert a YAML file to a key set. * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ // -- Imports ------------------------------------------------------------------ #include "convert.hpp" #include "listener.hpp" #include "parser.hpp" #include "state.hpp" #include "walk.hpp" #define TAO_PEGTL_NAMESPACE yaypeg #include <tao/pegtl/contrib/parse_tree.hpp> namespace yaypeg { using kdb::Key; using kdb::KeySet; using std::string; // -- Function ----------------------------------------------------------------- /** * @brief This function converts the given YAML file to keys and adds the * result to `keySet`. * * @param keySet The function adds the converted keys to this variable. * @param parent The function uses this parent key of `keySet` to emit error * information. * @param filename This parameter stores the path of the YAML file this * function converts. * * @retval -1 if there was an error converting the YAML file * @retval 0 if parsing was successful and the function did not change the * given keyset * @retval 1 if parsing was successful and the function did change `keySet` */ int addToKeySet (KeySet & keySet, Key & parent, string const & filename) { using std::runtime_error; using tao::TAO_PEGTL_NAMESPACE::analyze; using tao::TAO_PEGTL_NAMESPACE::file_input; using tao::TAO_PEGTL_NAMESPACE::normal; using tao::TAO_PEGTL_NAMESPACE::parse_error; using tao::TAO_PEGTL_NAMESPACE::parse_tree::parse; State state; #if DEBUG // Check grammar for problematic code if (analyze<yaml> () != 0) { throw runtime_error ("PEGTLs analyze function found problems while checking the top level grammar rule `yaml`!"); return -1; } #endif file_input<> input{ filename }; /* For detailed debugging information, please use the control class `tracer` instead of `normal`. */ auto root = parse<yaml, selector, action, normal> (input, state); Listener listener{ parent }; walk (listener, *root); auto keys = listener.getKeySet (); int status = (keys.size () <= 0) ? 0 : 1; keySet.append (keys); return status; } } // namespace yaypeg <|endoftext|>
<commit_before>#include <chrono> #include <cstdint> #include <iostream> #include <map> #include <memory> #include <string> #include <thread> #include <utility> #include <uv.h> #include <vector> #include "../log.h" #include "../message_buffer.h" #include "../result.h" #include "../status.h" #include "../thread.h" #include "polled_root.h" #include "polling_thread.h" using std::endl; using std::move; using std::ostream; using std::string; using std::to_string; using std::unique_ptr; using std::vector; PollingThread::PollingThread(uv_async_t *main_callback) : Thread("polling thread", main_callback), poll_interval{DEFAULT_POLL_INTERVAL}, poll_throttle{DEFAULT_POLL_THROTTLE} { freeze(); } Result<> PollingThread::body() { while (true) { LOGGER << "Handling commands." << endl; Result<size_t> cr = handle_commands(); if (cr.is_error()) { LOGGER << "Unable to process incoming commands: " << cr << endl; } else if (is_stopping()) { LOGGER << "Polling thread stopping." << endl; return ok_result(); } Result<> r = cycle(); if (r.is_error()) { LOGGER << "Polling cycle failure " << r << "." << endl; return r.propagate_as_void(); } LOGGER << "Sleeping for " << poll_interval.count() << "ms." << endl; std::this_thread::sleep_for(poll_interval); } } Result<> PollingThread::cycle() { MessageBuffer buffer; size_t remaining = poll_throttle; size_t roots_left = roots.size(); LOGGER << "Polling " << plural(roots_left, "root") << " with " << plural(poll_throttle, "throttle slot") << "." << endl; for (auto &it : roots) { PolledRoot &root = it.second; size_t allotment = remaining / roots_left; LOGGER << "Polling " << root << " with an allotment of " << plural(allotment, "throttle slot") << "." << endl; size_t progress = root.advance(buffer, allotment); remaining -= progress; if (progress != allotment) { LOGGER << root << " only consumed " << plural(progress, "throttle slot") << "." << endl; } roots_left--; } // Ack any commands whose roots are now fully populated. vector<ChannelID> to_erase; for (auto &split : pending_splits) { const ChannelID &channel_id = split.first; const PendingSplit &pending_split = split.second; size_t populated_roots = 0; auto channel_roots = roots.equal_range(channel_id); for (auto root = channel_roots.first; root != channel_roots.second; ++root) { if (root->second.is_all_populated()) populated_roots++; } if (populated_roots >= pending_split.second) { buffer.ack(pending_split.first, channel_id, true, ""); to_erase.push_back(channel_id); } } for (ChannelID &channel_id : to_erase) { pending_splits.erase(channel_id); } return emit_all(buffer.begin(), buffer.end()); } Result<Thread::OfflineCommandOutcome> PollingThread::handle_offline_command(const CommandPayload *command) { Result<OfflineCommandOutcome> r = Thread::handle_offline_command(command); if (r.is_error()) return r; if (command->get_action() == COMMAND_ADD) { return ok_result(TRIGGER_RUN); } if (command->get_action() == COMMAND_POLLING_INTERVAL) { handle_polling_interval_command(command); } if (command->get_action() == COMMAND_POLLING_THROTTLE) { handle_polling_throttle_command(command); } if (command->get_action() == COMMAND_STATUS) { handle_status_command(command); } return ok_result(OFFLINE_ACK); } Result<Thread::CommandOutcome> PollingThread::handle_add_command(const CommandPayload *command) { ostream &logline = LOGGER << "Adding poll root at path " << command->get_root(); if (!command->get_recursive()) logline << " (non-recursively)"; logline << " to channel " << command->get_channel_id() << " with " << plural(command->get_split_count(), "split") << "." << endl; roots.emplace(std::piecewise_construct, std::forward_as_tuple(command->get_channel_id()), std::forward_as_tuple(string(command->get_root()), command->get_channel_id(), command->get_recursive())); auto existing = pending_splits.find(command->get_channel_id()); if (existing != pending_splits.end()) { bool inconsistent = false; string msg("Inconsistent split ADD command received by polling thread: "); const CommandID &existing_command_id = existing->second.first; const size_t &split_count = existing->second.second; if (existing_command_id != command->get_id()) { inconsistent = true; msg += " command ID ("; msg += to_string(existing_command_id); msg += " => "; msg += to_string(command->get_id()); msg += ")"; } if (split_count != command->get_split_count()) { if (inconsistent) { msg += " and"; } msg += " split count ("; msg += to_string(split_count); msg += " => "; msg += to_string(command->get_split_count()); msg += ")"; } if (inconsistent) { return Result<CommandOutcome>::make_error(move(msg)); } return ok_result(NOTHING); } if (command->get_id() != NULL_COMMAND_ID) { pending_splits.emplace(std::piecewise_construct, std::forward_as_tuple(command->get_channel_id()), std::forward_as_tuple(command->get_id(), command->get_split_count())); if (command->get_split_count() == 0u) { return ok_result(ACK); } } return ok_result(NOTHING); } Result<Thread::CommandOutcome> PollingThread::handle_remove_command(const CommandPayload *command) { const ChannelID &channel_id = command->get_channel_id(); LOGGER << "Removing poll roots at channel " << channel_id << "." << endl; roots.erase(command->get_channel_id()); // Ensure that we ack the ADD command even if the REMOVE command arrives before all of its splits populate. auto pending = pending_splits.find(channel_id); if (pending != pending_splits.end()) { const PendingSplit &split = pending->second; const CommandID &add_command_id = split.first; Result<> r0 = emit(Message(AckPayload(add_command_id, channel_id, false, "Command cancelled"))); pending_splits.erase(pending); if (r0.is_error()) return r0.propagate<CommandOutcome>(); } if (roots.empty()) { LOGGER << "Final root removed." << endl; return ok_result(TRIGGER_STOP); } return ok_result(ACK); } Result<Thread::CommandOutcome> PollingThread::handle_polling_interval_command(const CommandPayload *command) { poll_interval = std::chrono::milliseconds(command->get_arg()); return ok_result(ACK); } Result<Thread::CommandOutcome> PollingThread::handle_polling_throttle_command(const CommandPayload *command) { poll_throttle = command->get_arg(); return ok_result(ACK); } Result<Thread::CommandOutcome> PollingThread::handle_status_command(const CommandPayload *command) { unique_ptr<Status> status{new Status()}; status->polling_thread_state = state_name(); status->polling_thread_ok = get_message(); status->polling_in_size = get_in_queue_size(); status->polling_in_ok = get_in_queue_error(); status->polling_out_size = get_out_queue_size(); status->polling_out_ok = get_out_queue_error(); status->polling_root_count = roots.size(); status->polling_entry_count = 0; for (auto &pair : roots) { status->polling_entry_count += pair.second.count_entries(); } Result<> r = emit(Message(StatusPayload(command->get_request_id(), move(status)))); return r.propagate(NOTHING); } <commit_msg>Measure polling cycles<commit_after>#include <chrono> #include <cstdint> #include <iostream> #include <map> #include <memory> #include <string> #include <thread> #include <utility> #include <uv.h> #include <vector> #include "../log.h" #include "../message_buffer.h" #include "../result.h" #include "../status.h" #include "../thread.h" #include "polled_root.h" #include "polling_thread.h" using std::endl; using std::move; using std::ostream; using std::string; using std::to_string; using std::unique_ptr; using std::vector; PollingThread::PollingThread(uv_async_t *main_callback) : Thread("polling thread", main_callback), poll_interval{DEFAULT_POLL_INTERVAL}, poll_throttle{DEFAULT_POLL_THROTTLE} { freeze(); } Result<> PollingThread::body() { while (true) { Timer t; LOGGER << "Handling commands." << endl; Result<size_t> cr = handle_commands(); if (cr.is_error()) { LOGGER << "Unable to process incoming commands: " << cr << endl; } else if (is_stopping()) { LOGGER << "Polling thread stopping." << endl; return ok_result(); } Result<> r = cycle(); if (r.is_error()) { LOGGER << "Polling cycle failure " << r << "." << endl; return r.propagate_as_void(); } LOGGER << "Polling cycle complete in " << t << ". Sleeping for " << poll_interval.count() << "ms." << endl; std::this_thread::sleep_for(poll_interval); } } Result<> PollingThread::cycle() { MessageBuffer buffer; size_t remaining = poll_throttle; size_t roots_left = roots.size(); LOGGER << "Polling " << plural(roots_left, "root") << " with " << plural(poll_throttle, "throttle slot") << "." << endl; for (auto &it : roots) { PolledRoot &root = it.second; size_t allotment = remaining / roots_left; LOGGER << "Polling " << root << " with an allotment of " << plural(allotment, "throttle slot") << "." << endl; size_t progress = root.advance(buffer, allotment); remaining -= progress; if (progress != allotment) { LOGGER << root << " only consumed " << plural(progress, "throttle slot") << "." << endl; } roots_left--; } // Ack any commands whose roots are now fully populated. vector<ChannelID> to_erase; for (auto &split : pending_splits) { const ChannelID &channel_id = split.first; const PendingSplit &pending_split = split.second; size_t populated_roots = 0; auto channel_roots = roots.equal_range(channel_id); for (auto root = channel_roots.first; root != channel_roots.second; ++root) { if (root->second.is_all_populated()) populated_roots++; } if (populated_roots >= pending_split.second) { buffer.ack(pending_split.first, channel_id, true, ""); to_erase.push_back(channel_id); } } for (ChannelID &channel_id : to_erase) { pending_splits.erase(channel_id); } return emit_all(buffer.begin(), buffer.end()); } Result<Thread::OfflineCommandOutcome> PollingThread::handle_offline_command(const CommandPayload *command) { Result<OfflineCommandOutcome> r = Thread::handle_offline_command(command); if (r.is_error()) return r; if (command->get_action() == COMMAND_ADD) { return ok_result(TRIGGER_RUN); } if (command->get_action() == COMMAND_POLLING_INTERVAL) { handle_polling_interval_command(command); } if (command->get_action() == COMMAND_POLLING_THROTTLE) { handle_polling_throttle_command(command); } if (command->get_action() == COMMAND_STATUS) { handle_status_command(command); } return ok_result(OFFLINE_ACK); } Result<Thread::CommandOutcome> PollingThread::handle_add_command(const CommandPayload *command) { ostream &logline = LOGGER << "Adding poll root at path " << command->get_root(); if (!command->get_recursive()) logline << " (non-recursively)"; logline << " to channel " << command->get_channel_id() << " with " << plural(command->get_split_count(), "split") << "." << endl; roots.emplace(std::piecewise_construct, std::forward_as_tuple(command->get_channel_id()), std::forward_as_tuple(string(command->get_root()), command->get_channel_id(), command->get_recursive())); auto existing = pending_splits.find(command->get_channel_id()); if (existing != pending_splits.end()) { bool inconsistent = false; string msg("Inconsistent split ADD command received by polling thread: "); const CommandID &existing_command_id = existing->second.first; const size_t &split_count = existing->second.second; if (existing_command_id != command->get_id()) { inconsistent = true; msg += " command ID ("; msg += to_string(existing_command_id); msg += " => "; msg += to_string(command->get_id()); msg += ")"; } if (split_count != command->get_split_count()) { if (inconsistent) { msg += " and"; } msg += " split count ("; msg += to_string(split_count); msg += " => "; msg += to_string(command->get_split_count()); msg += ")"; } if (inconsistent) { return Result<CommandOutcome>::make_error(move(msg)); } return ok_result(NOTHING); } if (command->get_id() != NULL_COMMAND_ID) { pending_splits.emplace(std::piecewise_construct, std::forward_as_tuple(command->get_channel_id()), std::forward_as_tuple(command->get_id(), command->get_split_count())); if (command->get_split_count() == 0u) { return ok_result(ACK); } } return ok_result(NOTHING); } Result<Thread::CommandOutcome> PollingThread::handle_remove_command(const CommandPayload *command) { const ChannelID &channel_id = command->get_channel_id(); LOGGER << "Removing poll roots at channel " << channel_id << "." << endl; roots.erase(command->get_channel_id()); // Ensure that we ack the ADD command even if the REMOVE command arrives before all of its splits populate. auto pending = pending_splits.find(channel_id); if (pending != pending_splits.end()) { const PendingSplit &split = pending->second; const CommandID &add_command_id = split.first; Result<> r0 = emit(Message(AckPayload(add_command_id, channel_id, false, "Command cancelled"))); pending_splits.erase(pending); if (r0.is_error()) return r0.propagate<CommandOutcome>(); } if (roots.empty()) { LOGGER << "Final root removed." << endl; return ok_result(TRIGGER_STOP); } return ok_result(ACK); } Result<Thread::CommandOutcome> PollingThread::handle_polling_interval_command(const CommandPayload *command) { poll_interval = std::chrono::milliseconds(command->get_arg()); return ok_result(ACK); } Result<Thread::CommandOutcome> PollingThread::handle_polling_throttle_command(const CommandPayload *command) { poll_throttle = command->get_arg(); return ok_result(ACK); } Result<Thread::CommandOutcome> PollingThread::handle_status_command(const CommandPayload *command) { unique_ptr<Status> status{new Status()}; status->polling_thread_state = state_name(); status->polling_thread_ok = get_message(); status->polling_in_size = get_in_queue_size(); status->polling_in_ok = get_in_queue_error(); status->polling_out_size = get_out_queue_size(); status->polling_out_ok = get_out_queue_error(); status->polling_root_count = roots.size(); status->polling_entry_count = 0; for (auto &pair : roots) { status->polling_entry_count += pair.second.count_entries(); } Result<> r = emit(Message(StatusPayload(command->get_request_id(), move(status)))); return r.propagate(NOTHING); } <|endoftext|>
<commit_before>#include "post_process/adminizer.hpp" #include <mapnik/params.hpp> #include <mapnik/datasource.hpp> #include <mapnik/datasource_cache.hpp> #include <mapnik/featureset.hpp> #include <boost/geometry.hpp> #include <boost/geometry/geometries/point.hpp> #include <boost/geometry/geometries/box.hpp> #include <boost/geometry/geometries/polygon.hpp> #include <boost/geometry/geometries/multi_point.hpp> #include <boost/geometry/multi/geometries/multi_linestring.hpp> #include <boost/geometry/index/rtree.hpp> // NOTE: this is included only because it's where mapnik::coord2d is // adapted to work with the boost::geometry stuff. we don't actually // clip any polygons. #include <mapnik/polygon_clipper.hpp> namespace bg = boost::geometry; namespace bgi = boost::geometry::index; using point_2d = bg::model::point<double, 2, bg::cs::cartesian>; using box_2d = bg::model::box<point_2d>; using linestring_2d = bg::model::linestring<point_2d>; using multi_point_2d = bg::model::multi_point<point_2d>; using multi_linestring_2d = bg::model::multi_linestring<linestring_2d>; using polygon_2d = bg::model::polygon<point_2d>; namespace { typedef std::pair<box_2d, unsigned int> value; struct entry { entry(polygon_2d &&p, mapnik::value &&v, unsigned int i) : polygon(p), value(v), index(i) { } polygon_2d polygon; mapnik::value value; unsigned int index; }; struct param_updater { mapnik::feature_ptr &m_feature; const std::string &m_param_name; bool m_collect; const mapnik::value_unicode_string &m_delimiter; std::set<unsigned int> m_indices; bool m_finished; param_updater(mapnik::feature_ptr &feat, const std::string &param_name, bool collect, const mapnik::value_unicode_string &delimiter) : m_feature(feat), m_param_name(param_name) , m_collect(collect) , m_delimiter(delimiter) , m_indices() , m_finished(false) { } void operator()(const entry &e) { m_indices.insert(e.index); // early termination only if we're looking for the first admin // area and just found it. m_finished = (!m_collect) && (e.index == 0); } void finish(const std::vector<entry> &entries) { if (!m_indices.empty()) { if (m_collect) { mapnik::value_unicode_string buffer; bool first = true; for (unsigned int i : m_indices) { if (first) { first = false; } else { buffer.append(m_delimiter); } buffer.append(entries[i].value.to_unicode()); } m_feature->put_new(m_param_name, buffer); } else { const entry &e = entries[*m_indices.begin()]; m_feature->put_new(m_param_name, e.value); } } } }; template <typename GeomType> struct intersects_iterator { const GeomType &m_geom; const std::vector<entry> &m_entries; param_updater &m_updater; intersects_iterator(const GeomType &geom, const std::vector<entry> &entries, param_updater &updater) : m_geom(geom), m_entries(entries), m_updater(updater) { } intersects_iterator &operator++() { // prefix return *this; } intersects_iterator &operator*() { return *this; } intersects_iterator &operator=(const value &v) { const entry &e = m_entries[v.second]; // do detailed intersection test, as the index only does bounding // box intersection tests. if (intersects(e.polygon)) { m_updater(e); } return *this; } bool intersects(const polygon_2d &) const; }; template <> bool intersects_iterator<multi_point_2d>::intersects(const polygon_2d &poly) const { // TODO: remove this hack when/if bg::intersects supports // intersection on multi type. for (auto point : m_geom) { if (bg::intersects(point, poly)) { return true; } } return false; } template <> bool intersects_iterator<multi_linestring_2d>::intersects(const polygon_2d &poly) const { // TODO: remove this hack when/if bg::intersects supports // intersection on multi type. for (auto line : m_geom) { if (bg::intersects(line, poly)) { return true; } } return false; } template <> bool intersects_iterator<polygon_2d>::intersects(const polygon_2d &poly) const { return bg::intersects(m_geom, poly); } template <typename RTreeType, typename GeomType> void try_update(RTreeType &index, const GeomType &geom, const std::vector<entry> &entries, param_updater &updater) { intersects_iterator<GeomType> itr(geom, entries, updater); index.query(bgi::intersects(bg::return_envelope<box_2d>(geom)), itr); } } // anonymous namespace namespace avecado { namespace post_process { using rtree = bgi::rtree<value, bgi::quadratic<16> >; /** * Post-process that applies administrative region attribution * to features, based on geographic location of the geometry. */ class adminizer : public izer { public: adminizer(pt::ptree const& config); virtual ~adminizer(); virtual void process(std::vector<mapnik::feature_ptr> &layer) const; private: mapnik::box2d<double> envelope(const std::vector<mapnik::feature_ptr> &layer) const; multi_point_2d make_boost_point(const mapnik::geometry_type &geom) const; multi_linestring_2d make_boost_linestring(const mapnik::geometry_type &geom) const; polygon_2d make_boost_polygon(const mapnik::geometry_type &geom) const; std::vector<entry> make_entries(const mapnik::box2d<double> &env) const; rtree make_index(const std::vector<entry> &entries) const; void adminize_feature(mapnik::feature_ptr &f, const rtree &index, const std::vector<entry> &entries) const; // the name of the parameter to take from the admin polygon and set // on the feature being adminized. std::string m_param_name; // if true, split geometries at admin polygon boundaries. if false, // do not modify the geometries. bool m_split; // if true, collect all matching admin parameters. if false, use the // first admin parameter only. bool m_collect; // string to use to separate parameter values when m_collect == true. mapnik::value_unicode_string m_delimiter; // data source to fetch matching admin boundaries from. std::shared_ptr<mapnik::datasource> m_datasource; }; adminizer::adminizer(pt::ptree const& config) : m_param_name(config.get<std::string>("param_name")) , m_split(false) , m_collect(false) , m_delimiter(icu::UnicodeString::fromUTF8(",")) { mapnik::parameters params; boost::optional<pt::ptree const &> datasource_config = config.get_child_optional("datasource"); if (datasource_config) { for (auto &kv : *datasource_config) { params[kv.first] = kv.second.data(); } } m_datasource = mapnik::datasource_cache::instance().create(params); boost::optional<std::string> split = config.get_optional<std::string>("split"); if (split) { m_split = *split == "true"; } boost::optional<std::string> collect = config.get_optional<std::string>("collect"); if (collect) { m_collect = *collect == "true"; } boost::optional<std::string> delimiter = config.get_optional<std::string>("delimiter"); if (delimiter) { m_delimiter = mapnik::value_unicode_string(icu::UnicodeString::fromUTF8(*delimiter)); } } adminizer::~adminizer() { } std::vector<entry> adminizer::make_entries(const mapnik::box2d<double> &env) const { // query the datasource // TODO: do we want to pass more things like scale denominator // and resolution type? mapnik::featureset_ptr fset = m_datasource->features(mapnik::query(env)); std::vector<entry> entries; unsigned int index = 0; mapnik::feature_ptr f; while (f = fset->next()) { mapnik::value param = f->get(m_param_name); for (auto const &geom : f->paths()) { // ignore all non-polygon types if (geom.type() == mapnik::geometry_type::types::Polygon) { entries.emplace_back(make_boost_polygon(geom), std::move(param), index++); } } } return entries; } rtree adminizer::make_index(const std::vector<entry> &entries) const { // create envelope boxes for entries, as these are needed // up-front for the packing algorithm. std::vector<value> values; values.reserve(entries.size()); const size_t num_entries = entries.size(); for (size_t i = 0; i < num_entries; ++i) { values.emplace_back(bg::return_envelope<box_2d>(entries[i].polygon), i); } // construct index using packing algorithm, which leads to // better distribution for querying. return rtree(values.begin(), values.end()); } void adminizer::adminize_feature(mapnik::feature_ptr &f, const rtree &index, const std::vector<entry> &entries) const { param_updater updater(f, m_param_name, m_collect, m_delimiter); for (auto const &geom : f->paths()) { if (geom.type() == mapnik::geometry_type::types::Point) { multi_point_2d multi_point = make_boost_point(geom); try_update(index, multi_point, entries, updater); } else if (geom.type() == mapnik::geometry_type::types::LineString) { multi_linestring_2d multi_line = make_boost_linestring(geom); try_update(index, multi_line, entries, updater); } else if (geom.type() == mapnik::geometry_type::types::Polygon) { polygon_2d poly = make_boost_polygon(geom); try_update(index, poly, entries, updater); } // quick exit the loop if there's nothing more to do. if (updater.m_finished) { break; } } updater.finish(entries); } void adminizer::process(std::vector<mapnik::feature_ptr> &layer) const { // build extent of all features in layer mapnik::box2d<double> env = envelope(layer); // construct an index over the bounding boxes of the geometry, // first extracting the geometries from mapnik's representation // and transforming them too boost::geometry's representation. std::vector<entry> entries = make_entries(env); rtree index = make_index(entries); // loop over features, finding which items from the datasource // they intersect with. for (mapnik::feature_ptr f : layer) { adminize_feature(f, index, entries); } } mapnik::box2d<double> adminizer::envelope(const std::vector<mapnik::feature_ptr> &layer) const { mapnik::box2d<double> result; bool first = true; for (auto const &feature : layer) { if (first) { result = feature->envelope(); } else { result.expand_to_include(feature->envelope()); } } return result; } multi_point_2d adminizer::make_boost_point(const mapnik::geometry_type &geom) const { /* Takes a mapnik geometry and makes a multi_point_2d from it. It has to be a * multipoint, since we don't know from geom.type() if it's a point or multipoint? */ multi_point_2d points; double x = 0, y = 0; geom.rewind(0); unsigned int cmd = mapnik::SEG_END; while ((cmd = geom.vertex(&x, &y)) != mapnik::SEG_END) { points.push_back(bg::make<point_2d>(x, y)); } return points; } multi_linestring_2d adminizer::make_boost_linestring(const mapnik::geometry_type &geom) const { multi_linestring_2d line; double x = 0, y = 0, prev_x = 0, prev_y = 0; geom.rewind(0); unsigned int cmd = mapnik::SEG_END; while ((cmd = geom.vertex(&x, &y)) != mapnik::SEG_END) { if (cmd == mapnik::SEG_MOVETO) { line.push_back(linestring_2d()); line.back().push_back(bg::make<point_2d>(x, y)); } else if (cmd == mapnik::SEG_LINETO) { if (std::abs(x - prev_x) < 1e-12 && std::abs(y - prev_y) < 1e-12) { continue; } line.back().push_back(bg::make<point_2d>(x, y)); } prev_x = x; prev_y = y; } return line; } polygon_2d adminizer::make_boost_polygon(const mapnik::geometry_type &geom) const { polygon_2d poly; double x = 0, y = 0, prev_x = 0, prev_y = 0; unsigned int ring_count = 0; geom.rewind(0); unsigned int cmd = mapnik::SEG_END; while ((cmd = geom.vertex(&x, &y)) != mapnik::SEG_END) { if (cmd == mapnik::SEG_MOVETO) { if (ring_count == 0) { bg::append(poly, bg::make<point_2d>(x, y)); } else { poly.inners().push_back(polygon_2d::inner_container_type::value_type()); bg::append(poly.inners().back(), bg::make<point_2d>(x, y)); } ++ring_count; } else if (cmd == mapnik::SEG_LINETO) { if (std::abs(x - prev_x) < 1e-12 && std::abs(y - prev_y) < 1e-12) { continue; } if (ring_count == 1) { bg::append(poly, bg::make<point_2d>(x, y)); } else { bg::append(poly.inners().back(), bg::make<point_2d>(x, y)); } } prev_x = x; prev_y = y; } return poly; } izer_ptr create_adminizer(pt::ptree const& config) { return std::make_shared<adminizer>(config); } } // namespace post_process } // namespace avecado <commit_msg>Refactoring in preparation for returning split features.<commit_after>#include "post_process/adminizer.hpp" #include <mapnik/params.hpp> #include <mapnik/datasource.hpp> #include <mapnik/datasource_cache.hpp> #include <mapnik/featureset.hpp> #include <boost/geometry.hpp> #include <boost/geometry/geometries/point.hpp> #include <boost/geometry/geometries/box.hpp> #include <boost/geometry/geometries/polygon.hpp> #include <boost/geometry/geometries/multi_point.hpp> #include <boost/geometry/multi/geometries/multi_linestring.hpp> #include <boost/geometry/index/rtree.hpp> // NOTE: this is included only because it's where mapnik::coord2d is // adapted to work with the boost::geometry stuff. we don't actually // clip any polygons. #include <mapnik/polygon_clipper.hpp> namespace bg = boost::geometry; namespace bgi = boost::geometry::index; using point_2d = bg::model::point<double, 2, bg::cs::cartesian>; using box_2d = bg::model::box<point_2d>; using linestring_2d = bg::model::linestring<point_2d>; using multi_point_2d = bg::model::multi_point<point_2d>; using multi_linestring_2d = bg::model::multi_linestring<linestring_2d>; using polygon_2d = bg::model::polygon<point_2d>; namespace { typedef std::pair<box_2d, unsigned int> value; struct entry { entry(polygon_2d &&p, mapnik::value &&v, unsigned int i) : polygon(p), value(v), index(i) { } polygon_2d polygon; mapnik::value value; unsigned int index; }; struct param_updater { bool m_collect; std::set<unsigned int> m_indices; bool m_finished; explicit param_updater(bool collect) : m_collect(collect) , m_indices() , m_finished(false) { } void operator()(const entry &e) { m_indices.insert(e.index); // early termination only if we're looking for the first admin // area and just found it. m_finished = (!m_collect) && (e.index == 0); } }; void update_feature_params(const param_updater &updater, const std::vector<entry> &entries, mapnik::feature_ptr &&feat, const std::string &param_name, const mapnik::value_unicode_string &delimiter, std::vector<mapnik::feature_ptr> &append_to) { append_to.emplace_back(feat); mapnik::feature_ptr &feature = append_to.back(); if (!updater.m_indices.empty()) { if (updater.m_collect) { mapnik::value_unicode_string buffer; bool first = true; for (unsigned int i : updater.m_indices) { if (first) { first = false; } else { buffer.append(delimiter); } buffer.append(entries[i].value.to_unicode()); } feature->put_new(param_name, buffer); } else { const entry &e = entries[*updater.m_indices.begin()]; feature->put_new(param_name, e.value); } } } template <typename GeomType> struct intersects_iterator { const GeomType &m_geom; const std::vector<entry> &m_entries; param_updater &m_updater; intersects_iterator(const GeomType &geom, const std::vector<entry> &entries, param_updater &updater) : m_geom(geom), m_entries(entries), m_updater(updater) { } intersects_iterator &operator++() { // prefix return *this; } intersects_iterator &operator*() { return *this; } intersects_iterator &operator=(const value &v) { const entry &e = m_entries[v.second]; // do detailed intersection test, as the index only does bounding // box intersection tests. if (intersects(e.polygon)) { m_updater(e); } return *this; } bool intersects(const polygon_2d &) const; }; template <> bool intersects_iterator<multi_point_2d>::intersects(const polygon_2d &poly) const { // TODO: remove this hack when/if bg::intersects supports // intersection on multi type. for (auto point : m_geom) { if (bg::intersects(point, poly)) { return true; } } return false; } template <> bool intersects_iterator<multi_linestring_2d>::intersects(const polygon_2d &poly) const { // TODO: remove this hack when/if bg::intersects supports // intersection on multi type. for (auto line : m_geom) { if (bg::intersects(line, poly)) { return true; } } return false; } template <> bool intersects_iterator<polygon_2d>::intersects(const polygon_2d &poly) const { return bg::intersects(m_geom, poly); } template <typename RTreeType, typename GeomType> void try_update(RTreeType &index, const GeomType &geom, const std::vector<entry> &entries, param_updater &updater) { intersects_iterator<GeomType> itr(geom, entries, updater); index.query(bgi::intersects(bg::return_envelope<box_2d>(geom)), itr); } } // anonymous namespace namespace avecado { namespace post_process { using rtree = bgi::rtree<value, bgi::quadratic<16> >; /** * Post-process that applies administrative region attribution * to features, based on geographic location of the geometry. */ class adminizer : public izer { public: adminizer(pt::ptree const& config); virtual ~adminizer(); virtual void process(std::vector<mapnik::feature_ptr> &layer) const; private: mapnik::box2d<double> envelope(const std::vector<mapnik::feature_ptr> &layer) const; multi_point_2d make_boost_point(const mapnik::geometry_type &geom) const; multi_linestring_2d make_boost_linestring(const mapnik::geometry_type &geom) const; polygon_2d make_boost_polygon(const mapnik::geometry_type &geom) const; std::vector<entry> make_entries(const mapnik::box2d<double> &env) const; rtree make_index(const std::vector<entry> &entries) const; void adminize_feature(mapnik::feature_ptr &&f, const rtree &index, const std::vector<entry> &entries, std::vector<mapnik::feature_ptr> &append_to) const; // the name of the parameter to take from the admin polygon and set // on the feature being adminized. std::string m_param_name; // if true, split geometries at admin polygon boundaries. if false, // do not modify the geometries. bool m_split; // if true, collect all matching admin parameters. if false, use the // first admin parameter only. bool m_collect; // string to use to separate parameter values when m_collect == true. mapnik::value_unicode_string m_delimiter; // data source to fetch matching admin boundaries from. std::shared_ptr<mapnik::datasource> m_datasource; }; adminizer::adminizer(pt::ptree const& config) : m_param_name(config.get<std::string>("param_name")) , m_split(false) , m_collect(false) , m_delimiter(icu::UnicodeString::fromUTF8(",")) { mapnik::parameters params; boost::optional<pt::ptree const &> datasource_config = config.get_child_optional("datasource"); if (datasource_config) { for (auto &kv : *datasource_config) { params[kv.first] = kv.second.data(); } } m_datasource = mapnik::datasource_cache::instance().create(params); boost::optional<std::string> split = config.get_optional<std::string>("split"); if (split) { m_split = *split == "true"; } boost::optional<std::string> collect = config.get_optional<std::string>("collect"); if (collect) { m_collect = *collect == "true"; } boost::optional<std::string> delimiter = config.get_optional<std::string>("delimiter"); if (delimiter) { m_delimiter = mapnik::value_unicode_string(icu::UnicodeString::fromUTF8(*delimiter)); } } adminizer::~adminizer() { } std::vector<entry> adminizer::make_entries(const mapnik::box2d<double> &env) const { // query the datasource // TODO: do we want to pass more things like scale denominator // and resolution type? mapnik::featureset_ptr fset = m_datasource->features(mapnik::query(env)); std::vector<entry> entries; unsigned int index = 0; mapnik::feature_ptr f; while (f = fset->next()) { mapnik::value param = f->get(m_param_name); for (auto const &geom : f->paths()) { // ignore all non-polygon types if (geom.type() == mapnik::geometry_type::types::Polygon) { entries.emplace_back(make_boost_polygon(geom), std::move(param), index++); } } } return entries; } rtree adminizer::make_index(const std::vector<entry> &entries) const { // create envelope boxes for entries, as these are needed // up-front for the packing algorithm. std::vector<value> values; values.reserve(entries.size()); const size_t num_entries = entries.size(); for (size_t i = 0; i < num_entries; ++i) { values.emplace_back(bg::return_envelope<box_2d>(entries[i].polygon), i); } // construct index using packing algorithm, which leads to // better distribution for querying. return rtree(values.begin(), values.end()); } void adminizer::adminize_feature(mapnik::feature_ptr &&f, const rtree &index, const std::vector<entry> &entries, std::vector<mapnik::feature_ptr> &append_to) const { param_updater updater(m_collect); for (auto const &geom : f->paths()) { if (geom.type() == mapnik::geometry_type::types::Point) { multi_point_2d multi_point = make_boost_point(geom); try_update(index, multi_point, entries, updater); } else if (geom.type() == mapnik::geometry_type::types::LineString) { multi_linestring_2d multi_line = make_boost_linestring(geom); try_update(index, multi_line, entries, updater); } else if (geom.type() == mapnik::geometry_type::types::Polygon) { polygon_2d poly = make_boost_polygon(geom); try_update(index, poly, entries, updater); } // quick exit the loop if there's nothing more to do. if (updater.m_finished) { break; } } update_feature_params(updater, entries, std::move(f), m_param_name, m_delimiter, append_to); } void adminizer::process(std::vector<mapnik::feature_ptr> &layer) const { // build extent of all features in layer mapnik::box2d<double> env = envelope(layer); // construct an index over the bounding boxes of the geometry, // first extracting the geometries from mapnik's representation // and transforming them too boost::geometry's representation. std::vector<entry> entries = make_entries(env); rtree index = make_index(entries); // loop over features, finding which items from the datasource // they intersect with. std::vector<mapnik::feature_ptr> new_features; for (mapnik::feature_ptr &f : layer) { adminize_feature(std::move(f), index, entries, new_features); } // move new features into the same array that we were passed. // this is so that we can add new features (e.g: when split). layer.clear(); layer.swap(new_features); } mapnik::box2d<double> adminizer::envelope(const std::vector<mapnik::feature_ptr> &layer) const { mapnik::box2d<double> result; bool first = true; for (auto const &feature : layer) { if (first) { result = feature->envelope(); } else { result.expand_to_include(feature->envelope()); } } return result; } multi_point_2d adminizer::make_boost_point(const mapnik::geometry_type &geom) const { /* Takes a mapnik geometry and makes a multi_point_2d from it. It has to be a * multipoint, since we don't know from geom.type() if it's a point or multipoint? */ multi_point_2d points; double x = 0, y = 0; geom.rewind(0); unsigned int cmd = mapnik::SEG_END; while ((cmd = geom.vertex(&x, &y)) != mapnik::SEG_END) { points.push_back(bg::make<point_2d>(x, y)); } return points; } multi_linestring_2d adminizer::make_boost_linestring(const mapnik::geometry_type &geom) const { multi_linestring_2d line; double x = 0, y = 0, prev_x = 0, prev_y = 0; geom.rewind(0); unsigned int cmd = mapnik::SEG_END; while ((cmd = geom.vertex(&x, &y)) != mapnik::SEG_END) { if (cmd == mapnik::SEG_MOVETO) { line.push_back(linestring_2d()); line.back().push_back(bg::make<point_2d>(x, y)); } else if (cmd == mapnik::SEG_LINETO) { if (std::abs(x - prev_x) < 1e-12 && std::abs(y - prev_y) < 1e-12) { continue; } line.back().push_back(bg::make<point_2d>(x, y)); } prev_x = x; prev_y = y; } return line; } polygon_2d adminizer::make_boost_polygon(const mapnik::geometry_type &geom) const { polygon_2d poly; double x = 0, y = 0, prev_x = 0, prev_y = 0; unsigned int ring_count = 0; geom.rewind(0); unsigned int cmd = mapnik::SEG_END; while ((cmd = geom.vertex(&x, &y)) != mapnik::SEG_END) { if (cmd == mapnik::SEG_MOVETO) { if (ring_count == 0) { bg::append(poly, bg::make<point_2d>(x, y)); } else { poly.inners().push_back(polygon_2d::inner_container_type::value_type()); bg::append(poly.inners().back(), bg::make<point_2d>(x, y)); } ++ring_count; } else if (cmd == mapnik::SEG_LINETO) { if (std::abs(x - prev_x) < 1e-12 && std::abs(y - prev_y) < 1e-12) { continue; } if (ring_count == 1) { bg::append(poly, bg::make<point_2d>(x, y)); } else { bg::append(poly.inners().back(), bg::make<point_2d>(x, y)); } } prev_x = x; prev_y = y; } return poly; } izer_ptr create_adminizer(pt::ptree const& config) { return std::make_shared<adminizer>(config); } } // namespace post_process } // namespace avecado <|endoftext|>
<commit_before>// Copyright (c) 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // minidump_dump.cc: Print the contents of a minidump file in somewhat // readable text. // // Author: Mark Mentovai #include <stdio.h> #include <string.h> #include "client/linux/minidump_writer/minidump_extension_linux.h" #include "google_breakpad/processor/minidump.h" #include "processor/logging.h" #include "processor/scoped_ptr.h" namespace { using google_breakpad::Minidump; using google_breakpad::MinidumpThreadList; using google_breakpad::MinidumpModuleList; using google_breakpad::MinidumpMemoryInfoList; using google_breakpad::MinidumpMemoryList; using google_breakpad::MinidumpException; using google_breakpad::MinidumpAssertion; using google_breakpad::MinidumpSystemInfo; using google_breakpad::MinidumpMiscInfo; using google_breakpad::MinidumpBreakpadInfo; static void DumpRawStream(Minidump *minidump, u_int32_t stream_type, const char *stream_name, int *errors) { u_int32_t length = 0; if (!minidump->SeekToStreamType(stream_type, &length)) { return; } printf("Stream %s:\n", stream_name); if (length == 0) { printf("\n"); return; } std::vector<char> contents(length); if (!minidump->ReadBytes(&contents[0], length)) { ++*errors; BPLOG(ERROR) << "minidump.ReadBytes failed"; return; } size_t current_offset = 0; while (current_offset < length) { size_t remaining = length - current_offset; printf("%.*s", remaining, &contents[current_offset]); char *next_null = reinterpret_cast<char *>( memchr(&contents[current_offset], 0, remaining)); if (next_null == NULL) break; printf("\\0\n"); size_t null_offset = next_null - &contents[0]; current_offset = null_offset + 1; } printf("\n\n"); } static bool PrintMinidumpDump(const char *minidump_file) { Minidump minidump(minidump_file); if (!minidump.Read()) { BPLOG(ERROR) << "minidump.Read() failed"; return false; } minidump.Print(); int errors = 0; MinidumpThreadList *thread_list = minidump.GetThreadList(); if (!thread_list) { ++errors; BPLOG(ERROR) << "minidump.GetThreadList() failed"; } else { thread_list->Print(); } MinidumpModuleList *module_list = minidump.GetModuleList(); if (!module_list) { ++errors; BPLOG(ERROR) << "minidump.GetModuleList() failed"; } else { module_list->Print(); } MinidumpMemoryList *memory_list = minidump.GetMemoryList(); if (!memory_list) { ++errors; BPLOG(ERROR) << "minidump.GetMemoryList() failed"; } else { memory_list->Print(); } MinidumpException *exception = minidump.GetException(); if (!exception) { BPLOG(INFO) << "minidump.GetException() failed"; } else { exception->Print(); } MinidumpAssertion *assertion = minidump.GetAssertion(); if (!assertion) { BPLOG(INFO) << "minidump.GetAssertion() failed"; } else { assertion->Print(); } MinidumpSystemInfo *system_info = minidump.GetSystemInfo(); if (!system_info) { ++errors; BPLOG(ERROR) << "minidump.GetSystemInfo() failed"; } else { system_info->Print(); } MinidumpMiscInfo *misc_info = minidump.GetMiscInfo(); if (!misc_info) { ++errors; BPLOG(ERROR) << "minidump.GetMiscInfo() failed"; } else { misc_info->Print(); } MinidumpBreakpadInfo *breakpad_info = minidump.GetBreakpadInfo(); if (!breakpad_info) { // Breakpad info is optional, so don't treat this as an error. BPLOG(INFO) << "minidump.GetBreakpadInfo() failed"; } else { breakpad_info->Print(); } MinidumpMemoryInfoList *memory_info_list = minidump.GetMemoryInfoList(); if (!memory_info_list) { ++errors; BPLOG(ERROR) << "minidump.GetMemoryInfoList() failed"; } else { memory_info_list->Print(); } DumpRawStream(&minidump, MD_LINUX_CMD_LINE, "MD_LINUX_CMD_LINE", &errors); DumpRawStream(&minidump, MD_LINUX_ENVIRON, "MD_LINUX_ENVIRON", &errors); DumpRawStream(&minidump, MD_LINUX_LSB_RELEASE, "MD_LINUX_LSB_RELEASE", &errors); DumpRawStream(&minidump, MD_LINUX_PROC_STATUS, "MD_LINUX_PROC_STATUS", &errors); DumpRawStream(&minidump, MD_LINUX_CPU_INFO, "MD_LINUX_CPU_INFO", &errors); DumpRawStream(&minidump, MD_LINUX_MAPS, "MD_LINUX_MAPS", &errors); return errors == 0; } } // namespace int main(int argc, char **argv) { BPLOG_INIT(&argc, &argv); if (argc != 2) { fprintf(stderr, "usage: %s <file>\n", argv[0]); return 1; } return PrintMinidumpDump(argv[1]) ? 0 : 1; } <commit_msg>Fix compiler warning.<commit_after>// Copyright (c) 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // minidump_dump.cc: Print the contents of a minidump file in somewhat // readable text. // // Author: Mark Mentovai #include <stdio.h> #include <string.h> #include "client/linux/minidump_writer/minidump_extension_linux.h" #include "google_breakpad/processor/minidump.h" #include "processor/logging.h" #include "processor/scoped_ptr.h" namespace { using google_breakpad::Minidump; using google_breakpad::MinidumpThreadList; using google_breakpad::MinidumpModuleList; using google_breakpad::MinidumpMemoryInfoList; using google_breakpad::MinidumpMemoryList; using google_breakpad::MinidumpException; using google_breakpad::MinidumpAssertion; using google_breakpad::MinidumpSystemInfo; using google_breakpad::MinidumpMiscInfo; using google_breakpad::MinidumpBreakpadInfo; static void DumpRawStream(Minidump *minidump, u_int32_t stream_type, const char *stream_name, int *errors) { u_int32_t length = 0; if (!minidump->SeekToStreamType(stream_type, &length)) { return; } printf("Stream %s:\n", stream_name); if (length == 0) { printf("\n"); return; } std::vector<char> contents(length); if (!minidump->ReadBytes(&contents[0], length)) { ++*errors; BPLOG(ERROR) << "minidump.ReadBytes failed"; return; } size_t current_offset = 0; while (current_offset < length) { size_t remaining = length - current_offset; // Printf requires an int and direct casting from size_t results // in compatibility warnings. u_int32_t int_remaining = remaining; printf("%.*s", int_remaining, &contents[current_offset]); char *next_null = reinterpret_cast<char *>( memchr(&contents[current_offset], 0, remaining)); if (next_null == NULL) break; printf("\\0\n"); size_t null_offset = next_null - &contents[0]; current_offset = null_offset + 1; } printf("\n\n"); } static bool PrintMinidumpDump(const char *minidump_file) { Minidump minidump(minidump_file); if (!minidump.Read()) { BPLOG(ERROR) << "minidump.Read() failed"; return false; } minidump.Print(); int errors = 0; MinidumpThreadList *thread_list = minidump.GetThreadList(); if (!thread_list) { ++errors; BPLOG(ERROR) << "minidump.GetThreadList() failed"; } else { thread_list->Print(); } MinidumpModuleList *module_list = minidump.GetModuleList(); if (!module_list) { ++errors; BPLOG(ERROR) << "minidump.GetModuleList() failed"; } else { module_list->Print(); } MinidumpMemoryList *memory_list = minidump.GetMemoryList(); if (!memory_list) { ++errors; BPLOG(ERROR) << "minidump.GetMemoryList() failed"; } else { memory_list->Print(); } MinidumpException *exception = minidump.GetException(); if (!exception) { BPLOG(INFO) << "minidump.GetException() failed"; } else { exception->Print(); } MinidumpAssertion *assertion = minidump.GetAssertion(); if (!assertion) { BPLOG(INFO) << "minidump.GetAssertion() failed"; } else { assertion->Print(); } MinidumpSystemInfo *system_info = minidump.GetSystemInfo(); if (!system_info) { ++errors; BPLOG(ERROR) << "minidump.GetSystemInfo() failed"; } else { system_info->Print(); } MinidumpMiscInfo *misc_info = minidump.GetMiscInfo(); if (!misc_info) { ++errors; BPLOG(ERROR) << "minidump.GetMiscInfo() failed"; } else { misc_info->Print(); } MinidumpBreakpadInfo *breakpad_info = minidump.GetBreakpadInfo(); if (!breakpad_info) { // Breakpad info is optional, so don't treat this as an error. BPLOG(INFO) << "minidump.GetBreakpadInfo() failed"; } else { breakpad_info->Print(); } MinidumpMemoryInfoList *memory_info_list = minidump.GetMemoryInfoList(); if (!memory_info_list) { ++errors; BPLOG(ERROR) << "minidump.GetMemoryInfoList() failed"; } else { memory_info_list->Print(); } DumpRawStream(&minidump, MD_LINUX_CMD_LINE, "MD_LINUX_CMD_LINE", &errors); DumpRawStream(&minidump, MD_LINUX_ENVIRON, "MD_LINUX_ENVIRON", &errors); DumpRawStream(&minidump, MD_LINUX_LSB_RELEASE, "MD_LINUX_LSB_RELEASE", &errors); DumpRawStream(&minidump, MD_LINUX_PROC_STATUS, "MD_LINUX_PROC_STATUS", &errors); DumpRawStream(&minidump, MD_LINUX_CPU_INFO, "MD_LINUX_CPU_INFO", &errors); DumpRawStream(&minidump, MD_LINUX_MAPS, "MD_LINUX_MAPS", &errors); return errors == 0; } } // namespace int main(int argc, char **argv) { BPLOG_INIT(&argc, &argv); if (argc != 2) { fprintf(stderr, "usage: %s <file>\n", argv[0]); return 1; } return PrintMinidumpDump(argv[1]) ? 0 : 1; } <|endoftext|>
<commit_before>#include "askpassphrasedialog.h" #include "ui_askpassphrasedialog.h" #include "guiconstants.h" #include "walletmodel.h" #include <QMessageBox> #include <QPushButton> #include <QKeyEvent> extern bool fWalletUnlockStakingOnly; AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) : QDialog(parent), ui(new Ui::AskPassphraseDialog), mode(mode), model(0), fCapsLock(false) { ui->setupUi(this); ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE); // Setup Caps Lock detection. ui->passEdit1->installEventFilter(this); ui->passEdit2->installEventFilter(this); ui->passEdit3->installEventFilter(this); ui->stakingCheckBox->setChecked(fWalletUnlockStakingOnly); switch(mode) { case Encrypt: // Ask passphrase x2 ui->passLabel1->hide(); ui->passEdit1->hide(); ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.")); setWindowTitle(tr("Encrypt wallet")); break; case UnlockStaking: ui->stakingCheckBox->setChecked(true); ui->stakingCheckBox->show(); // fallthru case Unlock: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Unlock wallet")); break; case Decrypt: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Decrypt wallet")); break; case ChangePass: // Ask old passphrase + new passphrase x2 setWindowTitle(tr("Change passphrase")); ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet.")); break; } textChanged(); connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); } AskPassphraseDialog::~AskPassphraseDialog() { // Attempt to overwrite text so that they do not linger around in memory ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size())); ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size())); ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size())); delete ui; } void AskPassphraseDialog::setModel(WalletModel *model) { this->model = model; } void AskPassphraseDialog::accept() { SecureString oldpass, newpass1, newpass2; if(!model) return; oldpass.reserve(MAX_PASSPHRASE_SIZE); newpass1.reserve(MAX_PASSPHRASE_SIZE); newpass2.reserve(MAX_PASSPHRASE_SIZE); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make this input mlock()'d to begin with. oldpass.assign(ui->passEdit1->text().toStdString().c_str()); newpass1.assign(ui->passEdit2->text().toStdString().c_str()); newpass2.assign(ui->passEdit3->text().toStdString().c_str()); switch(mode) { case Encrypt: { if(newpass1.empty() || newpass2.empty()) { // Cannot encrypt with empty passphrase break; } QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"), tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval == QMessageBox::Yes) { if(newpass1 == newpass2) { if(model->setWalletEncrypted(true, newpass1)) { QMessageBox::warning(this, tr("Wallet encrypted"), "<qt>" + tr("Clam will close now to finish the encryption process. " "Remember that encrypting your wallet cannot fully protect " "your coins from being stolen by malware infecting your computer.") + "<br><br><b>" + tr("IMPORTANT: Any previous backups you have made of your wallet file " "should be replaced with the newly generated, encrypted wallet file. " "For security reasons, previous backups of the unencrypted wallet file " "will become useless as soon as you start using the new, encrypted wallet.") + "</b></qt>"); QApplication::quit(); } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted.")); } QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } } else { QDialog::reject(); // Cancelled } } break; case UnlockStaking: case Unlock: if(!model->setWalletLocked(false, oldpass)) { QMessageBox::critical(this, tr("Wallet unlock failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { fWalletUnlockStakingOnly = ui->stakingCheckBox->isChecked(); QDialog::accept(); // Success } break; case Decrypt: if(!model->setWalletEncrypted(false, oldpass)) { QMessageBox::critical(this, tr("Wallet decryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { QDialog::accept(); // Success } break; case ChangePass: if(newpass1 == newpass2) { if(model->changePassphrase(oldpass, newpass1)) { QMessageBox::information(this, tr("Wallet encrypted"), tr("Wallet passphrase was successfully changed.")); QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } break; } } void AskPassphraseDialog::textChanged() { // Validate input, set Ok button to enabled when acceptable bool acceptable = false; switch(mode) { case Encrypt: // New passphrase x2 acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; case UnlockStaking: case Unlock: // Old passphrase x1 case Decrypt: acceptable = !ui->passEdit1->text().isEmpty(); break; case ChangePass: // Old passphrase x1, new passphrase x2 acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; } ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable); } bool AskPassphraseDialog::event(QEvent *event) { // Detect Caps Lock key press. if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); if (ke->key() == Qt::Key_CapsLock) { fCapsLock = !fCapsLock; } if (fCapsLock) { ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else { ui->capsLabel->clear(); } } return QWidget::event(event); } bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event) { /* Detect Caps Lock. * There is no good OS-independent way to check a key state in Qt, but we * can detect Caps Lock by checking for the following condition: * Shift key is down and the result is a lower case character, or * Shift key is not down and the result is an upper case character. */ if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); QString str = ke->text(); if (str.length() != 0) { const QChar *psz = str.unicode(); bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0; if ((fShift && psz->isLower()) || (!fShift && psz->isUpper())) { fCapsLock = true; ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else if (psz->isLetter()) { fCapsLock = false; ui->capsLabel->clear(); } } } return QDialog::eventFilter(object, event); } <commit_msg>Consistent lettering<commit_after>#include "askpassphrasedialog.h" #include "ui_askpassphrasedialog.h" #include "guiconstants.h" #include "walletmodel.h" #include <QMessageBox> #include <QPushButton> #include <QKeyEvent> extern bool fWalletUnlockStakingOnly; AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) : QDialog(parent), ui(new Ui::AskPassphraseDialog), mode(mode), model(0), fCapsLock(false) { ui->setupUi(this); ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE); // Setup Caps Lock detection. ui->passEdit1->installEventFilter(this); ui->passEdit2->installEventFilter(this); ui->passEdit3->installEventFilter(this); ui->stakingCheckBox->setChecked(fWalletUnlockStakingOnly); switch(mode) { case Encrypt: // Ask passphrase x2 ui->passLabel1->hide(); ui->passEdit1->hide(); ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>.")); setWindowTitle(tr("Encrypt wallet")); break; case UnlockStaking: ui->stakingCheckBox->setChecked(true); ui->stakingCheckBox->show(); // fallthru case Unlock: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Unlock wallet")); break; case Decrypt: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Decrypt wallet")); break; case ChangePass: // Ask old passphrase + new passphrase x2 setWindowTitle(tr("Change passphrase")); ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet.")); break; } textChanged(); connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); } AskPassphraseDialog::~AskPassphraseDialog() { // Attempt to overwrite text so that they do not linger around in memory ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size())); ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size())); ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size())); delete ui; } void AskPassphraseDialog::setModel(WalletModel *model) { this->model = model; } void AskPassphraseDialog::accept() { SecureString oldpass, newpass1, newpass2; if(!model) return; oldpass.reserve(MAX_PASSPHRASE_SIZE); newpass1.reserve(MAX_PASSPHRASE_SIZE); newpass2.reserve(MAX_PASSPHRASE_SIZE); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make this input mlock()'d to begin with. oldpass.assign(ui->passEdit1->text().toStdString().c_str()); newpass1.assign(ui->passEdit2->text().toStdString().c_str()); newpass2.assign(ui->passEdit3->text().toStdString().c_str()); switch(mode) { case Encrypt: { if(newpass1.empty() || newpass2.empty()) { // Cannot encrypt with empty passphrase break; } QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"), tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval == QMessageBox::Yes) { if(newpass1 == newpass2) { if(model->setWalletEncrypted(true, newpass1)) { QMessageBox::warning(this, tr("Wallet encrypted"), "<qt>" + tr("Clam will close now to finish the encryption process. " "Remember that encrypting your wallet cannot fully protect " "your coins from being stolen by malware infecting your computer.") + "<br><br><b>" + tr("IMPORTANT: Any previous backups you have made of your wallet file " "should be replaced with the newly generated, encrypted wallet file. " "For security reasons, previous backups of the unencrypted wallet file " "will become useless as soon as you start using the new, encrypted wallet.") + "</b></qt>"); QApplication::quit(); } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted.")); } QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } } else { QDialog::reject(); // Cancelled } } break; case UnlockStaking: case Unlock: if(!model->setWalletLocked(false, oldpass)) { QMessageBox::critical(this, tr("Wallet unlock failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { fWalletUnlockStakingOnly = ui->stakingCheckBox->isChecked(); QDialog::accept(); // Success } break; case Decrypt: if(!model->setWalletEncrypted(false, oldpass)) { QMessageBox::critical(this, tr("Wallet decryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { QDialog::accept(); // Success } break; case ChangePass: if(newpass1 == newpass2) { if(model->changePassphrase(oldpass, newpass1)) { QMessageBox::information(this, tr("Wallet encrypted"), tr("Wallet passphrase was successfully changed.")); QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } break; } } void AskPassphraseDialog::textChanged() { // Validate input, set Ok button to enabled when acceptable bool acceptable = false; switch(mode) { case Encrypt: // New passphrase x2 acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; case UnlockStaking: case Unlock: // Old passphrase x1 case Decrypt: acceptable = !ui->passEdit1->text().isEmpty(); break; case ChangePass: // Old passphrase x1, new passphrase x2 acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; } ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable); } bool AskPassphraseDialog::event(QEvent *event) { // Detect Caps Lock key press. if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); if (ke->key() == Qt::Key_CapsLock) { fCapsLock = !fCapsLock; } if (fCapsLock) { ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else { ui->capsLabel->clear(); } } return QWidget::event(event); } bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event) { /* Detect Caps Lock. * There is no good OS-independent way to check a key state in Qt, but we * can detect Caps Lock by checking for the following condition: * Shift key is down and the result is a lower case character, or * Shift key is not down and the result is an upper case character. */ if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); QString str = ke->text(); if (str.length() != 0) { const QChar *psz = str.unicode(); bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0; if ((fShift && psz->isLower()) || (!fShift && psz->isUpper())) { fCapsLock = true; ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else if (psz->isLetter()) { fCapsLock = false; ui->capsLabel->clear(); } } } return QDialog::eventFilter(object, event); } <|endoftext|>
<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved. #ifndef RDB_PROTOCOL_WIRE_FUNC_HPP_ #define RDB_PROTOCOL_WIRE_FUNC_HPP_ #include <functional> #include <map> #include <string> #include <vector> #include "containers/uuid.hpp" #include "rdb_protocol/counted_term.hpp" #include "rdb_protocol/pb_utils.hpp" #include "rdb_protocol/sym.hpp" #include "rdb_protocol/var_types.hpp" #include "rpc/serialize_macros.hpp" template <class> class counted_t; class Datum; class Term; namespace ql { class func_t; class env_t; class wire_func_t { public: wire_func_t(); explicit wire_func_t(const counted_t<func_t> &f); ~wire_func_t(); wire_func_t(const wire_func_t &copyee); wire_func_t &operator=(const wire_func_t &assignee); // Constructs a wire_func_t with a body and arglist and backtrace, but no scope. I // hope you remembered to propagate the backtrace to body! wire_func_t(protob_t<const Term> body, std::vector<sym_t> arg_names, protob_t<const Backtrace> backtrace); counted_t<func_t> compile_wire_func() const; protob_t<const Backtrace> get_bt() const; void rdb_serialize(write_message_t &msg) const; // NOLINT(runtime/references) archive_result_t rdb_deserialize(read_stream_t *s); private: counted_t<func_t> func; }; class group_wire_func_t { public: group_wire_func_t() { } explicit group_wire_func_t(std::vector<counted_t<func_t> > &&_funcs); std::vector<counted_t<func_t> > compile_funcs() const; RDB_MAKE_ME_SERIALIZABLE_1(funcs); private: std::vector<wire_func_t> funcs; }; class map_wire_func_t : public wire_func_t { public: template <class... Args> explicit map_wire_func_t(Args... args) : wire_func_t(args...) { } // Safely constructs a map wire func, that couldn't possibly capture any surprise // variables. static map_wire_func_t make_safely( pb::dummy_var_t dummy_var, const std::function<protob_t<Term>(sym_t argname)> &body_generator, protob_t<const Backtrace> backtrace); }; class filter_wire_func_t { public: filter_wire_func_t() { } filter_wire_func_t(const ql::wire_func_t &_filter_func, const boost::optional<ql::wire_func_t> &_default_filter_val) : filter_func(_filter_func), default_filter_val(_default_filter_val) { } filter_wire_func_t(const counted_t<func_t> &_filter_func, const boost::optional<ql::wire_func_t> &_default_filter_val) : filter_func(_filter_func), default_filter_val(_default_filter_val) { } ql::wire_func_t filter_func; boost::optional<ql::wire_func_t> default_filter_val; }; RDB_DECLARE_SERIALIZABLE(filter_wire_func_t); class reduce_wire_func_t : public wire_func_t { public: template <class... Args> explicit reduce_wire_func_t(Args... args) : wire_func_t(args...) { } }; class concatmap_wire_func_t : public wire_func_t { public: template <class... Args> explicit concatmap_wire_func_t(Args... args) : wire_func_t(args...) { } }; // These are fake functions because we don't need to send anything. struct count_wire_func_t { RDB_MAKE_ME_SERIALIZABLE_0(); }; class bt_wire_func_t { public: void rdb_serialize(write_message_t &msg) const; // NOLINT archive_result_t rdb_deserialize(read_stream_t *s); protob_t<const Backtrace> get_bt() const { return bt; } protected: bt_wire_func_t() : bt(make_counted_backtrace()) { } explicit bt_wire_func_t(const protob_t<const Backtrace> &_bt) : bt(_bt) { } private: protob_t<const Backtrace> bt; }; class sum_wire_func_t : public bt_wire_func_t { public: template<class... Args> explicit sum_wire_func_t(Args... args) : bt_wire_func_t(args...) { } }; class avg_wire_func_t : public bt_wire_func_t { public: template<class... Args> explicit avg_wire_func_t(Args... args) : bt_wire_func_t(args...) { } }; struct min_wire_func_t { min_wire_func_t() { } explicit min_wire_func_t(const protob_t<const Backtrace> &) { } RDB_MAKE_ME_SERIALIZABLE_0(); }; struct max_wire_func_t { max_wire_func_t() { } explicit max_wire_func_t(const protob_t<const Backtrace> &) { } RDB_MAKE_ME_SERIALIZABLE_0(); }; } // namespace ql #endif // RDB_PROTOCOL_WIRE_FUNC_HPP_ <commit_msg>updated NOLINT<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved. #ifndef RDB_PROTOCOL_WIRE_FUNC_HPP_ #define RDB_PROTOCOL_WIRE_FUNC_HPP_ #include <functional> #include <map> #include <string> #include <vector> #include "containers/uuid.hpp" #include "rdb_protocol/counted_term.hpp" #include "rdb_protocol/pb_utils.hpp" #include "rdb_protocol/sym.hpp" #include "rdb_protocol/var_types.hpp" #include "rpc/serialize_macros.hpp" template <class> class counted_t; class Datum; class Term; namespace ql { class func_t; class env_t; class wire_func_t { public: wire_func_t(); explicit wire_func_t(const counted_t<func_t> &f); ~wire_func_t(); wire_func_t(const wire_func_t &copyee); wire_func_t &operator=(const wire_func_t &assignee); // Constructs a wire_func_t with a body and arglist and backtrace, but no scope. I // hope you remembered to propagate the backtrace to body! wire_func_t(protob_t<const Term> body, std::vector<sym_t> arg_names, protob_t<const Backtrace> backtrace); counted_t<func_t> compile_wire_func() const; protob_t<const Backtrace> get_bt() const; void rdb_serialize(write_message_t &msg) const; // NOLINT(runtime/references) archive_result_t rdb_deserialize(read_stream_t *s); private: counted_t<func_t> func; }; class group_wire_func_t { public: group_wire_func_t() { } explicit group_wire_func_t(std::vector<counted_t<func_t> > &&_funcs); std::vector<counted_t<func_t> > compile_funcs() const; RDB_MAKE_ME_SERIALIZABLE_1(funcs); private: std::vector<wire_func_t> funcs; }; class map_wire_func_t : public wire_func_t { public: template <class... Args> explicit map_wire_func_t(Args... args) : wire_func_t(args...) { } // Safely constructs a map wire func, that couldn't possibly capture any surprise // variables. static map_wire_func_t make_safely( pb::dummy_var_t dummy_var, const std::function<protob_t<Term>(sym_t argname)> &body_generator, protob_t<const Backtrace> backtrace); }; class filter_wire_func_t { public: filter_wire_func_t() { } filter_wire_func_t(const ql::wire_func_t &_filter_func, const boost::optional<ql::wire_func_t> &_default_filter_val) : filter_func(_filter_func), default_filter_val(_default_filter_val) { } filter_wire_func_t(const counted_t<func_t> &_filter_func, const boost::optional<ql::wire_func_t> &_default_filter_val) : filter_func(_filter_func), default_filter_val(_default_filter_val) { } ql::wire_func_t filter_func; boost::optional<ql::wire_func_t> default_filter_val; }; RDB_DECLARE_SERIALIZABLE(filter_wire_func_t); class reduce_wire_func_t : public wire_func_t { public: template <class... Args> explicit reduce_wire_func_t(Args... args) : wire_func_t(args...) { } }; class concatmap_wire_func_t : public wire_func_t { public: template <class... Args> explicit concatmap_wire_func_t(Args... args) : wire_func_t(args...) { } }; // These are fake functions because we don't need to send anything. struct count_wire_func_t { RDB_MAKE_ME_SERIALIZABLE_0(); }; class bt_wire_func_t { public: void rdb_serialize(write_message_t &msg) const; // NOLINT(runtime/references) archive_result_t rdb_deserialize(read_stream_t *s); protob_t<const Backtrace> get_bt() const { return bt; } protected: bt_wire_func_t() : bt(make_counted_backtrace()) { } explicit bt_wire_func_t(const protob_t<const Backtrace> &_bt) : bt(_bt) { } private: protob_t<const Backtrace> bt; }; class sum_wire_func_t : public bt_wire_func_t { public: template<class... Args> explicit sum_wire_func_t(Args... args) : bt_wire_func_t(args...) { } }; class avg_wire_func_t : public bt_wire_func_t { public: template<class... Args> explicit avg_wire_func_t(Args... args) : bt_wire_func_t(args...) { } }; struct min_wire_func_t { min_wire_func_t() { } explicit min_wire_func_t(const protob_t<const Backtrace> &) { } RDB_MAKE_ME_SERIALIZABLE_0(); }; struct max_wire_func_t { max_wire_func_t() { } explicit max_wire_func_t(const protob_t<const Backtrace> &) { } RDB_MAKE_ME_SERIALIZABLE_0(); }; } // namespace ql #endif // RDB_PROTOCOL_WIRE_FUNC_HPP_ <|endoftext|>
<commit_before>/************************************************************************* * * REALM CONFIDENTIAL * __________________ * * [2011] - [2012] Realm Inc * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Realm Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Realm Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Realm Incorporated. * **************************************************************************/ #ifndef REALM_UTIL_FILE_MAPPER_HPP #define REALM_UTIL_FILE_MAPPER_HPP #include <realm/util/file.hpp> namespace realm { namespace util { void *mmap(int fd, size_t size, File::AccessMode access, size_t offset, const char *encryption_key); void munmap(void *addr, size_t size) noexcept; void* mremap(int fd, size_t file_offset, void* old_addr, size_t old_size, File::AccessMode a, size_t new_size); void msync(void *addr, size_t size); #if REALM_ENABLE_ENCRYPTION extern bool encryption_is_in_use; typedef size_t (*Header_to_size)(const char* addr); void do_encryption_read_barrier(const void* addr, size_t size, Header_to_size header_to_size); void do_encryption_write_barrier(const void* addr, size_t size); void inline encryption_read_barrier(const void* addr, size_t size, Header_to_size header_to_size = nullptr) { if (encryption_is_in_use) do_encryption_read_barrier(addr, size, header_to_size); } void inline encryption_write_barrier(const void* addr, size_t size) { if (encryption_is_in_use) do_encryption_write_barrier(addr, size); } #else void inline encryption_read_barrier(const void*, size_t) {} void inline encryption_write_barrier(const void*, size_t) {} #endif // helpers for encrypted Maps template<typename T> void encryption_read_barrier(File::Map<T>& map, size_t index, size_t num_elements = 1) { T* addr = map.get_addr(); encryption_read_barrier(addr+index, sizeof(T)*num_elements); } template<typename T> void encryption_write_barrier(File::Map<T>& map, size_t index, size_t num_elements = 1) { T* addr = map.get_addr(); encryption_write_barrier(addr+index, sizeof(T)*num_elements); } File::SizeType encrypted_size_to_data_size(File::SizeType size) noexcept; File::SizeType data_size_to_encrypted_size(File::SizeType size) noexcept; size_t round_up_to_page_size(size_t size) noexcept; } } #endif <commit_msg>fixed a function prototype when encryption disabled<commit_after>/************************************************************************* * * REALM CONFIDENTIAL * __________________ * * [2011] - [2012] Realm Inc * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Realm Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Realm Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Realm Incorporated. * **************************************************************************/ #ifndef REALM_UTIL_FILE_MAPPER_HPP #define REALM_UTIL_FILE_MAPPER_HPP #include <realm/util/file.hpp> namespace realm { namespace util { void *mmap(int fd, size_t size, File::AccessMode access, size_t offset, const char *encryption_key); void munmap(void *addr, size_t size) noexcept; void* mremap(int fd, size_t file_offset, void* old_addr, size_t old_size, File::AccessMode a, size_t new_size); void msync(void *addr, size_t size); #if REALM_ENABLE_ENCRYPTION extern bool encryption_is_in_use; typedef size_t (*Header_to_size)(const char* addr); void do_encryption_read_barrier(const void* addr, size_t size, Header_to_size header_to_size); void do_encryption_write_barrier(const void* addr, size_t size); void inline encryption_read_barrier(const void* addr, size_t size, Header_to_size header_to_size = nullptr) { if (encryption_is_in_use) do_encryption_read_barrier(addr, size, header_to_size); } void inline encryption_write_barrier(const void* addr, size_t size) { if (encryption_is_in_use) do_encryption_write_barrier(addr, size); } #else void inline encryption_read_barrier(const void*, size_t, Header_to_size header_to_size = nullptr) {} void inline encryption_write_barrier(const void*, size_t) {} #endif // helpers for encrypted Maps template<typename T> void encryption_read_barrier(File::Map<T>& map, size_t index, size_t num_elements = 1) { T* addr = map.get_addr(); encryption_read_barrier(addr+index, sizeof(T)*num_elements); } template<typename T> void encryption_write_barrier(File::Map<T>& map, size_t index, size_t num_elements = 1) { T* addr = map.get_addr(); encryption_write_barrier(addr+index, sizeof(T)*num_elements); } File::SizeType encrypted_size_to_data_size(File::SizeType size) noexcept; File::SizeType data_size_to_encrypted_size(File::SizeType size) noexcept; size_t round_up_to_page_size(size_t size) noexcept; } } #endif <|endoftext|>
<commit_before>/* * Copyright 2016 <Lennart Nachtigall> <firesurfer65@yahoo.de> * * 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 "Entity.h" namespace ros2_components { EntityBase::EntityBase(int64_t _id, bool _subscribe, std::shared_ptr<rclcpp::node::Node> _parentNode, string _className) { this->id = _id; this->subscriber = _subscribe; this->parentNode = _parentNode; this->className = _className; this->active = true; REFLECT(id); REFLECT(virtualEntity); REFLECT(className); REFLECT(active) qRegisterMetaType<int64_t>("int64_t"); qRegisterMetaType<std::string>("std::string"); } int64_t EntityBase::getId() { return id; } string EntityBase::getName() { return getClassName() + std::to_string(id); } string EntityBase::getClassName() { /* const QMetaObject* metaObject = this->metaObject(); std::string localClassName = metaObject->className(); localClassName.erase(0, localClassName.find_last_of(":")+1);*/ return className; } void EntityBase::addChild(std::shared_ptr<EntityBase> child, bool remote) { LOG(LogLevel::Info) << "addChild called with: " << child->getName() << std::endl; childs.push_back(child); child->setParent(shared_from_this()); connect(child.get(), &EntityBase::childAdded,this, &EntityBase::on_child_added,Qt::DirectConnection); connect(child.get(), &EntityBase::childRemoved,this, &EntityBase::on_child_removed,Qt::DirectConnection); emit childAdded(child,child->getParent(),0,remote); } void EntityBase::removeChild(std::shared_ptr<EntityBase> child, bool remote) { auto iteratorPos = std::find(childs.begin(), childs.end(), child) ; if(iteratorPos != childs.end()) { childs.erase(iteratorPos); } else throw std::runtime_error("Can't remove given child - child not found!"); disconnect(child.get(), &EntityBase::childAdded,this, &EntityBase::on_child_added); emit childRemoved(child,child->getParent(),0, remote); } std::shared_ptr<EntityBase> EntityBase::getChildById(int64_t id) { for(auto & child: childs) { if(child->getId() == id) { //Do to bug in ROS 2 this might throw an exception //if(!child->WasMetaInformationUpdated()) //child->updateParameters(); return child; } } throw std::runtime_error("Child with id: " + std::to_string(id) + " not found"); } uint64_t EntityBase::countChilds() { return childs.size(); } std::shared_ptr<EntityBase> EntityBase::getParent() { return this->parent; } void EntityBase::setParent(std::shared_ptr<EntityBase> par) { this->parent = par; } string EntityBase::getTopicName() { if(!isSubscriber()) { return pubBase->get_topic_name(); } else return subBase->get_topic_name(); } void EntityBase::updateParameters() { LOG(LogLevel::Info) << "Updating Parameters" << std::endl; updated = true; std::vector<std::string> myParameters; for(auto & par: internalmap) { myParameters.push_back(getName()+ "."+par->key); } auto parameters = parameterClient->get_parameters({myParameters}); if (parameters.wait_for(10_s) != std::future_status::ready) { LOG(LogLevel::Fatal) <<"get parameters service call failed"<< std::endl; return; } for (auto & parameter : parameters.get()) { std::string reducedParameter = parameter.get_name(); reducedParameter.erase(0,reducedParameter.find_last_of(".")+1); for (auto & internal_val : internalmap) { if(internal_val->key == reducedParameter) { /* * uint8 PARAMETER_NOT_SET=0 * uint8 PARAMETER_BOOL=1 * uint8 PARAMETER_INTEGER=2 * uint8 PARAMETER_DOUBLE=3 * uint8 PARAMETER_STRING=4 * uint8 PARAMETER_BYTES=5 */ switch(parameter.get_type()) { case rcl_interfaces::msg::ParameterType::PARAMETER_BOOL: { SpecificElement<bool>* elem = static_cast<SpecificElement<bool>*>(internal_val); elem->setValue(parameter.as_bool()); break; } case rcl_interfaces::msg::ParameterType::PARAMETER_INTEGER: { SpecificElement<int64_t>* elem = static_cast<SpecificElement<int64_t>*>(internal_val); elem->setValue(parameter.as_int()); break; } case rcl_interfaces::msg::ParameterType::PARAMETER_DOUBLE: { SpecificElement<double>* elem = static_cast<SpecificElement<double>*>(internal_val); elem->setValue(parameter.as_double()); break; } case rcl_interfaces::msg::ParameterType::PARAMETER_STRING: { SpecificElement<std::string>* elem = static_cast<SpecificElement<std::string>*>(internal_val); elem->setValue(parameter.as_string()); break; } case rcl_interfaces::msg::ParameterType::PARAMETER_BYTES: { SpecificElement<std::vector<uint8_t>>* elem = static_cast<SpecificElement<std::vector<uint8_t>>*>(internal_val); elem->setValue(parameter.as_bytes()); break; } case rcl_interfaces::msg::ParameterType::PARAMETER_NOT_SET: { break; } } } } } emit parametersUpdated(); } void EntityBase::publishMetaInformation() { LOG(LogLevel::Info) << "Publish meta information in: " << getName() << std::endl; std::vector< rclcpp::parameter::ParameterVariant> params; for(auto it = internalmap.begin(); it != internalmap.end(); it++) { params.push_back((*it)->getParameterVariant(getName())); //(*it)->print(); } auto set_parameters_results = this->parameterClient->set_parameters(params); if (set_parameters_results.wait_for(20_s) != std::future_status::ready) { throw std::runtime_error("Couldn't access parameter server!"); } } string EntityBase::getAutogeneratedClassName() { int status; char * demangled = abi::__cxa_demangle(typeid(*this).name(),0,0,&status); std::string tempname = std::string(demangled); if(tempname.find_last_of(":") != std::string::npos) tempname.erase(0, tempname.find_last_of(":")+1); return tempname; } void EntityBase::on_child_added(std::shared_ptr<EntityBase> child,std::shared_ptr<EntityBase> parent,int depth, bool remote) { if(parent != NULL && child != NULL) LOG(LogLevel::Info) << "child"<<child->getName()<< "added to: " <<parent->getName() << " depth: " << depth << std::endl; emit childAdded(child,parent, depth+1,remote); } void EntityBase::on_child_removed(std::shared_ptr<EntityBase> child, std::shared_ptr<EntityBase> parent, int depth, bool remote) { LOG(LogLevel::Info) << "child"<<child->getName()<< "removed from: " <<parent->getName() << " depth: " << depth << std::endl; emit childRemoved(child,parent, depth+1,remote); } void EntityBase::IterateThroughAllProperties(std::function<void(QMetaProperty)> func) { const QMetaObject* metaObj = this->metaObject(); while(metaObj != NULL) { for (int i = metaObj->propertyOffset(); i < metaObj->propertyCount(); ++i) { func(metaObj->property(i)); } metaObj = metaObj->superClass(); } } void EntityBase::Advertise(AdvertisementType type) { if(this->advertisementPublisher != NULL) { ros2_components_msg::msg::EntityAdvertisement::SharedPtr msg = std::make_shared<ros2_components_msg::msg::EntityAdvertisement>(); msg->advertisementtype = (int)type; msg->id = getId(); if(getParent() != NULL) msg->parent = getParent()->getId(); else msg->parent = -1; msg->type = this->className; builtin_interfaces::msg::Time time; simpleLogger::set_now(time); msg->stamp = time; std::vector<int64_t> ids; for(auto & child: childs) { msg->childtypes.push_back(child->getClassName()); ids.push_back(child->getId()); } msg->childids = ids; msg->name = getName(); advertisementPublisher->publish(msg); } } } <commit_msg>added parent type to message<commit_after>/* * Copyright 2016 <Lennart Nachtigall> <firesurfer65@yahoo.de> * * 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 "Entity.h" namespace ros2_components { EntityBase::EntityBase(int64_t _id, bool _subscribe, std::shared_ptr<rclcpp::node::Node> _parentNode, string _className) { this->id = _id; this->subscriber = _subscribe; this->parentNode = _parentNode; this->className = _className; this->active = true; REFLECT(id); REFLECT(virtualEntity); REFLECT(className); REFLECT(active) qRegisterMetaType<int64_t>("int64_t"); qRegisterMetaType<std::string>("std::string"); } int64_t EntityBase::getId() { return id; } string EntityBase::getName() { return getClassName() + std::to_string(id); } string EntityBase::getClassName() { /* const QMetaObject* metaObject = this->metaObject(); std::string localClassName = metaObject->className(); localClassName.erase(0, localClassName.find_last_of(":")+1);*/ return className; } void EntityBase::addChild(std::shared_ptr<EntityBase> child, bool remote) { LOG(LogLevel::Info) << "addChild called with: " << child->getName() << std::endl; childs.push_back(child); child->setParent(shared_from_this()); connect(child.get(), &EntityBase::childAdded,this, &EntityBase::on_child_added,Qt::DirectConnection); connect(child.get(), &EntityBase::childRemoved,this, &EntityBase::on_child_removed,Qt::DirectConnection); emit childAdded(child,child->getParent(),0,remote); } void EntityBase::removeChild(std::shared_ptr<EntityBase> child, bool remote) { auto iteratorPos = std::find(childs.begin(), childs.end(), child) ; if(iteratorPos != childs.end()) { childs.erase(iteratorPos); } else throw std::runtime_error("Can't remove given child - child not found!"); disconnect(child.get(), &EntityBase::childAdded,this, &EntityBase::on_child_added); emit childRemoved(child,child->getParent(),0, remote); } std::shared_ptr<EntityBase> EntityBase::getChildById(int64_t id) { for(auto & child: childs) { if(child->getId() == id) { //Do to bug in ROS 2 this might throw an exception //if(!child->WasMetaInformationUpdated()) //child->updateParameters(); return child; } } throw std::runtime_error("Child with id: " + std::to_string(id) + " not found"); } uint64_t EntityBase::countChilds() { return childs.size(); } std::shared_ptr<EntityBase> EntityBase::getParent() { return this->parent; } void EntityBase::setParent(std::shared_ptr<EntityBase> par) { this->parent = par; } string EntityBase::getTopicName() { if(!isSubscriber()) { return pubBase->get_topic_name(); } else return subBase->get_topic_name(); } void EntityBase::updateParameters() { LOG(LogLevel::Info) << "Updating Parameters" << std::endl; updated = true; std::vector<std::string> myParameters; for(auto & par: internalmap) { myParameters.push_back(getName()+ "."+par->key); } auto parameters = parameterClient->get_parameters({myParameters}); if (parameters.wait_for(10_s) != std::future_status::ready) { LOG(LogLevel::Fatal) <<"get parameters service call failed"<< std::endl; return; } for (auto & parameter : parameters.get()) { std::string reducedParameter = parameter.get_name(); reducedParameter.erase(0,reducedParameter.find_last_of(".")+1); for (auto & internal_val : internalmap) { if(internal_val->key == reducedParameter) { /* * uint8 PARAMETER_NOT_SET=0 * uint8 PARAMETER_BOOL=1 * uint8 PARAMETER_INTEGER=2 * uint8 PARAMETER_DOUBLE=3 * uint8 PARAMETER_STRING=4 * uint8 PARAMETER_BYTES=5 */ switch(parameter.get_type()) { case rcl_interfaces::msg::ParameterType::PARAMETER_BOOL: { SpecificElement<bool>* elem = static_cast<SpecificElement<bool>*>(internal_val); elem->setValue(parameter.as_bool()); break; } case rcl_interfaces::msg::ParameterType::PARAMETER_INTEGER: { SpecificElement<int64_t>* elem = static_cast<SpecificElement<int64_t>*>(internal_val); elem->setValue(parameter.as_int()); break; } case rcl_interfaces::msg::ParameterType::PARAMETER_DOUBLE: { SpecificElement<double>* elem = static_cast<SpecificElement<double>*>(internal_val); elem->setValue(parameter.as_double()); break; } case rcl_interfaces::msg::ParameterType::PARAMETER_STRING: { SpecificElement<std::string>* elem = static_cast<SpecificElement<std::string>*>(internal_val); elem->setValue(parameter.as_string()); break; } case rcl_interfaces::msg::ParameterType::PARAMETER_BYTES: { SpecificElement<std::vector<uint8_t>>* elem = static_cast<SpecificElement<std::vector<uint8_t>>*>(internal_val); elem->setValue(parameter.as_bytes()); break; } case rcl_interfaces::msg::ParameterType::PARAMETER_NOT_SET: { break; } } } } } emit parametersUpdated(); } void EntityBase::publishMetaInformation() { LOG(LogLevel::Info) << "Publish meta information in: " << getName() << std::endl; std::vector< rclcpp::parameter::ParameterVariant> params; for(auto it = internalmap.begin(); it != internalmap.end(); it++) { params.push_back((*it)->getParameterVariant(getName())); //(*it)->print(); } auto set_parameters_results = this->parameterClient->set_parameters(params); if (set_parameters_results.wait_for(20_s) != std::future_status::ready) { throw std::runtime_error("Couldn't access parameter server!"); } } string EntityBase::getAutogeneratedClassName() { int status; char * demangled = abi::__cxa_demangle(typeid(*this).name(),0,0,&status); std::string tempname = std::string(demangled); if(tempname.find_last_of(":") != std::string::npos) tempname.erase(0, tempname.find_last_of(":")+1); return tempname; } void EntityBase::on_child_added(std::shared_ptr<EntityBase> child,std::shared_ptr<EntityBase> parent,int depth, bool remote) { if(parent != NULL && child != NULL) LOG(LogLevel::Info) << "child"<<child->getName()<< "added to: " <<parent->getName() << " depth: " << depth << std::endl; emit childAdded(child,parent, depth+1,remote); } void EntityBase::on_child_removed(std::shared_ptr<EntityBase> child, std::shared_ptr<EntityBase> parent, int depth, bool remote) { LOG(LogLevel::Info) << "child"<<child->getName()<< "removed from: " <<parent->getName() << " depth: " << depth << std::endl; emit childRemoved(child,parent, depth+1,remote); } void EntityBase::IterateThroughAllProperties(std::function<void(QMetaProperty)> func) { const QMetaObject* metaObj = this->metaObject(); while(metaObj != NULL) { for (int i = metaObj->propertyOffset(); i < metaObj->propertyCount(); ++i) { func(metaObj->property(i)); } metaObj = metaObj->superClass(); } } void EntityBase::Advertise(AdvertisementType type) { if(this->advertisementPublisher != NULL) { ros2_components_msg::msg::EntityAdvertisement::SharedPtr msg = std::make_shared<ros2_components_msg::msg::EntityAdvertisement>(); msg->advertisementtype = (int)type; msg->id = getId(); if(getParent() != NULL) { msg->parent = getParent()->getId(); msg->parenttype = getParent()->getClassName(); } else { msg->parent = -1; msg->parenttype = ""; } msg->type = this->className; builtin_interfaces::msg::Time time; simpleLogger::set_now(time); msg->stamp = time; std::vector<int64_t> ids; for(auto & child: childs) { msg->childtypes.push_back(child->getClassName()); ids.push_back(child->getId()); } msg->childids = ids; msg->name = getName(); advertisementPublisher->publish(msg); } } } <|endoftext|>
<commit_before>// Copyright 2014 The Crashpad Authors. All rights reserved. // // 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 "snapshot/mac/mach_o_image_annotations_reader.h" #include <mach-o/loader.h> #include <mach/mach.h> #include <sys/types.h> #include <utility> #include "base/logging.h" #include "client/crashpad_info.h" #include "client/simple_string_dictionary.h" #include "snapshot/mac/mach_o_image_reader.h" #include "snapshot/mac/process_reader_mac.h" #include "snapshot/snapshot_constants.h" #include "util/stdlib/strnlen.h" namespace crashpad { MachOImageAnnotationsReader::MachOImageAnnotationsReader( ProcessReaderMac* process_reader, const MachOImageReader* image_reader, const std::string& name) : name_(name), process_reader_(process_reader), image_reader_(image_reader) {} std::vector<std::string> MachOImageAnnotationsReader::Vector() const { std::vector<std::string> vector_annotations; ReadCrashReporterClientAnnotations(&vector_annotations); ReadDyldErrorStringAnnotation(&vector_annotations); return vector_annotations; } std::map<std::string, std::string> MachOImageAnnotationsReader::SimpleMap() const { std::map<std::string, std::string> simple_map_annotations; ReadCrashpadSimpleAnnotations(&simple_map_annotations); return simple_map_annotations; } std::vector<AnnotationSnapshot> MachOImageAnnotationsReader::AnnotationsList() const { std::vector<AnnotationSnapshot> annotations; ReadCrashpadAnnotationsList(&annotations); return annotations; } void MachOImageAnnotationsReader::ReadCrashReporterClientAnnotations( std::vector<std::string>* vector_annotations) const { mach_vm_address_t crash_info_address; const process_types::section* crash_info_section = image_reader_->GetSectionByName( SEG_DATA, "__crash_info", &crash_info_address); if (!crash_info_section) { return; } process_types::crashreporter_annotations_t crash_info; if (!crash_info.Read(process_reader_, crash_info_address)) { LOG(WARNING) << "could not read crash info from " << name_; return; } if (crash_info.version != 4 && crash_info.version != 5) { LOG(WARNING) << "unexpected crash info version " << crash_info.version << " in " << name_; return; } size_t expected_size = process_types::crashreporter_annotations_t::ExpectedSizeForVersion( process_reader_, crash_info.version); if (crash_info_section->size < expected_size) { LOG(WARNING) << "small crash info section size " << crash_info_section->size << " < " << expected_size << " for version " << crash_info.version << " in " << name_; return; } // This number was totally made up out of nowhere, but it seems prudent to // enforce some limit. constexpr size_t kMaxMessageSize = 1024; if (crash_info.message) { std::string message; if (process_reader_->Memory()->ReadCStringSizeLimited( crash_info.message, kMaxMessageSize, &message)) { vector_annotations->push_back(message); } else { LOG(WARNING) << "could not read crash message in " << name_; } } if (crash_info.message2) { std::string message; if (process_reader_->Memory()->ReadCStringSizeLimited( crash_info.message2, kMaxMessageSize, &message)) { vector_annotations->push_back(message); } else { LOG(WARNING) << "could not read crash message 2 in " << name_; } } } void MachOImageAnnotationsReader::ReadDyldErrorStringAnnotation( std::vector<std::string>* vector_annotations) const { // dyld stores its error string at the external symbol for |const char // error_string[1024]|. See 10.9.5 dyld-239.4/src/dyld.cpp error_string. if (image_reader_->FileType() != MH_DYLINKER) { return; } mach_vm_address_t error_string_address; if (!image_reader_->LookUpExternalDefinedSymbol("_error_string", &error_string_address)) { return; } std::string message; // 1024 here is distinct from kMaxMessageSize above, because it refers to a // precisely-sized buffer inside dyld. if (process_reader_->Memory()->ReadCStringSizeLimited( error_string_address, 1024, &message)) { if (!message.empty()) { vector_annotations->push_back(message); } } else { LOG(WARNING) << "could not read dylinker error string from " << name_; } } void MachOImageAnnotationsReader::ReadCrashpadSimpleAnnotations( std::map<std::string, std::string>* simple_map_annotations) const { process_types::CrashpadInfo crashpad_info; if (!image_reader_->GetCrashpadInfo(&crashpad_info) || !crashpad_info.simple_annotations) { return; } std::vector<SimpleStringDictionary::Entry> simple_annotations(SimpleStringDictionary::num_entries); if (!process_reader_->Memory()->Read( crashpad_info.simple_annotations, simple_annotations.size() * sizeof(simple_annotations[0]), &simple_annotations[0])) { LOG(WARNING) << "could not read simple annotations from " << name_; return; } for (const auto& entry : simple_annotations) { size_t key_length = strnlen(entry.key, sizeof(entry.key)); if (key_length) { std::string key(entry.key, key_length); std::string value(entry.value, strnlen(entry.value, sizeof(entry.value))); if (!simple_map_annotations->insert(std::make_pair(key, value)).second) { LOG(INFO) << "duplicate simple annotation " << key << " in " << name_; } } } } // TODO(rsesek): When there is a platform-agnostic remote memory reader // interface available, use it so that the implementation is not duplicated // in the PEImageAnnotationsReader. void MachOImageAnnotationsReader::ReadCrashpadAnnotationsList( std::vector<AnnotationSnapshot>* annotations) const { process_types::CrashpadInfo crashpad_info; if (!image_reader_->GetCrashpadInfo(&crashpad_info) || !crashpad_info.annotations_list) { return; } process_types::AnnotationList annotation_list_object; if (!annotation_list_object.Read(process_reader_, crashpad_info.annotations_list)) { LOG(WARNING) << "could not read annotations list object in " << name_; return; } process_types::Annotation current = annotation_list_object.head; for (size_t index = 0; current.link_node != annotation_list_object.tail_pointer && index < kMaxNumberOfAnnotations; ++index) { if (!current.Read(process_reader_, current.link_node)) { LOG(WARNING) << "could not read annotation at index " << index << " in " << name_; return; } if (current.size == 0) { continue; } AnnotationSnapshot snapshot; snapshot.type = current.type; snapshot.value.resize(current.size); if (!process_reader_->Memory()->ReadCStringSizeLimited( current.name, Annotation::kNameMaxLength, &snapshot.name)) { LOG(WARNING) << "could not read annotation name at index " << index << " in " << name_; continue; } size_t size = std::min(static_cast<size_t>(current.size), Annotation::kValueMaxSize); if (!process_reader_->Memory()->Read( current.value, size, snapshot.value.data())) { LOG(WARNING) << "could not read annotation value at index " << index << " in " << name_; continue; } annotations->push_back(std::move(snapshot)); } } } // namespace crashpad <commit_msg>Update comment to reflect current state<commit_after>// Copyright 2014 The Crashpad Authors. All rights reserved. // // 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 "snapshot/mac/mach_o_image_annotations_reader.h" #include <mach-o/loader.h> #include <mach/mach.h> #include <sys/types.h> #include <utility> #include "base/logging.h" #include "client/crashpad_info.h" #include "client/simple_string_dictionary.h" #include "snapshot/mac/mach_o_image_reader.h" #include "snapshot/mac/process_reader_mac.h" #include "snapshot/snapshot_constants.h" #include "util/stdlib/strnlen.h" namespace crashpad { MachOImageAnnotationsReader::MachOImageAnnotationsReader( ProcessReaderMac* process_reader, const MachOImageReader* image_reader, const std::string& name) : name_(name), process_reader_(process_reader), image_reader_(image_reader) {} std::vector<std::string> MachOImageAnnotationsReader::Vector() const { std::vector<std::string> vector_annotations; ReadCrashReporterClientAnnotations(&vector_annotations); ReadDyldErrorStringAnnotation(&vector_annotations); return vector_annotations; } std::map<std::string, std::string> MachOImageAnnotationsReader::SimpleMap() const { std::map<std::string, std::string> simple_map_annotations; ReadCrashpadSimpleAnnotations(&simple_map_annotations); return simple_map_annotations; } std::vector<AnnotationSnapshot> MachOImageAnnotationsReader::AnnotationsList() const { std::vector<AnnotationSnapshot> annotations; ReadCrashpadAnnotationsList(&annotations); return annotations; } void MachOImageAnnotationsReader::ReadCrashReporterClientAnnotations( std::vector<std::string>* vector_annotations) const { mach_vm_address_t crash_info_address; const process_types::section* crash_info_section = image_reader_->GetSectionByName( SEG_DATA, "__crash_info", &crash_info_address); if (!crash_info_section) { return; } process_types::crashreporter_annotations_t crash_info; if (!crash_info.Read(process_reader_, crash_info_address)) { LOG(WARNING) << "could not read crash info from " << name_; return; } if (crash_info.version != 4 && crash_info.version != 5) { LOG(WARNING) << "unexpected crash info version " << crash_info.version << " in " << name_; return; } size_t expected_size = process_types::crashreporter_annotations_t::ExpectedSizeForVersion( process_reader_, crash_info.version); if (crash_info_section->size < expected_size) { LOG(WARNING) << "small crash info section size " << crash_info_section->size << " < " << expected_size << " for version " << crash_info.version << " in " << name_; return; } // This number was totally made up out of nowhere, but it seems prudent to // enforce some limit. constexpr size_t kMaxMessageSize = 1024; if (crash_info.message) { std::string message; if (process_reader_->Memory()->ReadCStringSizeLimited( crash_info.message, kMaxMessageSize, &message)) { vector_annotations->push_back(message); } else { LOG(WARNING) << "could not read crash message in " << name_; } } if (crash_info.message2) { std::string message; if (process_reader_->Memory()->ReadCStringSizeLimited( crash_info.message2, kMaxMessageSize, &message)) { vector_annotations->push_back(message); } else { LOG(WARNING) << "could not read crash message 2 in " << name_; } } } void MachOImageAnnotationsReader::ReadDyldErrorStringAnnotation( std::vector<std::string>* vector_annotations) const { // dyld stores its error string at the external symbol for |const char // error_string[1024]|. See 10.9.5 dyld-239.4/src/dyld.cpp error_string. if (image_reader_->FileType() != MH_DYLINKER) { return; } mach_vm_address_t error_string_address; if (!image_reader_->LookUpExternalDefinedSymbol("_error_string", &error_string_address)) { return; } std::string message; // 1024 here is distinct from kMaxMessageSize above, because it refers to a // precisely-sized buffer inside dyld. if (process_reader_->Memory()->ReadCStringSizeLimited( error_string_address, 1024, &message)) { if (!message.empty()) { vector_annotations->push_back(message); } } else { LOG(WARNING) << "could not read dylinker error string from " << name_; } } void MachOImageAnnotationsReader::ReadCrashpadSimpleAnnotations( std::map<std::string, std::string>* simple_map_annotations) const { process_types::CrashpadInfo crashpad_info; if (!image_reader_->GetCrashpadInfo(&crashpad_info) || !crashpad_info.simple_annotations) { return; } std::vector<SimpleStringDictionary::Entry> simple_annotations(SimpleStringDictionary::num_entries); if (!process_reader_->Memory()->Read( crashpad_info.simple_annotations, simple_annotations.size() * sizeof(simple_annotations[0]), &simple_annotations[0])) { LOG(WARNING) << "could not read simple annotations from " << name_; return; } for (const auto& entry : simple_annotations) { size_t key_length = strnlen(entry.key, sizeof(entry.key)); if (key_length) { std::string key(entry.key, key_length); std::string value(entry.value, strnlen(entry.value, sizeof(entry.value))); if (!simple_map_annotations->insert(std::make_pair(key, value)).second) { LOG(INFO) << "duplicate simple annotation " << key << " in " << name_; } } } } // TODO(https://crbug.com/crashpad/270): Replace implementations of // ReadCrashpadAnnotationsList and ReadCrashpadSimpleAnnotations with the // platform-agnostic implementations in ImageAnnotationReader. void MachOImageAnnotationsReader::ReadCrashpadAnnotationsList( std::vector<AnnotationSnapshot>* annotations) const { process_types::CrashpadInfo crashpad_info; if (!image_reader_->GetCrashpadInfo(&crashpad_info) || !crashpad_info.annotations_list) { return; } process_types::AnnotationList annotation_list_object; if (!annotation_list_object.Read(process_reader_, crashpad_info.annotations_list)) { LOG(WARNING) << "could not read annotations list object in " << name_; return; } process_types::Annotation current = annotation_list_object.head; for (size_t index = 0; current.link_node != annotation_list_object.tail_pointer && index < kMaxNumberOfAnnotations; ++index) { if (!current.Read(process_reader_, current.link_node)) { LOG(WARNING) << "could not read annotation at index " << index << " in " << name_; return; } if (current.size == 0) { continue; } AnnotationSnapshot snapshot; snapshot.type = current.type; snapshot.value.resize(current.size); if (!process_reader_->Memory()->ReadCStringSizeLimited( current.name, Annotation::kNameMaxLength, &snapshot.name)) { LOG(WARNING) << "could not read annotation name at index " << index << " in " << name_; continue; } size_t size = std::min(static_cast<size_t>(current.size), Annotation::kValueMaxSize); if (!process_reader_->Memory()->Read( current.value, size, snapshot.value.data())) { LOG(WARNING) << "could not read annotation value at index " << index << " in " << name_; continue; } annotations->push_back(std::move(snapshot)); } } } // namespace crashpad <|endoftext|>
<commit_before>/* Copyright (c) Nathan Eloe, 2014 This file is part of MongoDB-Cpp. MongoDB-Cpp is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MongoDB-Cpp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with MongoDB-Cpp. If not, see <http://www.gnu.org/licenses/>. */ /*! * \file find.cpp * \author Nathan Eloe * \brief tests find and findOne functionality of the mongo cxx driver */ #include "../connection/mongoclient.h" #include "../connection/cursor.h" #include "gtest/gtest.h" #include "fixture.h" #include <iostream> TEST_F (MongoDriverTest, FindOneAny) { bson::Document d = c.findOne (FINDCOLL); ASSERT_NE (0, d.field_names().size()); } TEST_F (MongoDriverTest, FindOneNoExist) { bson::Document d = c.findOne (FINDCOLL, {{"A", 1}}); ASSERT_EQ (0, d.field_names().size()); } TEST_F (MongoDriverTest, FindOneFilter) { bson::Document d = c.findOne (FINDCOLL, {{"a", 5}}); ASSERT_EQ (5, d["a"].data<int>()); } TEST_F (MongoDriverTest, FindOneOnly) { bson::Document d = c.findOne (FINDCOLL, {{"b", 8}}); ASSERT_EQ (8, d["b"].data<int>()); } TEST_F (MongoDriverTest, FindOneProject) { bson::Document d = c.findOne (FINDCOLL, {{"a", 5}}, {{"a", 1}}); ASSERT_GE (2, d.field_names().size()); //can still have the _id apparently... ugh ASSERT_EQ (5, d["a"].data<int>()); ASSERT_EQ (1, d.field_names().count ("a")); ASSERT_EQ (1, d.field_names().count ("_id")); ASSERT_EQ (0, d.field_names().count ("b")); } TEST_F (MongoDriverTest, FindOneProjectFilter) { bson::Document d = c.findOne (FINDCOLL, {{"a", 5}}, {{"a", 0}}); ASSERT_NE (0, d.field_names().size()); ASSERT_EQ (0, d.field_names().count ("a")); } TEST_F (MongoDriverTest, FindAll) { int count = 0; mongo::Cursor curr = c.find (FINDCOLL); while (curr.more()) { count++; curr.next(); } ASSERT_EQ (10004, count); } TEST_F (MongoDriverTest, FindProjectFilter) { int count = 0; mongo::Cursor curr = c.find (FINDCOLL, {{"a", 5}}, {{"a", 0}}); while (curr.more()) { count++; curr.next(); } ASSERT_EQ (2, count); }<commit_msg>basic tests for asyncrhonous finding<commit_after>/* Copyright (c) Nathan Eloe, 2014 This file is part of MongoDB-Cpp. MongoDB-Cpp is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MongoDB-Cpp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with MongoDB-Cpp. If not, see <http://www.gnu.org/licenses/>. */ /*! * \file find.cpp * \author Nathan Eloe * \brief tests find and findOne functionality of the mongo cxx driver */ #include "../connection/mongoclient.h" #include "../connection/cursor.h" #include "gtest/gtest.h" #include "fixture.h" #include <iostream> #include <set> TEST_F (MongoDriverTest, FindOneAny) { bson::Document d = c.findOne (FINDCOLL); ASSERT_NE (0, d.field_names().size()); } TEST_F (MongoDriverTest, FindOneNoExist) { bson::Document d = c.findOne (FINDCOLL, {{"A", 1}}); ASSERT_EQ (0, d.field_names().size()); } TEST_F (MongoDriverTest, FindOneFilter) { bson::Document d = c.findOne (FINDCOLL, {{"a", 5}}); ASSERT_EQ (5, d["a"].data<int>()); } TEST_F (MongoDriverTest, FindOneOnly) { bson::Document d = c.findOne (FINDCOLL, {{"b", 8}}); ASSERT_EQ (8, d["b"].data<int>()); } TEST_F (MongoDriverTest, FindOneProject) { bson::Document d = c.findOne (FINDCOLL, {{"a", 5}}, {{"a", 1}}); ASSERT_GE (2, d.field_names().size()); //can still have the _id apparently... ugh ASSERT_EQ (5, d["a"].data<int>()); ASSERT_EQ (1, d.field_names().count ("a")); ASSERT_EQ (1, d.field_names().count ("_id")); ASSERT_EQ (0, d.field_names().count ("b")); } TEST_F (MongoDriverTest, FindOneProjectFilter) { bson::Document d = c.findOne (FINDCOLL, {{"a", 5}}, {{"a", 0}}); ASSERT_NE (0, d.field_names().size()); ASSERT_EQ (0, d.field_names().count ("a")); } TEST_F (MongoDriverTest, FindAll) { int count = 0; mongo::Cursor curr = c.find (FINDCOLL); while (curr.more()) { count++; curr.next(); } ASSERT_EQ (10004, count); } TEST_F (MongoDriverTest, FindProjectFilter) { int count = 0; mongo::Cursor curr = c.find (FINDCOLL, {{"a", 5}}, {{"a", 0}}); while (curr.more()) { count++; curr.next(); } ASSERT_EQ (2, count); } TEST_F (MongoDriverTest, AsyncFindOneTest) { std::set<int> dispatched, retrieved; bson::Document d; int id; for (int i=0; i<10; i++) { dispatched.insert(c.dispatch_findOne(FINDCOLL, {{"a", 5}}, {{"a", 1}})); ASSERT_EQ(i+1, dispatched.size()); } for (int i=0; i<10; i++) { id = c.async_recv(d); ASSERT_GE (2, d.field_names().size()); //can still have the _id apparently... ugh ASSERT_EQ (5, d["a"].data<int>()); ASSERT_EQ (1, d.field_names().count ("a")); ASSERT_EQ (1, d.field_names().count ("_id")); ASSERT_EQ (0, d.field_names().count ("b")); ASSERT_EQ(1, dispatched.count(id)); retrieved.insert(id); ASSERT_EQ(i+1, retrieved.size()); } } TEST_F (MongoDriverTest, AsyncFindTest) { std::set<int> dispatched, retrieved; mongo::Cursor curr; int id, count = 0; for (int i=0; i<10; i++) { dispatched.insert(c.dispatch_find(FINDCOLL, {{"a", 5}}, {{"a", 0}})); ASSERT_EQ(i+1, dispatched.size()); } for (int i=0; i<10; i++) { count = 0; id = c.async_recv(curr); while (curr.more()) { count++; curr.next(); } retrieved.insert(id); ASSERT_EQ(i+1, retrieved.size()); ASSERT_EQ(1, dispatched.count(id)); ASSERT_EQ(2, count); } }<|endoftext|>
<commit_before>// $Id: petsc_interface.C,v 1.26 2004-09-27 14:54:26 jwpeterson Exp $ // The libMesh Finite Element Library. // Copyright (C) 2002-2004 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "libmesh_common.h" #ifdef HAVE_PETSC // C++ includes // Local Includes #include "petsc_interface.h" /*----------------------- functions ----------------------------------*/ template <typename T> void PetscInterface<T>::clear () { if (this->initialized()) { this->_is_initialized = false; int ierr=0; // 2.1.x & earlier style #if (PETSC_VERSION_MAJOR == 2) && (PETSC_VERSION_MINOR <= 1) ierr = SLESDestroy(_sles); CHKERRABORT(PETSC_COMM_WORLD,ierr); // 2.2.0 & newer style #else ierr = KSPDestroy(_ksp); CHKERRABORT(PETSC_COMM_WORLD,ierr); #endif // Mimic PETSc default solver and preconditioner this->_solver_type = GMRES; if (libMesh::n_processors() == 1) this->_preconditioner_type = ILU_PRECOND; else this->_preconditioner_type = BLOCK_JACOBI_PRECOND; } } template <typename T> void PetscInterface<T>::init () { int ierr=0; // Initialize the data structures if not done so already. if (!this->initialized()) { this->_is_initialized = true; // 2.1.x & earlier style #if (PETSC_VERSION_MAJOR == 2) && (PETSC_VERSION_MINOR <= 1) // Create the linear solver context ierr = SLESCreate (PETSC_COMM_WORLD, &_sles); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Create the Krylov subspace & preconditioner contexts ierr = SLESGetKSP (_sles, &_ksp); CHKERRABORT(PETSC_COMM_WORLD,ierr); ierr = SLESGetPC (_sles, &_pc); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Have the Krylov subspace method use our good initial guess rather than 0 ierr = KSPSetInitialGuessNonzero (_ksp, PETSC_TRUE); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Set user-specified solver and preconditioner types this->set_petsc_solver_type(); this->set_petsc_preconditioner_type(); // Set the options from user-input // Set runtime options, e.g., // -ksp_type <type> -pc_type <type> -ksp_monitor -ksp_rtol <rtol> // These options will override those specified above as long as // SLESSetFromOptions() is called _after_ any other customization // routines. ierr = SLESSetFromOptions (_sles); CHKERRABORT(PETSC_COMM_WORLD,ierr); // 2.2.0 & newer style #else // Create the linear solver context ierr = KSPCreate (PETSC_COMM_WORLD, &_ksp); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Create the preconditioner context ierr = KSPGetPC (_ksp, &_pc); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Have the Krylov subspace method use our good initial guess rather than 0 ierr = KSPSetInitialGuessNonzero (_ksp, PETSC_TRUE); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Set user-specified solver and preconditioner types this->set_petsc_solver_type(); this->set_petsc_preconditioner_type(); // Set the options from user-input // Set runtime options, e.g., // -ksp_type <type> -pc_type <type> -ksp_monitor -ksp_rtol <rtol> // These options will override those specified above as long as // KSPSetFromOptions() is called _after_ any other customization // routines. ierr = KSPSetFromOptions (_ksp); CHKERRABORT(PETSC_COMM_WORLD,ierr); #endif } } template <typename T> std::pair<unsigned int, Real> PetscInterface<T>::solve (SparseMatrix<T>& matrix_in, SparseMatrix<T>& precond_in, NumericVector<T>& solution_in, NumericVector<T>& rhs_in, const double tol, const unsigned int m_its) { this->init (); PetscMatrix<T>* matrix = dynamic_cast<PetscMatrix<T>*>(&matrix_in); PetscMatrix<T>* precond = dynamic_cast<PetscMatrix<T>*>(&precond_in); PetscVector<T>* solution = dynamic_cast<PetscVector<T>*>(&solution_in); PetscVector<T>* rhs = dynamic_cast<PetscVector<T>*>(&rhs_in); // We cast to pointers so we can be sure that they succeeded // by comparing the result against NULL. assert(matrix != NULL); assert(precond != NULL); assert(solution != NULL); assert(rhs != NULL); int ierr=0; int its=0, max_its = static_cast<int>(m_its); PetscReal final_resid=0.; // Close the matrices and vectors in case this wasn't already done. matrix->close (); precond->close (); solution->close (); rhs->close (); // If matrix != precond, then this means we have specified a // special preconditioner, so reset preconditioner type to PCMAT. if (matrix != precond) { this->_preconditioner_type = USER_PRECOND; this->set_petsc_preconditioner_type (); } // 2.1.x & earlier style #if (PETSC_VERSION_MAJOR == 2) && (PETSC_VERSION_MINOR <= 1) // Set operators. The input matrix works as the preconditioning matrix ierr = SLESSetOperators(_sles, matrix->mat, precond->mat, SAME_NONZERO_PATTERN); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Set the tolerances for the iterative solver. Use the user-supplied // tolerance for the relative residual & leave the others at default values. ierr = KSPSetTolerances (_ksp, tol, PETSC_DEFAULT, PETSC_DEFAULT, max_its); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Solve the linear system ierr = SLESSolve (_sles, rhs->vec, solution->vec, &its); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Get the norm of the final residual to return to the user. ierr = KSPGetResidualNorm (_ksp, &final_resid); CHKERRABORT(PETSC_COMM_WORLD,ierr); // 2.2.0 & newer style #else // Set operators. The input matrix works as the preconditioning matrix ierr = KSPSetOperators(_ksp, matrix->mat, precond->mat, SAME_NONZERO_PATTERN); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Set the tolerances for the iterative solver. Use the user-supplied // tolerance for the relative residual & leave the others at default values. ierr = KSPSetTolerances (_ksp, tol, PETSC_DEFAULT, PETSC_DEFAULT, max_its); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Set the solution vector to use ierr = KSPSetSolution (_ksp, solution->vec); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Set the RHS vector to use ierr = KSPSetRhs (_ksp, rhs->vec); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Solve the linear system ierr = KSPSolve (_ksp); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Get the number of iterations required for convergence ierr = KSPGetIterationNumber (_ksp, &its); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Get the norm of the final residual to return to the user. ierr = KSPGetResidualNorm (_ksp, &final_resid); CHKERRABORT(PETSC_COMM_WORLD,ierr); #endif // return the # of its. and the final residual norm. return std::make_pair(its, final_resid); } template <typename T> void PetscInterface<T>::set_petsc_solver_type() { int ierr = 0; switch (this->_solver_type) { case CG: ierr = KSPSetType (_ksp, (char*) KSPCG); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case CR: ierr = KSPSetType (_ksp, (char*) KSPCR); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case CGS: ierr = KSPSetType (_ksp, (char*) KSPCGS); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case BICG: ierr = KSPSetType (_ksp, (char*) KSPBICG); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case TCQMR: ierr = KSPSetType (_ksp, (char*) KSPTCQMR); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case TFQMR: ierr = KSPSetType (_ksp, (char*) KSPTFQMR); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case LSQR: ierr = KSPSetType (_ksp, (char*) KSPLSQR); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case BICGSTAB: ierr = KSPSetType (_ksp, (char*) KSPBCGS); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case MINRES: ierr = KSPSetType (_ksp, (char*) KSPMINRES); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case GMRES: ierr = KSPSetType (_ksp, (char*) KSPGMRES); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case RICHARDSON: ierr = KSPSetType (_ksp, (char*) KSPRICHARDSON); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case CHEBYSHEV: ierr = KSPSetType (_ksp, (char*) KSPCHEBYCHEV); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; default: std::cerr << "ERROR: Unsupported PETSC Solver: " << this->_solver_type << std::endl << "Continuing with PETSC defaults" << std::endl; } } template <typename T> void PetscInterface<T>::set_petsc_preconditioner_type() { int ierr = 0; switch (this->_preconditioner_type) { case IDENTITY_PRECOND: ierr = PCSetType (_pc, (char*) PCNONE); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case CHOLESKY_PRECOND: ierr = PCSetType (_pc, (char*) PCCHOLESKY); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case ICC_PRECOND: ierr = PCSetType (_pc, (char*) PCICC); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case ILU_PRECOND: ierr = PCSetType (_pc, (char*) PCILU); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case LU_PRECOND: ierr = PCSetType (_pc, (char*) PCLU); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case ASM_PRECOND: ierr = PCSetType (_pc, (char*) PCASM); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case JACOBI_PRECOND: ierr = PCSetType (_pc, (char*) PCJACOBI); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case BLOCK_JACOBI_PRECOND: ierr = PCSetType (_pc, (char*) PCBJACOBI); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case SOR_PRECOND: ierr = PCSetType (_pc, (char*) PCSOR); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case EISENSTAT_PRECOND: ierr = PCSetType (_pc, (char*) PCEISENSTAT); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; #if !((PETSC_VERSION_MAJOR == 2) && (PETSC_VERSION_MINOR <= 1) && (PETSC_VERSION_SUBMINOR <= 1)) case USER_PRECOND: ierr = PCSetType (_pc, (char*) PCMAT); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; #endif default: std::cerr << "ERROR: Unsupported PETSC Preconditioner: " << this->_preconditioner_type << std::endl << "Continuing with PETSC defaults" << std::endl; } } //------------------------------------------------------------------ // Explicit instantiations template class PetscInterface<Number>; #endif // #ifdef HAVE_PETSC <commit_msg>fix for PETSc 2.2.1 courtesy of Martin Luthi<commit_after>// $Id: petsc_interface.C,v 1.27 2004-09-29 13:27:13 benkirk Exp $ // The libMesh Finite Element Library. // Copyright (C) 2002-2004 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "libmesh_common.h" #ifdef HAVE_PETSC // C++ includes // Local Includes #include "petsc_interface.h" /*----------------------- functions ----------------------------------*/ template <typename T> void PetscInterface<T>::clear () { if (this->initialized()) { this->_is_initialized = false; int ierr=0; // 2.1.x & earlier style #if (PETSC_VERSION_MAJOR == 2) && (PETSC_VERSION_MINOR <= 1) ierr = SLESDestroy(_sles); CHKERRABORT(PETSC_COMM_WORLD,ierr); // 2.2.0 & newer style #else ierr = KSPDestroy(_ksp); CHKERRABORT(PETSC_COMM_WORLD,ierr); #endif // Mimic PETSc default solver and preconditioner this->_solver_type = GMRES; if (libMesh::n_processors() == 1) this->_preconditioner_type = ILU_PRECOND; else this->_preconditioner_type = BLOCK_JACOBI_PRECOND; } } template <typename T> void PetscInterface<T>::init () { int ierr=0; // Initialize the data structures if not done so already. if (!this->initialized()) { this->_is_initialized = true; // 2.1.x & earlier style #if (PETSC_VERSION_MAJOR == 2) && (PETSC_VERSION_MINOR <= 1) // Create the linear solver context ierr = SLESCreate (PETSC_COMM_WORLD, &_sles); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Create the Krylov subspace & preconditioner contexts ierr = SLESGetKSP (_sles, &_ksp); CHKERRABORT(PETSC_COMM_WORLD,ierr); ierr = SLESGetPC (_sles, &_pc); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Have the Krylov subspace method use our good initial guess rather than 0 ierr = KSPSetInitialGuessNonzero (_ksp, PETSC_TRUE); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Set user-specified solver and preconditioner types this->set_petsc_solver_type(); this->set_petsc_preconditioner_type(); // Set the options from user-input // Set runtime options, e.g., // -ksp_type <type> -pc_type <type> -ksp_monitor -ksp_rtol <rtol> // These options will override those specified above as long as // SLESSetFromOptions() is called _after_ any other customization // routines. ierr = SLESSetFromOptions (_sles); CHKERRABORT(PETSC_COMM_WORLD,ierr); // 2.2.0 & newer style #else // Create the linear solver context ierr = KSPCreate (PETSC_COMM_WORLD, &_ksp); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Create the preconditioner context ierr = KSPGetPC (_ksp, &_pc); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Have the Krylov subspace method use our good initial guess rather than 0 ierr = KSPSetInitialGuessNonzero (_ksp, PETSC_TRUE); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Set user-specified solver and preconditioner types this->set_petsc_solver_type(); this->set_petsc_preconditioner_type(); // Set the options from user-input // Set runtime options, e.g., // -ksp_type <type> -pc_type <type> -ksp_monitor -ksp_rtol <rtol> // These options will override those specified above as long as // KSPSetFromOptions() is called _after_ any other customization // routines. ierr = KSPSetFromOptions (_ksp); CHKERRABORT(PETSC_COMM_WORLD,ierr); #endif } } template <typename T> std::pair<unsigned int, Real> PetscInterface<T>::solve (SparseMatrix<T>& matrix_in, SparseMatrix<T>& precond_in, NumericVector<T>& solution_in, NumericVector<T>& rhs_in, const double tol, const unsigned int m_its) { this->init (); PetscMatrix<T>* matrix = dynamic_cast<PetscMatrix<T>*>(&matrix_in); PetscMatrix<T>* precond = dynamic_cast<PetscMatrix<T>*>(&precond_in); PetscVector<T>* solution = dynamic_cast<PetscVector<T>*>(&solution_in); PetscVector<T>* rhs = dynamic_cast<PetscVector<T>*>(&rhs_in); // We cast to pointers so we can be sure that they succeeded // by comparing the result against NULL. assert(matrix != NULL); assert(precond != NULL); assert(solution != NULL); assert(rhs != NULL); int ierr=0; int its=0, max_its = static_cast<int>(m_its); PetscReal final_resid=0.; // Close the matrices and vectors in case this wasn't already done. matrix->close (); precond->close (); solution->close (); rhs->close (); // If matrix != precond, then this means we have specified a // special preconditioner, so reset preconditioner type to PCMAT. if (matrix != precond) { this->_preconditioner_type = USER_PRECOND; this->set_petsc_preconditioner_type (); } // 2.1.x & earlier style #if (PETSC_VERSION_MAJOR == 2) && (PETSC_VERSION_MINOR <= 1) // Set operators. The input matrix works as the preconditioning matrix ierr = SLESSetOperators(_sles, matrix->mat, precond->mat, SAME_NONZERO_PATTERN); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Set the tolerances for the iterative solver. Use the user-supplied // tolerance for the relative residual & leave the others at default values. ierr = KSPSetTolerances (_ksp, tol, PETSC_DEFAULT, PETSC_DEFAULT, max_its); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Solve the linear system ierr = SLESSolve (_sles, rhs->vec, solution->vec, &its); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Get the norm of the final residual to return to the user. ierr = KSPGetResidualNorm (_ksp, &final_resid); CHKERRABORT(PETSC_COMM_WORLD,ierr); // 2.2.0 #elif (PETSC_VERSION_MAJOR == 2) && (PETSC_VERSION_MINOR == 2) && (PETSC_VERSION_SUBMINOR == 0) // Set operators. The input matrix works as the preconditioning matrix ierr = KSPSetOperators(_ksp, matrix->mat, precond->mat, SAME_NONZERO_PATTERN); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Set the tolerances for the iterative solver. Use the user-supplied // tolerance for the relative residual & leave the others at default values. ierr = KSPSetTolerances (_ksp, tol, PETSC_DEFAULT, PETSC_DEFAULT, max_its); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Set the solution vector to use ierr = KSPSetSolution (_ksp, solution->vec); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Set the RHS vector to use ierr = KSPSetRhs (_ksp, rhs->vec); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Solve the linear system ierr = KSPSolve (_ksp); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Get the number of iterations required for convergence ierr = KSPGetIterationNumber (_ksp, &its); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Get the norm of the final residual to return to the user. ierr = KSPGetResidualNorm (_ksp, &final_resid); CHKERRABORT(PETSC_COMM_WORLD,ierr); // 2.2.1 & newer style #else // Set operators. The input matrix works as the preconditioning matrix ierr = KSPSetOperators(_ksp, matrix->mat, precond->mat, SAME_NONZERO_PATTERN); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Set the tolerances for the iterative solver. Use the user-supplied // tolerance for the relative residual & leave the others at default values. ierr = KSPSetTolerances (_ksp, tol, PETSC_DEFAULT, PETSC_DEFAULT, max_its); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Solve the linear system ierr = KSPSolve (_ksp, rhs->vec, solution->vec); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Get the number of iterations required for convergence ierr = KSPGetIterationNumber (_ksp, &its); CHKERRABORT(PETSC_COMM_WORLD,ierr); // Get the norm of the final residual to return to the user. ierr = KSPGetResidualNorm (_ksp, &final_resid); CHKERRABORT(PETSC_COMM_WORLD,ierr); #endif // return the # of its. and the final residual norm. return std::make_pair(its, final_resid); } template <typename T> void PetscInterface<T>::set_petsc_solver_type() { int ierr = 0; switch (this->_solver_type) { case CG: ierr = KSPSetType (_ksp, (char*) KSPCG); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case CR: ierr = KSPSetType (_ksp, (char*) KSPCR); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case CGS: ierr = KSPSetType (_ksp, (char*) KSPCGS); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case BICG: ierr = KSPSetType (_ksp, (char*) KSPBICG); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case TCQMR: ierr = KSPSetType (_ksp, (char*) KSPTCQMR); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case TFQMR: ierr = KSPSetType (_ksp, (char*) KSPTFQMR); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case LSQR: ierr = KSPSetType (_ksp, (char*) KSPLSQR); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case BICGSTAB: ierr = KSPSetType (_ksp, (char*) KSPBCGS); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case MINRES: ierr = KSPSetType (_ksp, (char*) KSPMINRES); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case GMRES: ierr = KSPSetType (_ksp, (char*) KSPGMRES); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case RICHARDSON: ierr = KSPSetType (_ksp, (char*) KSPRICHARDSON); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case CHEBYSHEV: ierr = KSPSetType (_ksp, (char*) KSPCHEBYCHEV); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; default: std::cerr << "ERROR: Unsupported PETSC Solver: " << this->_solver_type << std::endl << "Continuing with PETSC defaults" << std::endl; } } template <typename T> void PetscInterface<T>::set_petsc_preconditioner_type() { int ierr = 0; switch (this->_preconditioner_type) { case IDENTITY_PRECOND: ierr = PCSetType (_pc, (char*) PCNONE); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case CHOLESKY_PRECOND: ierr = PCSetType (_pc, (char*) PCCHOLESKY); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case ICC_PRECOND: ierr = PCSetType (_pc, (char*) PCICC); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case ILU_PRECOND: ierr = PCSetType (_pc, (char*) PCILU); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case LU_PRECOND: ierr = PCSetType (_pc, (char*) PCLU); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case ASM_PRECOND: ierr = PCSetType (_pc, (char*) PCASM); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case JACOBI_PRECOND: ierr = PCSetType (_pc, (char*) PCJACOBI); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case BLOCK_JACOBI_PRECOND: ierr = PCSetType (_pc, (char*) PCBJACOBI); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case SOR_PRECOND: ierr = PCSetType (_pc, (char*) PCSOR); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; case EISENSTAT_PRECOND: ierr = PCSetType (_pc, (char*) PCEISENSTAT); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; #if !((PETSC_VERSION_MAJOR == 2) && (PETSC_VERSION_MINOR <= 1) && (PETSC_VERSION_SUBMINOR <= 1)) case USER_PRECOND: ierr = PCSetType (_pc, (char*) PCMAT); CHKERRABORT(PETSC_COMM_WORLD,ierr); return; #endif default: std::cerr << "ERROR: Unsupported PETSC Preconditioner: " << this->_preconditioner_type << std::endl << "Continuing with PETSC defaults" << std::endl; } } //------------------------------------------------------------------ // Explicit instantiations template class PetscInterface<Number>; #endif // #ifdef HAVE_PETSC <|endoftext|>
<commit_before>#include "cy_hair_loader.h" #include <stdio.h> #include <math.h> namespace embree { // ------------------------------------------- // -- Based on the format by Cem Yuksel -- // -- www.cemyuksel.com/research/hairmodels -- // ------------------------------------------- #define CY_HAIR_FILE_SEGMENTS_BIT 1 #define CY_HAIR_FILE_POINTS_BIT 2 #define CY_HAIR_FILE_THICKNESS_BIT 4 #define CY_HAIR_FILE_TRANSPARENCY_BIT 8 #define CY_HAIR_FILE_COLORS_BIT 16 #define CY_HAIR_FILE_INFO_SIZE 88 struct cyHeader { char signature[4]; ///< This should be "HAIR" unsigned int numStrands; ///< number of hair strands unsigned int numPoints; ///< total number of points of all strands unsigned int bitarrays; ///< bit array of data in the file unsigned int defaultSegments; ///< default number of segments of each strand float defaultThickness; ///< default thickness of hair strands float defaultTransparency; ///< default transparency of hair strands float defaultColor[3]; ///< default color of hair strands char info[CY_HAIR_FILE_INFO_SIZE]; ///< information about the file }; class cyHairFile { public: cyHairFile() : segments(NULL), points(NULL), thickness(NULL), transparency(NULL), colors(NULL) {init(); } ~cyHairFile() { if ( segments ) delete [] segments; if ( points ) delete [] points; if ( colors ) delete [] colors; if ( thickness ) delete [] thickness; if ( transparency ) delete [] transparency; } void init() { header.signature[0] = 'H'; header.signature[1] = 'A'; header.signature[2] = 'I'; header.signature[3] = 'R'; header.numStrands = 0; header.numPoints = 0; header.bitarrays = 0; header.defaultSegments = 0; header.defaultThickness = 1.0f; header.defaultTransparency = 0.0f; header.defaultColor[0] = 1.0f; header.defaultColor[1] = 1.0f; header.defaultColor[2] = 1.0f; memset( header.info, '\0', CY_HAIR_FILE_INFO_SIZE ); } int load( const char *filename ) { DBG_PRINT(filename); init(); FILE *file; file = fopen( filename, "rb" ); if ( file == NULL ) throw std::runtime_error("can't open file"); size_t h = fread( &header, sizeof(cyHeader), 1, file ); if ( h < 1 ) throw std::runtime_error("can't read header"); if ( strncmp( header.signature, "HAIR", 4) != 0 ) throw std::runtime_error("wrong signature"); if ( header.bitarrays & CY_HAIR_FILE_SEGMENTS_BIT ) { segments = new unsigned short[ header.numStrands ]; size_t r = fread( segments, sizeof(unsigned short), header.numStrands, file ); if ( r < header.numStrands ) throw std::runtime_error("error reading segments"); } if ( header.bitarrays & CY_HAIR_FILE_POINTS_BIT ) { points = new float[ header.numPoints*3 ]; size_t r = fread( points, sizeof(float), header.numPoints*3, file ); if ( r < header.numPoints*3 ) throw std::runtime_error("error reading points"); } if ( header.bitarrays & CY_HAIR_FILE_THICKNESS_BIT ) { thickness = new float[ header.numPoints ]; size_t r = fread( thickness, sizeof(float), header.numPoints, file ); if ( r < header.numPoints ) throw std::runtime_error("error reading thickness values"); } if ( header.bitarrays & CY_HAIR_FILE_TRANSPARENCY_BIT ) { transparency = new float[ header.numPoints ]; size_t r = fread( transparency, sizeof(float), header.numPoints, file ); if ( r < header.numPoints ) throw std::runtime_error("error reading transparency values"); } if ( header.bitarrays & CY_HAIR_FILE_COLORS_BIT ) { colors = new float[ header.numPoints*3 ]; size_t r = fread( colors, sizeof(float), header.numPoints*3, file ); if ( r < header.numPoints*3 ) throw std::runtime_error("error reading color values"); } fclose( file ); return header.numStrands; } cyHeader header; unsigned short *segments; float *points; float *thickness; float *transparency; float *colors; }; void loadCYHair(const FileName& fileName, OBJScene& scene, Vec3fa& offset) { cyHairFile cyFile; int numHairs = cyFile.load(fileName.c_str()); std::cout << "Successfully loaded hair data" << std::endl; OBJScene::HairSet* hairset = new OBJScene::HairSet; for (size_t i=0;i<cyFile.header.numPoints;i++) { Vec3fa v; v.x = cyFile.points[3*i+0]; v.y = cyFile.points[3*i+1]; v.z = cyFile.points[3*i+2]; v.w = cyFile.thickness ? cyFile.thickness[i] : 0.1f; v.x-=offset.x; v.y-=offset.y; v.z-=offset.z; hairset->v.push_back(v); } ssize_t index = 0; for (ssize_t i=0;i<cyFile.header.numStrands;i++) { if (cyFile.segments) { ssize_t numSegments = cyFile.segments[i]; for (ssize_t j=0; j<numSegments-2; j+=3) { hairset->hairs.push_back(OBJScene::Hair(index + j,i)); } index += numSegments; } else { ssize_t numSegments = cyFile.header.defaultSegments; for (ssize_t j=0; j<numSegments-2; j+=3) { hairset->hairs.push_back(OBJScene::Hair(index + j,i)); } index += numSegments; } } scene.hairsets.push_back(hairset); int numPoints = hairset->v.size(); int numSegments = hairset->hairs.size(); PRINT(numHairs); PRINT(numSegments); PRINT(numPoints); } } <commit_msg>bugfix<commit_after>#include "cy_hair_loader.h" #include <stdio.h> #include <math.h> namespace embree { // ------------------------------------------- // -- Based on the format by Cem Yuksel -- // -- www.cemyuksel.com/research/hairmodels -- // ------------------------------------------- #define CY_HAIR_FILE_SEGMENTS_BIT 1 #define CY_HAIR_FILE_POINTS_BIT 2 #define CY_HAIR_FILE_THICKNESS_BIT 4 #define CY_HAIR_FILE_TRANSPARENCY_BIT 8 #define CY_HAIR_FILE_COLORS_BIT 16 #define CY_HAIR_FILE_INFO_SIZE 88 struct cyHeader { char signature[4]; ///< This should be "HAIR" unsigned int numStrands; ///< number of hair strands unsigned int numPoints; ///< total number of points of all strands unsigned int bitarrays; ///< bit array of data in the file unsigned int defaultSegments; ///< default number of segments of each strand float defaultThickness; ///< default thickness of hair strands float defaultTransparency; ///< default transparency of hair strands float defaultColor[3]; ///< default color of hair strands char info[CY_HAIR_FILE_INFO_SIZE]; ///< information about the file }; class cyHairFile { public: cyHairFile() : segments(NULL), points(NULL), thickness(NULL), transparency(NULL), colors(NULL) {init(); } ~cyHairFile() { if ( segments ) delete [] segments; if ( points ) delete [] points; if ( colors ) delete [] colors; if ( thickness ) delete [] thickness; if ( transparency ) delete [] transparency; } void init() { header.signature[0] = 'H'; header.signature[1] = 'A'; header.signature[2] = 'I'; header.signature[3] = 'R'; header.numStrands = 0; header.numPoints = 0; header.bitarrays = 0; header.defaultSegments = 0; header.defaultThickness = 1.0f; header.defaultTransparency = 0.0f; header.defaultColor[0] = 1.0f; header.defaultColor[1] = 1.0f; header.defaultColor[2] = 1.0f; memset( header.info, '\0', CY_HAIR_FILE_INFO_SIZE ); } int load( const char *filename ) { DBG_PRINT(filename); init(); FILE *file; file = fopen( filename, "rb" ); if ( file == NULL ) throw std::runtime_error("can't open file"); size_t h = fread( &header, sizeof(cyHeader), 1, file ); if ( h < 1 ) throw std::runtime_error("can't read header"); if ( strncmp( header.signature, "HAIR", 4) != 0 ) throw std::runtime_error("wrong signature"); if ( header.bitarrays & CY_HAIR_FILE_SEGMENTS_BIT ) { segments = new unsigned short[ header.numStrands ]; size_t r = fread( segments, sizeof(unsigned short), header.numStrands, file ); if ( r < header.numStrands ) throw std::runtime_error("error reading segments"); } if ( header.bitarrays & CY_HAIR_FILE_POINTS_BIT ) { points = new float[ header.numPoints*3 ]; size_t r = fread( points, sizeof(float), header.numPoints*3, file ); if ( r < header.numPoints*3 ) throw std::runtime_error("error reading points"); } if ( header.bitarrays & CY_HAIR_FILE_THICKNESS_BIT ) { thickness = new float[ header.numPoints ]; size_t r = fread( thickness, sizeof(float), header.numPoints, file ); if ( r < header.numPoints ) throw std::runtime_error("error reading thickness values"); } if ( header.bitarrays & CY_HAIR_FILE_TRANSPARENCY_BIT ) { transparency = new float[ header.numPoints ]; size_t r = fread( transparency, sizeof(float), header.numPoints, file ); if ( r < header.numPoints ) throw std::runtime_error("error reading transparency values"); } if ( header.bitarrays & CY_HAIR_FILE_COLORS_BIT ) { colors = new float[ header.numPoints*3 ]; size_t r = fread( colors, sizeof(float), header.numPoints*3, file ); if ( r < header.numPoints*3 ) throw std::runtime_error("error reading color values"); } fclose( file ); return header.numStrands; } cyHeader header; unsigned short *segments; float *points; float *thickness; float *transparency; float *colors; }; void loadCYHair(const FileName& fileName, OBJScene& scene, Vec3fa& offset) { cyHairFile cyFile; int numHairs = cyFile.load(fileName.c_str()); std::cout << "Successfully loaded hair data" << std::endl; OBJScene::HairSet* hairset = new OBJScene::HairSet; for (size_t i=0;i<cyFile.header.numPoints;i++) { Vec3fa v; v.x = cyFile.points[3*i+0]; v.y = cyFile.points[3*i+1]; v.z = cyFile.points[3*i+2]; v.w = cyFile.thickness ? cyFile.thickness[i] : 0.1f; v.x-=offset.x; v.y-=offset.y; v.z-=offset.z; hairset->v.push_back(v); } ssize_t index = 0; for (ssize_t i=0;i<cyFile.header.numStrands;i++) { if (cyFile.segments) { ssize_t numSegments = cyFile.segments[i]; for (ssize_t j=0; j<numSegments-3; j+=3) { hairset->hairs.push_back(OBJScene::Hair(index + j,i)); } index += numSegments+1; } else { ssize_t numSegments = cyFile.header.defaultSegments; for (ssize_t j=0; j<numSegments-3; j+=3) { hairset->hairs.push_back(OBJScene::Hair(index + j,i)); } index += numSegments+1; } } scene.hairsets.push_back(hairset); int numPoints = hairset->v.size(); int numSegments = hairset->hairs.size(); PRINT(numHairs); PRINT(numSegments); PRINT(numPoints); } } <|endoftext|>
<commit_before>// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #ifndef ROCKSDB_LITE #include <mutex> #include <string> #include <thread> #include <vector> #include "db/db_impl.h" #include "rocksdb/db.h" #include "rocksdb/env.h" #include "util/string_util.h" #include "util/sync_point.h" #include "util/testharness.h" namespace rocksdb { class CompactFilesTest : public testing::Test { public: CompactFilesTest() { env_ = Env::Default(); db_name_ = test::TmpDir(env_) + "/compact_files_test"; } std::string db_name_; Env* env_; }; // A class which remembers the name of each flushed file. class FlushedFileCollector : public EventListener { public: FlushedFileCollector() {} ~FlushedFileCollector() {} virtual void OnFlushCompleted( DB* db, const FlushJobInfo& info) override { std::lock_guard<std::mutex> lock(mutex_); flushed_files_.push_back(info.file_path); } std::vector<std::string> GetFlushedFiles() { std::lock_guard<std::mutex> lock(mutex_); std::vector<std::string> result; for (auto fname : flushed_files_) { result.push_back(fname); } return result; } void ClearFlushedFiles() { flushed_files_.clear(); } private: std::vector<std::string> flushed_files_; std::mutex mutex_; }; TEST_F(CompactFilesTest, L0ConflictsFiles) { Options options; // to trigger compaction more easily const int kWriteBufferSize = 10000; const int kLevel0Trigger = 2; options.create_if_missing = true; options.compaction_style = kCompactionStyleLevel; // Small slowdown and stop trigger for experimental purpose. options.level0_slowdown_writes_trigger = 20; options.level0_stop_writes_trigger = 20; options.level0_stop_writes_trigger = 20; options.write_buffer_size = kWriteBufferSize; options.level0_file_num_compaction_trigger = kLevel0Trigger; options.compression = kNoCompression; DB* db = nullptr; DestroyDB(db_name_, options); Status s = DB::Open(options, db_name_, &db); assert(s.ok()); assert(db); rocksdb::SyncPoint::GetInstance()->LoadDependency({ {"CompactFilesImpl:0", "BackgroundCallCompaction:0"}, {"BackgroundCallCompaction:1", "CompactFilesImpl:1"}, }); rocksdb::SyncPoint::GetInstance()->EnableProcessing(); // create couple files // Background compaction starts and waits in BackgroundCallCompaction:0 for (int i = 0; i < kLevel0Trigger * 4; ++i) { db->Put(WriteOptions(), ToString(i), ""); db->Put(WriteOptions(), ToString(100 - i), ""); db->Flush(FlushOptions()); } rocksdb::ColumnFamilyMetaData meta; db->GetColumnFamilyMetaData(&meta); std::string file1; for (auto& file : meta.levels[0].files) { ASSERT_EQ(0, meta.levels[0].level); if (file1 == "") { file1 = file.db_path + "/" + file.name; } else { std::string file2 = file.db_path + "/" + file.name; // Another thread starts a compact files and creates an L0 compaction // The background compaction then notices that there is an L0 compaction // already in progress and doesn't do an L0 compaction // Once the background compaction finishes, the compact files finishes ASSERT_OK( db->CompactFiles(rocksdb::CompactionOptions(), {file1, file2}, 0)); break; } } rocksdb::SyncPoint::GetInstance()->DisableProcessing(); delete db; } TEST_F(CompactFilesTest, ObsoleteFiles) { Options options; // to trigger compaction more easily const int kWriteBufferSize = 65536; options.create_if_missing = true; // Disable RocksDB background compaction. options.compaction_style = kCompactionStyleNone; // Small slowdown and stop trigger for experimental purpose. options.level0_slowdown_writes_trigger = 20; options.level0_stop_writes_trigger = 20; options.write_buffer_size = kWriteBufferSize; options.max_write_buffer_number = 2; options.compression = kNoCompression; // Add listener FlushedFileCollector* collector = new FlushedFileCollector(); options.listeners.emplace_back(collector); DB* db = nullptr; DestroyDB(db_name_, options); Status s = DB::Open(options, db_name_, &db); assert(s.ok()); assert(db); // create couple files for (int i = 1000; i < 2000; ++i) { db->Put(WriteOptions(), ToString(i), std::string(kWriteBufferSize / 10, 'a' + (i % 26))); } auto l0_files = collector->GetFlushedFiles(); ASSERT_OK(db->CompactFiles(CompactionOptions(), l0_files, 1)); reinterpret_cast<DBImpl*>(db)->TEST_WaitForCompact(); // verify all compaction input files are deleted for (auto fname : l0_files) { ASSERT_EQ(Status::NotFound(), env_->FileExists(fname)); } delete db; } TEST_F(CompactFilesTest, NotCutOutputOnLevel0) { Options options; options.create_if_missing = true; // Disable RocksDB background compaction. options.compaction_style = kCompactionStyleNone; options.level0_slowdown_writes_trigger = 1000; options.level0_stop_writes_trigger = 1000; options.write_buffer_size = 65536; options.max_write_buffer_number = 2; options.compression = kNoCompression; options.max_compaction_bytes = 5000; // Add listener FlushedFileCollector* collector = new FlushedFileCollector(); options.listeners.emplace_back(collector); DB* db = nullptr; DestroyDB(db_name_, options); Status s = DB::Open(options, db_name_, &db); assert(s.ok()); assert(db); // create couple files for (int i = 0; i < 500; ++i) { db->Put(WriteOptions(), ToString(i), std::string(1000, 'a' + (i % 26))); } reinterpret_cast<DBImpl*>(db)->TEST_WaitForFlushMemTable(); auto l0_files_1 = collector->GetFlushedFiles(); collector->ClearFlushedFiles(); for (int i = 0; i < 500; ++i) { db->Put(WriteOptions(), ToString(i), std::string(1000, 'a' + (i % 26))); } reinterpret_cast<DBImpl*>(db)->TEST_WaitForFlushMemTable(); auto l0_files_2 = collector->GetFlushedFiles(); ASSERT_OK(db->CompactFiles(CompactionOptions(), l0_files_1, 0)); ASSERT_OK(db->CompactFiles(CompactionOptions(), l0_files_2, 0)); // no assertion failure delete db; } TEST_F(CompactFilesTest, CapturingPendingFiles) { Options options; options.create_if_missing = true; // Disable RocksDB background compaction. options.compaction_style = kCompactionStyleNone; // Always do full scans for obsolete files (needed to reproduce the issue). options.delete_obsolete_files_period_micros = 0; // Add listener. FlushedFileCollector* collector = new FlushedFileCollector(); options.listeners.emplace_back(collector); DB* db = nullptr; DestroyDB(db_name_, options); Status s = DB::Open(options, db_name_, &db); assert(s.ok()); assert(db); // Create 5 files. for (int i = 0; i < 5; ++i) { db->Put(WriteOptions(), "key" + ToString(i), "value"); db->Flush(FlushOptions()); } auto l0_files = collector->GetFlushedFiles(); EXPECT_EQ(5, l0_files.size()); rocksdb::SyncPoint::GetInstance()->LoadDependency({ {"CompactFilesImpl:2", "CompactFilesTest.CapturingPendingFiles:0"}, {"CompactFilesTest.CapturingPendingFiles:1", "CompactFilesImpl:3"}, }); rocksdb::SyncPoint::GetInstance()->EnableProcessing(); // Start compacting files. std::thread compaction_thread( [&] { EXPECT_OK(db->CompactFiles(CompactionOptions(), l0_files, 1)); }); // In the meantime flush another file. TEST_SYNC_POINT("CompactFilesTest.CapturingPendingFiles:0"); db->Put(WriteOptions(), "key5", "value"); db->Flush(FlushOptions()); TEST_SYNC_POINT("CompactFilesTest.CapturingPendingFiles:1"); compaction_thread.join(); rocksdb::SyncPoint::GetInstance()->DisableProcessing(); delete db; // Make sure we can reopen the DB. s = DB::Open(options, db_name_, &db); ASSERT_TRUE(s.ok()); assert(db); delete db; } } // namespace rocksdb int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } #else #include <stdio.h> int main(int argc, char** argv) { fprintf(stderr, "SKIPPED as DBImpl::CompactFiles is not supported in ROCKSDB_LITE\n"); return 0; } #endif // !ROCKSDB_LITE <commit_msg>Fix CompactFilesTest.ObsoleteFiles timeout (#1353)<commit_after>// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #ifndef ROCKSDB_LITE #include <mutex> #include <string> #include <thread> #include <vector> #include "db/db_impl.h" #include "rocksdb/db.h" #include "rocksdb/env.h" #include "util/string_util.h" #include "util/sync_point.h" #include "util/testharness.h" namespace rocksdb { class CompactFilesTest : public testing::Test { public: CompactFilesTest() { env_ = Env::Default(); db_name_ = test::TmpDir(env_) + "/compact_files_test"; } std::string db_name_; Env* env_; }; // A class which remembers the name of each flushed file. class FlushedFileCollector : public EventListener { public: FlushedFileCollector() {} ~FlushedFileCollector() {} virtual void OnFlushCompleted( DB* db, const FlushJobInfo& info) override { std::lock_guard<std::mutex> lock(mutex_); flushed_files_.push_back(info.file_path); } std::vector<std::string> GetFlushedFiles() { std::lock_guard<std::mutex> lock(mutex_); std::vector<std::string> result; for (auto fname : flushed_files_) { result.push_back(fname); } return result; } void ClearFlushedFiles() { flushed_files_.clear(); } private: std::vector<std::string> flushed_files_; std::mutex mutex_; }; TEST_F(CompactFilesTest, L0ConflictsFiles) { Options options; // to trigger compaction more easily const int kWriteBufferSize = 10000; const int kLevel0Trigger = 2; options.create_if_missing = true; options.compaction_style = kCompactionStyleLevel; // Small slowdown and stop trigger for experimental purpose. options.level0_slowdown_writes_trigger = 20; options.level0_stop_writes_trigger = 20; options.level0_stop_writes_trigger = 20; options.write_buffer_size = kWriteBufferSize; options.level0_file_num_compaction_trigger = kLevel0Trigger; options.compression = kNoCompression; DB* db = nullptr; DestroyDB(db_name_, options); Status s = DB::Open(options, db_name_, &db); assert(s.ok()); assert(db); rocksdb::SyncPoint::GetInstance()->LoadDependency({ {"CompactFilesImpl:0", "BackgroundCallCompaction:0"}, {"BackgroundCallCompaction:1", "CompactFilesImpl:1"}, }); rocksdb::SyncPoint::GetInstance()->EnableProcessing(); // create couple files // Background compaction starts and waits in BackgroundCallCompaction:0 for (int i = 0; i < kLevel0Trigger * 4; ++i) { db->Put(WriteOptions(), ToString(i), ""); db->Put(WriteOptions(), ToString(100 - i), ""); db->Flush(FlushOptions()); } rocksdb::ColumnFamilyMetaData meta; db->GetColumnFamilyMetaData(&meta); std::string file1; for (auto& file : meta.levels[0].files) { ASSERT_EQ(0, meta.levels[0].level); if (file1 == "") { file1 = file.db_path + "/" + file.name; } else { std::string file2 = file.db_path + "/" + file.name; // Another thread starts a compact files and creates an L0 compaction // The background compaction then notices that there is an L0 compaction // already in progress and doesn't do an L0 compaction // Once the background compaction finishes, the compact files finishes ASSERT_OK( db->CompactFiles(rocksdb::CompactionOptions(), {file1, file2}, 0)); break; } } rocksdb::SyncPoint::GetInstance()->DisableProcessing(); delete db; } TEST_F(CompactFilesTest, ObsoleteFiles) { Options options; // to trigger compaction more easily const int kWriteBufferSize = 65536; options.create_if_missing = true; // Disable RocksDB background compaction. options.compaction_style = kCompactionStyleNone; options.level0_slowdown_writes_trigger = (1 << 30); options.level0_stop_writes_trigger = (1 << 30); options.write_buffer_size = kWriteBufferSize; options.max_write_buffer_number = 2; options.compression = kNoCompression; // Add listener FlushedFileCollector* collector = new FlushedFileCollector(); options.listeners.emplace_back(collector); DB* db = nullptr; DestroyDB(db_name_, options); Status s = DB::Open(options, db_name_, &db); assert(s.ok()); assert(db); // create couple files for (int i = 1000; i < 2000; ++i) { db->Put(WriteOptions(), ToString(i), std::string(kWriteBufferSize / 10, 'a' + (i % 26))); } auto l0_files = collector->GetFlushedFiles(); ASSERT_OK(db->CompactFiles(CompactionOptions(), l0_files, 1)); reinterpret_cast<DBImpl*>(db)->TEST_WaitForCompact(); // verify all compaction input files are deleted for (auto fname : l0_files) { ASSERT_EQ(Status::NotFound(), env_->FileExists(fname)); } delete db; } TEST_F(CompactFilesTest, NotCutOutputOnLevel0) { Options options; options.create_if_missing = true; // Disable RocksDB background compaction. options.compaction_style = kCompactionStyleNone; options.level0_slowdown_writes_trigger = 1000; options.level0_stop_writes_trigger = 1000; options.write_buffer_size = 65536; options.max_write_buffer_number = 2; options.compression = kNoCompression; options.max_compaction_bytes = 5000; // Add listener FlushedFileCollector* collector = new FlushedFileCollector(); options.listeners.emplace_back(collector); DB* db = nullptr; DestroyDB(db_name_, options); Status s = DB::Open(options, db_name_, &db); assert(s.ok()); assert(db); // create couple files for (int i = 0; i < 500; ++i) { db->Put(WriteOptions(), ToString(i), std::string(1000, 'a' + (i % 26))); } reinterpret_cast<DBImpl*>(db)->TEST_WaitForFlushMemTable(); auto l0_files_1 = collector->GetFlushedFiles(); collector->ClearFlushedFiles(); for (int i = 0; i < 500; ++i) { db->Put(WriteOptions(), ToString(i), std::string(1000, 'a' + (i % 26))); } reinterpret_cast<DBImpl*>(db)->TEST_WaitForFlushMemTable(); auto l0_files_2 = collector->GetFlushedFiles(); ASSERT_OK(db->CompactFiles(CompactionOptions(), l0_files_1, 0)); ASSERT_OK(db->CompactFiles(CompactionOptions(), l0_files_2, 0)); // no assertion failure delete db; } TEST_F(CompactFilesTest, CapturingPendingFiles) { Options options; options.create_if_missing = true; // Disable RocksDB background compaction. options.compaction_style = kCompactionStyleNone; // Always do full scans for obsolete files (needed to reproduce the issue). options.delete_obsolete_files_period_micros = 0; // Add listener. FlushedFileCollector* collector = new FlushedFileCollector(); options.listeners.emplace_back(collector); DB* db = nullptr; DestroyDB(db_name_, options); Status s = DB::Open(options, db_name_, &db); assert(s.ok()); assert(db); // Create 5 files. for (int i = 0; i < 5; ++i) { db->Put(WriteOptions(), "key" + ToString(i), "value"); db->Flush(FlushOptions()); } auto l0_files = collector->GetFlushedFiles(); EXPECT_EQ(5, l0_files.size()); rocksdb::SyncPoint::GetInstance()->LoadDependency({ {"CompactFilesImpl:2", "CompactFilesTest.CapturingPendingFiles:0"}, {"CompactFilesTest.CapturingPendingFiles:1", "CompactFilesImpl:3"}, }); rocksdb::SyncPoint::GetInstance()->EnableProcessing(); // Start compacting files. std::thread compaction_thread( [&] { EXPECT_OK(db->CompactFiles(CompactionOptions(), l0_files, 1)); }); // In the meantime flush another file. TEST_SYNC_POINT("CompactFilesTest.CapturingPendingFiles:0"); db->Put(WriteOptions(), "key5", "value"); db->Flush(FlushOptions()); TEST_SYNC_POINT("CompactFilesTest.CapturingPendingFiles:1"); compaction_thread.join(); rocksdb::SyncPoint::GetInstance()->DisableProcessing(); delete db; // Make sure we can reopen the DB. s = DB::Open(options, db_name_, &db); ASSERT_TRUE(s.ok()); assert(db); delete db; } } // namespace rocksdb int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } #else #include <stdio.h> int main(int argc, char** argv) { fprintf(stderr, "SKIPPED as DBImpl::CompactFiles is not supported in ROCKSDB_LITE\n"); return 0; } #endif // !ROCKSDB_LITE <|endoftext|>
<commit_before>#include "catch.hpp" #include <iostream> #include "Database_Creator.hpp" #include "Database_Sorter.hpp" person readPerson(std::string file_name, size_t index) { person result; std::ifstream file(file_name); for (size_t i = 0; i < index + 1; i++) { file >> result; } file.close(); return result; } /*bool isALessThanB(char A, char B, bool is_capital) { std::string alphabet; if (is_capital) { alphabet = " АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"; } else { alphabet = " абвгдеёжзийклмнопрстуфхцчшщъыьэюя"; } size_t A_i; size_t B_i; for (size_t i = 0; i < alphabet.size(); i++) { if (alphabet[i] == A) { A_i = i; } if (alphabet[i] == B) { B_i = i; } } return A_i < B_i; }*/ bool isANotMoreThanB(person A, person B) { for (size_t i = 0; i < A.surname.length(); i++) { char A_char = A.surname[i]; char B_char = (i < B.surname.length()) ? B.surname[i] : ' '; if (letterI(A.surname[i], i == 0) < letterI(B.surname[i], i == 0)) { return true; } else { if (A.surname[i] != B.surname[i]) { return false; } } } return true; } SCENARIO("LetterI", "[l]") { REQUIRE(letterI('A', true) == 1); REQUIRE(letterI('d', false) == 4); } SCENARIO("Sort", "[s]") { //setlocale(LC_ALL, "ru_RU.utf8"); std::ifstream ru("russian_letters.txt"); for (size_t i = 0; i < 6; i++) { std::string str; ru >> str; russian_letters[i] = str[0]; } ru.close(); size_t n_persons = 2001; size_t RAM_amount = 10000; std::string names_file_name = "Names"; std::string surnames_file_name = "Surnames"; std::string database_file_name = "database.txt"; std::string output_file_name = "sorted_database.txt"; { Database_Creator database_creator(database_file_name, names_file_name, surnames_file_name, n_persons); Database_Sorter database_sorter(database_file_name, output_file_name, RAM_amount); size_t start = clock(); database_sorter.sortDatabase(); size_t result = clock() - start; std::cout << result << std::endl; system("pause"); } for (size_t i = 0; i < 1000; i++) { size_t person1_i = rand() % n_persons; size_t person2_i = person1_i + rand() % (n_persons - person1_i); person person1 = readPerson(output_file_name, person1_i); person person2 = readPerson(output_file_name, person2_i); REQUIRE(isANotMoreThanB(person1, person2)); } /*std::string str = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"; REQUIRE(letterI(str[1], true) == 2); REQUIRE(letterI(str[2], true) == 3); REQUIRE(letterI(str[3], true) == 4); REQUIRE(letterI(str[4], true) == 5);*/ } <commit_msg>Update init.cpp<commit_after>#include "catch.hpp" #include <iostream> #include "Database_Creator.hpp" #include "Database_Sorter.hpp" person readPerson(std::string file_name, size_t index) { person result; std::ifstream file(file_name); for (size_t i = 0; i < index + 1; i++) { file >> result; } file.close(); return result; } /*bool isALessThanB(char A, char B, bool is_capital) { std::string alphabet; if (is_capital) { alphabet = " АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"; } else { alphabet = " абвгдеёжзийклмнопрстуфхцчшщъыьэюя"; } size_t A_i; size_t B_i; for (size_t i = 0; i < alphabet.size(); i++) { if (alphabet[i] == A) { A_i = i; } if (alphabet[i] == B) { B_i = i; } } return A_i < B_i; }*/ bool isANotMoreThanB(person A, person B) { for (size_t i = 0; i < A.surname.length(); i++) { char A_char = A.surname[i]; char B_char = (i < B.surname.length()) ? B.surname[i] : ' '; if (letterI(A.surname[i], i == 0) < letterI(B.surname[i], i == 0)) { return true; } else { if (A.surname[i] != B.surname[i]) { return false; } } } return true; } SCENARIO("LetterI", "[l]") { REQUIRE(letterI('A', true) == 1); REQUIRE(letterI('d', false) == 4); } SCENARIO("Sort", "[s]") { //setlocale(LC_ALL, "ru_RU.utf8"); std::ifstream ru("russian_letters.txt"); for (size_t i = 0; i < 6; i++) { std::string str; ru >> str; russian_letters[i] = str[0]; } ru.close(); size_t n_persons = 2001; size_t RAM_amount = 10000; std::string names_file_name = "Names"; std::string surnames_file_name = "Surnames"; std::string database_file_name = "database.txt"; std::string output_file_name = "sorted_database.txt"; { Database_Creator database_creator(database_file_name, names_file_name, surnames_file_name, n_persons); Database_Sorter database_sorter(database_file_name, output_file_name, RAM_amount); size_t start = clock(); database_sorter.sortDatabase(); size_t result = clock() - start; std::cout << result << std::endl; system("pause"); } for (size_t i = 0; i < 25; i++) { size_t person1_i = rand() % n_persons; size_t person2_i = person1_i + rand() % (n_persons - person1_i); person person1 = readPerson(output_file_name, person1_i); person person2 = readPerson(output_file_name, person2_i); REQUIRE(isANotMoreThanB(person1, person2)); } /*std::string str = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"; REQUIRE(letterI(str[1], true) == 2); REQUIRE(letterI(str[2], true) == 3); REQUIRE(letterI(str[3], true) == 4); REQUIRE(letterI(str[4], true) == 5);*/ } <|endoftext|>
<commit_before>#include <stack.hpp> #include <catch.hpp> SCENARIO("init", "[init]") { stack<int> A; REQUIRE(array_size_() == 0); REQUIRE(count_() == 0); } SCENARIO("Push", "[push]") { stack<int> A; A.push(1); A.push(2); REQUIRE(A.count_() == 2)); } SCENARIO("Pop", "[pop]") { stack<int> A; A.push(1); A.push(2); A.pop(); REQUIRE(A.count_() == 1)); } SCENARIO("oper=", "[oper=]"){ stack<int> A; A.push(1); A.push(2); stack<int> B; B = A; REQUIRE(B.count_() == 2)); } <commit_msg>Update init.cpp<commit_after>#include <stack.hpp> #include <catch.hpp> SCENARIO("init", "[init]") { stack<int> A; REQUIRE(A.array_size_() == 0); REQUIRE(A.count_() == 0); } SCENARIO("Push", "[push]") { stack<int> A; A.push(1); A.push(2); REQUIRE(A.count_() == 2)); } SCENARIO("Pop", "[pop]") { stack<int> A; A.push(1); A.push(2); A.pop(); REQUIRE(A.count_() == 1)); } SCENARIO("oper=", "[oper=]"){ stack<int> A; A.push(1); A.push(2); stack<int> B; B = A; REQUIRE(B.count_() == 2)); } <|endoftext|>
<commit_before>#define CATCH_CONFIG_RUNNER #include <catch.hpp> #include "sphere.cpp" #include "box.hpp" #include "color.hpp" #include <glm/vec3.hpp> #include <string> #include <glm/glm.hpp> #include <glm/gtx/intersect.hpp> #include <iostream> #include <fstream> #include <sdfloader.hpp> #include <string> #include <scene.hpp> #include <triangle.hpp> TEST_CASE("material parse test for sdfloader","[sdfloader]") { Scene scene; std::ifstream file; //must be relative to current shell dir or absolute file.open("input.sdf"); REQUIRE(file.is_open()); //check if file exists sdf_loadScene(file,scene); Material tmp = scene.materials["red"]; std::cout << tmp << std::endl; REQUIRE(tmp.get_name() == "red"); tmp = scene.materials["blue"]; REQUIRE(tmp.get_name() == "blue"); std::cout << tmp << std::endl; file.close(); } TEST_CASE("testing triangle class","[triangle]") { Triangle tri{Material{}, "Dereck", glm::vec3{0.0,0.0,0.0}, glm::vec3{2.0,0.0,0.0}, glm::vec3{1.0,2.0,0.0}}; glm::vec3 testp1{0.0,0.0,0.0}; glm::vec3 testp2{2.0,0.0,0.0}; glm::vec3 testp3{1.0,2.0,0.0}; REQUIRE(testp1 == tri.get_p1()); REQUIRE(testp2 == tri.get_p2()); REQUIRE(testp3 == tri.get_p3()); REQUIRE("Dereck" == tri.name()); REQUIRE(Approx{2.0f} == tri.area()); std::cout << "Funzt" << std::endl; Triangle tri2{Material{}, "Durak", glm::vec3{-1.0,0.0,0.0}, glm::vec3{1.0,0.0,0.0}, glm::vec3{0.0,2.0,0.0}}; REQUIRE(Approx{2.0f} == tri2.area()); Triangle tri3{Material{}, "Yorrick", glm::vec3{0.0,0.0,0.0}, glm::vec3{2.0,0.0,0.0}, glm::vec3{1.0,4.0,-2.0}}; REQUIRE(Approx{4.4721f} == tri3.area()); } TEST_CASE("get volume of sphere", "[volume]") { Sphere sphere; REQUIRE(sphere.volume() == Approx(4.1888)); } TEST_CASE("get area of sphere", "[area]") { Sphere sphere; REQUIRE(sphere.area() == Approx(12.5664)); } TEST_CASE("get radius of sphere", "[radius]") { Sphere sphere; REQUIRE(sphere.radius() == 1); } TEST_CASE("get center of sphere", "[center]") { Sphere sphere; glm::vec3 tmp{0,0,0}; REQUIRE(sphere.center() == tmp); } TEST_CASE("constructors of sphere", "[constructors]") { Sphere s1; Sphere s2{{0,0,0},1}; REQUIRE(s1.center() == s2.center()); REQUIRE(s1.radius() == s2.radius()); REQUIRE(s1.area() == s2.area()); REQUIRE(s1.volume() == s2.volume()); } TEST_CASE("constructors for box", "[constructors]") { Box b1; glm::vec3 tmp{0,0,0}; REQUIRE(b1.min() == tmp); tmp = {1,1,1}; REQUIRE(b1.max() == tmp); Box b2{{1,1,3},{3,2,2}}; tmp = {1,1,2}; REQUIRE(b2.min() == tmp); tmp = {3,2,3}; REQUIRE(b2.max() == tmp); } TEST_CASE("get area of box", "[area]") { Box box; REQUIRE(box.area() == 6); } TEST_CASE("get volume of box", "[area]") { Box box; REQUIRE(box.volume() == 1); } /*TEST_CASE("get color of sphere", "[color]") { Sphere sphere; Color tmp{100,100,100}; REQUIRE(sphere.color().r == tmp.r); REQUIRE(sphere.color().g == tmp.g); REQUIRE(sphere.color().b == tmp.b); }*/ TEST_CASE("get name of sphere", "[name]") { Sphere sphere; REQUIRE(sphere.name() == "default"); } /*TEST_CASE("shape constructor for sphere") { Sphere sphere{{1,2,3},4.2,{255,200,200},"test"}; REQUIRE(sphere.name() == "test"); REQUIRE(sphere.color().r == 255); glm::vec3 tmp{1,2,3}; REQUIRE(sphere.center() == tmp); REQUIRE(sphere.radius() == 4.2); }*/ /*TEST_CASE("get color of box", "[color]") { Box box; Color tmp{100,100,100}; REQUIRE(box.color().r == tmp.r); REQUIRE(box.color().g == tmp.g); REQUIRE(box.color().b == tmp.b); }*/ TEST_CASE("get name of box", "[name]") { Box box; REQUIRE(box.name() == "default"); } /*TEST_CASE("shape constructor for box") { Box box{{1,2,3},{4,5,6},{255,200,200},"test"}; REQUIRE(box.name() == "test"); REQUIRE(box.color().r == 255); glm::vec3 tmp{1,2,3}; REQUIRE(box.min() == tmp); tmp = {4,5,6}; REQUIRE(box.max() == tmp); }*/ TEST_CASE("use ostream of shape", "[ostream]") { Sphere sphere; std::cout << sphere << std::endl; } TEST_CASE("use ostream of box", "[ostream]") { Box box; std::cout << box << std::endl; } TEST_CASE("intersectRaySphere", "[intersect]") { //Ray glm :: vec3 ray_origin (0.0 ,0.0 ,0.0); //ray direction has to be normalized! //you can use: //v = glm::normalize(some_vector) glm::vec3 ray_direction(0.0,0.0,1.0); // Sphere glm::vec3 sphere_center(0.0,0.0,5.0); float sphere_radius(1.0); float distance (0.0); auto result = glm::intersectRaySphere( ray_origin, ray_direction, sphere_center, sphere_radius, distance); REQUIRE(distance == Approx(4.0f)); } TEST_CASE("intersect ray with sphere method","[intersect]") { Ray ray{{0.0f,0.0f,0.0f},{0.0,0.0,1.0}}; Sphere sphere{{0.0,0.0,5.0},1.0}; float distance{0.0}; REQUIRE(sphere.intersect(ray,distance) == true); REQUIRE(distance == Approx(4.0f)); } /*TEST_CASE("virtual constructor of shape","[constructor]") { std::cout << "\r\ntest-case: 'virtual constructor of shape'" << std::endl; Color red(255,0,0); glm::vec3 position(0,0,0); Sphere* s1 = new Sphere(position,1.2,red,"sphere0"); Shape* s2 = new Sphere(position,1.2,red,"sphere1"); s1->print(std::cout); s2->print(std::cout); delete s1; delete s2; }*/ //TEST_CASE("intersect ray with box method","[intersect]") { // Ray ray{{0.0f,0.0f,0.0f},{0.0,0.0,1.0}}; // Box box{{-1,-1,2},{1,1,2}}; // float distance{0.0}; // REQUIRE(box.intersect(ray,distance) == true); // REQUIRE(distance == Approx(2.0f)); //} TEST_CASE("intersect box","[intersect]") { Box box{{1,1,0},{3,3,2}}; Ray ray{{0,1,0},{0.5,0.5,0.5}}; float distance; REQUIRE(box.intersect(ray,distance)); REQUIRE(distance == Approx(sqrt(3))); } TEST_CASE("intersect box with negative min","[intersect]") { Box box{{-3,-0.5,-0.5},{-3.2, 0.5, 0.5}}; Ray ray{{0,0,0},{-1,0,0}}; float distance{0}; REQUIRE(box.intersect(ray,distance)); REQUIRE(distance == 3); } int main(int argc, char *argv[]) { return Catch::Session().run(argc, argv); } /* Aufgabe 6.7 s1 ist ein shared Pointer vom Typ sphere. s2 ist ein shared pointer vom Typ shape. s1 ist hier statisch, da ihm nur Objekte des Typs sphere zugewiesen werden koennen. s2 dagegen ist dynamisch, weil es sich um einen Typ der Basisklasse handelt: Es kann ihr sowohl ein Objekt vom Typ der Basisklasse, als auch eines der abgeleiteten Klasse zugewiesen werden. Falls sphere noch eine abgeleitete Klasse haette, so wuerde s1 auch insofern dynamisch sein, als dass man ein Objekt der abgeleiteten Klasse zuweisen kann. */ /* Aufgabe 6.8 Output with virtual: test-case: 'virtual constructor of shape' Construction of sphere Construction of sphere name: sphere0 color: (255,0,0) center: [0,0,0] radius: 1.2 name: sphere1 color: (255,0,0) center: [0,0,0] radius: 1.2 Destruction of sphere Destruction of shape Destruction of sphere Destruction of shape Output without virtual: test-case: 'virtual constructor of shape' Construction of sphere Construction of sphere name: sphere0 color: (255,0,0) center: [0,0,0] radius: 1.2 name: sphere1 color: (255,0,0) center: [0,0,0] radius: 1.2 Destruction of sphere Destruction of shape Destruction of shape Wenn der Destruktor von shape als virtual deklariert ist, so wird beim Loeschen auch der ueberschreibende Destruktor aufgerufen, da es sich um einen Pointer auf ein Objekt des abgeleiteten Typs handelt. Laesst man das virtual weg, so wir nur der Destruktor der Basisklasse aufgerufen (es findet ja keine Ueberschreibung statt). */ <commit_msg>added tests for ray-triangle-intersection<commit_after>#define CATCH_CONFIG_RUNNER #include <catch.hpp> #include "sphere.cpp" #include "box.hpp" #include "color.hpp" #include <glm/vec3.hpp> #include <string> #include <glm/glm.hpp> #include <glm/gtx/intersect.hpp> #include <iostream> #include <fstream> #include <sdfloader.hpp> #include <string> #include <scene.hpp> #include <triangle.hpp> TEST_CASE("material parse test for sdfloader","[sdfloader]") { Scene scene; std::ifstream file; //must be relative to current shell dir or absolute file.open("input.sdf"); REQUIRE(file.is_open()); //check if file exists sdf_loadScene(file,scene); Material tmp = scene.materials["red"]; std::cout << tmp << std::endl; REQUIRE(tmp.get_name() == "red"); tmp = scene.materials["blue"]; REQUIRE(tmp.get_name() == "blue"); std::cout << tmp << std::endl; file.close(); } TEST_CASE("testing triangle class","[triangle]") { Triangle tri{Material{}, "Dereck", glm::vec3{0.0,0.0,0.0}, glm::vec3{2.0,0.0,0.0}, glm::vec3{1.0,2.0,0.0}}; glm::vec3 testp1{0.0,0.0,0.0}; glm::vec3 testp2{2.0,0.0,0.0}; glm::vec3 testp3{1.0,2.0,0.0}; REQUIRE(testp1 == tri.get_p1()); REQUIRE(testp2 == tri.get_p2()); REQUIRE(testp3 == tri.get_p3()); REQUIRE("Dereck" == tri.name()); REQUIRE(Approx{2.0f} == tri.area()); std::cout << "Funzt" << std::endl; Triangle tri2{Material{}, "Durak", glm::vec3{-1.0,0.0,0.0}, glm::vec3{1.0,0.0,0.0}, glm::vec3{0.0,2.0,0.0}}; REQUIRE(Approx{2.0f} == tri2.area()); Triangle tri3{Material{}, "Yorrick", glm::vec3{0.0,0.0,0.0}, glm::vec3{2.0,0.0,0.0}, glm::vec3{1.0,4.0,-2.0}}; REQUIRE(Approx{4.4721f} == tri3.area()); } TEST_CASE("get volume of sphere", "[volume]") { Sphere sphere; REQUIRE(sphere.volume() == Approx(4.1888)); } TEST_CASE("get area of sphere", "[area]") { Sphere sphere; REQUIRE(sphere.area() == Approx(12.5664)); } TEST_CASE("get radius of sphere", "[radius]") { Sphere sphere; REQUIRE(sphere.radius() == 1); } TEST_CASE("get center of sphere", "[center]") { Sphere sphere; glm::vec3 tmp{0,0,0}; REQUIRE(sphere.center() == tmp); } TEST_CASE("constructors of sphere", "[constructors]") { Sphere s1; Sphere s2{{0,0,0},1}; REQUIRE(s1.center() == s2.center()); REQUIRE(s1.radius() == s2.radius()); REQUIRE(s1.area() == s2.area()); REQUIRE(s1.volume() == s2.volume()); } TEST_CASE("constructors for box", "[constructors]") { Box b1; glm::vec3 tmp{0,0,0}; REQUIRE(b1.min() == tmp); tmp = {1,1,1}; REQUIRE(b1.max() == tmp); Box b2{{1,1,3},{3,2,2}}; tmp = {1,1,2}; REQUIRE(b2.min() == tmp); tmp = {3,2,3}; REQUIRE(b2.max() == tmp); } TEST_CASE("get area of box", "[area]") { Box box; REQUIRE(box.area() == 6); } TEST_CASE("get volume of box", "[area]") { Box box; REQUIRE(box.volume() == 1); } /*TEST_CASE("get color of sphere", "[color]") { Sphere sphere; Color tmp{100,100,100}; REQUIRE(sphere.color().r == tmp.r); REQUIRE(sphere.color().g == tmp.g); REQUIRE(sphere.color().b == tmp.b); }*/ TEST_CASE("get name of sphere", "[name]") { Sphere sphere; REQUIRE(sphere.name() == "default"); } /*TEST_CASE("shape constructor for sphere") { Sphere sphere{{1,2,3},4.2,{255,200,200},"test"}; REQUIRE(sphere.name() == "test"); REQUIRE(sphere.color().r == 255); glm::vec3 tmp{1,2,3}; REQUIRE(sphere.center() == tmp); REQUIRE(sphere.radius() == 4.2); }*/ /*TEST_CASE("get color of box", "[color]") { Box box; Color tmp{100,100,100}; REQUIRE(box.color().r == tmp.r); REQUIRE(box.color().g == tmp.g); REQUIRE(box.color().b == tmp.b); }*/ TEST_CASE("get name of box", "[name]") { Box box; REQUIRE(box.name() == "default"); } /*TEST_CASE("shape constructor for box") { Box box{{1,2,3},{4,5,6},{255,200,200},"test"}; REQUIRE(box.name() == "test"); REQUIRE(box.color().r == 255); glm::vec3 tmp{1,2,3}; REQUIRE(box.min() == tmp); tmp = {4,5,6}; REQUIRE(box.max() == tmp); }*/ TEST_CASE("use ostream of shape", "[ostream]") { Sphere sphere; std::cout << sphere << std::endl; } TEST_CASE("use ostream of box", "[ostream]") { Box box; std::cout << box << std::endl; } TEST_CASE("intersectRaySphere", "[intersect]") { //Ray glm :: vec3 ray_origin (0.0 ,0.0 ,0.0); //ray direction has to be normalized! //you can use: //v = glm::normalize(some_vector) glm::vec3 ray_direction(0.0,0.0,1.0); // Sphere glm::vec3 sphere_center(0.0,0.0,5.0); float sphere_radius(1.0); float distance (0.0); auto result = glm::intersectRaySphere( ray_origin, ray_direction, sphere_center, sphere_radius, distance); REQUIRE(distance == Approx(4.0f)); } TEST_CASE("intersect ray with sphere method","[intersect]") { Ray ray{{0.0f,0.0f,0.0f},{0.0,0.0,1.0}}; Sphere sphere{{0.0,0.0,5.0},1.0}; float distance{0.0}; REQUIRE(sphere.intersect(ray,distance) == true); REQUIRE(distance == Approx(4.0f)); } /*TEST_CASE("virtual constructor of shape","[constructor]") { std::cout << "\r\ntest-case: 'virtual constructor of shape'" << std::endl; Color red(255,0,0); glm::vec3 position(0,0,0); Sphere* s1 = new Sphere(position,1.2,red,"sphere0"); Shape* s2 = new Sphere(position,1.2,red,"sphere1"); s1->print(std::cout); s2->print(std::cout); delete s1; delete s2; }*/ //TEST_CASE("intersect ray with box method","[intersect]") { // Ray ray{{0.0f,0.0f,0.0f},{0.0,0.0,1.0}}; // Box box{{-1,-1,2},{1,1,2}}; // float distance{0.0}; // REQUIRE(box.intersect(ray,distance) == true); // REQUIRE(distance == Approx(2.0f)); //} TEST_CASE("intersect box","[intersect]") { Box box{{1,1,0},{3,3,2}}; Ray ray{{0,1,0},{0.5,0.5,0.5}}; float distance; REQUIRE(box.intersect(ray,distance)); REQUIRE(distance == Approx(sqrt(3))); } TEST_CASE("intersect box with negative min","[intersect]") { Box box{{-3,-0.5,-0.5},{-3.2, 0.5, 0.5}}; Ray ray{{0,0,0},{-1,0,0}}; float distance{0}; REQUIRE(box.intersect(ray,distance)); REQUIRE(distance == 3); } TEST_CASE("intersect ray with triangle", "[intersect]"){ Ray ray{{0,0,0},{0,-1,0}}; Triangle test_tri{{0,-3,1},{2,-3,-0.5},{-2,-3,-0.5}}; float distance{0}; REQUIRE(test_tri.intersect(ray, distance)); REQUIRE(3 == distance); } int main(int argc, char *argv[]) { return Catch::Session().run(argc, argv); } /* Aufgabe 6.7 s1 ist ein shared Pointer vom Typ sphere. s2 ist ein shared pointer vom Typ shape. s1 ist hier statisch, da ihm nur Objekte des Typs sphere zugewiesen werden koennen. s2 dagegen ist dynamisch, weil es sich um einen Typ der Basisklasse handelt: Es kann ihr sowohl ein Objekt vom Typ der Basisklasse, als auch eines der abgeleiteten Klasse zugewiesen werden. Falls sphere noch eine abgeleitete Klasse haette, so wuerde s1 auch insofern dynamisch sein, als dass man ein Objekt der abgeleiteten Klasse zuweisen kann. */ /* Aufgabe 6.8 Output with virtual: test-case: 'virtual constructor of shape' Construction of sphere Construction of sphere name: sphere0 color: (255,0,0) center: [0,0,0] radius: 1.2 name: sphere1 color: (255,0,0) center: [0,0,0] radius: 1.2 Destruction of sphere Destruction of shape Destruction of sphere Destruction of shape Output without virtual: test-case: 'virtual constructor of shape' Construction of sphere Construction of sphere name: sphere0 color: (255,0,0) center: [0,0,0] radius: 1.2 name: sphere1 color: (255,0,0) center: [0,0,0] radius: 1.2 Destruction of sphere Destruction of shape Destruction of shape Wenn der Destruktor von shape als virtual deklariert ist, so wird beim Loeschen auch der ueberschreibende Destruktor aufgerufen, da es sich um einen Pointer auf ein Objekt des abgeleiteten Typs handelt. Laesst man das virtual weg, so wir nur der Destruktor der Basisklasse aufgerufen (es findet ja keine Ueberschreibung statt). */ <|endoftext|>
<commit_before>/* * Copyright (C) 2007-2013 German Aerospace Center (DLR/SC) * * Created: 2012-10-17 Markus Litz <Markus.Litz@dlr.de> * * 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 "gtest/gtest.h" #include "CTiglLogging.h" #include <tixi.h> #ifdef HAVE_VLD #include <vld.h> #endif // make tixi quiet void tixiSilentMessage(MessageType , const char *, ...){} int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); tigl::CTiglLogging::Instance().SetTimeIdInFilenameEnabled(false); // disable any console logging tigl::CTiglLogging::Instance().SetConsoleVerbosity(TILOG_SILENT); tigl::CTiglLogging::Instance().LogToFile("tigltest"); // disable tixi output tixiSetPrintMsgFunc(tixiSilentMessage); int retval = RUN_ALL_TESTS(); tixiCleanup(); return retval; } <commit_msg>Fixed build issue with new tixi 2.2.1<commit_after>/* * Copyright (C) 2007-2013 German Aerospace Center (DLR/SC) * * Created: 2012-10-17 Markus Litz <Markus.Litz@dlr.de> * * 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 "gtest/gtest.h" #include "CTiglLogging.h" #include <tixi.h> #ifdef HAVE_VLD #include <vld.h> #endif // make tixi quiet void tixiSilentMessage(MessageType , const char *){} int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); tigl::CTiglLogging::Instance().SetTimeIdInFilenameEnabled(false); // disable any console logging tigl::CTiglLogging::Instance().SetConsoleVerbosity(TILOG_SILENT); tigl::CTiglLogging::Instance().LogToFile("tigltest"); // disable tixi output tixiSetPrintMsgFunc(tixiSilentMessage); int retval = RUN_ALL_TESTS(); tixiCleanup(); return retval; } <|endoftext|>
<commit_before> #include <gloperate/base/GLContextUtils.h> #include <cassert> #include <cppassist/logging/logging.h> #include <glbinding/gl/gl.h> #include <glbinding-aux/ContextInfo.h> using namespace gl; namespace gloperate { gloperate::GLContextFormat GLContextUtils::retrieveFormat() { // Create context format description gloperate::GLContextFormat format; // Retrieve format GLint i; GLboolean b; format.setVersion(retrieveVersion()); format.setProfile(retrieveProfile()); if (format.profile() != GLContextFormat::Profile::Core) { i = -1; glGetIntegerv(GLenum::GL_RED_BITS, &i); format.setRedBufferSize(i); i = -1; glGetIntegerv(GLenum::GL_GREEN_BITS, &i); format.setGreenBufferSize(i); i = -1; glGetIntegerv(GLenum::GL_BLUE_BITS, &i); format.setBlueBufferSize(i); i = -1; glGetIntegerv(GLenum::GL_ALPHA_BITS, &i); format.setAlphaBufferSize(i); i = -1; glGetIntegerv(GLenum::GL_DEPTH_BITS, &i); format.setDepthBufferSize(i); i = -1; glGetIntegerv(GLenum::GL_STENCIL_BITS, &i); format.setStencilBufferSize(i); b = GL_FALSE; glGetBooleanv(GLenum::GL_STEREO, &b); format.setStereo(b == GL_TRUE); } i = -1; glGetIntegerv(GLenum::GL_SAMPLES, &i); format.setSamples(i); return format; } glbinding::Version GLContextUtils::retrieveVersion() { return glbinding::aux::ContextInfo::version(); } GLContextFormat::Profile GLContextUtils::retrieveProfile() { assert(0 != glbinding::getCurrentContext()); gl::ContextProfileMask profileMask = gl::GL_NONE_BIT; glGetIntegerv(GLenum::GL_CONTEXT_PROFILE_MASK, reinterpret_cast<GLint*>(&profileMask)); if (static_cast<GLint>(profileMask) <= 0) // probably a context < 3.2 with no support for profiles { return GLContextFormat::Profile::None; } if ((profileMask & GL_CONTEXT_CORE_PROFILE_BIT) != gl::GL_NONE_BIT) { return GLContextFormat::Profile::Core; } if ((profileMask & GL_CONTEXT_COMPATIBILITY_PROFILE_BIT) != gl::GL_NONE_BIT) { return GLContextFormat::Profile::Compatibility; } return GLContextFormat::Profile::None; } std::string GLContextUtils::version() { assert(0 != glbinding::getCurrentContext()); return glbinding::aux::ContextInfo::version().toString(); } std::string GLContextUtils::profile() { return GLContextFormat::profileString(retrieveProfile()); } std::string GLContextUtils::vendor() { assert(0 != glbinding::getCurrentContext()); return glbinding::aux::ContextInfo::vendor(); } std::string GLContextUtils::renderer() { assert(0 != glbinding::getCurrentContext()); return glbinding::aux::ContextInfo::renderer(); } } // namespace gloperate <commit_msg>Remove assertions using the old glbinding interface<commit_after> #include <gloperate/base/GLContextUtils.h> #include <cassert> #include <cppassist/logging/logging.h> #include <glbinding/gl/gl.h> #include <glbinding-aux/ContextInfo.h> using namespace gl; namespace gloperate { gloperate::GLContextFormat GLContextUtils::retrieveFormat() { // Create context format description gloperate::GLContextFormat format; // Retrieve format GLint i; GLboolean b; format.setVersion(retrieveVersion()); format.setProfile(retrieveProfile()); if (format.profile() != GLContextFormat::Profile::Core) { i = -1; glGetIntegerv(GLenum::GL_RED_BITS, &i); format.setRedBufferSize(i); i = -1; glGetIntegerv(GLenum::GL_GREEN_BITS, &i); format.setGreenBufferSize(i); i = -1; glGetIntegerv(GLenum::GL_BLUE_BITS, &i); format.setBlueBufferSize(i); i = -1; glGetIntegerv(GLenum::GL_ALPHA_BITS, &i); format.setAlphaBufferSize(i); i = -1; glGetIntegerv(GLenum::GL_DEPTH_BITS, &i); format.setDepthBufferSize(i); i = -1; glGetIntegerv(GLenum::GL_STENCIL_BITS, &i); format.setStencilBufferSize(i); b = GL_FALSE; glGetBooleanv(GLenum::GL_STEREO, &b); format.setStereo(b == GL_TRUE); } i = -1; glGetIntegerv(GLenum::GL_SAMPLES, &i); format.setSamples(i); return format; } glbinding::Version GLContextUtils::retrieveVersion() { return glbinding::aux::ContextInfo::version(); } GLContextFormat::Profile GLContextUtils::retrieveProfile() { gl::ContextProfileMask profileMask = gl::GL_NONE_BIT; glGetIntegerv(GLenum::GL_CONTEXT_PROFILE_MASK, reinterpret_cast<GLint*>(&profileMask)); if (static_cast<GLint>(profileMask) <= 0) // probably a context < 3.2 with no support for profiles { return GLContextFormat::Profile::None; } if ((profileMask & GL_CONTEXT_CORE_PROFILE_BIT) != gl::GL_NONE_BIT) { return GLContextFormat::Profile::Core; } if ((profileMask & GL_CONTEXT_COMPATIBILITY_PROFILE_BIT) != gl::GL_NONE_BIT) { return GLContextFormat::Profile::Compatibility; } return GLContextFormat::Profile::None; } std::string GLContextUtils::version() { return glbinding::aux::ContextInfo::version().toString(); } std::string GLContextUtils::profile() { return GLContextFormat::profileString(retrieveProfile()); } std::string GLContextUtils::vendor() { return glbinding::aux::ContextInfo::vendor(); } std::string GLContextUtils::renderer() { return glbinding::aux::ContextInfo::renderer(); } } // namespace gloperate <|endoftext|>
<commit_before>/* C++ interface test */ #include "libmemcached/memcached.hpp" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <time.h> #include "server.h" #include "test.h" #include <string> using namespace std; using namespace memcache; extern "C" { test_return basic_test(memcached_st *memc); test_return increment_test(memcached_st *memc); test_return basic_master_key_test(memcached_st *memc); test_return mget_result_function(memcached_st *memc); test_return mget_test(memcached_st *memc); memcached_return callback_counter(memcached_st *, memcached_result_st *, void *context); void *world_create(void); void world_destroy(void *p); } static void populate_vector(vector<char> &vec, const string &str) { vec.reserve(str.length()); vec.assign(str.begin(), str.end()); } static void copy_vec_to_string(vector<char> &vec, string &str) { str.clear(); if (! vec.empty()) { str.assign(vec.begin(), vec.end()); } } test_return basic_test(memcached_st *memc) { Memcache foo(memc); const string value_set("This is some data"); std::vector<char> value; std::vector<char> test_value; populate_vector(value, value_set); foo.set("mine", value, 0, 0); foo.get("mine", test_value); assert((memcmp(&test_value[0], &value[0], test_value.size()) == 0)); return TEST_SUCCESS; } test_return increment_test(memcached_st *memc) { Memcache mcach(memc); bool rc; const string key("blah"); const string inc_value("1"); std::vector<char> inc_val; vector<char> ret_value; string ret_string; uint64_t int_inc_value; uint64_t int_ret_value; populate_vector(inc_val, inc_value); rc= mcach.set(key, inc_val, 0, 0); if (rc == false) { return TEST_FAILURE; } mcach.get(key, ret_value); if (ret_value.empty()) { return TEST_FAILURE; } copy_vec_to_string(ret_value, ret_string); int_inc_value= uint64_t(atol(inc_value.c_str())); int_ret_value= uint64_t(atol(ret_string.c_str())); assert(int_ret_value == int_inc_value); rc= mcach.increment(key, 1, &int_ret_value); assert(rc == true); assert(int_ret_value == 2); rc= mcach.increment(key, 1, &int_ret_value); assert(rc == true); assert(int_ret_value == 3); rc= mcach.increment(key, 5, &int_ret_value); assert(rc == true); assert(int_ret_value == 8); return TEST_SUCCESS; } test_return basic_master_key_test(memcached_st *memc) { Memcache foo(memc); const string value_set("Data for server A"); vector<char> value; vector<char> test_value; const string master_key_a("server-a"); const string master_key_b("server-b"); const string key("xyz"); populate_vector(value, value_set); foo.setByKey(master_key_a, key, value, 0, 0); foo.getByKey(master_key_a, key, test_value); assert((memcmp(&value[0], &test_value[0], value.size()) == 0)); test_value.clear(); foo.getByKey(master_key_b, key, test_value); assert((memcmp(&value[0], &test_value[0], value.size()) == 0)); return TEST_SUCCESS; } /* Count the results */ memcached_return callback_counter(memcached_st *, memcached_result_st *, void *context) { unsigned int *counter= static_cast<unsigned int *>(context); *counter= *counter + 1; return MEMCACHED_SUCCESS; } test_return mget_result_function(memcached_st *memc) { Memcache mc(memc); bool rc; string key1("fudge"); string key2("son"); string key3("food"); vector<string> keys; vector< vector<char> *> values; vector<char> val1; vector<char> val2; vector<char> val3; populate_vector(val1, key1); populate_vector(val2, key2); populate_vector(val3, key3); keys.reserve(3); keys.push_back(key1); keys.push_back(key2); keys.push_back(key3); values.reserve(3); values.push_back(&val1); values.push_back(&val2); values.push_back(&val3); unsigned int counter; memcached_execute_function callbacks[1]; /* We need to empty the server before we continue the test */ rc= mc.flush(0); rc= mc.setAll(keys, values, 50, 9); assert(rc == true); rc= mc.mget(keys); assert(rc == true); callbacks[0]= &callback_counter; counter= 0; rc= mc.fetchExecute(callbacks, static_cast<void *>(&counter), 1); assert(counter == 3); return TEST_SUCCESS; } test_return mget_test(memcached_st *memc) { Memcache mc(memc); bool rc; memcached_return mc_rc; vector<string> keys; vector< vector<char> *> values; keys.reserve(3); keys.push_back("fudge"); keys.push_back("son"); keys.push_back("food"); vector<char> val1; vector<char> val2; vector<char> val3; populate_vector(val1, "fudge"); populate_vector(val2, "son"); populate_vector(val3, "food"); values.reserve(3); values.push_back(&val1); values.push_back(&val2); values.push_back(&val3); string return_key; vector<char> return_value; /* We need to empty the server before we continue the test */ rc= mc.flush(0); assert(rc == true); rc= mc.mget(keys); assert(rc == true); while ((mc_rc= mc.fetch(return_key, return_value)) != MEMCACHED_END) { assert(return_value.size() != 0); return_value.clear(); } assert(mc_rc == MEMCACHED_END); rc= mc.setAll(keys, values, 50, 9); assert(rc == true); rc= mc.mget(keys); assert(rc == true); while ((mc_rc= mc.fetch(return_key, return_value)) != MEMCACHED_END) { assert(return_key.length() == return_value.size()); assert(!memcmp(&return_value[0], return_key.c_str(), return_value.size())); } return TEST_SUCCESS; } test_st tests[] ={ { "basic", 0, basic_test }, { "basic_master_key", 0, basic_master_key_test }, { "increment_test", 0, increment_test }, { "mget", 1, mget_test }, { "mget_result_function", 1, mget_result_function }, {0, 0, 0} }; collection_st collection[] ={ {"block", 0, 0, tests}, {0, 0, 0, 0} }; #define SERVERS_TO_CREATE 1 extern "C" void *world_create(void) { server_startup_st *construct; construct= (server_startup_st *)malloc(sizeof(server_startup_st)); memset(construct, 0, sizeof(server_startup_st)); construct->count= SERVERS_TO_CREATE; server_startup(construct); return construct; } void world_destroy(void *p) { server_startup_st *construct= static_cast<server_startup_st *>(p); memcached_server_st *servers= static_cast<memcached_server_st *>(construct->servers); memcached_server_list_free(servers); server_shutdown(construct); free(construct); } void get_world(world_st *world) { world->collections= collection; world->create= world_create; world->destroy= world_destroy; } <commit_msg>Added simple exception test to the C++ test case file.<commit_after>/* C++ interface test */ #include "libmemcached/memcached.hpp" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <time.h> #include "server.h" #include "test.h" #include <string> #include <iostream> using namespace std; using namespace memcache; extern "C" { test_return basic_test(memcached_st *memc); test_return increment_test(memcached_st *memc); test_return basic_master_key_test(memcached_st *memc); test_return mget_result_function(memcached_st *memc); test_return mget_test(memcached_st *memc); memcached_return callback_counter(memcached_st *, memcached_result_st *, void *context); void *world_create(void); void world_destroy(void *p); } static void populate_vector(vector<char> &vec, const string &str) { vec.reserve(str.length()); vec.assign(str.begin(), str.end()); } static void copy_vec_to_string(vector<char> &vec, string &str) { str.clear(); if (! vec.empty()) { str.assign(vec.begin(), vec.end()); } } test_return basic_test(memcached_st *memc) { Memcache foo(memc); const string value_set("This is some data"); std::vector<char> value; std::vector<char> test_value; populate_vector(value, value_set); foo.set("mine", value, 0, 0); foo.get("mine", test_value); assert((memcmp(&test_value[0], &value[0], test_value.size()) == 0)); /* * Simple test of the exceptions here...this should throw an exception * saying that the key is empty. */ try { foo.set("", value, 0, 0); } catch (Error &err) { return TEST_SUCCESS; } return TEST_FAILURE; } test_return increment_test(memcached_st *memc) { Memcache mcach(memc); bool rc; const string key("blah"); const string inc_value("1"); std::vector<char> inc_val; vector<char> ret_value; string ret_string; uint64_t int_inc_value; uint64_t int_ret_value; populate_vector(inc_val, inc_value); rc= mcach.set(key, inc_val, 0, 0); if (rc == false) { return TEST_FAILURE; } mcach.get(key, ret_value); if (ret_value.empty()) { return TEST_FAILURE; } copy_vec_to_string(ret_value, ret_string); int_inc_value= uint64_t(atol(inc_value.c_str())); int_ret_value= uint64_t(atol(ret_string.c_str())); assert(int_ret_value == int_inc_value); rc= mcach.increment(key, 1, &int_ret_value); assert(rc == true); assert(int_ret_value == 2); rc= mcach.increment(key, 1, &int_ret_value); assert(rc == true); assert(int_ret_value == 3); rc= mcach.increment(key, 5, &int_ret_value); assert(rc == true); assert(int_ret_value == 8); return TEST_SUCCESS; } test_return basic_master_key_test(memcached_st *memc) { Memcache foo(memc); const string value_set("Data for server A"); vector<char> value; vector<char> test_value; const string master_key_a("server-a"); const string master_key_b("server-b"); const string key("xyz"); populate_vector(value, value_set); foo.setByKey(master_key_a, key, value, 0, 0); foo.getByKey(master_key_a, key, test_value); assert((memcmp(&value[0], &test_value[0], value.size()) == 0)); test_value.clear(); foo.getByKey(master_key_b, key, test_value); assert((memcmp(&value[0], &test_value[0], value.size()) == 0)); return TEST_SUCCESS; } /* Count the results */ memcached_return callback_counter(memcached_st *, memcached_result_st *, void *context) { unsigned int *counter= static_cast<unsigned int *>(context); *counter= *counter + 1; return MEMCACHED_SUCCESS; } test_return mget_result_function(memcached_st *memc) { Memcache mc(memc); bool rc; string key1("fudge"); string key2("son"); string key3("food"); vector<string> keys; vector< vector<char> *> values; vector<char> val1; vector<char> val2; vector<char> val3; populate_vector(val1, key1); populate_vector(val2, key2); populate_vector(val3, key3); keys.reserve(3); keys.push_back(key1); keys.push_back(key2); keys.push_back(key3); values.reserve(3); values.push_back(&val1); values.push_back(&val2); values.push_back(&val3); unsigned int counter; memcached_execute_function callbacks[1]; /* We need to empty the server before we continue the test */ rc= mc.flush(0); rc= mc.setAll(keys, values, 50, 9); assert(rc == true); rc= mc.mget(keys); assert(rc == true); callbacks[0]= &callback_counter; counter= 0; rc= mc.fetchExecute(callbacks, static_cast<void *>(&counter), 1); assert(counter == 3); return TEST_SUCCESS; } test_return mget_test(memcached_st *memc) { Memcache mc(memc); bool rc; memcached_return mc_rc; vector<string> keys; vector< vector<char> *> values; keys.reserve(3); keys.push_back("fudge"); keys.push_back("son"); keys.push_back("food"); vector<char> val1; vector<char> val2; vector<char> val3; populate_vector(val1, "fudge"); populate_vector(val2, "son"); populate_vector(val3, "food"); values.reserve(3); values.push_back(&val1); values.push_back(&val2); values.push_back(&val3); string return_key; vector<char> return_value; /* We need to empty the server before we continue the test */ rc= mc.flush(0); assert(rc == true); rc= mc.mget(keys); assert(rc == true); while ((mc_rc= mc.fetch(return_key, return_value)) != MEMCACHED_END) { assert(return_value.size() != 0); return_value.clear(); } assert(mc_rc == MEMCACHED_END); rc= mc.setAll(keys, values, 50, 9); assert(rc == true); rc= mc.mget(keys); assert(rc == true); while ((mc_rc= mc.fetch(return_key, return_value)) != MEMCACHED_END) { assert(return_key.length() == return_value.size()); assert(!memcmp(&return_value[0], return_key.c_str(), return_value.size())); } return TEST_SUCCESS; } test_st tests[] ={ { "basic", 0, basic_test }, { "basic_master_key", 0, basic_master_key_test }, { "increment_test", 0, increment_test }, { "mget", 1, mget_test }, { "mget_result_function", 1, mget_result_function }, {0, 0, 0} }; collection_st collection[] ={ {"block", 0, 0, tests}, {0, 0, 0, 0} }; #define SERVERS_TO_CREATE 1 extern "C" void *world_create(void) { server_startup_st *construct; construct= (server_startup_st *)malloc(sizeof(server_startup_st)); memset(construct, 0, sizeof(server_startup_st)); construct->count= SERVERS_TO_CREATE; server_startup(construct); return construct; } void world_destroy(void *p) { server_startup_st *construct= static_cast<server_startup_st *>(p); memcached_server_st *servers= static_cast<memcached_server_st *>(construct->servers); memcached_server_list_free(servers); server_shutdown(construct); free(construct); } void get_world(world_st *world) { world->collections= collection; world->create= world_create; world->destroy= world_destroy; } <|endoftext|>
<commit_before> #ifndef _CONF_H_ #define _CONF_H_ #include "utility.hpp" #define VE_VERSION "r1.0.3-20150122" #define VE_INFO "vdceye Manager r1.0.3 2015" #ifdef WIN32 #define VE_NVR_CLIENT #else #define VE_NVR #endif /* NVR Client feature */ #ifdef VE_NVR_CLIENT #define VE_RECORDER_MGR_CLIENT_SUPPORT #endif /* NVR feature */ #ifdef VE_NVR #define VE_RECORDER_MGR_SERVER_SUPPORT #endif #define CONF_NAME_MAX 128 /* support Camera num */ #define CONF_MAP_MAX 4096 #define CONF_USER_PASSWORD_MAX 1024 #define CONF_PATH_MAX 1024 /* 0xFF FFFF to 0xFFFF FFFF is for status for the map */ #define CONF_MAP_INVALID_MIN 0xFFFFFF #define CONF_KEY_STR_MAX 16 /* Support VMS(site, recorder) num */ #define CONF_VMS_NUM_MAX 128 #define CONF_VIEW_NUM_MAX 128 /* IP camera Group max num */ #define CONF_VGROUP_NUM_MAX 128 #define VSC_CONF_KEY "ConfVSCSystem" #define VSC_CONF_LIC_KEY "ConfVSCLicense" #define VSC_CONF_CHANNEL_KEY "ConfVSCDevice" #define VSC_CONF_VIPC_KEY "ConfVSCVIPC" #define VSC_CONF_VMS_KEY "ConfVSCVms" #define VSC_CONF_VIEW_KEY "ConfVSCView" #define VSC_CONF_VGROUP_KEY "ConfVSCVGroup" #define VSC_CONF_HDFS_RECORD_KEY "ConfVSCHdfsRec" #define VSC_CONF_EMAP_FILE_KEY "ConfVSCEmapFile" #define VSC_CONF_EMAP_CONF_KEY "ConfVSCEmapConf" #define VSC_CONF_PARAM_MAX 1024 #define VSC_CONF_PARAM_S_MAX 128 /* Max camera in one view */ #define VSC_CONF_VIEW_CH_MAX 256 /* Max camera in one Group */ #define VSC_CONF_VGROUP_CH_MAX 256 typedef enum { VSC_DEVICE_CAM = 1, VSC_DEVICE_RECORDER, VSC_DEVICE_LAST } VSCDeviceType; /* Device Type */ typedef enum { VSC_SUB_DEVICE_USB_CAM = 1, VSC_SUB_DEVICE_FILE, VSC_SUB_DEVICE_RTSP, VSC_SUB_DEVICE_ONVIF, VSC_SUB_DEVICE_ONVIF_RECODER, VSC_SUB_DEVICE_GB28181, VSC_SUB_DEVICE_LAST } VSCDeviceSubType; typedef enum { VSC_VMS_RECORDER = 1, VSC_VMS_SITE, VSC_VMS_VIRTUL_IPC, VSC_VMS_LAST } VSCVmsType; typedef enum { VSC_SUB_VMS_PG = 1, VSC_SUB_VMS_ZB, VSC_SUB_VIPC_FILE, VSC_SUB_VIPC_LIVE, VSC_SUB_VMS_LAST } VSCVmsSubType; /* Control command */ typedef enum { LAYOUT_MODE_1 = 1, LAYOUT_MODE_2X2, LAYOUT_MODE_3X3, LAYOUT_MODE_4X4, LAYOUT_MODE_6, LAYOUT_MODE_8, LAYOUT_MODE_12p1, LAYOUT_MODE_5x5, LAYOUT_MODE_6x6, LAYOUT_MODE_8x8, LAYOUT_MODE_ONE, LAYOUT_MODE_LAST } VideoWallLayoutMode; #pragma pack(push, 1 ) typedef struct __VSCConfSystemKey { s8 Key[CONF_KEY_STR_MAX]; __VSCConfSystemKey() { memset(Key, 0, CONF_KEY_STR_MAX); strcpy(Key, VSC_CONF_KEY); } }VSCConfSystemKey; typedef struct __VSCConfLicenseKey { s8 Key[CONF_KEY_STR_MAX]; __VSCConfLicenseKey() { memset(Key, 0, CONF_KEY_STR_MAX); strcpy(Key, VSC_CONF_LIC_KEY); } }VSCConfLicenseKey; typedef struct __VSCConfDeviceKey { u32 nId; s8 Key[CONF_KEY_STR_MAX]; __VSCConfDeviceKey(u32 id) { memset(Key, 0, CONF_KEY_STR_MAX); strcpy(Key, VSC_CONF_CHANNEL_KEY); nId = id; } }VSCConfDeviceKey; typedef struct __VSCConfVIPCKey { u32 nId; s8 Key[CONF_KEY_STR_MAX]; __VSCConfVIPCKey(u32 id) { memset(Key, 0, CONF_KEY_STR_MAX); strcpy(Key, VSC_CONF_VIPC_KEY); nId = id; } }VSCConfVIPCKey; typedef struct __VSCConfVmsKey { s8 Key[CONF_KEY_STR_MAX]; __VSCConfVmsKey() { memset(Key, 0, CONF_KEY_STR_MAX); strcpy(Key, VSC_CONF_VMS_KEY); } }VSCConfVmsKey; typedef struct __VSCConfViewKey { s8 Key[CONF_KEY_STR_MAX]; __VSCConfViewKey() { memset(Key, 0, CONF_KEY_STR_MAX); strcpy(Key, VSC_CONF_VIEW_KEY); } }VSCConfViewKey; /* Camera Group key */ typedef struct __VSCConfGroupKey { s8 Key[CONF_KEY_STR_MAX]; __VSCConfGroupKey() { memset(Key, 0, CONF_KEY_STR_MAX); strcpy(Key, VSC_CONF_VGROUP_KEY); } }VSCConfVGroupKey; /* HDFS Reocrd key */ typedef struct __VSCConfHdfsRecordKey { s8 Key[CONF_KEY_STR_MAX]; __VSCConfHdfsRecordKey() { memset(Key, 0, CONF_KEY_STR_MAX); strcpy(Key, VSC_CONF_HDFS_RECORD_KEY); } }VSCConfHdfsRecordKey; typedef struct __VSCConfData__ { u32 DeviceMap[CONF_MAP_MAX]; u32 Language; u32 DeviceNum; u32 VIPCMap[CONF_MAP_MAX]; u32 VIPCNum; }VSCConfData__; typedef struct __VSCConfData { union { VSCConfData__ conf; u8 whole[1024 * 128]; } data; }VSCConfData; typedef struct __VSCDeviceData__ { u32 nId; VSCDeviceType nType; VSCDeviceSubType nSubType; s8 Name[CONF_NAME_MAX]; s8 Param[VSC_CONF_PARAM_MAX]; s8 IP[VSC_CONF_PARAM_MAX]; s8 Port[VSC_CONF_PARAM_MAX]; s8 User[VSC_CONF_PARAM_MAX]; s8 Password[VSC_CONF_PARAM_MAX]; /* Camera Param */ s8 RtspLocation[VSC_CONF_PARAM_MAX]; s8 FileLocation[VSC_CONF_PARAM_MAX]; s8 OnvifAddress[VSC_CONF_PARAM_MAX]; s8 CameraIndex[VSC_CONF_PARAM_MAX];/* This is For USB Camera */ u32 UseProfileToken;/* 1 stand for use, 0 stand for do not use */ s8 OnvifProfileToken[VSC_CONF_PARAM_MAX]; /* Recording */ u32 Recording;/* 1 stand for recording, 0 stand for do record */ u32 GroupId; u32 HdfsRecording;/* 1 stand for recording, 0 stand for do record */ /* Second stream, only for VA */ u32 UseProfileToken2;/* 1 stand for use, 0 stand for do not use */ s8 OnvifProfileToken2[VSC_CONF_PARAM_MAX]; u32 ConnectType;/* 0 UDP, 1 Multicast , 2 TCP, 3 HTTP */ }VSCDeviceData__; typedef struct __VSCConfHdfsRecordData__ { s8 NameNode[VSC_CONF_PARAM_MAX]; s8 Port[VSC_CONF_PARAM_MAX]; s8 User[VSC_CONF_PARAM_MAX]; s8 Password[VSC_CONF_PARAM_MAX]; int FileInterval;/* In Seconds */ }VSCConfHdfsRecordData__; typedef struct __VSCVmsDataItem__ { u32 nId; VSCVmsType nType; VSCVmsSubType nSubType; s8 Name[CONF_NAME_MAX]; s8 Param[VSC_CONF_PARAM_MAX]; s8 IP[VSC_CONF_PARAM_MAX]; s8 Port[VSC_CONF_PARAM_MAX]; s8 User[VSC_CONF_PARAM_MAX]; s8 Password[VSC_CONF_PARAM_MAX]; s8 OnvifAddress[VSC_CONF_PARAM_MAX]; u32 GroupId; u32 Used;/* 1 stand for used, 0 stand for not used */ }VSCVmsDataItem; typedef struct __VSCViewDataItem__ { u32 nId; s8 Name[CONF_NAME_MAX]; /* Map for this view */ u32 Map[VSC_CONF_VIEW_CH_MAX]; VideoWallLayoutMode Mode; u32 Used;/* 1 stand for used, 0 stand for not used */ }VSCViewDataItem; /* IP Camera Group */ typedef struct __VSCVGroupDataItem__ { u32 nId; s8 Name[CONF_NAME_MAX]; /* Map for this group */ u32 Map[VSC_CONF_VGROUP_CH_MAX]; u32 Used;/* 1 stand for used, 0 stand for not used */ }VSCVGroupDataItem; typedef struct __VSCVIPCDataItem__ { u32 nId; VSCVmsType nType; VSCVmsSubType nSubType; s8 Name[CONF_NAME_MAX]; s8 Param[VSC_CONF_PARAM_S_MAX]; s32 nStreamId; s8 IP[VSC_CONF_PARAM_S_MAX]; s8 Port[VSC_CONF_PARAM_S_MAX]; s8 User[VSC_CONF_PARAM_S_MAX]; s8 Password[VSC_CONF_PARAM_S_MAX]; s8 OnvifAddress[VSC_CONF_PARAM_S_MAX]; }VSCVIPCDataItem__; typedef struct __VSCVmsData__ { VSCVmsDataItem vms[CONF_VMS_NUM_MAX]; }VSCVmsData__; typedef struct __VSCViewData__ { VSCViewDataItem view[CONF_VIEW_NUM_MAX]; }VSCViewData__; typedef struct __VSCVGroupData__ { VSCVGroupDataItem group[CONF_VGROUP_NUM_MAX]; }VSCVGroupData__; typedef struct __VSCDeviceData { union { VSCDeviceData__ conf; u8 whole[1024 * 128]; } data; }VSCDeviceData; typedef struct __VSCVmsData { union { VSCVmsData__ conf; u8 whole[1024 * 128]; } data; }VSCVmsData; typedef struct __VSCViewData { union { VSCViewData__ conf; u8 whole[1024 * 128]; } data; }VSCViewData; typedef struct __VSCVGroupData { union { VSCVGroupData__ conf; u8 whole[1024 * 128]; } data; }VSCVGroupData; typedef struct __VSCVIPCData { union { VSCVIPCDataItem__ conf; u8 whole[1024 * 128]; } data; }VSCVIPCData; typedef struct __VSCHdfsRecordData { union { VSCConfHdfsRecordData__ conf; u8 whole[1024 * 128]; } data; }VSCHdfsRecordData; inline void VSCVmsDataItemDefault(VSCVmsDataItem &item) { sprintf(item.Name, "Recorder"); strcpy(item.IP, "192.168.0.1"); strcpy(item.Port, "80"); strcpy(item.User, "admin"); strcpy(item.Password, "admin"); strcpy(item.Param, "none"); item.Used = 0; item.nId = 0; item.GroupId = 0; } inline void VSCViewDataItemDefault(VSCViewDataItem &item) { memset(&item, 0, sizeof(VSCViewDataItem)); sprintf(item.Name, "View"); item.Mode = LAYOUT_MODE_3X3; } inline void VSCVGroupDataItemDefault(VSCVGroupDataItem &item) { memset(&item, 0, sizeof(VSCVGroupDataItem)); sprintf(item.Name, "Group"); } inline void VSCVIPCDataItemDefault(VSCVIPCDataItem__ &item) { sprintf(item.Name, "Virutal IPC"); strcpy(item.IP, "192.168.0.1"); strcpy(item.Port, "8000"); strcpy(item.User, "admin"); strcpy(item.Password, "admin"); item.nStreamId = 1; } inline void VSCHdfsRecordDataItemDefault(VSCConfHdfsRecordData__ &item) { strcpy(item.NameNode, "localhost");//default for hdd strcpy(item.Port, "8020");//0 for hdd strcpy(item.User, "admin"); strcpy(item.Password, "admin"); item.FileInterval = 30;/* 30s */ } #pragma pack(pop) #endif /* _CONF_H_ */ <commit_msg>add mining conf<commit_after> #ifndef _CONF_H_ #define _CONF_H_ #include "utility.hpp" #define VE_VERSION "r1.0.3-20150122" #define VE_INFO "vdceye Manager r1.0.3 2015" #ifdef WIN32 #define VE_NVR_CLIENT #else #define VE_NVR #endif /* NVR Client feature */ #ifdef VE_NVR_CLIENT #define VE_RECORDER_MGR_CLIENT_SUPPORT #endif /* NVR feature */ #ifdef VE_NVR #define VE_RECORDER_MGR_SERVER_SUPPORT #endif #define CONF_NAME_MAX 128 /* support Camera num */ #define CONF_MAP_MAX 4096 #define CONF_USER_PASSWORD_MAX 1024 #define CONF_PATH_MAX 1024 /* 0xFF FFFF to 0xFFFF FFFF is for status for the map */ #define CONF_MAP_INVALID_MIN 0xFFFFFF #define CONF_KEY_STR_MAX 16 /* Support VMS(site, recorder) num */ #define CONF_VMS_NUM_MAX 128 #define CONF_VIEW_NUM_MAX 128 /* IP camera Group max num */ #define CONF_VGROUP_NUM_MAX 128 #define VSC_CONF_KEY "ConfVSCSystem" #define VSC_CONF_LIC_KEY "ConfVSCLicense" #define VSC_CONF_CHANNEL_KEY "ConfVSCDevice" #define VSC_CONF_VIPC_KEY "ConfVSCVIPC" #define VSC_CONF_VMS_KEY "ConfVSCVms" #define VSC_CONF_VIEW_KEY "ConfVSCView" #define VSC_CONF_VGROUP_KEY "ConfVSCVGroup" #define VSC_CONF_HDFS_RECORD_KEY "ConfVSCHdfsRec" #define VSC_CONF_EMAP_FILE_KEY "ConfVSCEmapFile" #define VSC_CONF_EMAP_CONF_KEY "ConfVSCEmapConf" #define VSC_CONF_PARAM_MAX 1024 #define VSC_CONF_PARAM_S_MAX 128 /* Max camera in one view */ #define VSC_CONF_VIEW_CH_MAX 256 /* Max camera in one Group */ #define VSC_CONF_VGROUP_CH_MAX 256 typedef enum { VSC_DEVICE_CAM = 1, VSC_DEVICE_RECORDER, VSC_DEVICE_LAST } VSCDeviceType; /* Device Type */ typedef enum { VSC_SUB_DEVICE_USB_CAM = 1, VSC_SUB_DEVICE_FILE, VSC_SUB_DEVICE_RTSP, VSC_SUB_DEVICE_ONVIF, VSC_SUB_DEVICE_ONVIF_RECODER, VSC_SUB_DEVICE_GB28181, VSC_SUB_DEVICE_LAST } VSCDeviceSubType; typedef enum { VSC_VMS_RECORDER = 1, VSC_VMS_SITE, VSC_VMS_VIRTUL_IPC, VSC_VMS_LAST } VSCVmsType; typedef enum { VSC_SUB_VMS_PG = 1, VSC_SUB_VMS_ZB, VSC_SUB_VIPC_FILE, VSC_SUB_VIPC_LIVE, VSC_SUB_VMS_LAST } VSCVmsSubType; /* Control command */ typedef enum { LAYOUT_MODE_1 = 1, LAYOUT_MODE_2X2, LAYOUT_MODE_3X3, LAYOUT_MODE_4X4, LAYOUT_MODE_6, LAYOUT_MODE_8, LAYOUT_MODE_12p1, LAYOUT_MODE_5x5, LAYOUT_MODE_6x6, LAYOUT_MODE_8x8, LAYOUT_MODE_ONE, LAYOUT_MODE_LAST } VideoWallLayoutMode; #pragma pack(push, 1 ) typedef struct __VSCConfSystemKey { s8 Key[CONF_KEY_STR_MAX]; __VSCConfSystemKey() { memset(Key, 0, CONF_KEY_STR_MAX); strcpy(Key, VSC_CONF_KEY); } }VSCConfSystemKey; typedef struct __VSCConfLicenseKey { s8 Key[CONF_KEY_STR_MAX]; __VSCConfLicenseKey() { memset(Key, 0, CONF_KEY_STR_MAX); strcpy(Key, VSC_CONF_LIC_KEY); } }VSCConfLicenseKey; typedef struct __VSCConfDeviceKey { u32 nId; s8 Key[CONF_KEY_STR_MAX]; __VSCConfDeviceKey(u32 id) { memset(Key, 0, CONF_KEY_STR_MAX); strcpy(Key, VSC_CONF_CHANNEL_KEY); nId = id; } }VSCConfDeviceKey; typedef struct __VSCConfVIPCKey { u32 nId; s8 Key[CONF_KEY_STR_MAX]; __VSCConfVIPCKey(u32 id) { memset(Key, 0, CONF_KEY_STR_MAX); strcpy(Key, VSC_CONF_VIPC_KEY); nId = id; } }VSCConfVIPCKey; typedef struct __VSCConfVmsKey { s8 Key[CONF_KEY_STR_MAX]; __VSCConfVmsKey() { memset(Key, 0, CONF_KEY_STR_MAX); strcpy(Key, VSC_CONF_VMS_KEY); } }VSCConfVmsKey; typedef struct __VSCConfViewKey { s8 Key[CONF_KEY_STR_MAX]; __VSCConfViewKey() { memset(Key, 0, CONF_KEY_STR_MAX); strcpy(Key, VSC_CONF_VIEW_KEY); } }VSCConfViewKey; /* Camera Group key */ typedef struct __VSCConfGroupKey { s8 Key[CONF_KEY_STR_MAX]; __VSCConfGroupKey() { memset(Key, 0, CONF_KEY_STR_MAX); strcpy(Key, VSC_CONF_VGROUP_KEY); } }VSCConfVGroupKey; /* HDFS Reocrd key */ typedef struct __VSCConfHdfsRecordKey { s8 Key[CONF_KEY_STR_MAX]; __VSCConfHdfsRecordKey() { memset(Key, 0, CONF_KEY_STR_MAX); strcpy(Key, VSC_CONF_HDFS_RECORD_KEY); } }VSCConfHdfsRecordKey; typedef struct __VSCConfData__ { u32 DeviceMap[CONF_MAP_MAX]; u32 Language; u32 DeviceNum; u32 VIPCMap[CONF_MAP_MAX]; u32 VIPCNum; u32 ConfVer;/* Current version is 0 */ }VSCConfData__; typedef struct __VSCConfData { union { VSCConfData__ conf; u8 whole[1024 * 128]; } data; }VSCConfData; typedef struct __VSCDeviceData__ { u32 nId; VSCDeviceType nType; VSCDeviceSubType nSubType; s8 Name[CONF_NAME_MAX]; s8 Param[VSC_CONF_PARAM_MAX]; s8 IP[VSC_CONF_PARAM_MAX]; s8 Port[VSC_CONF_PARAM_MAX]; s8 User[VSC_CONF_PARAM_MAX]; s8 Password[VSC_CONF_PARAM_MAX]; /* Camera Param */ s8 RtspLocation[VSC_CONF_PARAM_MAX]; s8 FileLocation[VSC_CONF_PARAM_MAX]; s8 OnvifAddress[VSC_CONF_PARAM_MAX]; s8 CameraIndex[VSC_CONF_PARAM_MAX];/* This is For USB Camera */ u32 UseProfileToken;/* 1 stand for use, 0 stand for do not use */ s8 OnvifProfileToken[VSC_CONF_PARAM_MAX]; /* Recording */ u32 Recording;/* 1 stand for recording, 0 stand for do record */ u32 GroupId; u32 HdfsRecording;/* 1 stand for recording, 0 stand for do record */ /* Second stream, only for VA */ s8 OnvifProfileToken2[VSC_CONF_PARAM_MAX]; u32 ConnectType;/* 0 UDP, 1 TCP, 2 Multicast, 3 HTTP */ u32 Mining;/* 1 stand for mining, 0 stand for no mining */ }VSCDeviceData__; typedef struct __VSCConfHdfsRecordData__ { s8 NameNode[VSC_CONF_PARAM_MAX]; s8 Port[VSC_CONF_PARAM_MAX]; s8 User[VSC_CONF_PARAM_MAX]; s8 Password[VSC_CONF_PARAM_MAX]; int FileInterval;/* In Seconds */ }VSCConfHdfsRecordData__; typedef struct __VSCVmsDataItem__ { u32 nId; VSCVmsType nType; VSCVmsSubType nSubType; s8 Name[CONF_NAME_MAX]; s8 Param[VSC_CONF_PARAM_MAX]; s8 IP[VSC_CONF_PARAM_MAX]; s8 Port[VSC_CONF_PARAM_MAX]; s8 User[VSC_CONF_PARAM_MAX]; s8 Password[VSC_CONF_PARAM_MAX]; s8 OnvifAddress[VSC_CONF_PARAM_MAX]; u32 GroupId; u32 Used;/* 1 stand for used, 0 stand for not used */ }VSCVmsDataItem; typedef struct __VSCViewDataItem__ { u32 nId; s8 Name[CONF_NAME_MAX]; /* Map for this view */ u32 Map[VSC_CONF_VIEW_CH_MAX]; VideoWallLayoutMode Mode; u32 Used;/* 1 stand for used, 0 stand for not used */ }VSCViewDataItem; /* IP Camera Group */ typedef struct __VSCVGroupDataItem__ { u32 nId; s8 Name[CONF_NAME_MAX]; /* Map for this group */ u32 Map[VSC_CONF_VGROUP_CH_MAX]; u32 Used;/* 1 stand for used, 0 stand for not used */ }VSCVGroupDataItem; typedef struct __VSCVIPCDataItem__ { u32 nId; VSCVmsType nType; VSCVmsSubType nSubType; s8 Name[CONF_NAME_MAX]; s8 Param[VSC_CONF_PARAM_S_MAX]; s32 nStreamId; s8 IP[VSC_CONF_PARAM_S_MAX]; s8 Port[VSC_CONF_PARAM_S_MAX]; s8 User[VSC_CONF_PARAM_S_MAX]; s8 Password[VSC_CONF_PARAM_S_MAX]; s8 OnvifAddress[VSC_CONF_PARAM_S_MAX]; }VSCVIPCDataItem__; typedef struct __VSCVmsData__ { VSCVmsDataItem vms[CONF_VMS_NUM_MAX]; }VSCVmsData__; typedef struct __VSCViewData__ { VSCViewDataItem view[CONF_VIEW_NUM_MAX]; }VSCViewData__; typedef struct __VSCVGroupData__ { VSCVGroupDataItem group[CONF_VGROUP_NUM_MAX]; }VSCVGroupData__; typedef struct __VSCDeviceData { union { VSCDeviceData__ conf; u8 whole[1024 * 128]; } data; }VSCDeviceData; typedef struct __VSCVmsData { union { VSCVmsData__ conf; u8 whole[1024 * 128]; } data; }VSCVmsData; typedef struct __VSCViewData { union { VSCViewData__ conf; u8 whole[1024 * 128]; } data; }VSCViewData; typedef struct __VSCVGroupData { union { VSCVGroupData__ conf; u8 whole[1024 * 128]; } data; }VSCVGroupData; typedef struct __VSCVIPCData { union { VSCVIPCDataItem__ conf; u8 whole[1024 * 128]; } data; }VSCVIPCData; typedef struct __VSCHdfsRecordData { union { VSCConfHdfsRecordData__ conf; u8 whole[1024 * 128]; } data; }VSCHdfsRecordData; inline void VSCVmsDataItemDefault(VSCVmsDataItem &item) { sprintf(item.Name, "Recorder"); strcpy(item.IP, "192.168.0.1"); strcpy(item.Port, "80"); strcpy(item.User, "admin"); strcpy(item.Password, "admin"); strcpy(item.Param, "none"); item.Used = 0; item.nId = 0; item.GroupId = 0; } inline void VSCViewDataItemDefault(VSCViewDataItem &item) { memset(&item, 0, sizeof(VSCViewDataItem)); sprintf(item.Name, "View"); item.Mode = LAYOUT_MODE_3X3; } inline void VSCVGroupDataItemDefault(VSCVGroupDataItem &item) { memset(&item, 0, sizeof(VSCVGroupDataItem)); sprintf(item.Name, "Group"); } inline void VSCVIPCDataItemDefault(VSCVIPCDataItem__ &item) { sprintf(item.Name, "Virutal IPC"); strcpy(item.IP, "192.168.0.1"); strcpy(item.Port, "8000"); strcpy(item.User, "admin"); strcpy(item.Password, "admin"); item.nStreamId = 1; } inline void VSCHdfsRecordDataItemDefault(VSCConfHdfsRecordData__ &item) { strcpy(item.NameNode, "localhost");//default for hdd strcpy(item.Port, "8020");//0 for hdd strcpy(item.User, "admin"); strcpy(item.Password, "admin"); item.FileInterval = 30;/* 30s */ } #pragma pack(pop) #endif /* _CONF_H_ */ <|endoftext|>
<commit_before><commit_msg>Added type info<commit_after><|endoftext|>
<commit_before>// Cruncher. #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <stdint.h> #include <assert.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <pthread.h> #include <gmp.h> using namespace std; #include <vector> #include <map> struct Computation; struct Subscription { mpz_t modulus; // Maps stream number to a base. map<uint64_t, mpz_t> bases; }; struct Computation { Subscription* sub; mpz_t accum; computation_t(Subscription* sub) : sub(sub) { mpz_init_set_ui(accum, 1); } }; int create_connection(const char* hostname, const char* service) { int fd; struct addrinfo* res = NULL; getaddrinfo(hostname, service, NULL, &res); fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if (connect(fd, res->ai_addr, res->ai_addrlen) != 0) { freeaddrinfo(res); perror(hostname); exit(1); } freeaddrinfo(res); return fd; } // Global storage. pthread_mutex_t global_lock; #define LOCK pthread_mutex_lock(&global_lock) #define UNLOCK pthread_mutex_unlock(&global_lock) // Maps subscription number to a subscription. map<uint64_t, subscription_t*> subscriptions; void* process_thread(void* cookie) { int pid = *(int*)cookie; delete (int*)cookie; // Grab the global lock. while (1) { LOCK; } return NULL; } int main(int argc, char** argv) { if (argc != 4) { fprintf(stderr, "Usage: cruncher <host> <port> <nthreads>\n"); exit(2); } int sockfd = create_connection(argv[1], argv[2]); printf("Connected.\n"); // Initialize the global lock and grab it. assert(pthread_mutex_init(&global_lock, NULL) == 0); LOCK; // Spawn worker threads. vector<pthread_t> threads; threads.resize(atoi(argv[2])); for (unsigned int i=0; i<threads.size(); i++) pthread_create(&threads[i], NULL, process_thread, (void*)new int(i)); #define READ_BUFFER_LENGTH 65536 char* buf = new char[READ_BUFFER_LENGTH+1]; // Make sure the whole buffer is null terminated. buf[READ_BUFFER_LENGTH] = 0; int buf_i = 0; #define READ_FIELD \ do { \ buf_i = 0; \ while (buf_i < READ_BUFFER_LENGTH) { \ buf[buf_i] = 0; read(sockfd, buf+buf_i, 1); \ if (buf[buf_i++] == 0) \ break; \ buf_i++; \ } \ } while (0) mpz_t temp_mpz; mpz_init(temp_mpz); // Wait for commands from the server. while (1) { char type; read(sockfd, &type, 1); uint64_t sub_id = 0; uint64_t stream_id = 0; uint64_t round_number = 0; #define FILL(x) read(sockfd, &x, sizeof x) switch (type) { case 's': // Add/update a subscription. FILL(sub_id); READ_FIELD; // Read in the modulus. mpz_set_str(temp_mpz, buf, 16); case 'a': // Add a new entry into a subscription. FILL(sub_id); FILL(stream_id); READ_FIELD; // Read in the base. mpz_set_str(temp_mpz, buf, 16); break; case 'b': // Remove a subscription pair. FILL(sub_id); break; case 'c': // Issue a computation. FILL(stream_id); FILL(round_number); break; case 'r': // Read out an answer. FILL(sub_id); FILL(round_number); break; case 'i': // Return status information. break; default: assert(0); } } return 0; } <commit_msg>Substantial improvements to cruncher.cpp<commit_after>// === Cruncher === // Copyright 2014, Peter Schmidt-Nielsen. // Licensed under the MIT license. // // This program connects to the server, and waits to be issued work. // The entire purpose is to evaluate the homomorphic matrix multiplication on a (potentially) sparse submatrix. // The allowed commands from the server to this program are documented: // In each case, "abc": string literal, I: 8 byte integer, Z: null terminated string hex number. // "s" I:subid Z:m -- Add a subscription with the given subscription ID, and the given modulus m. // "a" I:subid I:streamid Z:base -- Add an entry to the given subscription corresponding to the given stream ID, with the given base. // "d" I:subid -- Remove a given subscription. // "c" I:streamid I:round Z:datum -- In the given round, the given stream reads the given datum. // The following commands return data back to the server: // "r" I:round -- Returns: I:numoffields <fields>, with each field being I:subid Z:result. // "i" -- Returns some basic information. // // The computation is performed by a pool of worker threads. #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <stdint.h> #include <assert.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <pthread.h> #include <semaphore.h> #include <gmp.h> using namespace std; #include <iostream> #include <vector> #include <map> // Specifies the maximum number of bytes in a variable length field in a command recieved over the network. #define READ_BUFFER_LENGTH 65536 typedef uint64_t RoundNum; typedef uint64_t SubId; typedef uint64_t StreamId; struct Subscription; struct Entry; struct Computation; // Global storage. namespace global { int thread_count; int bits_per_field; int default_tradeoff; // Maps subscription number to a subscription. map<SubId, Subscription*> subscriptions; // Maps a round and subid to a computation object. map<RoundNum, map<SubId, Computation*>> computations; // Data used for communication between the workers and the main thread. StreamId job_stream_id; RoundNum job_round_number; mpz_t* job_datum; // This lock synchronizes reads and writes to subscriptions and computations. pthread_rwlock_t globals_rwlock; // These semaphores are used to send jobs to worker threads, and signal the main thread that the job data has been read respectively. sem_t job_available, job_read_complete; } #define READ_LOCK_GLOBALS pthread_rwlock_rdlock(&global::globals_rwlock) #define WRITE_LOCK_GLOBALS pthread_rwlock_wrlock(&global::globals_rwlock) #define UNLOCK_GLOBALS pthread_rwlock_unlock(&global::globals_rwlock) struct Subscription { mpz_t modulus; // Maps stream number to an entry. map<StreamId, Entry*> entries; Subscription(mpz_t _modulus) { mpz_init_set(modulus, _modulus); } ~Subscription() { mpz_clear(modulus); for (auto it = entries.begin(); it != entries.end(); it++) { delete it->second; } } }; struct Entry { mpz_t base; int tradeoff; int table_length; mpz_t* precomputed_table; Subscription* parent; Entry(Subscription* parent, mpz_t _base) : tradeoff(0), table_length(0), precomputed_table(NULL), parent(parent) { mpz_init_set(base, _base); } ~Entry() { mpz_clear(base); free_table(); } void free_table() { if (precomputed_table == NULL) return; for (int i = 0; i < table_length; i++) mpz_clear(precomputed_table[i]); tradeoff = 0; table_length = 0; precomputed_table = NULL; delete* precomputed_table; } inline int get_required_chunks() { // The number of required chunks is ceil(bits_per_field / tradeoff) return (global::bits_per_field + tradeoff - 1) / tradeoff; } inline int get_nums_per_chunk() { // Each chunk has one number per non-zero bit pattern of up to tradeoff bits. return (1 << tradeoff) - 1; } void rebuild_table(int new_tradeoff) { free_table(); tradeoff = new_tradeoff; // A tradeoff value of zero disables the precomputed table mode. if (tradeoff == 0) return; int required_chunks = get_required_chunks(); int nums_per_chunk = get_nums_per_chunk(); precomputed_table = new mpz_t[required_chunks * nums_per_chunk]; mpz_t x, y; mpz_init_set(x, base); mpz_init(y); for (int chunk = 0; chunk < required_chunks; chunk++) { mpz_set_ui(y, 1); for (int i = 0; i < nums_per_chunk; i++) { mpz_mul(y, x, y); mpz_mod(y, y, parent->modulus); mpz_init_set(precomputed_table[chunk*nums_per_chunk + i], y); } // Advance x by tradeoff bits. mpz_powm_ui(x, x, 1 << tradeoff, parent->modulus); } mpz_clear(x); mpz_clear(y); } void exponentiate(mpz_t dest, mpz_t datum) { // gmp_printf("Exponentiating: %Zd ** %Zd mod %Zd\n", base, datum, parent->modulus); // If no table is built, run a vanilla modular exponentiation. if (tradeoff == 0) { mpz_powm(dest, base, datum, parent->modulus); return; } // Otherwise, let's use our table. // A copy of datum, to avoid mutating our input. mpz_t _datum; mpz_init_set(_datum, datum); int required_chunks = get_required_chunks(); int nums_per_chunk = get_nums_per_chunk(); int table_index = 0; mp_limb_t bit_mask = (1 << tradeoff) - 1; mpz_set_ui(dest, 1); for (int chunk = 0; chunk < required_chunks; chunk++) { // Get the bit pattern for this chunk. mp_limb_t bits = mpz_getlimbn(_datum, 0) & bit_mask; // Right shift the bits. mpz_tdiv_q_2exp(_datum, _datum, tradeoff); if (bits != 0) { // Multiply in the appropriate table entry. // The subtraction of 1 is because we don't need a table entry for the zero bit pattern. mpz_mul(dest, dest, precomputed_table[table_index + bits - 1]); mpz_mod(dest, dest, parent->modulus); } table_index += nums_per_chunk; } } }; struct Computation { Subscription* sub; mpz_t* accums; Computation(Subscription* sub) : sub(sub) { // Allocate one accumulator per thread, so that multiple threads can work on the computation at the same time. // In the end, the answer is the product of these accumulators. accums = new mpz_t[global::thread_count]; for (int i = 0; i < global::thread_count; i++) mpz_init_set_ui(accums[i], 1); } ~Computation() { for (int i = 0; i < global::thread_count; i++) mpz_clear(accums[i]); delete* accums; } void process_datum(int thread_index, StreamId stream, mpz_t datum) { Entry* entry = sub->entries[stream]; mpz_t local; mpz_init(local); entry->exponentiate(local, datum); // gmp_printf("Computed additional: %Zd\n", local); mpz_mul(accums[thread_index], accums[thread_index], local); mpz_mod(accums[thread_index], accums[thread_index], sub->modulus); mpz_clear(local); } void produce_result(mpz_t output) { mpz_set_ui(output, 1); // Multiply all the thread-specific accumulators together. for (int i = 0; i < global::thread_count; i++) { mpz_mul(output, output, accums[i]); mpz_mod(output, output, sub->modulus); } } }; int create_connection(const char* hostname, const char* service) { int fd; struct addrinfo* res = NULL; getaddrinfo(hostname, service, NULL, &res); fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if (connect(fd, res->ai_addr, res->ai_addrlen) != 0) { freeaddrinfo(res); perror(hostname); exit(1); } freeaddrinfo(res); return fd; } void* process_thread(void* cookie) { int thread_index = *(int*)cookie; delete (int*)cookie; mpz_t datum; mpz_init(datum); while (1) { // Grab a job. sem_wait(&global::job_available); // Read in the job. StreamId stream_id = global::job_stream_id; RoundNum round_number = global::job_round_number; mpz_set(datum, *global::job_datum); // Release the global lock, indicating that the global job data can be mutated, and used to issue another job to a different thread. sem_post(&global::job_read_complete); // Find each subscription object, and build the computation required. // gmp_printf("Performing job: stream=%i round=%i datum=%Zd\n", stream_id, round_number, datum); READ_LOCK_GLOBALS; for (auto it = global::subscriptions.begin(); it != global::subscriptions.end(); it++) { SubId sub_id = it->first; Computation* comp = global::computations[round_number][sub_id]; comp->process_datum(thread_index, stream_id, datum); } UNLOCK_GLOBALS; } mpz_clear(datum); return NULL; } int main(int argc, char** argv) { if (argc != 4) { fprintf(stderr, "Usage: cruncher <host> <port> <nthreads>\n"); exit(2); } int sockfd = create_connection(argv[1], argv[2]); printf("Connected.\n"); assert(sem_init(&global::job_available, 0, 0) == 0); assert(sem_init(&global::job_read_complete, 0, 0) == 0); assert(pthread_rwlock_init(&global::globals_rwlock, NULL) == 0); // Set some reasonable defaults. global::bits_per_field = 2048; global::default_tradeoff = 0; global::thread_count = atoi(argv[3]); printf("Using %i threads.\n", global::thread_count); // Spawn worker threads. vector<pthread_t> threads; threads.resize(global::thread_count); for (int i=0; i<global::thread_count; i++) pthread_create(&threads[i], NULL, process_thread, (void*)new int(i)); char* buf = new char[READ_BUFFER_LENGTH+1]; // Make sure the whole buffer is null terminated. buf[READ_BUFFER_LENGTH] = 0; int buf_i = 0; #define READ_FIELD \ do { \ buf_i = 0; \ while (buf_i < READ_BUFFER_LENGTH) { \ buf[buf_i] = 0; \ read(sockfd, buf+buf_i, 1); \ if (buf[buf_i++] == 0) \ break; \ } \ } while (0) mpz_t temp_mpz; mpz_init(temp_mpz); // Wait for commands from the server in an infinite loop. while (1) { char type = -1; if (read(sockfd, &type, 1) != 1) break; SubId sub_id = 0; StreamId stream_id = 0; RoundNum round_number = 0; #define FILL(x) read(sockfd, &x, sizeof x) switch (type) { case 's': // Add a subscription. FILL(sub_id); READ_FIELD; // Read in the modulus. mpz_set_str(temp_mpz, buf, 16); // gmp_printf("Adding subscription: sub=%i mod=%Zd\n", sub_id, temp_mpz); // Create the subscription. WRITE_LOCK_GLOBALS; global::subscriptions[sub_id] = new Subscription(temp_mpz); UNLOCK_GLOBALS; break; case 'a': // Add a new entry into a subscription. FILL(sub_id); FILL(stream_id); READ_FIELD; // Read in the base. mpz_set_str(temp_mpz, buf, 16); // gmp_printf("Adding entry: sub=%i stream=%i base=%Zd\n", sub_id, stream_id, temp_mpz); WRITE_LOCK_GLOBALS; // Make sure the sub_id is real. if (global::subscriptions.count(sub_id) == 1) { Subscription* sub = global::subscriptions[sub_id]; // Delete a previous entry, if it exists. if (sub->entries.count(stream_id) == 1) delete sub->entries[stream_id]; Entry* entry = sub->entries[stream_id] = new Entry(sub, temp_mpz); // TODO: Rebuilding the table is expensive! // Eventually, move this to a worker thread. entry->rebuild_table(global::default_tradeoff); } UNLOCK_GLOBALS; break; case 'd': // Remove a subscription. FILL(sub_id); WRITE_LOCK_GLOBALS; if (global::subscriptions.count(sub_id) == 1) { delete global::subscriptions[sub_id]; global::subscriptions.erase(global::subscriptions.find(sub_id)); } UNLOCK_GLOBALS; break; case 'c': { // Issue a computation. FILL(stream_id); FILL(round_number); READ_FIELD; // Read in the datum. mpz_set_str(temp_mpz, buf, 16); // gmp_printf("Computation: stream=%i round=%i datum=%Zd\n", stream_id, round_number, temp_mpz); // Create any new computation objects required. WRITE_LOCK_GLOBALS; map<SubId, Computation*>& comps = global::computations[round_number]; for (auto it = global::subscriptions.begin(); it != global::subscriptions.end(); it++) { // Create a computation object for this subscription in this round number. if (comps.count(it->first) == 0) comps[it->first] = new Computation(it->second); } UNLOCK_GLOBALS; // Fill up the global job description. global::job_stream_id = stream_id; global::job_round_number = round_number; global::job_datum = &temp_mpz; sem_post(&global::job_available); sem_wait(&global::job_read_complete); break; } case 'r': { // Read out completed answers. FILL(round_number); // gmp_printf("Replying: round=%lu\n", round_number); WRITE_LOCK_GLOBALS; map<SubId, Computation*>& comps = global::computations[round_number]; uint64_t field = comps.size(); // gmp_printf("Lengths: %i %i\n", global::computations.size(), comps.size()); write(sockfd, &field, 8); for (auto it = comps.begin(); it != comps.end(); it++) { field = it->first; write(sockfd, &field, 8); it->second->produce_result(temp_mpz); int bytes = gmp_snprintf(buf, READ_BUFFER_LENGTH, "%Zx", temp_mpz); assert(bytes < READ_BUFFER_LENGTH); write(sockfd, buf, bytes+1); } UNLOCK_GLOBALS; break; } case 'i': // Return status information. write(sockfd, "Status.\n", 8); break; default: fprintf(stderr, "Got invalid command character: %i\n", type); assert(0); } } printf("Exiting.\n"); close(sockfd); return 0; } <|endoftext|>