Json::Value sinsp_filter_check::rawval_to_json(uint8_t* rawval, const filtercheck_field_info* finfo, uint32_t len) { ASSERT(rawval != NULL); ASSERT(finfo != NULL); switch(finfo->m_type) { case PT_INT8: if(finfo->m_print_format == PF_DEC) { return *(int8_t *)rawval; } else if(finfo->m_print_format == PF_HEX) { return rawval_to_string(rawval, finfo, len); } else { ASSERT(false); return Json::Value::null; } case PT_INT16: if(finfo->m_print_format == PF_DEC) { return *(int16_t *)rawval; } else if(finfo->m_print_format == PF_HEX) { return rawval_to_string(rawval, finfo, len); } else { ASSERT(false); return Json::Value::null; } case PT_INT32: if(finfo->m_print_format == PF_DEC) { return *(int32_t *)rawval; } else if(finfo->m_print_format == PF_HEX) { return rawval_to_string(rawval, finfo, len); } else { ASSERT(false); return Json::Value::null; } case PT_INT64: case PT_PID: if(finfo->m_print_format == PF_DEC) { return (Json::Value::Int64)*(int64_t *)rawval; } else { return rawval_to_string(rawval, finfo, len); } case PT_L4PROTO: // This can be resolved in the future case PT_UINT8: if(finfo->m_print_format == PF_DEC) { return *(uint8_t *)rawval; } else if(finfo->m_print_format == PF_HEX) { return rawval_to_string(rawval, finfo, len); } else { ASSERT(false); return Json::Value::null; } case PT_PORT: // This can be resolved in the future case PT_UINT16: if(finfo->m_print_format == PF_DEC) { return *(uint16_t *)rawval; } else if(finfo->m_print_format == PF_HEX) { return rawval_to_string(rawval, finfo, len); } else { ASSERT(false); return Json::Value::null; } case PT_UINT32: if(finfo->m_print_format == PF_DEC) { return *(uint32_t *)rawval; } else if(finfo->m_print_format == PF_HEX) { return rawval_to_string(rawval, finfo, len); } else { ASSERT(false); return Json::Value::null; } case PT_UINT64: case PT_RELTIME: case PT_ABSTIME: if(finfo->m_print_format == PF_DEC) { return (Json::Value::UInt64)*(uint64_t *)rawval; } else if( finfo->m_print_format == PF_10_PADDED_DEC || finfo->m_print_format == PF_HEX) { return rawval_to_string(rawval, finfo, len); } else { ASSERT(false); return Json::Value::null; } case PT_SOCKADDR: case PT_SOCKFAMILY: ASSERT(false); return Json::Value::null; case PT_BOOL: return Json::Value((bool)(*(uint32_t*)rawval != 0)); case PT_CHARBUF: case PT_BYTEBUF: case PT_IPV4ADDR: return rawval_to_string(rawval, finfo, len); default: ASSERT(false); throw sinsp_exception("wrong event type " + to_string((long long) finfo->m_type)); } }
void CerrarArchivoNode::ValidateSemantic() { TypeNode* type = archiveToClose->ValidateSemantic(); if (type->GetName().compare("TypeArchivo")!=0) throw invalid_argument("Se esperaba que variable fuera de tipo archivo. Columna: "+to_string(column)+" Fila: "+to_string(row) ); }
void draw(HyperspaceSaverSettings *inSettings){ if(inSettings->first){ if(inSettings->dUseTunnels){ // only tunnels use caustic textures glDisable(GL_FOG); // Caustic textures can only be created after rendering context has been created // because they have to be drawn and then read back from the framebuffer. #ifdef WIN32 if(doingPreview) // super fast for Windows previewer inSettings->theCausticTextures = new causticTextures(8, inSettings->numAnimTexFrames, 32, 32, 1.0f, 0.01f, 10.0f); else // normal #endif inSettings->theCausticTextures = new causticTextures(8, inSettings->numAnimTexFrames, 100, 256, 1.0f, 0.01f, 20.0f); glEnable(GL_FOG); } if(inSettings->dShaders){ #ifdef WIN32 if(doingPreview) // super fast for Windows previewer inSettings->theWNCM = new wavyNormalCubeMaps(inSettings->numAnimTexFrames, 32); else // normal #endif inSettings->theWNCM = new wavyNormalCubeMaps(inSettings->numAnimTexFrames, 128); } glViewport(inSettings->viewport[0], inSettings->viewport[1], inSettings->viewport[2], inSettings->viewport[3]); inSettings->first = 0; } // Variables for printing text static float computeTime = 0.0f; static float drawTime = 0.0f; //static rsTimer computeTimer, drawTimer; // start compute time timer //computeTimer.tick(); glMatrixMode(GL_MODELVIEW); // Camera movements static float camHeading[3] = {0.0f, 0.0f, 0.0f}; // current, target, and last static int changeCamHeading = 1; static float camHeadingChangeTime[2] = {20.0f, 0.0f}; // total, elapsed static float camRoll[3] = {0.0f, 0.0f, 0.0f}; // current, target, and last static int changeCamRoll = 1; static float camRollChangeTime[2] = {1.0f, 0.0f}; // total, elapsed camHeadingChangeTime[1] += inSettings->frameTime; if(camHeadingChangeTime[1] >= camHeadingChangeTime[0]){ // Choose new direction camHeadingChangeTime[0] = rsRandf(15.0f) + 5.0f; camHeadingChangeTime[1] = 0.0f; camHeading[2] = camHeading[1]; // last = target if(changeCamHeading){ // face forward most of the time if(rsRandi(6)) camHeading[1] = 0.0f; // face backward the rest of the time else if(rsRandi(2)) camHeading[1] = RS_PI; else camHeading[1] = -RS_PI; changeCamHeading = 0; } else changeCamHeading = 1; } float t = camHeadingChangeTime[1] / camHeadingChangeTime[0]; t = 0.5f * (1.0f - cosf(RS_PI * t)); camHeading[0] = camHeading[1] * t + camHeading[2] * (1.0f - t); camRollChangeTime[1] += inSettings->frameTime; if(camRollChangeTime[1] >= camRollChangeTime[0]){ // Choose new roll angle camRollChangeTime[0] = rsRandf(5.0f) + 10.0f; camRollChangeTime[1] = 0.0f; camRoll[2] = camRoll[1]; // last = target if(changeCamRoll){ camRoll[1] = rsRandf(RS_PIx2*2) - RS_PIx2; changeCamRoll = 0; } else changeCamRoll = 1; } t = camRollChangeTime[1] / camRollChangeTime[0]; t = 0.5f * (1.0f - cosf(RS_PI * t)); camRoll[0] = camRoll[1] * t + camRoll[2] * (1.0f - t); static float pathDir[3] = {0.0f, 0.0f, -1.0f}; inSettings->thePath->moveAlongPath(float(inSettings->dSpeed) * inSettings->frameTime * 0.04f); inSettings->thePath->update(inSettings->frameTime); inSettings->thePath->getPoint(inSettings->dDepth + 2, inSettings->thePath->step, inSettings->camPos); inSettings->thePath->getBaseDirection(inSettings->dDepth + 2, inSettings->thePath->step, pathDir); float pathAngle = atan2f(-pathDir[0], -pathDir[2]); glLoadIdentity(); glRotatef((pathAngle + camHeading[0]) * RS_RAD2DEG, 0, 1, 0); glRotatef(camRoll[0] * RS_RAD2DEG, 0, 0, 1); glGetFloatv(GL_MODELVIEW_MATRIX, inSettings->billboardMat); glLoadIdentity(); glRotatef(-camRoll[0] * RS_RAD2DEG, 0, 0, 1); glRotatef((-pathAngle - camHeading[0]) * RS_RAD2DEG, 0, 1, 0); glTranslatef(inSettings->camPos[0]*-1, inSettings->camPos[1]*-1, inSettings->camPos[2]*-1); glGetDoublev(GL_MODELVIEW_MATRIX, inSettings->modelMat); inSettings->unroll = camRoll[0] * RS_RAD2DEG; if(inSettings->dUseGoo){ // calculate diagonal fov float diagFov = 0.5f * float(inSettings->dFov) / RS_RAD2DEG; diagFov = tanf(diagFov); diagFov = sqrtf(diagFov * diagFov + (diagFov * inSettings->aspectRatio * diagFov * inSettings->aspectRatio)); diagFov = 2.0f * atanf(diagFov); inSettings->theGoo->update(inSettings->camPos[0], inSettings->camPos[2], pathAngle + camHeading[0], diagFov, inSettings); } // measure compute time //computeTime += computeTimer.tick(); // start draw time timer //drawTimer.tick(); // clear glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // draw stars glCullFace(GL_BACK); glEnable(GL_CULL_FACE); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glBlendFunc(GL_SRC_ALPHA, GL_ONE); glEnable(GL_BLEND); glEnable(GL_TEXTURE_2D); glActiveTextureARB(GL_TEXTURE2_ARB); glBindTexture(GL_TEXTURE_2D, NULL); glActiveTextureARB(GL_TEXTURE1_ARB); glBindTexture(GL_TEXTURE_2D, NULL); glActiveTextureARB(GL_TEXTURE0_ARB); glBindTexture(GL_TEXTURE_2D, inSettings->flaretex[0]); static float temppos[2]; for(int i=0; i<inSettings->dStars; i++){ temppos[0] = inSettings->stars[i]->pos[0] - inSettings->camPos[0]; temppos[1] = inSettings->stars[i]->pos[2] - inSettings->camPos[2]; if(temppos[0] > inSettings->depth){ inSettings->stars[i]->pos[0] -= inSettings->depth * 2.0f; inSettings->stars[i]->lastPos[0] -= inSettings->depth * 2.0f; } if(temppos[0] < inSettings->depth*-1){ inSettings->stars[i]->pos[0] += inSettings->depth * 2.0f; inSettings->stars[i]->lastPos[0] += inSettings->depth * 2.0f; } if(temppos[1] > inSettings->depth){ inSettings->stars[i]->pos[2] -= inSettings->depth * 2.0f; inSettings->stars[i]->lastPos[2] -= inSettings->depth * 2.0f; } if(temppos[1] < inSettings->depth*-1){ inSettings->stars[i]->pos[2] += inSettings->depth * 2.0f; inSettings->stars[i]->lastPos[2] += inSettings->depth * 2.0f; } inSettings->stars[i]->draw(inSettings->camPos, inSettings->unroll, inSettings->modelMat, inSettings->projMat, inSettings->viewport); } glDisable(GL_CULL_FACE); // pick animated texture frame static float textureTime = 0.0f; textureTime += inSettings->frameTime; // loop frames every 2 seconds const float texFrameTime(2.0f / float(inSettings->numAnimTexFrames)); while(textureTime > texFrameTime){ textureTime -= texFrameTime; inSettings->whichTexture ++; } while(inSettings->whichTexture >= inSettings->numAnimTexFrames) inSettings->whichTexture -= inSettings->numAnimTexFrames; // alpha component gets normalmap lerp value const float lerp = textureTime / texFrameTime; // draw goo if(inSettings->dUseGoo){ // calculate color static float goo_rgb_phase[3] = {-0.1f, -0.1f, -0.1f}; static float goo_rgb_speed[3] = {rsRandf(0.02f) + 0.02f, rsRandf(0.02f) + 0.02f, rsRandf(0.02f) + 0.02f}; float goo_rgb[4]; for(int i=0; i<3; i++){ goo_rgb_phase[i] += goo_rgb_speed[i] * inSettings->frameTime; if(goo_rgb_phase[i] >= RS_PIx2) goo_rgb_phase[i] -= RS_PIx2; goo_rgb[i] = sinf(goo_rgb_phase[i]); if(goo_rgb[i] < 0.0f) goo_rgb[i] = 0.0f; } // setup textures if(inSettings->dShaders){ goo_rgb[3] = lerp; glDisable(GL_TEXTURE_2D); glEnable(GL_TEXTURE_CUBE_MAP_ARB); glActiveTextureARB(GL_TEXTURE2_ARB); glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, inSettings->nebulatex); glActiveTextureARB(GL_TEXTURE1_ARB); glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, inSettings->theWNCM->texture[(inSettings->whichTexture + 1) % inSettings->numAnimTexFrames]); glActiveTextureARB(GL_TEXTURE0_ARB); glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, inSettings->theWNCM->texture[inSettings->whichTexture]); glUseProgramObjectARB(gooProgram); } else{ goo_rgb[3] = 1.0f; glBindTexture(GL_TEXTURE_2D, inSettings->nebulatex); glEnable(GL_TEXTURE_2D); glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP); glEnable(GL_TEXTURE_GEN_S); glEnable(GL_TEXTURE_GEN_T); } // draw it glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glBlendFunc(GL_SRC_ALPHA, GL_ONE); glEnable(GL_BLEND); glColor4fv(goo_rgb); inSettings->theGoo->draw(); if(inSettings->dShaders){ glDisable(GL_TEXTURE_CUBE_MAP_ARB); glUseProgramObjectARB(0); } else{ glDisable(GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_T); } } // update starburst static float starBurstTime = 300.0f; // burst after 5 minutes starBurstTime -= inSettings->frameTime; if(starBurstTime <= 0.0f){ float pos[] = {inSettings->camPos[0] + (pathDir[0] * inSettings->depth * (0.5f + rsRandf(0.5f))), rsRandf(2.0f) - 1.0f, inSettings->camPos[2] + (pathDir[2] * inSettings->depth * (0.5f + rsRandf(0.5f)))}; inSettings->theStarBurst->restart(pos); // it won't actually restart unless it's ready to starBurstTime = rsRandf(240.0f) + 60.0f; // burst again within 1-5 minutes } if(inSettings->dShaders) inSettings->theStarBurst->draw(lerp, inSettings); else inSettings->theStarBurst->draw(inSettings); // draw tunnel if(inSettings->dUseTunnels){ inSettings->theTunnel->make(inSettings->frameTime, inSettings->dShaders); glCullFace(GL_BACK); glEnable(GL_CULL_FACE); glEnable(GL_TEXTURE_2D); if(inSettings->dShaders){ glActiveTextureARB(GL_TEXTURE1_ARB); glBindTexture(GL_TEXTURE_2D, inSettings->theCausticTextures->caustictex[(inSettings->whichTexture + 1) % inSettings->numAnimTexFrames]); glActiveTextureARB(GL_TEXTURE0_ARB); glBindTexture(GL_TEXTURE_2D, inSettings->theCausticTextures->caustictex[inSettings->whichTexture]); glUseProgramObjectARB(tunnelProgram); inSettings->theTunnel->draw(lerp); glUseProgramObjectARB(0); } else{ glBindTexture(GL_TEXTURE_2D, inSettings->theCausticTextures->caustictex[inSettings->whichTexture]); inSettings->theTunnel->draw(); } glDisable(GL_CULL_FACE); } // draw sun with lens flare glDisable(GL_FOG); float flarepos[3] = {0.0f, 2.0f, 0.0f}; glBindTexture(GL_TEXTURE_2D, inSettings->flaretex[0]); inSettings->sunStar->draw(inSettings->camPos, inSettings->unroll, inSettings->modelMat, inSettings->projMat, inSettings->viewport); float diff[3] = {flarepos[0] - inSettings->camPos[0], flarepos[1] - inSettings->camPos[1], flarepos[2] - inSettings->camPos[2]}; float alpha = 0.5f - 0.005f * sqrtf(diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2]); if(alpha > 0.0f) flare(flarepos, 1.0f, 1.0f, 1.0f, alpha, inSettings); glEnable(GL_FOG); // measure draw time //drawTime += drawTimer.tick(); // write text static float totalTime = 0.0f; totalTime += inSettings->frameTime; static std::vector<std::string> strvec; static int frames = 0; ++frames; if(frames == 60){ strvec.clear(); std::string str1 = " FPS = " + to_string(60.0f / totalTime); strvec.push_back(str1); std::string str2 = "compute time = " + to_string(computeTime / 60.0f); strvec.push_back(str2); std::string str3 = " draw time = " + to_string(drawTime / 60.0f); strvec.push_back(str3); totalTime = 0.0f; computeTime = 0.0f; drawTime = 0.0f; frames = 0; } if(inSettings->kStatistics){ glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0.0f, 50.0f * inSettings->aspectRatio, 0.0f, 50.0f, -1.0f, 1.0f); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glTranslatef(1.0f, 48.0f, 0.0f); glColor3f(1.0f, 0.6f, 0.0f); inSettings->textwriter->draw(strvec); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); } #ifdef WIN32 wglSwapLayerBuffers(hdc, WGL_SWAP_MAIN_PLANE); #endif #ifdef RS_XSCREENSAVER glXSwapBuffers(xdisplay, xwindow); #endif }
void SimManager::writeProperties() { // declaration for Logging std::pair<LogCategory, LogLevel> logM = Logger::getLogMode(LC_SOLV, LL_INFO); LOGGER_WRITE_TUPLE("SimManager: Computation time", logM); LOGGER_WRITE_TUPLE("SimManager: Simulation end time: " + to_string(_tEnd), logM); //LOGGER_WRITE("Rechenzeit in Sekunden: " + to_string>(_tClockEnd-_tClockStart), logM); LOGGER_WRITE_TUPLE("Simulation info from solver:", logM); _solver->writeSimulationInfo(); /* // Zeit if(_settings->_globalSettings->bEndlessSim) { LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Geforderte Simulationszeit: endlos"),logM); //LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Rechenzeit: ") + boost::lexical_cast<std::string>(_tClockEnd-_tClockStart),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Endzeit Toleranz: ") + boost::lexical_cast<std::string>(config->getSimControllerSettings()->dTendTol),logM); } else { LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Geforderte Simulationszeit: ") + boost::lexical_cast<std::string>(_tEnd),logM); //_infoStream << "Rechenzeit: " << (_tClockEnd-_tClockStart); //LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Rechenzeit: ") + boost::lexical_cast<std::string>(_tClockEnd-_tClockStart),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Endzeit Toleranz: ") + boost::lexical_cast<std::string>(_config->getSimControllerSettings()->dTendTol),logM); } if(_settings->_globalSettings->bRealtimeSim) { LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Echtzeit Simulationszeit aktiv:"),logM); log->wirte(boost::lexical_cast<std::string>("Faktor: ") + boost::lexical_cast<std::string>(_settings->_globalSettings->dRealtimeFactor),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Aktive Rechenzeit (Pause Zeit): ") + boost::lexical_cast<std::string>(_tClockEnd-_tClockStart-_dataPool->getPauseDelay()) + boost::lexical_cast<std::string>("(") + boost::lexical_cast<std::string>(_dataPool->getPauseDelay()) + boost::lexical_cast<std::string>(")"),logM); } if(_dimSolver == 1) { if(!(_solver->getSolverStatus() & ISolver::ERROR_STOP)) LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Simulation erfolgreich."),logM); else LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Fehler bei der Simulation!"),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Schritte insgesamt des Solvers: ") + boost::lexical_cast<std::string>(_totStps.at(0)),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Akzeptierte Schritte des Solvers: ") + boost::lexical_cast<std::string>(_accStps.at(0)),logM); log->wrtie(boost::lexical_cast<std::string>("Verworfene Schritte des Solvers: ") + boost::lexical_cast<std::string>(_rejStps.at(0)),logM); if(Logger::getInstance()->isOutput(logM) _solver->writeSimulationInfo(); } else { LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Anzahl Solver: ") + boost::lexical_cast<std::string>(_dimSolver),logM) ; if(_completelyDecoupledSystems || !(_settings->bDynCouplingStepSize)) { LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Koppelschrittweitensteuerung: fix "),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Ausgabeschrittweite: ") + boost::lexical_cast<std::string>(_config->getGlobalSettings()->gethOutput()),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Koppelschrittweite: ") + boost::lexical_cast<std::string>(_settings->dHcpl), logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Anzahl Koppelschritte: ") + boost::lexical_cast<std::string>(_totCouplStps),logM) ; if(abs(_settings->_globalSettings->tEnd - _tEnd) < 10*UROUND) LOGGER_WRITE(boost::lexical_cast<std::string>("Integration erfolgreich. IDID= ") + boost::lexical_cast<std::string>(_dbgId), logM); else LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Solver run time simmgr_error. "),logM); } else { LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Koppelschrittweitensteuerung: dynamisch"),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Ausgabeschrittweite: ") + boost::lexical_cast<std::string>(_config->getGlobalSettings()->gethOutput()),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Koppelschrittweite für nächsten Schritt: ") + boost::lexical_cast<std::string>(_H),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Maximal verwendete Schrittweite: ") + boost::lexical_cast<std::string>(_Hmax),logM) ; LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Minimal verwendete Schrittweite: ") + boost::lexical_cast<std::string>(_Hmin),logM) ; LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Obere Grenze für Schrittweite: ") + boost::lexical_cast<std::string>(_settings->dHuplim),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Untere Grenze für Schrittweite: ") + boost::lexical_cast<std::string>(_settings->dHlowlim),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("k-Faktor für Schrittweite: ") + boost::lexical_cast<std::string>(_settings->dK),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Savety-Faktor: ") + boost::lexical_cast<std::string>(_settings->dC),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Upscale-Faktor: ") + boost::lexical_cast<std::string>(_settings->dCmax),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Downscale-Faktor: ") + boost::lexical_cast<std::string>(_settings->dCmin),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Fehlertoleranz: ") + boost::lexical_cast<std::string>(_settings->dErrTol),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Fehlertoleranz für Single Step: ") + boost::lexical_cast<std::string>(_settings->dSingleStepTol),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Anzahl Koppelschritte insgesamt: ") + boost::lexical_cast<std::string>(_totCouplStps),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Anzahl Einfach-Schritte: ") + boost::lexical_cast<std::string>(_singleStps),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Davon akzeptierte Schritte: ") + boost::lexical_cast<std::string>(_accCouplStps),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Davon verworfene Schritte: ") + boost::lexical_cast<std::string>(_rejCouplStps),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Max. nacheinander verwerfbare Schritte: ") + boost::lexical_cast<std::string>(_settings->iMaxRejSteps),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Max. nacheinander verworfene Schritte: ") + boost::lexical_cast<std::string>(_rejCouplStpsRow),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Zeitpunkt meiste verworfene Schritte: ") + boost::lexical_cast<std::string>(_tRejCouplStpsRow),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Anfangsschrittweite: ") + boost::lexical_cast<std::string>(_Hinit),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("bei einem Fehler: ") + boost::lexical_cast<std::string>(_simmgr_errorInit),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("nach verworfenen Schritten: ") + boost::lexical_cast<std::string>(_rejCouplStpsInit),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Wenn Fehler knapp unter 1+ErrTol bei 0 verworf. Schritte, dann war Anfangsschrittweite gut gewählt.\n\n"),logM); if(_dbgId == 0 && (abs(_settings->_globalSettings->tEnd - _tEnd) < 10*UROUND)) LOGGER_WRITE(boost::lexical_cast<std::string>("Integration erfolgreich. IDID= ") + boost::lexical_cast<std::string>(_dbgId) + boost::lexical_cast<std::string>("\n\n"),logM); else if(_dbgId == -1) LOGGER_WRITE(boost::lexical_cast<std::string>("Integration abgebrochen. Fehlerbetrag zu groß (ev. Kopplung zu starr?). IDID= ") + boost::lexical_cast<std::string>(_dbgId),logM); else if(_dbgId == -2) LOGGER_WRITE(boost::lexical_cast<std::string>("Integration abgebrochen. Mehr als ") + boost::lexical_cast<std::string>(_settings->iMaxRejSteps) + boost::lexical_cast<std::string>(" dirket nacheinander verworfenen Schritte. IDID= ") + boost::lexical_cast<std::string>(_dbgId),logM); else if(_dbgId == -3) LOGGER_WRITE(boost::lexical_cast<std::string>("Integration abgebrochen. Koppelschrittweite kleiner als ") + boost::lexical_cast<std::string>(_settings->dHlowlim) + boost::lexical_cast<std::string>(". IDID= ") + boost::lexical_cast<std::string>(_dbgId),logM); else LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Solver run time simmgr_error"),logM); } // Schritte der Solver for(int i=0; i<_dimSolver; ++i) { if(!(_solver[i]->getSolverStatus() & ISolver::ERROR_STOP)) LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Simulation mit Solver[") + boost::lexical_cast<std::string>(i) + boost::lexical_cast<std::string>("] erfolgreich."),logM); else LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Fehler bei der Simulation in Solver[") + boost::lexical_cast<std::string>(i) + boost::lexical_cast<std::string>("]!"),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Schritte insgesamt Solver[") + boost::lexical_cast<std::string>(i) + boost::lexical_cast<std::string>("]: ") + boost::lexical_cast<std::string>(_totStps.at(i)),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Akzeptierte Schritte Solver[") + boost::lexical_cast<std::string>(i) + boost::lexical_cast<std::string>("]: ") + boost::lexical_cast<std::string>(_accStps.at(i)),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("Verworfene Schritte Solver[") + boost::lexical_cast<std::string>(i) + boost::lexical_cast<std::string>("]: ") + boost::lexical_cast<std::string>(_rejStps.at(i)),logM); } // Solver-Properties for(int i=0; i<_dimSolver; ++i) { LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("-----------------------------------------"),logM); LOGGER_WRITE_TUPLE(boost::lexical_cast<std::string>("simmgr_info Ausgabe Solver[") + boost::lexical_cast<std::string>(i) + boost::lexical_cast<std::string>("]"),logM); if(Logger::getInstance()->isOutput(logM)) _solver[i]->writeSimulationInfo(os); } } */ }
void ssa_parser_c::parse() { boost::regex sec_styles_ass_re("^\\s*\\[V4\\+\\s+Styles\\]", boost::regex::perl | boost::regex::icase); boost::regex sec_styles_re( "^\\s*\\[V4\\s+Styles\\]", boost::regex::perl | boost::regex::icase); boost::regex sec_info_re( "^\\s*\\[Script\\s+Info\\]", boost::regex::perl | boost::regex::icase); boost::regex sec_events_re( "^\\s*\\[Events\\]", boost::regex::perl | boost::regex::icase); boost::regex sec_graphics_re( "^\\s*\\[Graphics\\]", boost::regex::perl | boost::regex::icase); boost::regex sec_fonts_re( "^\\s*\\[Fonts\\]", boost::regex::perl | boost::regex::icase); int num = 0; ssa_section_e section = SSA_SECTION_NONE; ssa_section_e previous_section = SSA_SECTION_NONE; std::string name_field = "Name"; std::string attachment_name, attachment_data_uu; m_io->setFilePointer(0, seek_beginning); while (!m_io->eof()) { std::string line; if (!m_io->getline2(line)) break; bool add_to_global = true; // A normal line. Let's see if this file is ASS and not SSA. if (!strcasecmp(line.c_str(), "ScriptType: v4.00+")) m_is_ass = true; else if (boost::regex_search(line, sec_styles_ass_re)) { m_is_ass = true; section = SSA_SECTION_V4STYLES; } else if (boost::regex_search(line, sec_styles_re)) section = SSA_SECTION_V4STYLES; else if (boost::regex_search(line, sec_info_re)) section = SSA_SECTION_INFO; else if (boost::regex_search(line, sec_events_re)) section = SSA_SECTION_EVENTS; else if (boost::regex_search(line, sec_graphics_re)) { section = SSA_SECTION_GRAPHICS; add_to_global = false; } else if (boost::regex_search(line, sec_fonts_re)) { section = SSA_SECTION_FONTS; add_to_global = false; } else if (SSA_SECTION_EVENTS == section) { if (balg::istarts_with(line, "Format: ")) { // Analyze the format string. m_format = split(&line.c_str()[strlen("Format: ")]); strip(m_format); // Let's see if "Actor" is used in the format instead of "Name". size_t i; for (i = 0; m_format.size() > i; ++i) if (balg::iequals(m_format[i], "actor")) { name_field = "Actor"; break; } } else if (balg::istarts_with(line, "Dialogue: ")) { if (m_format.empty()) throw mtx::input::extended_x(Y("ssa_reader: Invalid format. Could not find the \"Format\" line in the \"[Events]\" section.")); std::string orig_line = line; line.erase(0, strlen("Dialogue: ")); // Trim the start. // Split the line into fields. std::vector<std::string> fields = split(line.c_str(), ",", m_format.size()); while (fields.size() < m_format.size()) fields.push_back(std::string("")); // Parse the start time. std::string stime = get_element("Start", fields); int64_t start = parse_time(stime); if (0 > start) { mxwarn_tid(m_file_name, m_tid, boost::format(Y("Malformed line? (%1%)\n")) % orig_line); continue; } // Parse the end time. stime = get_element("End", fields); int64_t end = parse_time(stime); if (0 > end) { mxwarn_tid(m_file_name, m_tid, boost::format(Y("Malformed line? (%1%)\n")) % orig_line); continue; } if (end < start) { mxwarn_tid(m_file_name, m_tid, boost::format(Y("Malformed line? (%1%)\n")) % orig_line); continue; } // Specs say that the following fields are to put into the block: // ReadOrder, Layer, Style, Name, MarginL, MarginR, MarginV, Effect, // Text std::string comma = ","; line = to_string(num) + comma + get_element("Layer", fields) + comma + get_element("Style", fields) + comma + get_element(name_field.c_str(), fields) + comma + get_element("MarginL", fields) + comma + get_element("MarginR", fields) + comma + get_element("MarginV", fields) + comma + get_element("Effect", fields) + comma + recode_text(fields); add(start, end, num, line); num++; add_to_global = false; } } else if ((SSA_SECTION_FONTS == section) || (SSA_SECTION_GRAPHICS == section)) { if (balg::istarts_with(line, "fontname:")) { add_attachment_maybe(attachment_name, attachment_data_uu, section); line.erase(0, strlen("fontname:")); strip(line, true); attachment_name = line; } else { strip(line, true); attachment_data_uu += line; } add_to_global = false; } if (add_to_global) { m_global += line; m_global += "\r\n"; } if (previous_section != section) add_attachment_maybe(attachment_name, attachment_data_uu, previous_section); previous_section = section; } sort(); }
/** Writes a 'referenceArticleId' containning the id of the article referenced @param referencedArticleId: id of the referenced article */ void ExtendedArticlesXMLGenerator::addReference(int referencedArticleId) { addOpenningTag(aXMLFile, "referencedArticleId"); addData(aXMLFile, to_string(referencedArticleId)); addClosingTag(aXMLFile, "referencedArticleId"); }
void testField() { auto const match = [&](field f, string_view s) { BEAST_EXPECT(iequals(to_string(f), s)); BEAST_EXPECT(string_to_field(s) == f); }; match(field::accept, "accept"); match(field::accept, "aCcept"); match(field::accept, "ACCEPT"); match(field::a_im, "A-IM"); match(field::accept, "Accept"); match(field::accept_additions, "Accept-Additions"); match(field::accept_charset, "Accept-Charset"); match(field::accept_datetime, "Accept-Datetime"); match(field::accept_encoding, "Accept-Encoding"); match(field::accept_features, "Accept-Features"); match(field::accept_language, "Accept-Language"); match(field::accept_patch, "Accept-Patch"); match(field::accept_post, "Accept-Post"); match(field::accept_ranges, "Accept-Ranges"); match(field::access_control, "Access-Control"); match(field::access_control_allow_credentials, "Access-Control-Allow-Credentials"); match(field::access_control_allow_headers, "Access-Control-Allow-Headers"); match(field::access_control_allow_methods, "Access-Control-Allow-Methods"); match(field::access_control_allow_origin, "Access-Control-Allow-Origin"); match(field::access_control_max_age, "Access-Control-Max-Age"); match(field::access_control_request_headers, "Access-Control-Request-Headers"); match(field::access_control_request_method, "Access-Control-Request-Method"); match(field::age, "Age"); match(field::allow, "Allow"); match(field::alpn, "ALPN"); match(field::also_control, "Also-Control"); match(field::alt_svc, "Alt-Svc"); match(field::alt_used, "Alt-Used"); match(field::alternate_recipient, "Alternate-Recipient"); match(field::alternates, "Alternates"); match(field::apparently_to, "Apparently-To"); match(field::apply_to_redirect_ref, "Apply-To-Redirect-Ref"); match(field::approved, "Approved"); match(field::archive, "Archive"); match(field::archived_at, "Archived-At"); match(field::article_names, "Article-Names"); match(field::article_updates, "Article-Updates"); match(field::authentication_control, "Authentication-Control"); match(field::authentication_info, "Authentication-Info"); match(field::authentication_results, "Authentication-Results"); match(field::authorization, "Authorization"); match(field::auto_submitted, "Auto-Submitted"); match(field::autoforwarded, "Autoforwarded"); match(field::autosubmitted, "Autosubmitted"); match(field::base, "Base"); match(field::bcc, "Bcc"); match(field::body, "Body"); match(field::c_ext, "C-Ext"); match(field::c_man, "C-Man"); match(field::c_opt, "C-Opt"); match(field::c_pep, "C-PEP"); match(field::c_pep_info, "C-PEP-Info"); match(field::cache_control, "Cache-Control"); match(field::caldav_timezones, "CalDAV-Timezones"); match(field::cancel_key, "Cancel-Key"); match(field::cancel_lock, "Cancel-Lock"); match(field::cc, "Cc"); match(field::close, "Close"); match(field::comments, "Comments"); match(field::compliance, "Compliance"); match(field::connection, "Connection"); match(field::content_alternative, "Content-Alternative"); match(field::content_base, "Content-Base"); match(field::content_description, "Content-Description"); match(field::content_disposition, "Content-Disposition"); match(field::content_duration, "Content-Duration"); match(field::content_encoding, "Content-Encoding"); match(field::content_features, "Content-features"); match(field::content_id, "Content-ID"); match(field::content_identifier, "Content-Identifier"); match(field::content_language, "Content-Language"); match(field::content_length, "Content-Length"); match(field::content_location, "Content-Location"); match(field::content_md5, "Content-MD5"); match(field::content_range, "Content-Range"); match(field::content_return, "Content-Return"); match(field::content_script_type, "Content-Script-Type"); match(field::content_style_type, "Content-Style-Type"); match(field::content_transfer_encoding, "Content-Transfer-Encoding"); match(field::content_type, "Content-Type"); match(field::content_version, "Content-Version"); match(field::control, "Control"); match(field::conversion, "Conversion"); match(field::conversion_with_loss, "Conversion-With-Loss"); match(field::cookie, "Cookie"); match(field::cookie2, "Cookie2"); match(field::cost, "Cost"); match(field::dasl, "DASL"); match(field::date, "Date"); match(field::date_received, "Date-Received"); match(field::dav, "DAV"); match(field::default_style, "Default-Style"); match(field::deferred_delivery, "Deferred-Delivery"); match(field::delivery_date, "Delivery-Date"); match(field::delta_base, "Delta-Base"); match(field::depth, "Depth"); match(field::derived_from, "Derived-From"); match(field::destination, "Destination"); match(field::differential_id, "Differential-ID"); match(field::digest, "Digest"); match(field::discarded_x400_ipms_extensions, "Discarded-X400-IPMS-Extensions"); match(field::discarded_x400_mts_extensions, "Discarded-X400-MTS-Extensions"); match(field::disclose_recipients, "Disclose-Recipients"); match(field::disposition_notification_options, "Disposition-Notification-Options"); match(field::disposition_notification_to, "Disposition-Notification-To"); match(field::distribution, "Distribution"); match(field::dkim_signature, "DKIM-Signature"); match(field::dl_expansion_history, "DL-Expansion-History"); match(field::downgraded_bcc, "Downgraded-Bcc"); match(field::downgraded_cc, "Downgraded-Cc"); match(field::downgraded_disposition_notification_to, "Downgraded-Disposition-Notification-To"); match(field::downgraded_final_recipient, "Downgraded-Final-Recipient"); match(field::downgraded_from, "Downgraded-From"); match(field::downgraded_in_reply_to, "Downgraded-In-Reply-To"); match(field::downgraded_mail_from, "Downgraded-Mail-From"); match(field::downgraded_message_id, "Downgraded-Message-Id"); match(field::downgraded_original_recipient, "Downgraded-Original-Recipient"); match(field::downgraded_rcpt_to, "Downgraded-Rcpt-To"); match(field::downgraded_references, "Downgraded-References"); match(field::downgraded_reply_to, "Downgraded-Reply-To"); match(field::downgraded_resent_bcc, "Downgraded-Resent-Bcc"); match(field::downgraded_resent_cc, "Downgraded-Resent-Cc"); match(field::downgraded_resent_from, "Downgraded-Resent-From"); match(field::downgraded_resent_reply_to, "Downgraded-Resent-Reply-To"); match(field::downgraded_resent_sender, "Downgraded-Resent-Sender"); match(field::downgraded_resent_to, "Downgraded-Resent-To"); match(field::downgraded_return_path, "Downgraded-Return-Path"); match(field::downgraded_sender, "Downgraded-Sender"); match(field::downgraded_to, "Downgraded-To"); match(field::ediint_features, "EDIINT-Features"); match(field::eesst_version, "Eesst-Version"); match(field::encoding, "Encoding"); match(field::encrypted, "Encrypted"); match(field::errors_to, "Errors-To"); match(field::etag, "ETag"); match(field::expect, "Expect"); match(field::expires, "Expires"); match(field::expiry_date, "Expiry-Date"); match(field::ext, "Ext"); match(field::followup_to, "Followup-To"); match(field::forwarded, "Forwarded"); match(field::from, "From"); match(field::generate_delivery_report, "Generate-Delivery-Report"); match(field::getprofile, "GetProfile"); match(field::hobareg, "Hobareg"); match(field::host, "Host"); match(field::http2_settings, "HTTP2-Settings"); match(field::if_, "If"); match(field::if_match, "If-Match"); match(field::if_modified_since, "If-Modified-Since"); match(field::if_none_match, "If-None-Match"); match(field::if_range, "If-Range"); match(field::if_schedule_tag_match, "If-Schedule-Tag-Match"); match(field::if_unmodified_since, "If-Unmodified-Since"); match(field::im, "IM"); match(field::importance, "Importance"); match(field::in_reply_to, "In-Reply-To"); match(field::incomplete_copy, "Incomplete-Copy"); match(field::injection_date, "Injection-Date"); match(field::injection_info, "Injection-Info"); match(field::jabber_id, "Jabber-ID"); match(field::keep_alive, "Keep-Alive"); match(field::keywords, "Keywords"); match(field::label, "Label"); match(field::language, "Language"); match(field::last_modified, "Last-Modified"); match(field::latest_delivery_time, "Latest-Delivery-Time"); match(field::lines, "Lines"); match(field::link, "Link"); match(field::list_archive, "List-Archive"); match(field::list_help, "List-Help"); match(field::list_id, "List-ID"); match(field::list_owner, "List-Owner"); match(field::list_post, "List-Post"); match(field::list_subscribe, "List-Subscribe"); match(field::list_unsubscribe, "List-Unsubscribe"); match(field::list_unsubscribe_post, "List-Unsubscribe-Post"); match(field::location, "Location"); match(field::lock_token, "Lock-Token"); match(field::man, "Man"); match(field::max_forwards, "Max-Forwards"); match(field::memento_datetime, "Memento-Datetime"); match(field::message_context, "Message-Context"); match(field::message_id, "Message-ID"); match(field::message_type, "Message-Type"); match(field::meter, "Meter"); match(field::method_check, "Method-Check"); match(field::method_check_expires, "Method-Check-Expires"); match(field::mime_version, "MIME-Version"); match(field::mmhs_acp127_message_identifier, "MMHS-Acp127-Message-Identifier"); match(field::mmhs_authorizing_users, "MMHS-Authorizing-Users"); match(field::mmhs_codress_message_indicator, "MMHS-Codress-Message-Indicator"); match(field::mmhs_copy_precedence, "MMHS-Copy-Precedence"); match(field::mmhs_exempted_address, "MMHS-Exempted-Address"); match(field::mmhs_extended_authorisation_info, "MMHS-Extended-Authorisation-Info"); match(field::mmhs_handling_instructions, "MMHS-Handling-Instructions"); match(field::mmhs_message_instructions, "MMHS-Message-Instructions"); match(field::mmhs_message_type, "MMHS-Message-Type"); match(field::mmhs_originator_plad, "MMHS-Originator-PLAD"); match(field::mmhs_originator_reference, "MMHS-Originator-Reference"); match(field::mmhs_other_recipients_indicator_cc, "MMHS-Other-Recipients-Indicator-CC"); match(field::mmhs_other_recipients_indicator_to, "MMHS-Other-Recipients-Indicator-To"); match(field::mmhs_primary_precedence, "MMHS-Primary-Precedence"); match(field::mmhs_subject_indicator_codes, "MMHS-Subject-Indicator-Codes"); match(field::mt_priority, "MT-Priority"); match(field::negotiate, "Negotiate"); match(field::newsgroups, "Newsgroups"); match(field::nntp_posting_date, "NNTP-Posting-Date"); match(field::nntp_posting_host, "NNTP-Posting-Host"); match(field::non_compliance, "Non-Compliance"); match(field::obsoletes, "Obsoletes"); match(field::opt, "Opt"); match(field::optional, "Optional"); match(field::optional_www_authenticate, "Optional-WWW-Authenticate"); match(field::ordering_type, "Ordering-Type"); match(field::organization, "Organization"); match(field::origin, "Origin"); match(field::original_encoded_information_types, "Original-Encoded-Information-Types"); match(field::original_from, "Original-From"); match(field::original_message_id, "Original-Message-ID"); match(field::original_recipient, "Original-Recipient"); match(field::original_sender, "Original-Sender"); match(field::original_subject, "Original-Subject"); match(field::originator_return_address, "Originator-Return-Address"); match(field::overwrite, "Overwrite"); match(field::p3p, "P3P"); match(field::path, "Path"); match(field::pep, "PEP"); match(field::pep_info, "Pep-Info"); match(field::pics_label, "PICS-Label"); match(field::position, "Position"); match(field::posting_version, "Posting-Version"); match(field::pragma, "Pragma"); match(field::prefer, "Prefer"); match(field::preference_applied, "Preference-Applied"); match(field::prevent_nondelivery_report, "Prevent-NonDelivery-Report"); match(field::priority, "Priority"); match(field::privicon, "Privicon"); match(field::profileobject, "ProfileObject"); match(field::protocol, "Protocol"); match(field::protocol_info, "Protocol-Info"); match(field::protocol_query, "Protocol-Query"); match(field::protocol_request, "Protocol-Request"); match(field::proxy_authenticate, "Proxy-Authenticate"); match(field::proxy_authentication_info, "Proxy-Authentication-Info"); match(field::proxy_authorization, "Proxy-Authorization"); match(field::proxy_connection, "Proxy-Connection"); match(field::proxy_features, "Proxy-Features"); match(field::proxy_instruction, "Proxy-Instruction"); match(field::public_, "Public"); match(field::public_key_pins, "Public-Key-Pins"); match(field::public_key_pins_report_only, "Public-Key-Pins-Report-Only"); match(field::range, "Range"); match(field::received, "Received"); match(field::received_spf, "Received-SPF"); match(field::redirect_ref, "Redirect-Ref"); match(field::references, "References"); match(field::referer, "Referer"); match(field::referer_root, "Referer-Root"); match(field::relay_version, "Relay-Version"); match(field::reply_by, "Reply-By"); match(field::reply_to, "Reply-To"); match(field::require_recipient_valid_since, "Require-Recipient-Valid-Since"); match(field::resent_bcc, "Resent-Bcc"); match(field::resent_cc, "Resent-Cc"); match(field::resent_date, "Resent-Date"); match(field::resent_from, "Resent-From"); match(field::resent_message_id, "Resent-Message-ID"); match(field::resent_reply_to, "Resent-Reply-To"); match(field::resent_sender, "Resent-Sender"); match(field::resent_to, "Resent-To"); match(field::resolution_hint, "Resolution-Hint"); match(field::resolver_location, "Resolver-Location"); match(field::retry_after, "Retry-After"); match(field::return_path, "Return-Path"); match(field::safe, "Safe"); match(field::schedule_reply, "Schedule-Reply"); match(field::schedule_tag, "Schedule-Tag"); match(field::sec_websocket_accept, "Sec-WebSocket-Accept"); match(field::sec_websocket_extensions, "Sec-WebSocket-Extensions"); match(field::sec_websocket_key, "Sec-WebSocket-Key"); match(field::sec_websocket_protocol, "Sec-WebSocket-Protocol"); match(field::sec_websocket_version, "Sec-WebSocket-Version"); match(field::security_scheme, "Security-Scheme"); match(field::see_also, "See-Also"); match(field::sender, "Sender"); match(field::sensitivity, "Sensitivity"); match(field::server, "Server"); match(field::set_cookie, "Set-Cookie"); match(field::set_cookie2, "Set-Cookie2"); match(field::setprofile, "SetProfile"); match(field::sio_label, "SIO-Label"); match(field::sio_label_history, "SIO-Label-History"); match(field::slug, "SLUG"); match(field::soapaction, "SoapAction"); match(field::solicitation, "Solicitation"); match(field::status_uri, "Status-URI"); match(field::strict_transport_security, "Strict-Transport-Security"); match(field::subject, "Subject"); match(field::subok, "SubOK"); match(field::subst, "Subst"); match(field::summary, "Summary"); match(field::supersedes, "Supersedes"); match(field::surrogate_capability, "Surrogate-Capability"); match(field::surrogate_control, "Surrogate-Control"); match(field::tcn, "TCN"); match(field::te, "TE"); match(field::timeout, "Timeout"); match(field::title, "Title"); match(field::to, "To"); match(field::topic, "Topic"); match(field::trailer, "Trailer"); match(field::transfer_encoding, "Transfer-Encoding"); match(field::ttl, "TTL"); match(field::ua_color, "UA-Color"); match(field::ua_media, "UA-Media"); match(field::ua_pixels, "UA-Pixels"); match(field::ua_resolution, "UA-Resolution"); match(field::ua_windowpixels, "UA-Windowpixels"); match(field::upgrade, "Upgrade"); match(field::urgency, "Urgency"); match(field::uri, "URI"); match(field::user_agent, "User-Agent"); match(field::variant_vary, "Variant-Vary"); match(field::vary, "Vary"); match(field::vbr_info, "VBR-Info"); match(field::version, "Version"); match(field::via, "Via"); match(field::want_digest, "Want-Digest"); match(field::warning, "Warning"); match(field::www_authenticate, "WWW-Authenticate"); match(field::x_archived_at, "X-Archived-At"); match(field::x_device_accept, "X-Device-Accept"); match(field::x_device_accept_charset, "X-Device-Accept-Charset"); match(field::x_device_accept_encoding, "X-Device-Accept-Encoding"); match(field::x_device_accept_language, "X-Device-Accept-Language"); match(field::x_device_user_agent, "X-Device-User-Agent"); match(field::x_frame_options, "X-Frame-Options"); match(field::x_mittente, "X-Mittente"); match(field::x_pgp_sig, "X-PGP-Sig"); match(field::x_ricevuta, "X-Ricevuta"); match(field::x_riferimento_message_id, "X-Riferimento-Message-ID"); match(field::x_tiporicevuta, "X-TipoRicevuta"); match(field::x_trasporto, "X-Trasporto"); match(field::x_verificasicurezza, "X-VerificaSicurezza"); match(field::x400_content_identifier, "X400-Content-Identifier"); match(field::x400_content_return, "X400-Content-Return"); match(field::x400_content_type, "X400-Content-Type"); match(field::x400_mts_identifier, "X400-MTS-Identifier"); match(field::x400_originator, "X400-Originator"); match(field::x400_received, "X400-Received"); match(field::x400_recipients, "X400-Recipients"); match(field::x400_trace, "X400-Trace"); match(field::xref, "Xref"); auto const unknown = [&](string_view s) { BEAST_EXPECT(string_to_field(s) == field::unknown); }; unknown(""); unknown("x"); }
void statsinfo::draw() { uielement::draw(); if (active) { statlabel.drawline(stats->getname(), position + vector2d(73, 25)); statlabel.drawline(stats->getjobname(), position + vector2d(73, 43)); statlabel.drawline("", position + vector2d(73, 61)); //guild statlabel.drawline(to_string(stats->getstat(MS_FAME)), position + vector2d(73, 79)); statlabel.drawline(to_string(stats->getmindamage()) + " ~ " + to_string(stats->getmaxdamage()), position + vector2d(73, 97)); statlabel.drawline(to_string(stats->getstat(MS_HP)) + " / " + to_string(stats->gettotal(MS_MAXHP)), position + vector2d(73, 115)); statlabel.drawline(to_string(stats->getstat(MS_MP)) + " / " + to_string(stats->gettotal(MS_MAXMP)), position + vector2d(73, 133)); statlabel.drawline(to_string(stats->getstat(MS_AP)), position + vector2d(79, 175)); statlabel.drawline(to_string(stats->getstat(MS_STR) + invent->gettotal(ES_STR)) + " (" + to_string(stats->getstat(MS_STR)) + " + " + to_string(invent->gettotal(ES_STR)) + ")", position + vector2d(73, 202)); statlabel.drawline(to_string(stats->getstat(MS_DEX) + invent->gettotal(ES_DEX)) + " (" + to_string(stats->getstat(MS_DEX)) + " + " + to_string(invent->gettotal(ES_DEX)) + ")", position + vector2d(73, 220)); statlabel.drawline(to_string(stats->getstat(MS_INT) + invent->gettotal(ES_INT)) + " (" + to_string(stats->getstat(MS_INT)) + " + " + to_string(invent->gettotal(ES_INT)) + ")", position + vector2d(73, 238)); statlabel.drawline(to_string(stats->getstat(MS_LUK) + invent->gettotal(ES_LUK)) + " (" + to_string(stats->getstat(MS_LUK)) + " + " + to_string(invent->gettotal(ES_LUK)) + ")", position + vector2d(73, 256)); if (showdetail) { vector2d detailpos = position + vector2d(213, 0); for (vector<texture>::iterator dtit = detailbgs.begin(); dtit != detailbgs.end(); ++dtit) { dtit->draw(detailpos); } abilities["none"].draw(detailpos); string critstr = to_string(static_cast<int>(stats->getcritical() * 100)); string mincritstr = to_string(static_cast<int>(stats->getmincrit() * 100)); string maxcritstr = to_string(static_cast<int>(stats->getmaxcrit() * 100)); string bdmstr = to_string(static_cast<int>(stats->getbossdmg() * 100)); string idefstr = to_string(static_cast<int>(stats->getignoredef() * 100)); string resistr = to_string(static_cast<int>(stats->getresist() * 100)); string stancestr = to_string(static_cast<int>(stats->getstance() * 100)); statlabel.drawline(to_string(stats->getattack()), detailpos + vector2d(73, 35)); statlabel.drawline(critstr + "%", detailpos + vector2d(73, 53)); statlabel.drawline(mincritstr + "%", detailpos + vector2d(73, 71)); statlabel.drawline(maxcritstr + "%", detailpos + vector2d(168, 71)); statlabel.drawline(bdmstr + "%", detailpos + vector2d(73, 89)); statlabel.drawline(idefstr + "%", detailpos + vector2d(168, 89)); statlabel.drawline(resistr + "%", detailpos + vector2d(73, 107)); statlabel.drawline(stancestr + "%", detailpos + vector2d(168, 107)); statlabel.drawline(to_string(invent->gettotal(ES_WDEF)), detailpos + vector2d(73, 125)); statlabel.drawline(to_string(invent->gettotal(ES_MDEF)), detailpos + vector2d(73, 143)); statlabel.drawline(to_string(stats->getaccuracy() + invent->getaccuracy()), detailpos + vector2d(73, 161)); statlabel.drawline("0", detailpos + vector2d(73, 179)); statlabel.drawline(to_string(invent->gettotal(ES_AVOID)), detailpos + vector2d(73, 197)); statlabel.drawline("0", detailpos + vector2d(73, 215)); statlabel.drawline(to_string(invent->gettotal(ES_SPEED) + 100) + "%", detailpos + vector2d(73, 233)); statlabel.drawline(to_string(invent->gettotal(ES_JUMP) + 100) + "%", detailpos + vector2d(168, 233)); statlabel.drawline(to_string(stats->gethonor()), detailpos + vector2d(73, 351)); } } }
rw::math::Q pathPlanning::invKin(double dx, double dy , double dz) { rw::kinematics::State state = this->state; rw::math::Transform3D<> t_tool_base = this->device.get()->baseTframe(this->toolFrame,state); Eigen::MatrixXd jq(this->device.get()->baseJframe(this->toolFrame,state).e().cols(), this->device.get()->baseJframe(this->toolFrame,state).e().rows()); jq = this->device.get()->baseJframe(this->toolFrame,state).e(); //cout << "Determinant: " <<rw::math::LinearAlgebra::det(jq) << endl; //Least square solver - dq = [j(q)]T (j(q)[j(q)]T)⁻1 du <=> dq = A*du Eigen::MatrixXd A (6,6); //A = jq.transpose()*(jq*jq.transpose()).inverse(); A = (jq*jq.transpose()).inverse()*jq.transpose(); std::vector<rw::math::Transform3D<> > out = sphere(dx,dy,dz); std::ofstream outfile; outfile.open("q_conf.txt", std::ios_base::app); cout << "invKin" << endl; for(unsigned int i = 0; i <= out.size() ; ++i ) { cout << "\r"+to_string(i); rw::math::Vector3D<> dif_p = out[i].P()-t_tool_base.P(); Eigen::Matrix3d dif = out[i].R().e()- t_tool_base.R().e(); rw::math::Rotation3D<> dif_r(dif); rw::math::RPY<> dif_rot(dif_r); Eigen::VectorXd du(6); du(0) = dif_p[0]; du(1) = dif_p[1]; du(2) = dif_p[2]; du(3) = dif_rot[0]; du(4) = dif_rot[1]; du(5) = dif_rot[2]; Eigen::VectorXd q(6); q = A*du; rw::math::Q q_current; q_current = this->device->getQ(this->state); rw::math::Q dq(q); rw::math::Q q_new = q_current+ dq; if(!collision(q_new) && !within_bound(q_new)) { std::string text = "setQ{" + to_string(q_new[0]) + ", " + to_string(q_new[1]) + ", " + to_string(q_new[2]) + ", " + to_string(q_new[3]) + ", " + to_string(q_new[4]) + ", " + to_string(q_new[5]) + "}"; //cout << text << endl; outfile << text << endl; } else { cout << endl; //cout << "\rfalse"; //cout << "collision" << endl; } } rw::math::Q bla(6); //Just used the text file for debugging purposes, Which why I just return a random Q config. return bla; }
std::string generateUuid() { boost::uuids::uuid u = boost::uuids::random_generator()(); return to_string(u); }
gsl_matrix * bootstrap_and_calc_adj_matrix( gsl_matrix * A, size_t num_steps, decimal threshold, CoexpressionMeasure filter, void (* interaction_matrix_generator_fnc)(gsl_matrix *, gsl_matrix *, CoexpressionMeasure), bool use_tmp_file = false ) { size_t num_elems = A->size1; //num_obs = A->size2; gsl_matrix * interaction = gsl_matrix_calloc(num_elems, num_elems); interaction_matrix_generator_fnc(A, interaction, filter); // Bootstrapping std::list<gsl_matrix *> boot_matrix; { detail::write_matrix_3d write_boot_matrix; if (use_tmp_file) write_boot_matrix.set_filename("tmp_file.out"); boost::mt19937 rng(time(NULL) - num_steps - int(threshold * 100)); for (size_t i = 0; i < num_steps; ++i) { std::cout << "step = " << i << std::endl; // DEBUG bootstrap_and_calc_adj_matrix_helper(A, boot_matrix, write_boot_matrix, filter, rng, interaction_matrix_generator_fnc, use_tmp_file); } } // Compute adjacency matrix detail::read_matrix_3d read_boot_matrix(num_elems, num_elems, num_steps); if (use_tmp_file) read_boot_matrix.set_filename("tmp_file.out"); gsl_matrix * adj_matrix = gsl_matrix_alloc(num_elems, num_elems); for (size_t r = 0; r < num_elems; ++r) { for (size_t c = 0; c < num_elems; ++c) { double value = gsl_matrix_get(interaction, r, c); gsl_vector * boot_z_vec = gsl_vector_calloc(num_steps); if (use_tmp_file) { read_boot_matrix.read(r, c, boot_z_vec); } else { size_t i = 0; for (std::list<gsl_matrix *>::iterator li = boot_matrix.begin(); li != boot_matrix.end(); ++li, ++i) gsl_vector_set(boot_z_vec, i, gsl_matrix_get(*li, r, c)); } double mean = gsl_stats_mean(boot_z_vec->data, boot_z_vec->stride, num_steps), sd = gsl_stats_sd(boot_z_vec->data, boot_z_vec->stride, num_steps); // DEBUG std::string filename = "boot_" + to_string(r) + "_" + to_string(c) + ".out"; FILE * outfile = fopen(filename.c_str(), "wb"); gsl_vector_fwrite(outfile, boot_z_vec); fclose(outfile); // END DEBUG if (value < (mean - threshold * sd) || value > (mean + threshold * sd)) gsl_matrix_set(adj_matrix, r, c, value); else gsl_matrix_set(adj_matrix, r, c, 0.0); gsl_vector_free(boot_z_vec); } } // Free interaction matrices gsl_matrix_free(interaction); if (!use_tmp_file) for (std::list<gsl_matrix *>::iterator li = boot_matrix.begin(); li != boot_matrix.end(); ++li) gsl_matrix_free(*li); return adj_matrix; }
bool isProcessRunning(int pid, const std::string &fileName) { if (pid <= 0) return false; qiLogDebug() << "Checking if process #" << pid << " is running"; std::string commandLine; #if BOOST_OS_WINDOWS HANDLE processHandle = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, static_cast<DWORD>(pid)); if (!processHandle) return false; qiLogDebug() << "Got handle for process #" << pid; DWORD exitCode = 0xFFFFFF; if (!GetExitCodeProcess(processHandle, &exitCode)) return false; if (exitCode != STILL_ACTIVE) return false; qiLogDebug() << "Process #" << pid << " is running"; if (fileName.empty()) return true; qiLogDebug() << "Checking process name for #" << pid; WCHAR winCommandLine[MAX_PATH]; DWORD clSize = GetProcessImageFileNameW( processHandle, winCommandLine, sizeof(winCommandLine) / sizeof(*winCommandLine)); CloseHandle(processHandle); if(clSize <= 0) return false; commandLine = qi::Path::fromNative(winCommandLine).str(); #elif BOOST_OS_MACOS int numberOfProcesses = proc_listpids(PROC_ALL_PIDS, 0, NULL, 0); if (numberOfProcesses == 0) { qiLogError() << "Cannot get number of processes"; return false; } std::vector<int> pids(numberOfProcesses, 0); numberOfProcesses = proc_listpids(PROC_ALL_PIDS, 0, pids.data(), sizeof(int) * pids.size()); if (numberOfProcesses == 0) { qiLogError() << "Cannot get list of processes"; return false; } if (std::find(pids.begin(), pids.end(), pid) == pids.end()) return false; if (fileName.empty()) return true; char procPidPath[PROC_PIDPATHINFO_MAXSIZE]; int res = proc_pidpath(pid, procPidPath, sizeof(char) * PROC_PIDPATHINFO_MAXSIZE); if (!res) { qiLogDebug() << "Failed to get process info: " << strerror(errno); return false; } commandLine = procPidPath; #else // Linux std::string pathInProc = "/proc/" + to_string(pid) + "/cmdline"; std::ifstream file(pathInProc); qiLogDebug() << "process #" << pid << " " << (file.is_open() ? "exists" : "does not exist"); if (!file) return false; if (fileName.empty()) { file.close(); return true; } std::getline(file, commandLine, '\0'); file.close(); #endif qiLogDebug() << "process #" << pid << " full command was: " << commandLine; const std::string actualProcessName = qi::Path(commandLine).filename(); qiLogDebug() << "process #" << pid << " executable was: " << actualProcessName << ", expected: " << (fileName + qi::path::detail::binSuffix()); return actualProcessName == (fileName + qi::path::detail::binSuffix()); }
void sinsp_filter_check::string_to_rawval(const char* str, uint32_t len, ppm_param_type ptype) { switch(ptype) { case PT_INT8: *(int8_t*)(&m_val_storage[0]) = sinsp_numparser::parsed8(str); break; case PT_INT16: *(int16_t*)(&m_val_storage[0]) = sinsp_numparser::parsed16(str); break; case PT_INT32: *(int32_t*)(&m_val_storage[0]) = sinsp_numparser::parsed32(str); break; case PT_INT64: case PT_FD: case PT_ERRNO: *(int64_t*)(&m_val_storage[0]) = sinsp_numparser::parsed64(str); break; case PT_L4PROTO: // This can be resolved in the future case PT_FLAGS8: case PT_UINT8: *(uint8_t*)(&m_val_storage[0]) = sinsp_numparser::parseu8(str); break; case PT_PORT: // This can be resolved in the future case PT_FLAGS16: case PT_UINT16: *(uint16_t*)(&m_val_storage[0]) = sinsp_numparser::parseu16(str); break; case PT_FLAGS32: case PT_UINT32: *(uint32_t*)(&m_val_storage[0]) = sinsp_numparser::parseu32(str); break; case PT_UINT64: *(uint64_t*)(&m_val_storage[0]) = sinsp_numparser::parseu64(str); break; case PT_RELTIME: case PT_ABSTIME: *(uint64_t*)(&m_val_storage[0]) = sinsp_numparser::parseu64(str); break; case PT_CHARBUF: case PT_SOCKADDR: case PT_SOCKFAMILY: { len = (uint32_t)strlen(str); if(len >= m_val_storage.size()) { throw sinsp_exception("filter parameter too long:" + string(str)); } memcpy((&m_val_storage[0]), str, len); m_val_storage[len] = 0; } break; case PT_BOOL: if(string(str) == "true") { *(uint32_t*)(&m_val_storage[0]) = 1; } else if(string(str) == "false") { *(uint32_t*)(&m_val_storage[0]) = 0; } else { throw sinsp_exception("filter error: unrecognized boolean value " + string(str)); } break; case PT_IPV4ADDR: if(inet_pton(AF_INET, str, (&m_val_storage[0])) != 1) { throw sinsp_exception("unrecognized IP address " + string(str)); } break; case PT_BYTEBUF: if(len >= m_val_storage.size()) { throw sinsp_exception("filter parameter too long:" + string(str)); } memcpy((&m_val_storage[0]), str, len); m_val_storage_len = len; break; default: ASSERT(false); throw sinsp_exception("wrong event type " + to_string((long long) m_field->m_type)); } }
char* sinsp_filter_check::rawval_to_string(uint8_t* rawval, const filtercheck_field_info* finfo, uint32_t len) { char* prfmt; ASSERT(rawval != NULL); ASSERT(finfo != NULL); switch(finfo->m_type) { case PT_INT8: if(finfo->m_print_format == PF_DEC) { prfmt = (char*)"%" PRId8; } else if(finfo->m_print_format == PF_HEX) { prfmt = (char*)"%" PRIX8; } else { ASSERT(false); return NULL; } snprintf(m_getpropertystr_storage, sizeof(m_getpropertystr_storage), prfmt, *(int8_t *)rawval); return m_getpropertystr_storage; case PT_INT16: if(finfo->m_print_format == PF_DEC) { prfmt = (char*)"%" PRId16; } else if(finfo->m_print_format == PF_HEX) { prfmt = (char*)"%" PRIX16; } else { ASSERT(false); return NULL; } snprintf(m_getpropertystr_storage, sizeof(m_getpropertystr_storage), prfmt, *(int16_t *)rawval); return m_getpropertystr_storage; case PT_INT32: if(finfo->m_print_format == PF_DEC) { prfmt = (char*)"%" PRId32; } else if(finfo->m_print_format == PF_HEX) { prfmt = (char*)"%" PRIX32; } else { ASSERT(false); return NULL; } snprintf(m_getpropertystr_storage, sizeof(m_getpropertystr_storage), prfmt, *(int32_t *)rawval); return m_getpropertystr_storage; case PT_INT64: case PT_PID: case PT_ERRNO: if(finfo->m_print_format == PF_DEC) { prfmt = (char*)"%" PRId64; } else if(finfo->m_print_format == PF_10_PADDED_DEC) { prfmt = (char*)"%09" PRId64; } else if(finfo->m_print_format == PF_HEX) { prfmt = (char*)"%" PRIX64; } else { prfmt = (char*)"%" PRId64; } snprintf(m_getpropertystr_storage, sizeof(m_getpropertystr_storage), prfmt, *(int64_t *)rawval); return m_getpropertystr_storage; case PT_L4PROTO: // This can be resolved in the future case PT_UINT8: if(finfo->m_print_format == PF_DEC) { prfmt = (char*)"%" PRIu8; } else if(finfo->m_print_format == PF_HEX) { prfmt = (char*)"%" PRIu8; } else { ASSERT(false); return NULL; } snprintf(m_getpropertystr_storage, sizeof(m_getpropertystr_storage), prfmt, *(uint8_t *)rawval); return m_getpropertystr_storage; case PT_PORT: // This can be resolved in the future case PT_UINT16: if(finfo->m_print_format == PF_DEC) { prfmt = (char*)"%" PRIu16; } else if(finfo->m_print_format == PF_HEX) { prfmt = (char*)"%" PRIu16; } else { ASSERT(false); return NULL; } snprintf(m_getpropertystr_storage, sizeof(m_getpropertystr_storage), prfmt, *(uint16_t *)rawval); return m_getpropertystr_storage; case PT_UINT32: if(finfo->m_print_format == PF_DEC) { prfmt = (char*)"%" PRIu32; } else if(finfo->m_print_format == PF_HEX) { prfmt = (char*)"%" PRIu32; } else { ASSERT(false); return NULL; } snprintf(m_getpropertystr_storage, sizeof(m_getpropertystr_storage), prfmt, *(uint32_t *)rawval); return m_getpropertystr_storage; case PT_UINT64: case PT_RELTIME: case PT_ABSTIME: if(finfo->m_print_format == PF_DEC) { prfmt = (char*)"%" PRIu64; } else if(finfo->m_print_format == PF_10_PADDED_DEC) { prfmt = (char*)"%09" PRIu64; } else if(finfo->m_print_format == PF_HEX) { prfmt = (char*)"%" PRIX64; } else { ASSERT(false); return NULL; } snprintf(m_getpropertystr_storage, sizeof(m_getpropertystr_storage), prfmt, *(uint64_t *)rawval); return m_getpropertystr_storage; case PT_CHARBUF: return (char*)rawval; case PT_BYTEBUF: if(rawval[len] == 0) { return (char*)rawval; } else { ASSERT(len < 1024 * 1024); if(len >= m_val_storage.size()) { m_val_storage.resize(len + 1); } memcpy(&m_val_storage[0], rawval, len); m_val_storage[len] = 0; return (char*)&m_val_storage[0]; } case PT_SOCKADDR: ASSERT(false); return NULL; case PT_SOCKFAMILY: ASSERT(false); return NULL; case PT_BOOL: if(*(uint32_t*)rawval != 0) { return (char*)"true"; } else { return (char*)"false"; } case PT_IPV4ADDR: snprintf(m_getpropertystr_storage, sizeof(m_getpropertystr_storage), "%" PRIu8 ".%" PRIu8 ".%" PRIu8 ".%" PRIu8, rawval[0], rawval[1], rawval[2], rawval[3]); return m_getpropertystr_storage; default: ASSERT(false); throw sinsp_exception("wrong event type " + to_string((long long) finfo->m_type)); } }
//Method of passing text needs refactoring void Game::Render(sf::Text fpsText, float fps, sf::Text preyText, sf::Text predText, sf::Text boidText, sf::Text dSepText, sf::Text dAliText, sf::Text dCohText, sf::Text dSepWText, sf::Text dAliWText, sf::Text dCohWText) { _window.clear(); //Updating and drawing text can possibly be put in it's own function as well fpsText.setString("Frames per Second: " + to_string(int(fps + 0.5))); _window.draw(fpsText); preyText.setString("Total Prey Count: " + to_string(flock.preyCount())); _window.draw(preyText); predText.setString("Total Predator Count: " + to_string(flock.predCount())); _window.draw(predText); boidText.setString("Total Boid Count: " + to_string(flock.getSize())); _window.draw(boidText); dSepText.setString("Separation Amount: " + to_string(int(flock.getBoid(0).getDesSep() + 0.5))); _window.draw(dSepText); dAliText.setString("Alignment Amount: " + to_string(int(flock.getBoid(0).getDesAli() + 0.5))); _window.draw(dAliText); dCohText.setString("Cohesion Amount: " + to_string(int(flock.getBoid(0).getDesCoh() + 0.5))); _window.draw(dCohText); dSepWText.setString("Separation Weight: " + to_string(flock.getBoid(0).getSepW())); _window.draw(dSepWText); dAliWText.setString("Alignment Weight: " + to_string(flock.getBoid(0).getAliW())); _window.draw(dAliWText); dCohWText.setString("Cohesion Weight: " + to_string(flock.getBoid(0).getCohW())); _window.draw(dCohWText); // Draws all of the Boids out, and applies functions that are needed to update. for (int i = 0; i < shapes.size(); i++) { _window.draw(shapes[i]); /*Drawing and updating of the boids FOV if (flock.getBoid(i).predatorStatus()) { window.draw(FOVs[i]); FOVs[i].setPosition(flock.getBoid(i).location.x, flock.getBoid(i).location.y); FOVs[i].move(-20, -12); } */ //cout << "Boid "<< i <<" Coordinates: (" << shapes[i].getPosition().x << ", " << shapes[i].getPosition().y << ")" << endl; //cout << "Boid Code " << i << " Location: (" << flock.getBoid(i).location.x << ", " << flock.getBoid(i).location.y << ")" << endl; // Matches up the location of the shape to the boid shapes[i].setPosition(flock.getBoid(i).location.x, flock.getBoid(i).location.y); // Calculates the angle where the velocity is pointing so that the triangle turns towards it. float theta = flock.getBoid(i).getAngle(flock.getBoid(i).velocity); shapes[i].setRotation(theta); // Prevent boids from moving off the screen through wrapping // If boid exits right boundary if (shapes[i].getPosition().x > _window_width) shapes[i].setPosition(shapes[i].getPosition().x - _window_width, shapes[i].getPosition().y); // If boid exits bottom boundary if (shapes[i].getPosition().y > _window_height) shapes[i].setPosition(shapes[i].getPosition().x, shapes[i].getPosition().y - _window_height); // If boid exits left boundary if (shapes[i].getPosition().x < 0) shapes[i].setPosition(shapes[i].getPosition().x + _window_width, shapes[i].getPosition().y); // If boid exits top boundary if (shapes[i].getPosition().y < 0) shapes[i].setPosition(shapes[i].getPosition().x, shapes[i].getPosition().y + _window_height); } // Applies the three rules to each boid in the flock and changes them accordingly. flock.flocking(); _window.display(); }
static uint32_t rawval_to_lua_stack(lua_State *ls, uint8_t* rawval, const filtercheck_field_info* finfo, uint32_t len) { ASSERT(rawval != NULL); ASSERT(finfo != NULL); switch(finfo->m_type) { case PT_INT8: lua_pushnumber(ls, *(int8_t*)rawval); return 1; case PT_INT16: lua_pushnumber(ls, *(int16_t*)rawval); return 1; case PT_INT32: lua_pushnumber(ls, *(int32_t*)rawval); return 1; case PT_INT64: case PT_ERRNO: case PT_PID: lua_pushnumber(ls, (double)*(int64_t*)rawval); return 1; case PT_L4PROTO: // This can be resolved in the future case PT_FLAGS8: case PT_UINT8: lua_pushnumber(ls, *(uint8_t*)rawval); return 1; case PT_PORT: // This can be resolved in the future case PT_FLAGS16: case PT_UINT16: lua_pushnumber(ls, *(uint16_t*)rawval); return 1; case PT_FLAGS32: case PT_UINT32: lua_pushnumber(ls, *(uint32_t*)rawval); return 1; case PT_UINT64: case PT_RELTIME: case PT_ABSTIME: lua_pushnumber(ls, (double)*(uint64_t*)rawval); return 1; case PT_CHARBUF: lua_pushstring(ls, (char*)rawval); return 1; case PT_BYTEBUF: if(rawval[len] == 0) { lua_pushstring(ls, (char*)rawval); return 1; } else { lua_getglobal(ls, "sichisel"); sinsp_chisel* ch = (sinsp_chisel*)lua_touserdata(ls, -1); lua_pop(ls, 1); uint32_t max_len = len < sizeof(ch->m_lua_fld_storage) ? len : sizeof(ch->m_lua_fld_storage) - 1; memcpy(ch->m_lua_fld_storage, rawval, max_len); ch->m_lua_fld_storage[max_len] = 0; lua_pushstring(ls, (char*)ch->m_lua_fld_storage); return 1; } case PT_SOCKADDR: ASSERT(false); return 0; case PT_SOCKFAMILY: ASSERT(false); return 0; case PT_BOOL: lua_pushboolean(ls, (*(uint32_t*)rawval != 0)); return 1; case PT_IPV4ADDR: { lua_getglobal(ls, "sichisel"); sinsp_chisel* ch = (sinsp_chisel*)lua_touserdata(ls, -1); lua_pop(ls, 1); snprintf(ch->m_lua_fld_storage, sizeof(ch->m_lua_fld_storage), "%" PRIu8 ".%" PRIu8 ".%" PRIu8 ".%" PRIu8, rawval[0], rawval[1], rawval[2], rawval[3]); lua_pushstring(ls, ch->m_lua_fld_storage); return 1; } default: ASSERT(false); throw sinsp_exception("wrong event type " + to_string((long long) finfo->m_type)); } }
bool isUnique(string word) { int len = word.length(); string str = word[0] + to_string(len - 2) + word[len - 1]; return m.find(str) == m.end() || (m[str].find(word) != m[str].end() && m[str].size() == 1); }
// { // account: <account>|<account_public_key> // account_index: <number> // optional, defaults to 0. // ledger_hash : <ledger> // ledger_index : <ledger_index> // limit: integer // optional // marker: opaque // optional, resume previous query // } Json::Value doAccountOffers (RPC::Context& context) { auto const& params (context.params); if (! params.isMember (jss::account)) return RPC::missing_field_error (jss::account); Ledger::pointer ledger; Json::Value result (RPC::lookupLedger (params, ledger, context.netOps)); if (! ledger) return result; std::string strIdent (params[jss::account].asString ()); bool bIndex (params.isMember (jss::account_index)); int const iIndex (bIndex ? params[jss::account_index].asUInt () : 0); DivvyAddress divvyAddress; Json::Value const jv = RPC::accountFromString ( divvyAddress, bIndex, strIdent, iIndex, false); if (! jv.empty ()) { for (Json::Value::const_iterator it (jv.begin ()); it != jv.end (); ++it) result[it.memberName ()] = it.key (); return result; } // Get info on account. result[jss::account] = divvyAddress.humanAccountID (); if (bIndex) result[jss::account_index] = iIndex; if (! ledger->exists(getAccountRootIndex( divvyAddress.getAccountID()))) return rpcError (rpcACT_NOT_FOUND); unsigned int limit; if (params.isMember (jss::limit)) { auto const& jvLimit (params[jss::limit]); if (! jvLimit.isIntegral ()) return RPC::expected_field_error (jss::limit, "unsigned integer"); limit = jvLimit.isUInt () ? jvLimit.asUInt () : std::max (0, jvLimit.asInt ()); if (context.role != Role::ADMIN) { limit = std::max (RPC::Tuning::minOffersPerRequest, std::min (limit, RPC::Tuning::maxOffersPerRequest)); } } else { limit = RPC::Tuning::defaultOffersPerRequest; } AccountID const& raAccount (divvyAddress.getAccountID ()); Json::Value& jsonOffers (result[jss::offers] = Json::arrayValue); std::vector <std::shared_ptr<SLE const>> offers; unsigned int reserve (limit); uint256 startAfter; std::uint64_t startHint; if (params.isMember(jss::marker)) { // We have a start point. Use limit - 1 from the result and use the // very last one for the resume. Json::Value const& marker (params[jss::marker]); if (! marker.isString ()) return RPC::expected_field_error (jss::marker, "string"); startAfter.SetHex (marker.asString ()); auto const sleOffer = fetch (*ledger, startAfter, getApp().getSLECache()); if (sleOffer == nullptr || sleOffer->getType () != ltOFFER || raAccount != sleOffer->getFieldAccount160 (sfAccount)) { return rpcError (rpcINVALID_PARAMS); } startHint = sleOffer->getFieldU64(sfOwnerNode); // Caller provided the first offer (startAfter), add it as first result Json::Value& obj (jsonOffers.append (Json::objectValue)); sleOffer->getFieldAmount (sfTakerPays).setJson (obj[jss::taker_pays]); sleOffer->getFieldAmount (sfTakerGets).setJson (obj[jss::taker_gets]); obj[jss::seq] = sleOffer->getFieldU32 (sfSequence); obj[jss::flags] = sleOffer->getFieldU32 (sfFlags); offers.reserve (reserve); } else { startHint = 0; // We have no start point, limit should be one higher than requested. offers.reserve (++reserve); } if (! forEachItemAfter(*ledger, raAccount, getApp().getSLECache(), startAfter, startHint, reserve, [&offers](std::shared_ptr<SLE const> const& offer) { if (offer->getType () == ltOFFER) { offers.emplace_back (offer); return true; } return false; })) { return rpcError (rpcINVALID_PARAMS); } if (offers.size () == reserve) { result[jss::limit] = limit; result[jss::marker] = to_string (offers.back ()->getIndex ()); offers.pop_back (); } for (auto const& offer : offers) { Json::Value& obj (jsonOffers.append (Json::objectValue)); offer->getFieldAmount (sfTakerPays).setJson (obj[jss::taker_pays]); offer->getFieldAmount (sfTakerGets).setJson (obj[jss::taker_gets]); obj[jss::seq] = offer->getFieldU32 (sfSequence); obj[jss::flags] = offer->getFieldU32 (sfFlags); } context.loadType = Resource::feeMediumBurdenRPC; return result; }
/** Writes in the xml file an 'articleId' node with the id of the article. @param articleId: id of the article to add */ void ExtendedArticlesXMLGenerator::addArticleId(int articleId) { addOpenningTag(aXMLFile, "articleId"); addData(aXMLFile, to_string(articleId)); addClosingTag(aXMLFile, "articleId"); }
/* ECMA-262 3rd Edition 15.7.4.2 */ static HRESULT Number_toString(script_ctx_t *ctx, vdisp_t *jsthis, WORD flags, DISPPARAMS *dp, VARIANT *retv, jsexcept_t *ei, IServiceProvider *sp) { NumberInstance *number; INT radix = 10; DOUBLE val; BSTR str; HRESULT hres; TRACE("\n"); if(!(number = number_this(jsthis))) return throw_type_error(ctx, ei, JS_E_NUMBER_EXPECTED, NULL); if(arg_cnt(dp)) { hres = to_int32(ctx, get_arg(dp, 0), ei, &radix); if(FAILED(hres)) return hres; if(radix<2 || radix>36) return throw_type_error(ctx, ei, JS_E_INVALIDARG, NULL); } if(V_VT(&number->num) == VT_I4) val = V_I4(&number->num); else val = V_R8(&number->num); if(radix==10 || isnan(val) || isinf(val)) { hres = to_string(ctx, &number->num, ei, &str); if(FAILED(hres)) return hres; } else { INT idx = 0; DOUBLE integ, frac, log_radix = 0; WCHAR buf[NUMBER_TOSTRING_BUF_SIZE+16]; BOOL exp = FALSE; if(val<0) { val = -val; buf[idx++] = '-'; } while(1) { integ = floor(val); frac = val-integ; if(integ == 0) buf[idx++] = '0'; while(integ>=1 && idx<NUMBER_TOSTRING_BUF_SIZE) { buf[idx] = fmod(integ, radix); if(buf[idx]<10) buf[idx] += '0'; else buf[idx] += 'a'-10; integ /= radix; idx++; } if(idx<NUMBER_TOSTRING_BUF_SIZE) { INT beg = buf[0]=='-'?1:0; INT end = idx-1; WCHAR wch; while(end > beg) { wch = buf[beg]; buf[beg++] = buf[end]; buf[end--] = wch; } } if(idx != NUMBER_TOSTRING_BUF_SIZE) buf[idx++] = '.'; while(frac>0 && idx<NUMBER_TOSTRING_BUF_SIZE) { frac *= radix; buf[idx] = fmod(frac, radix); frac -= buf[idx]; if(buf[idx]<10) buf[idx] += '0'; else buf[idx] += 'a'-10; idx++; } if(idx==NUMBER_TOSTRING_BUF_SIZE && !exp) { exp = TRUE; idx = (buf[0]=='-') ? 1 : 0; log_radix = floor(log(val)/log(radix)); val *= pow(radix, -log_radix); continue; } break; } while(buf[idx-1] == '0') idx--; if(buf[idx-1] == '.') idx--; if(exp) { if(log_radix==0) buf[idx] = 0; else { static const WCHAR formatW[] = {'(','e','%','c','%','d',')',0}; WCHAR ch; if(log_radix<0) { log_radix = -log_radix; ch = '-'; } else ch = '+'; sprintfW(&buf[idx], formatW, ch, (int)log_radix); } } else buf[idx] = '\0'; str = SysAllocString(buf); if(!str) return E_OUTOFMEMORY; } if(retv) { V_VT(retv) = VT_BSTR; V_BSTR(retv) = str; }else { SysFreeString(str); } return S_OK; }
char const * options::get_string(char const * n, char const * default_value) const { sexpr const & r = get_sexpr(n); return !is_nil(r) && is_string(r) ? to_string(r).c_str() : default_value; }
string CodeGenerator::generate(const SyntaxTreePtr &tree) { switch (StrHasher::hash(tree->tree_name->name())) { case StrHasher::hash_const(STR("VAR")): if (tree->nodes.size() > 3) { auto var_name = std::dynamic_pointer_cast<TreeElementLeaf>(tree->nodes[0])->leaf->name(); auto expression = generate(std::dynamic_pointer_cast<TreeElementNode>(tree->nodes[3])->node); Emit(STR("= ") + var_name + STR(" ") + expression); } break; case StrHasher::hash_const(STR("BOOL_EXPRESSION")): { auto op = std::dynamic_pointer_cast<TreeElementLeaf>(tree->nodes[1])->leaf->name(); auto expression1 = generate(std::dynamic_pointer_cast<TreeElementNode>(tree->nodes[0])->node); auto expression2 = generate(std::dynamic_pointer_cast<TreeElementNode>(tree->nodes[2])->node); return Emit(op + STR(" ") + expression1 + STR(" ") + expression2); } case StrHasher::hash_const(STR("CASE_EXPRESSION")): { static int case_temp_count = 1; auto selector = generate(std::dynamic_pointer_cast<TreeElementNode>(tree->nodes[1])->node); auto cases = std::dynamic_pointer_cast<TreeElementNode>(tree->nodes[2])->node->nodes; auto endLabel = getNewLabel(); std::vector<string> caseLabels; for (auto case_statement : cases) { caseLabels.push_back(getNewLabel()); auto node = std::dynamic_pointer_cast<TreeElementNode>(case_statement)->node; auto caseExpr = generate(std::dynamic_pointer_cast<TreeElementNode>(node->nodes[1])->node); auto res = Emit(STR("== ") + selector + STR(" ") + caseExpr); Emit(STR("IFTRUE ") + res + STR(" ") + caseLabels.back()); } if (tree->nodes.size() > 4) { auto elseExpr = generate(std::dynamic_pointer_cast<TreeElementNode>(tree->nodes[4])->node); Emit(STR("= _CASETEMP") + to_string(++case_temp_count) + STR(" ") + elseExpr); Emit(STR("GOTO ") + endLabel); } int i = 0; for (auto case_statement : cases) { auto node = std::dynamic_pointer_cast<TreeElementNode>(case_statement)->node; auto caseResult = generate(std::dynamic_pointer_cast<TreeElementNode>(node->nodes[3])->node); Emit(caseLabels[i++] + STR(":")); Emit(STR("= _CASETEMP") + to_string(case_temp_count) + STR(" ") + caseResult); Emit(STR("GOTO ") + endLabel); } Emit(endLabel + STR(":")); return STR("_CASETEMP") + to_string(case_temp_count--); } case StrHasher::hash_const(STR("EXPRESSION")): { if (tree->nodes.size() == 1) { // id or literal or other expression if (std::dynamic_pointer_cast<TreeElementLeaf>(tree->nodes[0])) return std::dynamic_pointer_cast<TreeElementLeaf>(tree->nodes[0])->leaf->name(); if (std::dynamic_pointer_cast<TreeElementNode>(tree->nodes[0])) return generate(std::dynamic_pointer_cast<TreeElementNode>(tree->nodes[0])->node); } else { return STR("Unknown expression."); } } case StrHasher::hash_const(STR("ASSIGN_STATEMENT")): { auto var_name = std::dynamic_pointer_cast<TreeElementLeaf>(tree->nodes[0])->leaf->name(); auto expression = generate(std::dynamic_pointer_cast<TreeElementNode>(tree->nodes[2])->node); Emit(STR("= ") + var_name + STR(" ") + expression); break; } case StrHasher::hash_const(STR("FOR_STATEMENT")): { auto for_var = std::dynamic_pointer_cast<TreeElementLeaf>(tree->nodes[1])->leaf->name(); bool is_reversed = tree->nodes[3]->type() == TreeElementType::LEAF; auto from = generate(std::dynamic_pointer_cast<TreeElementNode>(tree->nodes[is_reversed ? 4 : 3])->node); auto to = generate(std::dynamic_pointer_cast<TreeElementNode>(tree->nodes[is_reversed ? 6 : 5])->node); auto start_label = getNewLabel(); Emit(STR("= ") + for_var + STR(" ") + from); Emit(start_label + STR(":")); generate(std::dynamic_pointer_cast<TreeElementNode>(tree->nodes[is_reversed ? 8 : 7])->node); Emit(STR("+ ") + for_var + (is_reversed ? STR(" -1") : STR(" 1"))); auto loop_condition = Emit(STR("== ") + for_var + STR(" ") + to); Emit(STR("IFFALSE ") + loop_condition + STR(" ") + start_label); } default: for(auto node : tree->nodes) if (node->type() == TreeElementType::NODE) generate(std::dynamic_pointer_cast<TreeElementNode>(node)->node); break; } return STR(""); }
static std::string format_json_value(nlohmann::json const &value) { return value.is_number() ? to_string(value.get<uint64_t>()) : value.is_boolean() ? std::string{value.get<bool>() ? "1" : "0"} : value.get<std::string>(); }
/*********************************************************************** * Method: alarmBase::dump * Params: * Returns: void * Effects: ***********************************************************************/ void alarmBase::dump() { cout << "Start Time : " + startTime << endl; cout << "Duration : " + to_string(duration) << endl; cout << "State : " + to_string(state) << endl; }
void GamePlay::determine() { vector<findWinner> fw; vector<findWinner> fw2; vector<findWinner> fw3; vector<string> fw4; for (size_t i = 0; i < listOfComputerPlayers.size(); i++) { listOfComputerPlayers[i].cpuHighCardValue = checks.highCardValues(listOfComputerPlayers[i].cpuhand); } playerHighCardValue = checks.highCardValues(playerhand); for (size_t i = 0; i < listOfComputerPlayers.size(); i++) { if (listOfComputerPlayers[i].didFold == false) { fw.push_back({ listOfComputerPlayers[i].CpuHandValue, listOfComputerPlayers[i].cpuHighCardValue, listOfComputerPlayers[i].cpucash, listOfComputerPlayers[i].name }); } } fw.push_back({ PlayerHandValue, playerHighCardValue, cash, "You" }); sort(fw.begin(), fw.end(), sortFunc); for (size_t i = 0; i < fw.size(); i++) { if (fw.back().handValue == fw[i].handValue) { fw2.push_back(fw[i]); } } if (fw2.size() > 1) { sort(fw2.begin(), fw2.end(), sortFunc1); for (size_t i = 0; i < fw2.size(); i++) { if (fw2.back().highCard == fw2[i].highCard) { fw3.push_back(fw2[i]); } } } if (fw3.size() > 1) { for (size_t i = 1; i < fw3.size(); i++) { if (fw3[0].name != fw3[i].name) { fw4.push_back(fw3[i].name); } fw4.push_back(fw3[0].name); } } if (fw3.size() <= 1) { if (fw2.size() < 1) { fw4.push_back(fw.back().name); } if (fw2.size() >= 1) { fw4.push_back(fw2.back().name); } } std::sort(fw4.begin(), fw4.end()); auto it = std::unique(fw4.begin(), fw4.end()); fw4.erase(it, fw4.end()); if (fw4.size() > 1) { int pot2 = pot / fw4.size(); if (fw4.size() == 2) { result = "Split Pot " + fw4[0] + " " + fw4[1] + " split $" + to_string(pot2) + " each!"; } if (fw4.size() == 3) { result = "Split Pot " + fw4[0] + " " + fw4[1] + " " + fw4[2] + " split $" + to_string(pot2) + " each!"; } if (fw4.size() == 4) { result = "Split Pot " + fw4[0] + " " + fw4[1] + " " + fw4[2] + " " + fw4[3] + " split $" + to_string(pot2) + " each!"; } for (string splitwinners : fw4) { if (splitwinners == "You") { cash = cash + pot2; } if (splitwinners == "Jim") { listOfComputerPlayers[0].cpucash = listOfComputerPlayers[0].cpucash + pot2; } if (splitwinners == "Tom") { listOfComputerPlayers[1].cpucash = listOfComputerPlayers[1].cpucash + pot2; } if (splitwinners == "John") { listOfComputerPlayers[2].cpucash = listOfComputerPlayers[2].cpucash + pot2; } } } else { if (fw4.back() == "You") { result = fw4.back() + " Win $" + to_string(pot)+"!!"; cash = cash + pot; } if (fw4.back() == "Jim") { result = fw4.back() + " Wins $" + to_string(pot) + "!!"; listOfComputerPlayers[0].cpucash = listOfComputerPlayers[0].cpucash + pot; } if (fw4.back() == "Tom") { result = fw4.back() + " Wins $" + to_string(pot) + "!!"; listOfComputerPlayers[1].cpucash = listOfComputerPlayers[1].cpucash + pot; } if (fw4.back() == "John") { result = fw4.back() + " Wins $" + to_string(pot) + "!!"; listOfComputerPlayers[2].cpucash = listOfComputerPlayers[2].cpucash + pot; } } }
std::vector<std::string> mwv::get_data() const { return {to_string(angle), to_string(type), to_string(speed), to_string(speed_unit), to_string(status)}; }
bool MyTblPlnrQUsrList::loadRecByQref( ubigint qref , PlnrQUsrList** rec ) { return loadRecBySQL("SELECT * FROM TblPlnrQUsrList WHERE qref = " + to_string(qref), rec); };
// Run the simulation. Run creates the boids that we'll display, checks for user // input, and updates the view void Game::Run() { for (int i = 0; i < BOID_AMOUNT; i++) { createBoid(_window_width / 2, _window_height / 2, false, sf::Color::Green, sf::Color::Blue); } //Whole block of text can probably simplified in a function as well in order to remove redundancy sf::Font font; font.loadFromFile("consola.ttf"); sf::Text fpsText("Frames per Second: ", font); fpsText.setColor(sf::Color::White); fpsText.setCharacterSize(12); fpsText.setPosition(_window_width - 162, 0); sf::Text preyText("Total Prey Count: " + to_string(flock.preyCount()), font); preyText.setColor(sf::Color::White); preyText.setCharacterSize(12); preyText.setPosition(_window_width - 155, 12); sf::Text predText("Total Predator Count: " + to_string(flock.predCount()), font); predText.setColor(sf::Color::White); predText.setCharacterSize(12); predText.setPosition(_window_width - 183, 24); sf::Text boidText("Total Boid Count: " + to_string(flock.getSize()), font); boidText.setColor(sf::Color::White); boidText.setCharacterSize(12); boidText.setPosition(_window_width - 155, 36); sf::Text dSepText("Separation Amount: " + to_string(flock.getBoid(0).getDesSep()), font); dSepText.setColor(sf::Color::White); dSepText.setCharacterSize(12); dSepText.setPosition(_window_width - 162, 60); sf::Text dAliText("Alignment Amount: " + to_string(flock.getBoid(0).getDesAli()), font); dAliText.setColor(sf::Color::White); dAliText.setCharacterSize(12); dAliText.setPosition(_window_width - 155, 72); sf::Text dCohText("Cohesion Amount: " + to_string(flock.getBoid(0).getDesCoh()), font); dCohText.setColor(sf::Color::White); dCohText.setCharacterSize(12); dCohText.setPosition(_window_width - 148, 84); sf::Text dSepWText("Separation Weight: " + to_string(flock.getBoid(0).getSepW()), font); dSepWText.setColor(sf::Color::White); dSepWText.setCharacterSize(12); dSepWText.setPosition(_window_width - 162, 108); sf::Text dAliWText("Alignment Weight: " + to_string(flock.getBoid(0).getAliW()), font); dAliWText.setColor(sf::Color::White); dAliWText.setCharacterSize(12); dAliWText.setPosition(_window_width - 155, 120); sf::Text dCohWText("Cohesion Weight: " + to_string(flock.getBoid(0).getCohW()), font); dCohWText.setColor(sf::Color::White); dCohWText.setCharacterSize(12); dCohWText.setPosition(_window_width - 148, 132); // Clock added to calculate frame rate, may cause a small amount of slowdown? sf::Clock clock; while (_window.isOpen()) { float currentTime = clock.restart().asSeconds(); float fps = 1 / currentTime; // 1 / refresh time = estimate of fps HandleInput(); Render(fpsText, fps, preyText, predText, boidText, dSepText, dAliText, dCohText, dSepWText, dAliWText, dCohWText); } }
fc::string json::to_pretty_string( const variant& v, output_formatting format /* = stringify_large_ints_and_doubles */ ) { return pretty_print(to_string(v, format), 2); }
void sinsp_filter::compile(const string& fltstr) { m_fltstr = fltstr; m_scansize = (uint32_t)m_fltstr.size(); while(true) { char a = next(); switch(a) { case 0: // // Finished parsing the filter string // if(m_nest_level != 0) { throw sinsp_exception("filter error: unexpected end of filter"); } if(m_state != ST_EXPRESSION_DONE) { throw sinsp_exception("filter error: unexpected end of filter at position " + to_string((long long) m_scanpos)); } // // Good filter // return; break; case '(': if(m_state != ST_NEED_EXPRESSION) { throw sinsp_exception("unexpected '(' after " + m_fltstr.substr(0, m_scanpos)); } push_expression(m_last_boolop); break; case ')': pop_expression(); break; case 'o': if(next() == 'r') { m_last_boolop = BO_OR; } else { throw sinsp_exception("syntax error in filter at position " + to_string((long long) m_scanpos)); } if(m_state != ST_EXPRESSION_DONE) { throw sinsp_exception("unexpected 'or' after " + m_fltstr.substr(0, m_scanpos)); } m_state = ST_NEED_EXPRESSION; break; case 'a': if(next() == 'n' && next() == 'd') { m_last_boolop = BO_AND; } else { throw sinsp_exception("syntax error in filter at position " + to_string((long long) m_scanpos)); } if(m_state != ST_EXPRESSION_DONE) { throw sinsp_exception("unexpected 'and' after " + m_fltstr.substr(0, m_scanpos)); } m_state = ST_NEED_EXPRESSION; break; case 'n': if(next() == 'o' && next() == 't') { m_last_boolop = (boolop)((uint32_t)m_last_boolop | BO_NOT); } else { throw sinsp_exception("syntax error in filter at position " + to_string((long long) m_scanpos)); } if(m_state != ST_EXPRESSION_DONE && m_state != ST_NEED_EXPRESSION) { throw sinsp_exception("unexpected 'not' after " + m_fltstr.substr(0, m_scanpos)); } m_state = ST_NEED_EXPRESSION; break; default: parse_check(m_curexpr, m_last_boolop); m_state = ST_EXPRESSION_DONE; break; } } vector<string> components = sinsp_split(m_fltstr, ' '); }